@sixb/server 0.1.26 → 0.2.0
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 +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2495 -1845
- package/dist/index.js.map +29 -27
- package/dist/routes/actions.d.ts +1 -1
- package/dist/routes/agent-approvals.d.ts +11 -5
- package/dist/routes/agent-approvals.d.ts.map +1 -1
- package/dist/routes/agent-children.d.ts +2 -2
- package/dist/routes/agent-computers.d.ts +214 -10
- package/dist/routes/agent-computers.d.ts.map +1 -1
- package/dist/routes/agent-runners.d.ts +1 -1
- package/dist/routes/agent-runners.d.ts.map +1 -1
- package/dist/routes/agents.d.ts +230 -24
- 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 +9 -0
- package/dist/routes/auth.d.ts.map +1 -1
- package/dist/routes/datasets.d.ts +93 -17
- package/dist/routes/datasets.d.ts.map +1 -1
- package/dist/routes/events.d.ts +1 -1
- package/dist/routes/links.d.ts +121 -81
- package/dist/routes/links.d.ts.map +1 -1
- package/dist/routes/logs.d.ts +3 -3
- package/dist/routes/objects.d.ts +149 -58
- package/dist/routes/objects.d.ts.map +1 -1
- package/dist/routes/observed-agent-threads.d.ts +23 -5
- package/dist/routes/observed-agent-threads.d.ts.map +1 -1
- package/dist/routes/pipelines.d.ts +2 -2
- package/dist/routes/projections.d.ts +122 -122
- package/dist/routes/rules.d.ts +2 -2
- package/dist/routes/telemetry.d.ts +0 -50
- package/dist/routes/telemetry.d.ts.map +1 -1
- package/dist/routes/webhook-runs.d.ts +1 -1
- package/dist/routes/workflows.d.ts +21 -10
- package/dist/routes/workflows.d.ts.map +1 -1
- package/dist/routes/ws/agents.d.ts +4 -1
- package/dist/routes/ws/agents.d.ts.map +1 -1
- package/dist/routes/ws/logs.d.ts +10 -10
- package/dist/schemas/actions.d.ts +3 -3
- package/dist/schemas/activity.d.ts +4 -4
- package/dist/schemas/agent-approvals.d.ts +21 -21
- package/dist/schemas/agents.d.ts +760 -107
- package/dist/schemas/agents.d.ts.map +1 -1
- package/dist/schemas/ai-accounting.d.ts +1114 -6
- package/dist/schemas/ai-accounting.d.ts.map +1 -1
- package/dist/schemas/auth.d.ts +47 -0
- package/dist/schemas/auth.d.ts.map +1 -1
- package/dist/schemas/datasets.d.ts +303 -60
- package/dist/schemas/datasets.d.ts.map +1 -1
- package/dist/schemas/event-payloads.d.ts +6 -6
- package/dist/schemas/events.d.ts +8 -8
- package/dist/schemas/lineage.d.ts +1272 -0
- package/dist/schemas/lineage.d.ts.map +1 -0
- package/dist/schemas/links.d.ts +4 -27
- package/dist/schemas/links.d.ts.map +1 -1
- package/dist/schemas/logs.d.ts +22 -22
- package/dist/schemas/objects.d.ts +7 -26
- package/dist/schemas/objects.d.ts.map +1 -1
- package/dist/schemas/pipelines.d.ts +12 -12
- package/dist/schemas/projections.d.ts +733 -733
- package/dist/schemas/rules.d.ts +4 -4
- package/dist/schemas/telemetry.d.ts +0 -13
- package/dist/schemas/telemetry.d.ts.map +1 -1
- package/dist/schemas/webhook-runs.d.ts +2 -2
- package/dist/schemas/workflows.d.ts +133 -44
- package/dist/schemas/workflows.d.ts.map +1 -1
- package/dist/server.d.ts +4 -0
- package/dist/server.d.ts.map +1 -1
- package/dist/utils/request-body.d.ts +5 -0
- package/dist/utils/request-body.d.ts.map +1 -1
- package/dist/utils/request-timing.d.ts +18 -0
- package/dist/utils/request-timing.d.ts.map +1 -0
- package/package.json +7 -7
- package/src/index.ts +1 -0
- package/src/routes/agent-approvals.ts +2 -2
- package/src/routes/agent-computers.ts +309 -87
- package/src/routes/agent-runners.ts +30 -6
- package/src/routes/agents.ts +187 -25
- package/src/routes/ai-accounting.ts +149 -12
- package/src/routes/auth.ts +24 -2
- package/src/routes/datasets.ts +55 -5
- package/src/routes/links.ts +43 -76
- package/src/routes/objects.ts +49 -42
- package/src/routes/observed-agent-threads.ts +2 -2
- package/src/routes/telemetry.ts +1 -42
- package/src/routes/ws/agents.ts +10 -1
- package/src/schemas/agents.ts +121 -6
- package/src/schemas/ai-accounting.ts +78 -15
- package/src/schemas/auth.ts +19 -0
- package/src/schemas/datasets.ts +36 -0
- package/src/schemas/lineage.ts +115 -0
- package/src/schemas/links.ts +3 -11
- package/src/schemas/objects.ts +6 -10
- package/src/schemas/telemetry.ts +0 -6
- package/src/server.ts +18 -2
- package/src/utils/request-body.ts +10 -4
- package/src/utils/request-timing.ts +136 -0
package/src/routes/agents.ts
CHANGED
|
@@ -4,9 +4,16 @@ import {
|
|
|
4
4
|
type AgentRunView,
|
|
5
5
|
type AgentThreadView,
|
|
6
6
|
type FileRef,
|
|
7
|
+
type LanguageModelEntry,
|
|
8
|
+
principalsEqual,
|
|
7
9
|
type SixbHostView,
|
|
8
10
|
} from "@sixb/core"
|
|
9
|
-
import {
|
|
11
|
+
import { sameComputerPlace } from "@sixb/core/internal/agent-run-storage-provider"
|
|
12
|
+
import {
|
|
13
|
+
assertConversationThread,
|
|
14
|
+
isRetryableAgentRun,
|
|
15
|
+
readAgentThreadContextUse,
|
|
16
|
+
} from "@sixb/core/internal/agents"
|
|
10
17
|
import { agentRunStreamId } from "@sixb/core/internal/agents/streams"
|
|
11
18
|
import { resolveFileRefAtPath } from "@sixb/core/internal/blob-storage"
|
|
12
19
|
import {
|
|
@@ -15,18 +22,25 @@ import {
|
|
|
15
22
|
type AgentRunDiagnostic,
|
|
16
23
|
type AgentStorage,
|
|
17
24
|
AgentStorageError,
|
|
25
|
+
type AgentThreadComputer,
|
|
18
26
|
type AgentThreadRecord,
|
|
19
27
|
type Principal,
|
|
20
28
|
} from "@sixb/core/storage"
|
|
21
29
|
import type { Elysia } from "elysia"
|
|
22
30
|
import { ZodError, z } from "zod"
|
|
23
31
|
import { accessTokenSecurityRequirement } from "../auth/access-token-boundary"
|
|
24
|
-
import {
|
|
32
|
+
import {
|
|
33
|
+
type RequestAuthState,
|
|
34
|
+
requestActor,
|
|
35
|
+
requestAuthState,
|
|
36
|
+
requireRequestSixb,
|
|
37
|
+
} from "../auth/scope"
|
|
25
38
|
import {
|
|
26
39
|
createFileContentResponse,
|
|
27
40
|
fileContentGetResponses,
|
|
28
41
|
fileContentHeadResponses,
|
|
29
42
|
} from "../files/content"
|
|
43
|
+
import { resolvedForDisplay } from "../models/display"
|
|
30
44
|
import { SIXB_SESSION_MUTATION_SECURITY_REQUIREMENT } from "../openapi/security"
|
|
31
45
|
import { OPENAPI_TAGS } from "../openapi/tags"
|
|
32
46
|
import {
|
|
@@ -41,6 +55,8 @@ import {
|
|
|
41
55
|
AgentRunListResponseSchema,
|
|
42
56
|
AgentRunParamsSchema,
|
|
43
57
|
AgentRunSchema,
|
|
58
|
+
AgentThreadContextQuerySchema,
|
|
59
|
+
AgentThreadContextSchema,
|
|
44
60
|
AgentThreadListQuerySchema,
|
|
45
61
|
AgentThreadListResponseSchema,
|
|
46
62
|
AgentThreadParamsSchema,
|
|
@@ -73,18 +89,25 @@ const AgentMessageFileContentQuerySchema = FileContentQuerySchema.extend({
|
|
|
73
89
|
const SHARING =
|
|
74
90
|
"Only the thread's owner adds participants: active users of the project, by id or by email. They read the whole conversation, its files and its live stream, and send messages that run with their own rights; a thread that runs on its owner's computer they only read. Nothing checks what they may see: the conversation holds what the Agent read with the rights of whoever asked."
|
|
75
91
|
|
|
76
|
-
/**
|
|
92
|
+
/**
|
|
93
|
+
* Threads as the API returns them to `viewer`, their owner and participants named by their
|
|
94
|
+
* accounts. Where a computer's thread runs, and whether `sixb` is open there, is its owner's alone.
|
|
95
|
+
*/
|
|
77
96
|
export async function serializeThreads(
|
|
78
97
|
host: SixbHostView,
|
|
79
|
-
threads: readonly AgentThreadView[]
|
|
98
|
+
threads: readonly AgentThreadView[],
|
|
99
|
+
viewer: Principal
|
|
80
100
|
): Promise<ReturnType<typeof AgentThreadSchema.parse>[]> {
|
|
81
|
-
const people = await
|
|
82
|
-
host,
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
101
|
+
const [placeOf, people] = await Promise.all([
|
|
102
|
+
computerPlaces(host, threads, viewer),
|
|
103
|
+
namePrincipals(
|
|
104
|
+
host,
|
|
105
|
+
threads.flatMap((thread) => [
|
|
106
|
+
thread.ownerPrincipal,
|
|
107
|
+
...thread.participants.map((participant) => participant.principal),
|
|
108
|
+
])
|
|
109
|
+
),
|
|
110
|
+
])
|
|
88
111
|
const named = (principal: Principal) => people.get(principalKey(principal)) ?? principal
|
|
89
112
|
|
|
90
113
|
return threads.map((thread) =>
|
|
@@ -103,7 +126,8 @@ export async function serializeThreads(
|
|
|
103
126
|
title: thread.title,
|
|
104
127
|
sandboxParams: thread.sandboxParams,
|
|
105
128
|
runsOn: thread.runsOn,
|
|
106
|
-
|
|
129
|
+
computer: placeOf(thread),
|
|
130
|
+
movedAt: thread.movedAt ? toIsoString(thread.movedAt) : undefined,
|
|
107
131
|
sandboxState: thread.sandboxState && {
|
|
108
132
|
name: thread.sandboxState.name,
|
|
109
133
|
status: thread.sandboxState.status,
|
|
@@ -121,13 +145,38 @@ export async function serializeThreads(
|
|
|
121
145
|
|
|
122
146
|
export async function serializeThread(
|
|
123
147
|
host: SixbHostView,
|
|
124
|
-
thread: AgentThreadView
|
|
148
|
+
thread: AgentThreadView,
|
|
149
|
+
viewer: Principal
|
|
125
150
|
): Promise<ReturnType<typeof AgentThreadSchema.parse>> {
|
|
126
|
-
const [serialized] = await serializeThreads(host, [thread])
|
|
151
|
+
const [serialized] = await serializeThreads(host, [thread], viewer)
|
|
127
152
|
if (!serialized) throw new Error(`[SixbServer] Could not serialize Agent thread '${thread.id}'.`)
|
|
128
153
|
return serialized
|
|
129
154
|
}
|
|
130
155
|
|
|
156
|
+
/** Where each of the viewer's own computer threads runs, and whether its folder is open now. */
|
|
157
|
+
async function computerPlaces(
|
|
158
|
+
host: SixbHostView,
|
|
159
|
+
threads: readonly AgentThreadView[],
|
|
160
|
+
viewer: Principal
|
|
161
|
+
): Promise<(thread: AgentThreadView) => (AgentThreadComputer & { online: boolean }) | undefined> {
|
|
162
|
+
const owned = (thread: AgentThreadView) =>
|
|
163
|
+
thread.computer !== undefined && principalsEqual(thread.ownerPrincipal, viewer)
|
|
164
|
+
const live =
|
|
165
|
+
host.storage.agents && threads.some(owned)
|
|
166
|
+
? await host.storage.agents.computers.listLive({
|
|
167
|
+
projectId: host.id,
|
|
168
|
+
ownerPrincipal: viewer,
|
|
169
|
+
now: new Date(),
|
|
170
|
+
})
|
|
171
|
+
: []
|
|
172
|
+
return (thread) => {
|
|
173
|
+
const computer = thread.computer
|
|
174
|
+
if (!computer || !owned(thread)) return undefined
|
|
175
|
+
const online = live.some((session) => sameComputerPlace(session.computer, computer))
|
|
176
|
+
return { ...computer, online }
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
131
180
|
function serializeMessage(
|
|
132
181
|
message: AgentMessageRecord,
|
|
133
182
|
annotations: readonly AgentRunDiagnostic[] = [],
|
|
@@ -146,6 +195,7 @@ function serializeMessage(
|
|
|
146
195
|
compaction: checkpoint
|
|
147
196
|
? {
|
|
148
197
|
checkpointId: checkpoint.id,
|
|
198
|
+
reason: checkpoint.reason,
|
|
149
199
|
summary: checkpoint.summary,
|
|
150
200
|
createdAt: toIsoString(checkpoint.createdAt),
|
|
151
201
|
}
|
|
@@ -354,7 +404,7 @@ export async function agentMessageFileContentResponse(
|
|
|
354
404
|
export async function readThreadMessages(
|
|
355
405
|
host: SixbHostView,
|
|
356
406
|
storage: AgentStorage,
|
|
357
|
-
thread: AgentThreadRecord,
|
|
407
|
+
thread: Pick<AgentThreadRecord, "id">,
|
|
358
408
|
query: z.infer<typeof AgentMessagesQuerySchema>
|
|
359
409
|
) {
|
|
360
410
|
const projectId = host.id
|
|
@@ -434,10 +484,20 @@ async function namePrincipals(
|
|
|
434
484
|
return new Map(named)
|
|
435
485
|
}
|
|
436
486
|
|
|
437
|
-
function principalKey(principal: Principal): string {
|
|
487
|
+
export function principalKey(principal: Principal): string {
|
|
438
488
|
return `${principal.type}:${principal.id}`
|
|
439
489
|
}
|
|
440
490
|
|
|
491
|
+
/** A thread as reading it answers: with the permission mode its reader shows. */
|
|
492
|
+
export async function serializeThreadRead(
|
|
493
|
+
host: SixbHostView,
|
|
494
|
+
sixb: ReturnType<typeof requireRequestSixb>,
|
|
495
|
+
thread: AgentThreadView
|
|
496
|
+
) {
|
|
497
|
+
const approvalMode = await sixb.agent.threads.getApprovalMode(thread.id)
|
|
498
|
+
return { ...(await serializeThread(host, thread, requestActor(sixb))), ...approvalMode }
|
|
499
|
+
}
|
|
500
|
+
|
|
441
501
|
export function registerAgentRoutes(app: Elysia, host: SixbHostView) {
|
|
442
502
|
return app
|
|
443
503
|
.get(
|
|
@@ -481,7 +541,7 @@ export function registerAgentRoutes(app: Elysia, host: SixbHostView) {
|
|
|
481
541
|
const result = await sixb.agent.threads.list(listInput)
|
|
482
542
|
|
|
483
543
|
return AgentThreadListResponseSchema.parse({
|
|
484
|
-
threads: await serializeThreads(host, result.threads),
|
|
544
|
+
threads: await serializeThreads(host, result.threads, requestActor(sixb)),
|
|
485
545
|
hasMore: result.hasMore,
|
|
486
546
|
total: result.total,
|
|
487
547
|
})
|
|
@@ -520,11 +580,12 @@ export function registerAgentRoutes(app: Elysia, host: SixbHostView) {
|
|
|
520
580
|
...(parsed.title === undefined ? {} : { title: parsed.title }),
|
|
521
581
|
...(parsed.sandbox === undefined ? {} : { sandbox: parsed.sandbox }),
|
|
522
582
|
...(parsed.runsOn === undefined ? {} : { runsOn: parsed.runsOn }),
|
|
583
|
+
...(parsed.computer === undefined ? {} : { computer: parsed.computer }),
|
|
523
584
|
})
|
|
524
585
|
|
|
525
586
|
set.status = 201
|
|
526
587
|
return CreateAgentThreadResponseSchema.parse({
|
|
527
|
-
thread: await serializeThread(host, thread),
|
|
588
|
+
thread: await serializeThread(host, thread, requestActor(sixb)),
|
|
528
589
|
})
|
|
529
590
|
} catch (error) {
|
|
530
591
|
return handleAgentRouteError(error, set)
|
|
@@ -565,8 +626,7 @@ export function registerAgentRoutes(app: Elysia, host: SixbHostView) {
|
|
|
565
626
|
return { error: "Agent thread not found" }
|
|
566
627
|
}
|
|
567
628
|
|
|
568
|
-
|
|
569
|
-
return { ...(await serializeThread(host, thread)), ...approvalMode }
|
|
629
|
+
return await serializeThreadRead(host, sixb, thread)
|
|
570
630
|
} catch (error) {
|
|
571
631
|
return handleAgentRouteError(error, set)
|
|
572
632
|
}
|
|
@@ -599,7 +659,7 @@ export function registerAgentRoutes(app: Elysia, host: SixbHostView) {
|
|
|
599
659
|
const parsed = AddAgentThreadParticipantsBodySchema.parse(body)
|
|
600
660
|
const thread = await sixb.agent.threads.participants.add(params.threadId, parsed.users)
|
|
601
661
|
|
|
602
|
-
return serializeThread(host, thread)
|
|
662
|
+
return serializeThread(host, thread, requestActor(sixb))
|
|
603
663
|
} catch (error) {
|
|
604
664
|
return handleAgentRouteError(error, set)
|
|
605
665
|
}
|
|
@@ -679,7 +739,7 @@ export function registerAgentRoutes(app: Elysia, host: SixbHostView) {
|
|
|
679
739
|
|
|
680
740
|
set.status = 201
|
|
681
741
|
return CreateAgentThreadResponseSchema.parse({
|
|
682
|
-
thread: await serializeThread(host, thread),
|
|
742
|
+
thread: await serializeThread(host, thread, requestActor(sixb)),
|
|
683
743
|
})
|
|
684
744
|
} catch (error) {
|
|
685
745
|
return handleAgentRouteError(error, set)
|
|
@@ -712,7 +772,7 @@ export function registerAgentRoutes(app: Elysia, host: SixbHostView) {
|
|
|
712
772
|
context.params.threadId,
|
|
713
773
|
context.body
|
|
714
774
|
)
|
|
715
|
-
return serializeThread(host, thread)
|
|
775
|
+
return serializeThread(host, thread, requestActor(sixb))
|
|
716
776
|
} catch (error) {
|
|
717
777
|
if (error instanceof AgentStorageError && error.code === "invalid_state") {
|
|
718
778
|
context.set.status = 409
|
|
@@ -744,14 +804,24 @@ export function registerAgentRoutes(app: Elysia, host: SixbHostView) {
|
|
|
744
804
|
"/api/agent-threads/:threadId/messages",
|
|
745
805
|
async (context) => {
|
|
746
806
|
const { params, query, set } = context
|
|
747
|
-
const
|
|
807
|
+
const authState = requestAuthState(context)
|
|
748
808
|
try {
|
|
749
809
|
const storage = host.storage.agents
|
|
750
810
|
if (!storage) {
|
|
751
811
|
return missingAgentStorageResponse(set)
|
|
752
812
|
}
|
|
753
813
|
|
|
754
|
-
|
|
814
|
+
// A run reads its own conversation alone, as it reads that conversation's files; a
|
|
815
|
+
// child or a workflow step reads none.
|
|
816
|
+
const thread =
|
|
817
|
+
authState.agentExecution && !authState.agentRun
|
|
818
|
+
? null
|
|
819
|
+
: await getAgentMessageFileContentThread({
|
|
820
|
+
authState,
|
|
821
|
+
storage,
|
|
822
|
+
projectId: host.id,
|
|
823
|
+
threadId: params.threadId,
|
|
824
|
+
})
|
|
755
825
|
if (!thread) {
|
|
756
826
|
set.status = 404
|
|
757
827
|
return { error: "Agent thread not found" }
|
|
@@ -778,6 +848,7 @@ export function registerAgentRoutes(app: Elysia, host: SixbHostView) {
|
|
|
778
848
|
summary: "List agent thread messages",
|
|
779
849
|
tags: [OPENAPI_TAGS.agentThreads.name],
|
|
780
850
|
operationId: "listAgentThreadMessages",
|
|
851
|
+
security: accessTokenSecurityRequirement("listAgentThreadMessages"),
|
|
781
852
|
},
|
|
782
853
|
}
|
|
783
854
|
)
|
|
@@ -986,6 +1057,97 @@ export function registerAgentRoutes(app: Elysia, host: SixbHostView) {
|
|
|
986
1057
|
},
|
|
987
1058
|
}
|
|
988
1059
|
)
|
|
1060
|
+
.get(
|
|
1061
|
+
"/api/agent-threads/:threadId/context",
|
|
1062
|
+
async (context) => {
|
|
1063
|
+
const { params, query, set } = context
|
|
1064
|
+
const sixb = requireRequestSixb(context)
|
|
1065
|
+
try {
|
|
1066
|
+
const storage = host.storage.agents
|
|
1067
|
+
const aiUsage = host.storage.aiUsage
|
|
1068
|
+
const language = host.definitions.models?.language
|
|
1069
|
+
if (!storage || !aiUsage) {
|
|
1070
|
+
return missingAgentStorageResponse(set)
|
|
1071
|
+
}
|
|
1072
|
+
|
|
1073
|
+
const parsed = AgentThreadContextQuerySchema.parse(query)
|
|
1074
|
+
if ((parsed.provider === undefined) !== (parsed.modelId === undefined)) {
|
|
1075
|
+
set.status = 400
|
|
1076
|
+
return { error: "Name the model with both 'provider' and 'modelId', or neither." }
|
|
1077
|
+
}
|
|
1078
|
+
|
|
1079
|
+
const thread = await sixb.agent.threads.getById(params.threadId)
|
|
1080
|
+
if (!thread) {
|
|
1081
|
+
set.status = 404
|
|
1082
|
+
return { error: "Agent thread not found" }
|
|
1083
|
+
}
|
|
1084
|
+
// A sub-agent's thread is measured through its conversation's turns.
|
|
1085
|
+
assertConversationThread(thread)
|
|
1086
|
+
|
|
1087
|
+
// The model asked for, else the one the latest turn ran on, else the default.
|
|
1088
|
+
const latest = await sixb.agent.runs.listForThread(thread.id, { limit: 1, order: "desc" })
|
|
1089
|
+
const latestSpec = latest?.runs[0]?.spec
|
|
1090
|
+
const latestModel = latestSpec?.model
|
|
1091
|
+
const entry: LanguageModelEntry | null | undefined =
|
|
1092
|
+
parsed.provider !== undefined && parsed.modelId !== undefined
|
|
1093
|
+
? language?.getByRef({ provider: parsed.provider, modelId: parsed.modelId })
|
|
1094
|
+
: ((latestModel && language?.getByRef(latestModel)) ?? language?.default)
|
|
1095
|
+
if (!entry) {
|
|
1096
|
+
set.status = 404
|
|
1097
|
+
return { error: "Language model not found" }
|
|
1098
|
+
}
|
|
1099
|
+
|
|
1100
|
+
// The reasoning the latest turn ran with, on its model; the model's default on another.
|
|
1101
|
+
const latestRunsOn =
|
|
1102
|
+
latestModel?.provider === entry.provider && latestModel.modelId === entry.modelId
|
|
1103
|
+
const reasoning = latestRunsOn ? latestSpec?.reasoning : entry.model.defaultReasoning
|
|
1104
|
+
|
|
1105
|
+
const use = await readAgentThreadContextUse(
|
|
1106
|
+
{ projectId: host.id, storage: { agents: storage, aiUsage } },
|
|
1107
|
+
{
|
|
1108
|
+
threadId: thread.id,
|
|
1109
|
+
model: await resolvedForDisplay(entry),
|
|
1110
|
+
...(reasoning === undefined ? {} : { reasoning }),
|
|
1111
|
+
}
|
|
1112
|
+
)
|
|
1113
|
+
return AgentThreadContextSchema.parse({
|
|
1114
|
+
...use,
|
|
1115
|
+
model: { provider: entry.provider, modelId: entry.modelId },
|
|
1116
|
+
...(use.lastCall
|
|
1117
|
+
? { lastCall: { ...use.lastCall, occurredAt: toIsoString(use.lastCall.occurredAt) } }
|
|
1118
|
+
: {}),
|
|
1119
|
+
...(use.lastCompaction
|
|
1120
|
+
? {
|
|
1121
|
+
lastCompaction: {
|
|
1122
|
+
...use.lastCompaction,
|
|
1123
|
+
createdAt: toIsoString(use.lastCompaction.createdAt),
|
|
1124
|
+
},
|
|
1125
|
+
}
|
|
1126
|
+
: {}),
|
|
1127
|
+
})
|
|
1128
|
+
} catch (error) {
|
|
1129
|
+
return handleAgentRouteError(error, set)
|
|
1130
|
+
}
|
|
1131
|
+
},
|
|
1132
|
+
{
|
|
1133
|
+
params: AgentThreadParamsSchema,
|
|
1134
|
+
query: AgentThreadContextQuerySchema,
|
|
1135
|
+
response: {
|
|
1136
|
+
200: AgentThreadContextSchema,
|
|
1137
|
+
400: ErrorResponseSchema,
|
|
1138
|
+
404: ErrorResponseSchema,
|
|
1139
|
+
409: AgentRequestErrorResponseSchema,
|
|
1140
|
+
501: ErrorResponseSchema,
|
|
1141
|
+
},
|
|
1142
|
+
detail: {
|
|
1143
|
+
summary: "Measure an agent thread's context against a model's limits",
|
|
1144
|
+
description:
|
|
1145
|
+
"What the conversation's next request starts from, the model's limit, and the latest compaction. Read by the context meter after each turn.",
|
|
1146
|
+
tags: [OPENAPI_TAGS.agentThreads.name],
|
|
1147
|
+
operationId: "getAgentThreadContext",
|
|
1148
|
+
},
|
|
1149
|
+
}
|
|
1150
|
+
)
|
|
989
1151
|
.get(
|
|
990
1152
|
"/api/agent-threads/:threadId/runs",
|
|
991
1153
|
async (context) => {
|
|
@@ -1,7 +1,9 @@
|
|
|
1
|
-
import type { SixbHostView } from "@sixb/core"
|
|
1
|
+
import type { AgentMessagePart, SixbHostView } from "@sixb/core"
|
|
2
2
|
import type {
|
|
3
3
|
AiAccountingAggregate,
|
|
4
|
+
AiAccountingFilters,
|
|
4
5
|
AiAccountingOverview,
|
|
6
|
+
AiAccountingRequester,
|
|
5
7
|
AiLimitPolicy,
|
|
6
8
|
AiLimitPolicyStatus,
|
|
7
9
|
AiModelCallAccountingItem,
|
|
@@ -45,7 +47,78 @@ function serializeAggregate(aggregate: AiAccountingAggregate) {
|
|
|
45
47
|
}
|
|
46
48
|
}
|
|
47
49
|
|
|
48
|
-
|
|
50
|
+
/** The person, source and kind filters a query names, as the storage reads them. */
|
|
51
|
+
function accountingFilters(parsed: {
|
|
52
|
+
readonly person?: string
|
|
53
|
+
readonly source?: string
|
|
54
|
+
readonly kind?: AiAccountingFilters["modelKind"]
|
|
55
|
+
}): Partial<Pick<AiAccountingFilters, "requester" | "source" | "modelKind">> {
|
|
56
|
+
const colon = parsed.person?.indexOf(":") ?? -1
|
|
57
|
+
return {
|
|
58
|
+
...(parsed.person === undefined
|
|
59
|
+
? {}
|
|
60
|
+
: {
|
|
61
|
+
requester:
|
|
62
|
+
parsed.person === "none"
|
|
63
|
+
? ("none" as const)
|
|
64
|
+
: {
|
|
65
|
+
type: parsed.person.slice(0, colon) as AiAccountingRequester["type"],
|
|
66
|
+
id: parsed.person.slice(colon + 1),
|
|
67
|
+
},
|
|
68
|
+
}),
|
|
69
|
+
...(parsed.source === undefined
|
|
70
|
+
? {}
|
|
71
|
+
: {
|
|
72
|
+
source: parsed.source.startsWith("workflow:")
|
|
73
|
+
? { kind: "workflow" as const, workflowId: parsed.source.slice("workflow:".length) }
|
|
74
|
+
: { kind: parsed.source as "agent" | "action" | "workflow" | "other" },
|
|
75
|
+
}),
|
|
76
|
+
...(parsed.kind === undefined ? {} : { modelKind: parsed.kind }),
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
type RequesterDetails = ReadonlyMap<string, { readonly name?: string; readonly email?: string }>
|
|
81
|
+
|
|
82
|
+
const requesterKey = (requester: AiAccountingRequester) => `${requester.type}:${requester.id}`
|
|
83
|
+
|
|
84
|
+
/** Each requester's name and email, read once for the page they are on. */
|
|
85
|
+
async function requesterDetails(
|
|
86
|
+
host: SixbHostView,
|
|
87
|
+
requesters: readonly (AiAccountingRequester | undefined)[]
|
|
88
|
+
): Promise<RequesterDetails> {
|
|
89
|
+
const auth = host.storage.auth
|
|
90
|
+
const details = new Map<string, { name?: string; email?: string }>()
|
|
91
|
+
if (!auth) return details
|
|
92
|
+
const unique = [
|
|
93
|
+
...new Map(
|
|
94
|
+
requesters.flatMap((requester) => (requester ? [[requesterKey(requester), requester]] : []))
|
|
95
|
+
).values(),
|
|
96
|
+
]
|
|
97
|
+
const userIds = unique.flatMap((requester) => (requester.type === "user" ? [requester.id] : []))
|
|
98
|
+
if (userIds.length > 0) {
|
|
99
|
+
for (const user of await auth.users.getByIds({ projectId: host.id, ids: userIds })) {
|
|
100
|
+
details.set(`user:${user.id}`, {
|
|
101
|
+
...(user.displayName ? { name: user.displayName } : {}),
|
|
102
|
+
email: user.email,
|
|
103
|
+
})
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
for (const requester of unique) {
|
|
107
|
+
if (requester.type !== "serviceAccount") continue
|
|
108
|
+
const account = await auth.serviceAccounts.getById({ projectId: host.id, id: requester.id })
|
|
109
|
+
if (account) details.set(requesterKey(requester), { name: account.name })
|
|
110
|
+
}
|
|
111
|
+
return details
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function serializeRequester(
|
|
115
|
+
requester: AiAccountingRequester | undefined,
|
|
116
|
+
details: RequesterDetails
|
|
117
|
+
) {
|
|
118
|
+
return requester ? { ...requester, ...details.get(requesterKey(requester)) } : undefined
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function serializeOverview(overview: AiAccountingOverview, details: RequesterDetails) {
|
|
49
122
|
return AiAccountingOverviewResponseSchema.parse({
|
|
50
123
|
range: {
|
|
51
124
|
from: overview.range.from.toISOString(),
|
|
@@ -58,11 +131,24 @@ function serializeOverview(overview: AiAccountingOverview) {
|
|
|
58
131
|
end: period.end.toISOString(),
|
|
59
132
|
...serializeAggregate(period),
|
|
60
133
|
})),
|
|
134
|
+
modelSeries: overview.modelSeries.map((model) => ({
|
|
135
|
+
providerId: model.providerId,
|
|
136
|
+
modelId: model.modelId,
|
|
137
|
+
series: model.series.map((period) => ({
|
|
138
|
+
start: period.start.toISOString(),
|
|
139
|
+
end: period.end.toISOString(),
|
|
140
|
+
...serializeAggregate(period),
|
|
141
|
+
})),
|
|
142
|
+
})),
|
|
61
143
|
models: overview.models.map((model) => ({
|
|
62
144
|
providerId: model.providerId,
|
|
63
145
|
modelId: model.modelId,
|
|
64
146
|
...serializeAggregate(model),
|
|
65
147
|
})),
|
|
148
|
+
people: overview.people.map((person) => ({
|
|
149
|
+
...(person.requester ? { requester: serializeRequester(person.requester, details) } : {}),
|
|
150
|
+
...serializeAggregate(person),
|
|
151
|
+
})),
|
|
66
152
|
kinds: overview.kinds.map((kind) => ({
|
|
67
153
|
...(kind.modelKind === undefined ? {} : { modelKind: kind.modelKind }),
|
|
68
154
|
...serializeAggregate(kind),
|
|
@@ -173,29 +259,54 @@ function handleAiLimitRouteError(error: unknown, set: { status?: number | string
|
|
|
173
259
|
async function serializeGroup(
|
|
174
260
|
group: AiModelCallGroup,
|
|
175
261
|
host: SixbHostView,
|
|
176
|
-
sixb: RequestAuthState["sixb"]
|
|
262
|
+
sixb: RequestAuthState["sixb"],
|
|
263
|
+
details: RequesterDetails
|
|
177
264
|
) {
|
|
178
265
|
// Accounting is project-wide; conversation titles and delegation keys remain private.
|
|
179
266
|
const thread =
|
|
180
267
|
group.attribution?.kind === "agent" && sixb
|
|
181
268
|
? await sixb.agent.threads.getById(group.attribution.threadId)
|
|
182
269
|
: null
|
|
183
|
-
|
|
270
|
+
// The conversation's turns and sub-agents, read together, for the sub-agents' names and what
|
|
271
|
+
// each turn was asked.
|
|
272
|
+
const agents = host.storage.agents
|
|
273
|
+
const runIds = thread
|
|
184
274
|
? group.executions.flatMap((execution) =>
|
|
185
|
-
execution.attribution?.kind === "
|
|
275
|
+
execution.attribution?.kind === "agent"
|
|
276
|
+
? [execution.attribution.agentRunId]
|
|
277
|
+
: execution.attribution?.kind === "subagent"
|
|
278
|
+
? [execution.attribution.subagentRunId]
|
|
279
|
+
: []
|
|
186
280
|
)
|
|
187
281
|
: []
|
|
188
|
-
const
|
|
189
|
-
|
|
190
|
-
?
|
|
282
|
+
const runs =
|
|
283
|
+
agents && runIds.length > 0
|
|
284
|
+
? await agents.runs.getByIds({ projectId: host.id, ids: runIds })
|
|
191
285
|
: []
|
|
192
286
|
const labels = new Map(
|
|
193
|
-
|
|
287
|
+
runs.flatMap((run) =>
|
|
194
288
|
run.kind === "subagent" ? [[run.executionId, run.spawnKey] as const] : []
|
|
195
289
|
)
|
|
196
290
|
)
|
|
291
|
+
const prompts = new Map(
|
|
292
|
+
agents
|
|
293
|
+
? await Promise.all(
|
|
294
|
+
runs.flatMap((run) =>
|
|
295
|
+
run.kind === "conversation"
|
|
296
|
+
? [
|
|
297
|
+
agents.messages
|
|
298
|
+
.getById({ projectId: host.id, id: run.triggerMessageId })
|
|
299
|
+
.then((message) => [run.executionId, message && promptOf(message)] as const),
|
|
300
|
+
]
|
|
301
|
+
: []
|
|
302
|
+
)
|
|
303
|
+
)
|
|
304
|
+
: []
|
|
305
|
+
)
|
|
306
|
+
const { requester, ...rest } = group
|
|
197
307
|
return {
|
|
198
|
-
...
|
|
308
|
+
...rest,
|
|
309
|
+
...(requester ? { requester: serializeRequester(requester, details) } : {}),
|
|
199
310
|
label: thread?.title,
|
|
200
311
|
canOpenThread: thread !== null,
|
|
201
312
|
firstCallAt: group.firstCallAt.toISOString(),
|
|
@@ -203,12 +314,24 @@ async function serializeGroup(
|
|
|
203
314
|
executions: group.executions.map((execution) => ({
|
|
204
315
|
...execution,
|
|
205
316
|
label: labels.get(execution.executionId),
|
|
317
|
+
prompt: prompts.get(execution.executionId) ?? undefined,
|
|
206
318
|
firstCallAt: execution.firstCallAt.toISOString(),
|
|
207
319
|
lastCallAt: execution.lastCallAt.toISOString(),
|
|
208
320
|
})),
|
|
209
321
|
}
|
|
210
322
|
}
|
|
211
323
|
|
|
324
|
+
/** The opening of the message that started a turn, on one line. */
|
|
325
|
+
function promptOf(message: { readonly parts: readonly AgentMessagePart[] }): string | undefined {
|
|
326
|
+
const text = message.parts
|
|
327
|
+
.flatMap((part) => (part.type === "text" ? [part.text] : []))
|
|
328
|
+
.join(" ")
|
|
329
|
+
.replace(/\s+/g, " ")
|
|
330
|
+
.trim()
|
|
331
|
+
if (!text) return undefined
|
|
332
|
+
return text.length > 160 ? `${text.slice(0, 159)}…` : text
|
|
333
|
+
}
|
|
334
|
+
|
|
212
335
|
export function registerAiAccountingRoutes(app: Elysia, host: SixbHostView) {
|
|
213
336
|
app.get(
|
|
214
337
|
"/api/ai/accounting/overview",
|
|
@@ -227,8 +350,13 @@ export function registerAiAccountingRoutes(app: Elysia, host: SixbHostView) {
|
|
|
227
350
|
bucket: parsed.bucket,
|
|
228
351
|
providerId: parsed.providerId,
|
|
229
352
|
modelId: parsed.modelId,
|
|
353
|
+
...accountingFilters(parsed),
|
|
230
354
|
})
|
|
231
|
-
|
|
355
|
+
const details = await requesterDetails(
|
|
356
|
+
host,
|
|
357
|
+
overview.people.map((person) => person.requester)
|
|
358
|
+
)
|
|
359
|
+
return serializeOverview(overview, details)
|
|
232
360
|
} catch (error) {
|
|
233
361
|
return handleRouteError(error, set)
|
|
234
362
|
}
|
|
@@ -266,6 +394,7 @@ export function registerAiAccountingRoutes(app: Elysia, host: SixbHostView) {
|
|
|
266
394
|
to: new Date(parsed.to),
|
|
267
395
|
providerId: parsed.providerId,
|
|
268
396
|
modelId: parsed.modelId,
|
|
397
|
+
...accountingFilters(parsed),
|
|
269
398
|
executionId: parsed.executionId,
|
|
270
399
|
valuationStatus: parsed.valuationStatus,
|
|
271
400
|
limit: parseOptionalInt(parsed.limit),
|
|
@@ -530,13 +659,21 @@ export function registerAiAccountingRoutes(app: Elysia, host: SixbHostView) {
|
|
|
530
659
|
to: new Date(parsed.to),
|
|
531
660
|
providerId: parsed.providerId,
|
|
532
661
|
modelId: parsed.modelId,
|
|
662
|
+
...accountingFilters(parsed),
|
|
533
663
|
valuationStatus: parsed.valuationStatus,
|
|
664
|
+
sort: parsed.sort,
|
|
534
665
|
limit: parseOptionalInt(parsed.limit),
|
|
535
666
|
offset: parseOptionalInt(parsed.offset),
|
|
536
667
|
})
|
|
668
|
+
const details = await requesterDetails(
|
|
669
|
+
host,
|
|
670
|
+
result.items.map((group) => group.requester)
|
|
671
|
+
)
|
|
537
672
|
return AiModelCallGroupsResponseSchema.parse({
|
|
538
673
|
...result,
|
|
539
|
-
items: await Promise.all(
|
|
674
|
+
items: await Promise.all(
|
|
675
|
+
result.items.map((group) => serializeGroup(group, host, sixb, details))
|
|
676
|
+
),
|
|
540
677
|
})
|
|
541
678
|
} catch (error) {
|
|
542
679
|
return handleRouteError(error, set)
|
package/src/routes/auth.ts
CHANGED
|
@@ -24,6 +24,7 @@ import {
|
|
|
24
24
|
verifyCsrfToken,
|
|
25
25
|
verifyDoubleSubmitCsrf,
|
|
26
26
|
} from "@sixb/core/internal/auth"
|
|
27
|
+
import { isAllowed } from "@sixb/core/internal/authorization"
|
|
27
28
|
import {
|
|
28
29
|
type AccessTokenRecord,
|
|
29
30
|
type AuthStorage,
|
|
@@ -119,6 +120,14 @@ type AuthenticatedAuthSessionResponse = {
|
|
|
119
120
|
readonly avatarUrl?: string
|
|
120
121
|
readonly groupIds: readonly string[]
|
|
121
122
|
}
|
|
123
|
+
readonly access: {
|
|
124
|
+
readonly members: boolean
|
|
125
|
+
readonly serviceAccounts: boolean
|
|
126
|
+
readonly usage: boolean
|
|
127
|
+
readonly activity: boolean
|
|
128
|
+
readonly console: boolean
|
|
129
|
+
readonly logs: boolean
|
|
130
|
+
}
|
|
122
131
|
readonly session: {
|
|
123
132
|
readonly id: string
|
|
124
133
|
readonly expiresAt: string
|
|
@@ -588,7 +597,7 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
|
|
|
588
597
|
return signedOutSessionResponse(host)
|
|
589
598
|
}
|
|
590
599
|
if (caller.session.bearer) {
|
|
591
|
-
return jsonResponse(authSessionBody(caller), 200)
|
|
600
|
+
return jsonResponse(authSessionBody(host, caller), 200)
|
|
592
601
|
}
|
|
593
602
|
|
|
594
603
|
const session = hasForegroundSessionActivity(request)
|
|
@@ -614,7 +623,7 @@ export function registerAuthRoutes(app: Elysia, host: SixbHostView, options: Aut
|
|
|
614
623
|
})
|
|
615
624
|
: null
|
|
616
625
|
return authSessionJsonResponse(
|
|
617
|
-
{ ...authSessionBody(session), csrfToken: csrf.token },
|
|
626
|
+
{ ...authSessionBody(host, session), csrfToken: csrf.token },
|
|
618
627
|
renewal?.headers ?? (csrf.setCookie ? [csrf.setCookie] : [])
|
|
619
628
|
)
|
|
620
629
|
},
|
|
@@ -2325,8 +2334,12 @@ function resolveSessionCsrfToken(input: {
|
|
|
2325
2334
|
}
|
|
2326
2335
|
|
|
2327
2336
|
function authSessionBody(
|
|
2337
|
+
host: SixbHostView,
|
|
2328
2338
|
session: AuthenticatedAuthSession
|
|
2329
2339
|
): Omit<AuthenticatedAuthSessionResponse, "csrfToken"> {
|
|
2340
|
+
// The same policies and grants the pages' own routes check.
|
|
2341
|
+
const capabilities = host.auth.getMembershipCapabilities({ callerGroups: session.groupIds }).holds
|
|
2342
|
+
const authorization = host.auth.contextFromSession(session)
|
|
2330
2343
|
return {
|
|
2331
2344
|
authenticated: true,
|
|
2332
2345
|
user: {
|
|
@@ -2336,6 +2349,14 @@ function authSessionBody(
|
|
|
2336
2349
|
avatarUrl: session.user.avatarUrl,
|
|
2337
2350
|
groupIds: [...session.groupIds],
|
|
2338
2351
|
},
|
|
2352
|
+
access: {
|
|
2353
|
+
members: capabilities.invite || capabilities.assignGroups || capabilities.suspend,
|
|
2354
|
+
serviceAccounts: capabilities.serviceAccounts,
|
|
2355
|
+
usage: isAllowed(authorization, { kind: "aiUsage.observe" }),
|
|
2356
|
+
activity: isAllowed(authorization, { kind: "activity.observe" }),
|
|
2357
|
+
console: isAllowed(authorization, { kind: "console.observe" }),
|
|
2358
|
+
logs: isAllowed(authorization, { kind: "logs.observe" }),
|
|
2359
|
+
},
|
|
2339
2360
|
session: { id: session.session.id, expiresAt: toIsoString(session.session.expiresAt) },
|
|
2340
2361
|
}
|
|
2341
2362
|
}
|
|
@@ -3105,6 +3126,7 @@ function serializeMemberSummary(member: MemberSummary) {
|
|
|
3105
3126
|
return {
|
|
3106
3127
|
...serializeManagedMember(member),
|
|
3107
3128
|
capabilities: member.capabilities,
|
|
3129
|
+
...(member.lastActiveAt ? { lastActiveAt: toIsoString(member.lastActiveAt) } : {}),
|
|
3108
3130
|
}
|
|
3109
3131
|
}
|
|
3110
3132
|
|