Repository navigation
Expand file tree
/
Copy pathjoins.ts
More file actions
245 lines (223 loc) · 11.9 KB
/
Copy pathjoins.ts
File metadata and controls
245 lines (223 loc) · 11.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
/**
* Who may read which log entry, and what a screen shows of each (LOGS_MANAGEMENT §7.1, §7.2, §9.3).
*
* Every scan, triage and CodeFix entry of a project is readable by anyone the route's `logs:read`
* let in. An agent entry is a chat's log, and one predicate decides it in the list, the content
* read, the download, the zip and the delete: a conversation of `readableConversationsWhere` (the
* person's own, and with write sharing in force the others' a sharing rule opens) whose route key
* is the entry's stem. `requireConversationRead` is not used: its author branch asks `agent:chat`
* (W+A), so an author below it would see an entry listed and then be refused opening it. The
* folder's meta names a session id too; it is never read for a decision (anyone on the host can
* edit it).
*
* The joins are display only: a triage entry shows its TriageRun, a CodeFix entry its Remediation,
* each looked up by the id its meta names and only within this project; "by" names a person only
* when they are the project's owner or a collaborator on it now (projectAccess), so a meta edited
* on the host cannot reveal another account's name. A chat's "by" is its author, or for one
* reassigned from a deleted account that account's name as the conversation list shows it; the
* reassignment columns are read only with the write switch on (conversationRetentionOn), like every
* other reader of them.
*
* Server-side only.
*/
import prisma from '@/lib/prisma'
import { conversationRetentionOn, readableConversationsWhere } from '@/lib/authz/conversationAccess'
import type { PermissionContext } from '@/lib/authz/guards'
import { projectAccess, type ProjectAccess } from '@/lib/authz/projectAccess'
import { isHashedKey, routeKey } from './ids'
import type { OrchestratorLogEntry } from './orchestratorLogs'
import { LOG_STATUSES, type LogEntry, type LogStatus } from './types'
/** The reader a route's guard answered: the project's access, and the person (the effective user). */
export interface LogReader {
access: ProjectAccess
projectId: string
viewerId: string
}
/** The reader of a route whose `requirePermission` named `projectId`. */
export function logReader(auth: PermissionContext, projectId: string): LogReader {
if (!auth.access) throw new Error('[logs] the route guard checked no project')
return { access: auth.access, projectId, viewerId: auth.effective.userId }
}
export interface AgentSession {
conversationId: string
title: string
agentRunning: boolean
createdAt: Date
/** Its author's name, else email; for one reassigned from a deleted account, "<their name> (account deleted)". */
author: string | null
}
const SESSION_SELECT = {
id: true, sessionId: true, title: true, agentRunning: true, createdAt: true,
user: { select: { name: true, email: true } },
} as const
const RETAINED_SELECT = { ...SESSION_SELECT, formerAuthorId: true, formerAuthorLabel: true } as const
interface SessionRow {
id: string
sessionId: string
title: string
agentRunning: boolean
createdAt: Date
user: { name: string | null; email: string } | null
formerAuthorId?: string | null
formerAuthorLabel?: string | null
}
const displayName = (user: { name: string | null; email: string } | null | undefined): string | null =>
user ? (user.name?.trim() || user.email) : null
// As the conversation list says it (conversationAccess.ts ConversationView, ConversationHistory.tsx).
function authorOf(row: SessionRow): string | null {
if (!row.formerAuthorId) return displayName(row.user)
return row.formerAuthorLabel ? `${row.formerAuthorLabel} (account deleted)` : null
}
/**
* The agent entries among `stems` that `reader` may read, each with its conversation: THE predicate.
* A stem is readable only when a conversation the reader may read has it as its route key. A plain
* key is its own session id, so those are looked up by it. A hashed key cannot be reversed, so only
* when one is asked are the readable conversations' session ids read (nothing else of them) and
* keyed, and the ones whose key was asked are looked up with the plain ones.
*/
export async function readableAgentSessions(reader: LogReader, stems: Iterable<string>): Promise<Map<string, AgentSession>> {
const wanted = new Set(stems)
const found = new Map<string, AgentSession>()
if (wanted.size === 0) return found
const readable = await readableConversationsWhere(reader.access, reader.projectId, reader.viewerId)
const sessionIds = [...wanted].filter((s) => !isHashedKey(s))
if (sessionIds.length < wanted.size) {
const all = await prisma.conversation.findMany({ where: readable, select: { sessionId: true } })
for (const { sessionId } of all) {
// A safe id is its own key, already looked up above; only the others are hashed.
const key = routeKey(sessionId)
if (isHashedKey(key) && wanted.has(key)) sessionIds.push(sessionId)
}
}
if (sessionIds.length === 0) return found
const rows: SessionRow[] = await prisma.conversation.findMany({
where: { AND: [readable, { sessionId: { in: sessionIds } }] },
select: conversationRetentionOn() ? RETAINED_SELECT : SESSION_SELECT,
})
for (const row of rows) {
const key = routeKey(row.sessionId)
if (!wanted.has(key)) continue
found.set(key, {
conversationId: row.id, title: row.title, agentRunning: row.agentRunning, createdAt: row.createdAt, author: authorOf(row),
})
}
return found
}
/** One agent entry's conversation, or null when the reader may not read it (the route answers 404). */
export async function readableAgentSession(reader: LogReader, stem: string): Promise<AgentSession | null> {
return (await readableAgentSessions(reader, [stem])).get(stem) ?? null
}
export interface ReadableEntries {
entries: OrchestratorLogEntry[]
/** The conversation of each readable agent entry, by stem. */
sessions: Map<string, AgentSession>
}
/** The listed entries `reader` may read: every non-agent one, and the agent ones the predicate opens. */
export async function readableEntries(reader: LogReader, listed: readonly OrchestratorLogEntry[]): Promise<ReadableEntries> {
const sessions = await readableAgentSessions(reader, listed.filter((e) => e.group === 'agent').map((e) => e.stem))
return { entries: listed.filter((e) => e.group !== 'agent' || sessions.has(e.stem)), sessions }
}
// A database id a meta names: anything else is never looked up.
const ROW_ID = /^[A-Za-z0-9_-]{1,64}$/
// "By" asks projectAccess once per person: a host-edited meta naming thousands must not cost thousands,
// and a list must not hold more than a few database connections at once.
const MAX_ACTORS = 50
const MEMBER_CHECKS_AT_ONCE = 5
const STATUSES: ReadonlySet<string> = new Set(LOG_STATUSES)
// TriageRun's own states, said as a log status.
const TRIAGE_STATUS: Readonly<Record<string, LogStatus>> = { publishing: 'running', completed_partial: 'completed' }
function text(meta: Record<string, unknown> | null, key: string, max = 200): string | null {
const v = meta?.[key]
return typeof v === 'string' && v !== '' && v.length <= max ? v : null
}
function count(meta: Record<string, unknown> | null, key: string): number | null {
const v = meta?.[key]
return typeof v === 'number' && Number.isSafeInteger(v) ? v : null
}
function iso(value: unknown): string | null {
if (typeof value !== 'string' || value.length > 40) return null
return Number.isNaN(Date.parse(value)) ? null : value
}
function status(value: unknown): LogStatus | null {
if (typeof value !== 'string') return null
const mapped = TRIAGE_STATUS[value] ?? value
return STATUSES.has(mapped) ? mapped as LogStatus : null
}
const rowId = (meta: Record<string, unknown> | null, key: string): string | null => {
const v = text(meta, key, 64)
return v && ROW_ID.test(v) ? v : null
}
/**
* The names of the people among `ids` who are the project's owner or a collaborator on it, by id.
* Membership is projectAccess's answer for each of them (owner or share; oversight and break-glass
* are not membership), so an expired share or sharing switched off names no one but the owner.
*/
export async function memberNames(reader: LogReader, ids: Iterable<string>): Promise<Map<string, string>> {
const unique = [...new Set(ids)].filter((id) => ROW_ID.test(id)).slice(0, MAX_ACTORS)
const members: string[] = []
for (let i = 0; i < unique.length; i += MEMBER_CHECKS_AT_ONCE) {
const batch = unique.slice(i, i + MEMBER_CHECKS_AT_ONCE)
const answers = await Promise.all(batch.map((id) => projectAccess({ userId: id }, reader.projectId)))
batch.forEach((id, n) => { if (answers[n]?.via === 'owner' || answers[n]?.via === 'share') members.push(id) })
}
if (members.length === 0) return new Map()
const users = await prisma.user.findMany({ where: { id: { in: members } }, select: { id: true, name: true, email: true } })
return new Map(users.map((u) => [u.id, displayName(u) as string]))
}
const newestFirst = (a: LogEntry, b: LogEntry): number =>
(b.startedAt ?? '').localeCompare(a.startedAt ?? '') || b.id.localeCompare(a.id)
/** What the list answers of each readable entry, newest first. */
export async function presentEntries(reader: LogReader, readable: ReadableEntries): Promise<LogEntry[]> {
const { entries, sessions } = readable
const triageIds = entries.filter((e) => e.group === 'triage').map((e) => rowId(e.meta, 'triage_run_id')).filter((v): v is string => !!v)
const remediationIds = entries.filter((e) => e.group === 'codefix').map((e) => rowId(e.meta, 'remediation_id')).filter((v): v is string => !!v)
const [runs, remediations] = await Promise.all([
triageIds.length === 0 ? [] : prisma.triageRun.findMany({
where: { id: { in: [...new Set(triageIds)] }, projectId: reader.projectId },
select: { id: true, status: true, startedAt: true, finishedAt: true, actorUserId: true },
}),
remediationIds.length === 0 ? [] : prisma.remediation.findMany({
where: { id: { in: [...new Set(remediationIds)] }, projectId: reader.projectId },
select: { id: true, title: true },
}),
])
const runById = new Map(runs.map((r) => [r.id, r]))
const remediationById = new Map(remediations.map((r) => [r.id, r]))
const actorOf = (e: OrchestratorLogEntry): string | null => {
if (e.group === 'triage') return runById.get(rowId(e.meta, 'triage_run_id') ?? '')?.actorUserId ?? null
return e.group === 'agent' || e.group === 'codefix' ? null : rowId(e.meta, 'actor_user_id')
}
const names = await memberNames(reader, entries.map(actorOf).filter((v): v is string => !!v))
return entries.map((e): LogEntry => {
const m = e.meta
const base: LogEntry = {
id: e.id, group: e.group, stem: e.stem, bytes: e.bytes, inUse: e.inUse, compressed: e.compressed, detail: e.detail,
status: status(m?.status), level: text(m, 'level', 32), startedAt: iso(m?.started_at), finishedAt: iso(m?.finished_at),
lines: count(m, 'lines'), truncated: m?.truncated === true, exitCode: count(m, 'exit_code'),
kind: text(m, 'kind', 64), runId: text(m, 'run_id', 200), by: null, title: null,
conversationId: null, triageRunId: null, remediationId: null,
}
const actor = actorOf(e)
if (actor) base.by = names.get(actor) ?? null
if (e.group === 'agent') {
const s = sessions.get(e.stem)!
return {
...base, inUse: s.agentRunning, status: s.agentRunning ? 'running' : null,
startedAt: base.startedAt ?? s.createdAt.toISOString(), by: s.author, title: s.title || null, conversationId: s.conversationId,
}
}
if (e.group === 'triage') {
const run = runById.get(rowId(m, 'triage_run_id') ?? '')
if (!run) return base
return {
...base, triageRunId: run.id, status: status(run.status) ?? base.status,
startedAt: run.startedAt.toISOString(), finishedAt: run.finishedAt?.toISOString() ?? base.finishedAt,
}
}
if (e.group === 'codefix') {
const remediation = remediationById.get(rowId(m, 'remediation_id') ?? '')
return remediation ? { ...base, remediationId: remediation.id, title: remediation.title } : base
}
return base
}).sort(newestFirst)
}