@mupt-ai/dari-gateway 1.0.334 → 1.0.336
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/dist/activity/conversation_detail.js +4 -1
- package/dist/activity/conversations.js +2 -1
- package/dist/activity/http.d.ts +28 -3
- package/dist/activity/http.js +15 -10
- package/dist/activity/imports.d.ts +29 -0
- package/dist/activity/imports.js +230 -0
- package/dist/activity/pull_requests.d.ts +29 -0
- package/dist/activity/pull_requests.js +295 -0
- package/dist/activity/routes.d.ts +1 -1
- package/dist/activity/routes.js +7 -1
- package/dist/http/handler.d.ts +3 -2
- package/dist/http/handler.js +8 -2
- package/dist/ingress/git_events.d.ts +2 -0
- package/dist/ingress/git_events.js +143 -0
- package/dist/link/budget.d.ts +27 -2
- package/dist/link/budget.js +63 -1
- package/dist/link/endpoints.js +179 -36
- package/dist/link/errors.d.ts +2 -0
- package/dist/link/errors.js +11 -2
- package/dist/link/grants.d.ts +6 -5
- package/dist/link/grants.js +11 -9
- package/dist/link/service.d.ts +27 -6
- package/dist/link/service.js +145 -21
- package/dist/link/sqlite_store.d.ts +7 -2
- package/dist/link/sqlite_store.js +57 -6
- package/dist/platform/platform.d.ts +72 -3
- package/dist/protocol/input/router_model.d.ts +1 -0
- package/dist/protocol/input/router_model.js +6 -2
- package/dist/runtime/runtime_reporter.d.ts +1 -0
- package/dist/runtime/runtime_reporter.js +3 -0
- package/dist/self_host/activity_store.d.ts +15 -2
- package/dist/self_host/activity_store.js +60 -7
- package/dist/self_host/platform.js +6 -0
- package/dist/self_host/resolve.d.ts +4 -5
- package/dist/self_host/resolve.js +20 -22
- package/dist/telemetry/report.js +21 -2
- package/dist/telemetry/tools/git_events.d.ts +36 -0
- package/dist/telemetry/tools/git_events.js +109 -0
- package/dist/telemetry/tools/observations.d.ts +8 -1
- package/dist/telemetry/tools/observations.js +1 -1
- package/dist/types.d.ts +1 -0
- package/package.json +2 -2
- package/src/activity/conversation_detail.ts +4 -1
- package/src/activity/conversations.ts +3 -2
- package/src/activity/http.ts +43 -12
- package/src/activity/imports.ts +278 -0
- package/src/activity/pull_requests.ts +342 -0
- package/src/activity/routes.ts +8 -2
- package/src/http/handler.ts +8 -2
- package/src/ingress/git_events.ts +145 -0
- package/src/link/budget.ts +80 -4
- package/src/link/endpoints.ts +171 -20
- package/src/link/errors.ts +12 -2
- package/src/link/grants.ts +22 -12
- package/src/link/service.ts +187 -24
- package/src/link/sqlite_store.ts +73 -10
- package/src/platform/platform.ts +57 -4
- package/src/protocol/input/router_model.ts +6 -2
- package/src/runtime/runtime_reporter.ts +5 -0
- package/src/self_host/activity_store.ts +79 -8
- package/src/self_host/platform.ts +6 -0
- package/src/self_host/resolve.ts +20 -25
- package/src/telemetry/report.ts +21 -2
- package/src/telemetry/tools/git_events.ts +125 -0
- package/src/telemetry/tools/observations.ts +1 -1
- package/src/types.ts +3 -0
|
@@ -0,0 +1,295 @@
|
|
|
1
|
+
/* Pull requests and the agent sessions that worked on them, read from each
|
|
2
|
+
session's git events: those the gateway read from its tool output
|
|
3
|
+
(`telemetry/tools/git_events.ts`) and the commits the Dari CLI's git hook
|
|
4
|
+
reported (`ingress/git_events.ts`). A session is linked to the pull
|
|
5
|
+
requests it opened or ran `gh pr` commands on, to the one its commit's hook
|
|
6
|
+
found open on the branch, and to those whose branch it pushed or committed
|
|
7
|
+
to. A push or commit goes to the latest pull request opened on its branch
|
|
8
|
+
before it, or else the first one opened after it. A pull request opened
|
|
9
|
+
without naming its branch is on the branch its session last pushed. */
|
|
10
|
+
import { conversationSummary, conversationTitles, fixedDecimal, groupKeyText, loadEntities, loadRecords, recordKey, } from "./conversation_records.js";
|
|
11
|
+
import { notFound } from "./params.js";
|
|
12
|
+
import { sql } from "./sql.js";
|
|
13
|
+
import { addDecimals, formatInstant, parseDecimal, readInstant, readInt, readOptionalString } from "./values.js";
|
|
14
|
+
// Session IDs per query: well inside every database's bound-value limit.
|
|
15
|
+
const SESSION_BATCH = 500;
|
|
16
|
+
const sessionKey = (sourceProtocol, agentSessionId) => `${sourceProtocol} ${agentSessionId}`;
|
|
17
|
+
const prKey = (repository, number) => `${repository}#${number}`;
|
|
18
|
+
async function loadGitEvents(db, organizationId, where) {
|
|
19
|
+
const rows = await db.all(sql `
|
|
20
|
+
select e.id, e.kind, e.repository, e.number, e.title, e.branch, e.commit_sha, e.source_protocol, e.agent_session_id,
|
|
21
|
+
e.ordinal, cast(e.occurred_at as text) as occurred_at
|
|
22
|
+
from routing_git_events e
|
|
23
|
+
where e.organization_id = ${organizationId} ${where}`);
|
|
24
|
+
return rows.map((row) => ({
|
|
25
|
+
id: String(row.id),
|
|
26
|
+
session: sessionKey(String(row.source_protocol), String(row.agent_session_id)),
|
|
27
|
+
kind: String(row.kind),
|
|
28
|
+
repository: String(row.repository),
|
|
29
|
+
number: row.number === null || row.number === undefined ? null : readInt(row.number),
|
|
30
|
+
title: readOptionalString(row.title),
|
|
31
|
+
branch: readOptionalString(row.branch),
|
|
32
|
+
commitSha: readOptionalString(row.commit_sha),
|
|
33
|
+
at: readInstant(row.occurred_at),
|
|
34
|
+
ordinal: readInt(row.ordinal),
|
|
35
|
+
}));
|
|
36
|
+
}
|
|
37
|
+
/** Whether an event names its branch's pull request only through the branch. */
|
|
38
|
+
const onBranch = (event) => event.kind === "push" || (event.kind === "commit" && event.number === null);
|
|
39
|
+
const unique = (values) => [...new Set([...values].filter((value) => value !== null))];
|
|
40
|
+
/**
|
|
41
|
+
* The page's sessions' events, plus the others that decide which pull
|
|
42
|
+
* requests they link to: every event on their branches or naming their pull
|
|
43
|
+
* requests, then the other events of the pull requests and pushers found.
|
|
44
|
+
*/
|
|
45
|
+
async function relatedGitEvents(db, organizationId, agentSessionIds) {
|
|
46
|
+
const own = await loadGitEvents(db, organizationId, sql `and e.agent_session_id in (${agentSessionIds})`);
|
|
47
|
+
const repositories = unique(own.map((event) => event.repository));
|
|
48
|
+
if (repositories.length === 0)
|
|
49
|
+
return [];
|
|
50
|
+
const numbers = unique(own.map((event) => event.number));
|
|
51
|
+
const near = await loadGitEvents(db, organizationId, sql `and e.repository in (${repositories})
|
|
52
|
+
and (e.branch in (${unique(own.map((event) => event.branch))}) or e.number in (${numbers}))`);
|
|
53
|
+
const pushers = unique(near.filter((event) => event.kind === "push").map((event) => event.session.split(" ")[1]));
|
|
54
|
+
const far = await loadGitEvents(db, organizationId, sql `and e.repository in (${repositories})
|
|
55
|
+
and (e.number in (${unique(near.map((event) => event.number)).filter((number) => !numbers.includes(number))})
|
|
56
|
+
or (e.agent_session_id in (${pushers}) and (e.kind = 'push' or (e.kind = 'opened' and e.branch is null))))`);
|
|
57
|
+
return [...new Map([...own, ...near, ...far].map((event) => [event.id, event])).values()];
|
|
58
|
+
}
|
|
59
|
+
/** The pull requests these events show, and the sessions linked to each. */
|
|
60
|
+
function buildPullRequests(unordered) {
|
|
61
|
+
const events = [...unordered].sort((a, b) => a.at - b.at || a.ordinal - b.ordinal || a.id.localeCompare(b.id));
|
|
62
|
+
const pullRequests = new Map();
|
|
63
|
+
const lastPushed = new Map();
|
|
64
|
+
events.forEach((event, seq) => {
|
|
65
|
+
if (event.kind === "push" && event.branch !== null)
|
|
66
|
+
lastPushed.set(`${event.session} ${event.repository}`, event.branch);
|
|
67
|
+
if (onBranch(event) || event.number === null)
|
|
68
|
+
return;
|
|
69
|
+
const key = prKey(event.repository, event.number);
|
|
70
|
+
const pr = pullRequests.get(key) ?? {
|
|
71
|
+
repository: event.repository,
|
|
72
|
+
number: event.number,
|
|
73
|
+
url: `https://github.com/${event.repository}/pull/${event.number}`,
|
|
74
|
+
title: null,
|
|
75
|
+
branch: null,
|
|
76
|
+
openedAt: event.at,
|
|
77
|
+
openedSeq: seq,
|
|
78
|
+
lastEventAt: event.at,
|
|
79
|
+
sessions: new Set(),
|
|
80
|
+
};
|
|
81
|
+
if (event.kind === "opened") {
|
|
82
|
+
pr.title ??= event.title;
|
|
83
|
+
// `gh pr create` without `--head` opens the branch the session pushed.
|
|
84
|
+
pr.branch ??= event.branch ?? lastPushed.get(`${event.session} ${event.repository}`) ?? null;
|
|
85
|
+
pr.openedAt = Math.min(pr.openedAt, event.at);
|
|
86
|
+
}
|
|
87
|
+
if (event.kind === "commit") {
|
|
88
|
+
// The hook found it open on this branch, so it is that branch's.
|
|
89
|
+
pr.title ??= event.title;
|
|
90
|
+
pr.branch ??= event.branch;
|
|
91
|
+
}
|
|
92
|
+
pr.lastEventAt = Math.max(pr.lastEventAt, event.at);
|
|
93
|
+
pr.sessions.add(event.session);
|
|
94
|
+
pullRequests.set(key, pr);
|
|
95
|
+
});
|
|
96
|
+
const byBranch = new Map();
|
|
97
|
+
for (const pr of pullRequests.values()) {
|
|
98
|
+
if (pr.branch === null)
|
|
99
|
+
continue;
|
|
100
|
+
const key = `${pr.repository} ${pr.branch}`;
|
|
101
|
+
byBranch.set(key, [...(byBranch.get(key) ?? []), pr].sort((a, b) => a.openedSeq - b.openedSeq));
|
|
102
|
+
}
|
|
103
|
+
events.forEach((event, seq) => {
|
|
104
|
+
if (!onBranch(event))
|
|
105
|
+
return;
|
|
106
|
+
const candidates = byBranch.get(`${event.repository} ${event.branch}`);
|
|
107
|
+
if (candidates === undefined)
|
|
108
|
+
return;
|
|
109
|
+
const pr = [...candidates].reverse().find((candidate) => candidate.openedSeq <= seq) ?? candidates[0];
|
|
110
|
+
pr.sessions.add(event.session);
|
|
111
|
+
pr.lastEventAt = Math.max(pr.lastEventAt, event.at);
|
|
112
|
+
});
|
|
113
|
+
return pullRequests;
|
|
114
|
+
}
|
|
115
|
+
/** The organization's pull requests and the sessions linked to each. */
|
|
116
|
+
async function loadPullRequests(db, organizationId) {
|
|
117
|
+
return buildPullRequests(await loadGitEvents(db, organizationId, sql ``));
|
|
118
|
+
}
|
|
119
|
+
/** Each of these sessions' pull requests, latest first. */
|
|
120
|
+
async function sessionPullRequests(db, organizationId, agentSessionIds) {
|
|
121
|
+
const bySession = new Map();
|
|
122
|
+
for (const pr of buildPullRequests(await relatedGitEvents(db, organizationId, agentSessionIds)).values()) {
|
|
123
|
+
for (const session of pr.sessions)
|
|
124
|
+
bySession.set(session, [...(bySession.get(session) ?? []), pr]);
|
|
125
|
+
}
|
|
126
|
+
return new Map([...bySession].map(([session, prs]) => [
|
|
127
|
+
session,
|
|
128
|
+
prs.sort((a, b) => b.openedAt - a.openedAt).map(({ repository, number, url, title }) => ({ repository, number, url, title })),
|
|
129
|
+
]));
|
|
130
|
+
}
|
|
131
|
+
/** The commits a session made that its git hook reported, oldest first. */
|
|
132
|
+
export async function sessionCommits(db, organizationId, sourceProtocol, agentSessionId) {
|
|
133
|
+
if (!sourceProtocol || !agentSessionId)
|
|
134
|
+
return [];
|
|
135
|
+
const events = await loadGitEvents(db, organizationId, sql `and e.source_protocol = ${sourceProtocol}
|
|
136
|
+
and e.agent_session_id = ${agentSessionId} and e.kind = 'commit'`);
|
|
137
|
+
return events
|
|
138
|
+
.filter((event) => event.commitSha !== null)
|
|
139
|
+
.sort((a, b) => a.at - b.at)
|
|
140
|
+
.map((event) => ({
|
|
141
|
+
repository: event.repository,
|
|
142
|
+
sha: event.commitSha,
|
|
143
|
+
branch: event.branch,
|
|
144
|
+
url: `https://github.com/${event.repository}/commit/${event.commitSha}`,
|
|
145
|
+
reported_at: formatInstant(event.at),
|
|
146
|
+
}));
|
|
147
|
+
}
|
|
148
|
+
/** The summaries, each with the pull requests its session worked on. */
|
|
149
|
+
export async function withPullRequests(db, organizationId, summaries) {
|
|
150
|
+
const ids = unique(summaries.map((summary) => summary.agent_session_id || null));
|
|
151
|
+
const linked = ids.length > 0 ? await sessionPullRequests(db, organizationId, ids) : new Map();
|
|
152
|
+
return summaries.map((summary) => ({
|
|
153
|
+
...summary,
|
|
154
|
+
pull_requests: summary.agent_session_id && summary.source_protocol
|
|
155
|
+
? linked.get(sessionKey(summary.source_protocol, summary.agent_session_id)) ?? []
|
|
156
|
+
: [],
|
|
157
|
+
}));
|
|
158
|
+
}
|
|
159
|
+
/** Each session's totals over all its steps. */
|
|
160
|
+
async function sessionTotals(db, organizationId, sessions) {
|
|
161
|
+
const totals = new Map();
|
|
162
|
+
const ids = [...new Set(sessions.map((session) => session.split(" ")[1]))];
|
|
163
|
+
for (let start = 0; start < ids.length; start += SESSION_BATCH) {
|
|
164
|
+
const rows = await db.all(sql `
|
|
165
|
+
select r.source_protocol, r.agent_session_id, r.attributed_user_id, r.selected_model,
|
|
166
|
+
count(r.id) as steps,
|
|
167
|
+
sum(coalesce(r.provider_total_tokens, 0)) as tokens,
|
|
168
|
+
cast(sum(r.provider_total_cost_usd) as text) as spend,
|
|
169
|
+
cast(min(r.received_at) as text) as first_at,
|
|
170
|
+
cast(max(r.received_at) as text) as last_at
|
|
171
|
+
from routing_requests r
|
|
172
|
+
where r.organization_id = ${organizationId}
|
|
173
|
+
and r.agent_session_id in (${ids.slice(start, start + SESSION_BATCH)})
|
|
174
|
+
group by r.source_protocol, r.agent_session_id, r.attributed_user_id, r.selected_model`);
|
|
175
|
+
for (const row of rows) {
|
|
176
|
+
const key = sessionKey(String(row.source_protocol), String(row.agent_session_id));
|
|
177
|
+
const firstAt = readInstant(row.first_at);
|
|
178
|
+
const lastAt = readInstant(row.last_at);
|
|
179
|
+
const entry = totals.get(key) ?? {
|
|
180
|
+
userId: readOptionalString(row.attributed_user_id), steps: 0, tokens: 0, spend: null, firstAt, lastAt, models: new Map(),
|
|
181
|
+
};
|
|
182
|
+
const steps = readInt(row.steps);
|
|
183
|
+
entry.steps += steps;
|
|
184
|
+
entry.tokens += readInt(row.tokens);
|
|
185
|
+
if (row.spend !== null && row.spend !== undefined) {
|
|
186
|
+
entry.spend = addDecimals(entry.spend ?? { coefficient: 0n, exponent: 0 }, parseDecimal(String(row.spend)));
|
|
187
|
+
}
|
|
188
|
+
entry.firstAt = Math.min(entry.firstAt, firstAt);
|
|
189
|
+
entry.lastAt = Math.max(entry.lastAt, lastAt);
|
|
190
|
+
if (row.selected_model !== null && row.selected_model !== undefined) {
|
|
191
|
+
entry.models.set(String(row.selected_model), (entry.models.get(String(row.selected_model)) ?? 0) + steps);
|
|
192
|
+
}
|
|
193
|
+
totals.set(key, entry);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
return totals;
|
|
197
|
+
}
|
|
198
|
+
async function userNames(db, ids) {
|
|
199
|
+
const names = new Map();
|
|
200
|
+
for (const row of await db.all(sql `select id, display_name, email from users where id in (${ids})`)) {
|
|
201
|
+
names.set(String(row.id), readOptionalString(row.display_name) || String(row.email));
|
|
202
|
+
}
|
|
203
|
+
return names;
|
|
204
|
+
}
|
|
205
|
+
/** The pull requests' summaries, in the order given. */
|
|
206
|
+
async function summaries(db, organizationId, pullRequests) {
|
|
207
|
+
const totals = await sessionTotals(db, organizationId, pullRequests.flatMap((pr) => [...pr.sessions]));
|
|
208
|
+
const names = await userNames(db, [...new Set([...totals.values()].map((t) => t.userId).filter((id) => id !== null))]);
|
|
209
|
+
return pullRequests.map((pr) => {
|
|
210
|
+
const sessions = [...pr.sessions].map((session) => totals.get(session)).filter((t) => t !== undefined);
|
|
211
|
+
let spend = null;
|
|
212
|
+
const models = new Map();
|
|
213
|
+
const people = new Map();
|
|
214
|
+
for (const session of sessions) {
|
|
215
|
+
if (session.spend !== null)
|
|
216
|
+
spend = addDecimals(spend ?? { coefficient: 0n, exponent: 0 }, session.spend);
|
|
217
|
+
for (const [model, steps] of session.models)
|
|
218
|
+
models.set(model, (models.get(model) ?? 0) + steps);
|
|
219
|
+
people.set(String(session.userId), {
|
|
220
|
+
user_id: session.userId,
|
|
221
|
+
name: session.userId === null ? null : names.get(session.userId) ?? null,
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
const first = sessions.length === 0 ? null : Math.min(...sessions.map((s) => s.firstAt));
|
|
225
|
+
const last = sessions.length === 0 ? null : Math.max(...sessions.map((s) => s.lastAt));
|
|
226
|
+
return {
|
|
227
|
+
repository: pr.repository,
|
|
228
|
+
number: pr.number,
|
|
229
|
+
url: pr.url,
|
|
230
|
+
title: pr.title,
|
|
231
|
+
branch: pr.branch,
|
|
232
|
+
opened_at: formatInstant(pr.openedAt),
|
|
233
|
+
conversation_count: sessions.length,
|
|
234
|
+
model_steps: sessions.reduce((sum, s) => sum + s.steps, 0),
|
|
235
|
+
provider_total_tokens: sessions.reduce((sum, s) => sum + s.tokens, 0),
|
|
236
|
+
provider_spend_usd: spend === null ? null : fixedDecimal(spend),
|
|
237
|
+
first_at: first === null ? null : formatInstant(first),
|
|
238
|
+
last_at: last === null ? null : formatInstant(last),
|
|
239
|
+
models: [...models].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).map(([model]) => model),
|
|
240
|
+
people: [...people.values()],
|
|
241
|
+
};
|
|
242
|
+
});
|
|
243
|
+
}
|
|
244
|
+
/** `GET pull-requests`: the organization's pull requests, latest activity first. */
|
|
245
|
+
export const pullRequests = async (request) => {
|
|
246
|
+
const { params, db } = request;
|
|
247
|
+
const search = (params.string("search", { maxLength: 200 }) ?? "").trim().toLowerCase();
|
|
248
|
+
const limit = params.int("limit", { default: 20, ge: 1, le: 100 });
|
|
249
|
+
const offset = params.int("offset", { default: 0, ge: 0 });
|
|
250
|
+
params.done();
|
|
251
|
+
const organizationId = request.admitted();
|
|
252
|
+
const matching = [...(await loadPullRequests(db, organizationId)).values()]
|
|
253
|
+
.filter((pr) => search === "" || [pr.repository, pr.title ?? "", `#${pr.number}`, pr.branch ?? ""].some((field) => field.toLowerCase().includes(search)))
|
|
254
|
+
.sort((a, b) => b.lastEventAt - a.lastEventAt || a.repository.localeCompare(b.repository) || b.number - a.number);
|
|
255
|
+
return {
|
|
256
|
+
pull_requests: await summaries(db, organizationId, matching.slice(offset, offset + limit)),
|
|
257
|
+
limit,
|
|
258
|
+
offset,
|
|
259
|
+
next_offset: matching.length > offset + limit ? offset + limit : null,
|
|
260
|
+
};
|
|
261
|
+
};
|
|
262
|
+
function pathPullRequest(request) {
|
|
263
|
+
const { owner, repo, number } = request.path;
|
|
264
|
+
if (!/^\d+$/.test(number))
|
|
265
|
+
throw notFound("Unknown pull request.");
|
|
266
|
+
return prKey(`${owner}/${repo}`.toLowerCase(), Number(number));
|
|
267
|
+
}
|
|
268
|
+
/** `GET pull-requests/{owner}/{repo}/{number}`: one pull request and its sessions. */
|
|
269
|
+
export const pullRequest = async (request) => {
|
|
270
|
+
request.params.done();
|
|
271
|
+
const organizationId = request.admitted();
|
|
272
|
+
const { db } = request;
|
|
273
|
+
const pr = (await loadPullRequests(db, organizationId)).get(pathPullRequest(request));
|
|
274
|
+
if (pr === undefined)
|
|
275
|
+
throw notFound("No agent session worked on this pull request.");
|
|
276
|
+
const [summary] = await summaries(db, organizationId, [pr]);
|
|
277
|
+
const ids = [...pr.sessions].map((session) => session.split(" ")[1]);
|
|
278
|
+
const records = await loadRecords(db, sql `r.organization_id = ${organizationId} and r.agent_session_id in (${ids})`);
|
|
279
|
+
const byGroup = new Map();
|
|
280
|
+
for (const record of records) {
|
|
281
|
+
if (!pr.sessions.has(sessionKey(String(record.sourceProtocol), String(record.agentSessionId))))
|
|
282
|
+
continue;
|
|
283
|
+
const text = groupKeyText(recordKey(record));
|
|
284
|
+
byGroup.set(text, [...(byGroup.get(text) ?? []), record]);
|
|
285
|
+
}
|
|
286
|
+
const keys = [...byGroup.values()].map((group) => recordKey(group[0]));
|
|
287
|
+
const titles = keys.length === 0 ? new Map() : await conversationTitles(db, organizationId, keys);
|
|
288
|
+
const entities = await loadEntities(db, records);
|
|
289
|
+
const conversations = [...byGroup.entries()].map(([text, group]) => conversationSummary(group, entities, titles.get(text), null));
|
|
290
|
+
const linked = await withPullRequests(db, organizationId, conversations);
|
|
291
|
+
return {
|
|
292
|
+
pull_request: summary,
|
|
293
|
+
conversations: linked.sort((a, b) => b.last_at.localeCompare(a.last_at)),
|
|
294
|
+
};
|
|
295
|
+
};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import type { ActivityRoute } from "./http.js";
|
|
2
|
-
export declare const ACTIVITY_ROUTES: ReadonlyArray<readonly [string, ActivityRoute]>;
|
|
2
|
+
export declare const ACTIVITY_ROUTES: ReadonlyArray<readonly [string, ActivityRoute, method?: "POST"]>;
|
package/dist/activity/routes.js
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
|
-
/* Every Activity route, by its path under `/routing/activity
|
|
1
|
+
/* Every Activity route, by its path under `/routing/activity/`: a read,
|
|
2
|
+
unless it names another method. */
|
|
2
3
|
import { filterOptions, models, overview, routers, series } from "./core.js";
|
|
3
4
|
import { conversation, conversations, payload, toolExchanges } from "./conversations.js";
|
|
5
|
+
import { importSession } from "./imports.js";
|
|
4
6
|
import { peopleKeys, peopleSeries } from "./people.js";
|
|
7
|
+
import { pullRequest, pullRequests } from "./pull_requests.js";
|
|
5
8
|
import { toolSkillDetail, toolSkillInventory, toolSkills } from "./tools.js";
|
|
6
9
|
export const ACTIVITY_ROUTES = [
|
|
7
10
|
["filter-options", filterOptions],
|
|
@@ -20,4 +23,7 @@ export const ACTIVITY_ROUTES = [
|
|
|
20
23
|
["tools-skills", toolSkills],
|
|
21
24
|
["tools-skills/detail", toolSkillDetail],
|
|
22
25
|
["tools-skills/inventory", toolSkillInventory],
|
|
26
|
+
["imports", importSession, "POST"],
|
|
27
|
+
["pull-requests", pullRequests],
|
|
28
|
+
["pull-requests/:owner/:repo/:number", pullRequest],
|
|
23
29
|
];
|
package/dist/http/handler.d.ts
CHANGED
|
@@ -7,8 +7,9 @@ export type GatewayHandlerOptions = {
|
|
|
7
7
|
/**
|
|
8
8
|
* The gateway's routed HTTP surface: `/v1/{chat/completions,responses,
|
|
9
9
|
* messages,models}` on the default router and `/{router_id}/v1/...` on a
|
|
10
|
-
* named one, the Dari
|
|
11
|
-
*
|
|
10
|
+
* named one, the Dari CLI's commit reports at `/v1/dari/git-events` on
|
|
11
|
+
* either, the Dari Link grant endpoints under `/v1/link/`, and the Activity
|
|
12
|
+
* reads under `/v1/organizations/{organization}/routing/activity/`. Binds
|
|
12
13
|
* `options.platform` for every request it serves.
|
|
13
14
|
*/
|
|
14
15
|
export declare function createRequestHandler(options: GatewayHandlerOptions): (request: Request) => Promise<Response>;
|
package/dist/http/handler.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { handleResponses, handleResponsesWebSocketFallback, } from "../ingress/codex.js";
|
|
2
2
|
import { handleActivityRequest } from "../activity/http.js";
|
|
3
|
+
import { handleGitEvents } from "../ingress/git_events.js";
|
|
3
4
|
import { handleLinkRequest, LINK_METADATA_PATH, LINK_ROUTE_PREFIX } from "../link/endpoints.js";
|
|
4
5
|
import { handleModels } from "../ingress/models.js";
|
|
5
6
|
import { handleMuseCodeModels } from "../ingress/muse_models.js";
|
|
@@ -11,8 +12,9 @@ import { errorResponse, HttpError } from "./errors.js";
|
|
|
11
12
|
/**
|
|
12
13
|
* The gateway's routed HTTP surface: `/v1/{chat/completions,responses,
|
|
13
14
|
* messages,models}` on the default router and `/{router_id}/v1/...` on a
|
|
14
|
-
* named one, the Dari
|
|
15
|
-
*
|
|
15
|
+
* named one, the Dari CLI's commit reports at `/v1/dari/git-events` on
|
|
16
|
+
* either, the Dari Link grant endpoints under `/v1/link/`, and the Activity
|
|
17
|
+
* reads under `/v1/organizations/{organization}/routing/activity/`. Binds
|
|
16
18
|
* `options.platform` for every request it serves.
|
|
17
19
|
*/
|
|
18
20
|
export function createRequestHandler(options) {
|
|
@@ -41,6 +43,10 @@ export function createRequestHandler(options) {
|
|
|
41
43
|
const activity = await handleActivityRequest(request, options.platform.activity);
|
|
42
44
|
if (activity !== null)
|
|
43
45
|
return activity;
|
|
46
|
+
const gitEvents = url.pathname.match(/^(?:\/([^/]+))?\/v1\/dari\/git-events$/);
|
|
47
|
+
if (request.method === "POST" && gitEvents !== null) {
|
|
48
|
+
return await handleGitEvents(request, gitEvents[1] ?? DEFAULT_ROUTER_ALIAS, options.platform.activity);
|
|
49
|
+
}
|
|
44
50
|
const endpoint = routedEndpoint(url.pathname);
|
|
45
51
|
if (endpoint?.protocol === "chat" && request.method === "POST") {
|
|
46
52
|
return await handleChatCompletions(request, endpoint.routerId, selectorBackend);
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
/* `POST /v1/dari/git-events`: the Dari CLI's git hook (`dari git-hook
|
|
2
|
+
post-commit`) reports a commit made in a coding agent's session. It
|
|
3
|
+
authenticates with the key the session's requests used and names the
|
|
4
|
+
agent's own session ID, so the session is found exactly as its requests
|
|
5
|
+
are stamped (`runtime/harness_identity`). Activity links the session to
|
|
6
|
+
the pull request on the commit's branch. */
|
|
7
|
+
import { sql } from "../activity/sql.js";
|
|
8
|
+
import { canonicalInstant, instantFromDate } from "../activity/values.js";
|
|
9
|
+
import { bearerToken } from "../http/auth.js";
|
|
10
|
+
import { errorResponse, HttpError } from "../http/errors.js";
|
|
11
|
+
import { scopedHarnessSessionId } from "../runtime/harness_identity/index.js";
|
|
12
|
+
import { resolveRouter } from "../strategies/routing.js";
|
|
13
|
+
const MAX_COMMITS = 50;
|
|
14
|
+
const UUID = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/;
|
|
15
|
+
const REPOSITORY = /^[\w.-]+\/[\w.-]+$/;
|
|
16
|
+
const SHA = /^[0-9a-f]{40}(?:[0-9a-f]{24})?$/;
|
|
17
|
+
// How far back a Codex subagent's thread is looked for.
|
|
18
|
+
const SUBAGENT_LOOKBACK_MS = 7 * 24 * 60 * 60 * 1000;
|
|
19
|
+
// Each agent's session as its requests carry it, and the protocol it speaks.
|
|
20
|
+
const HARNESSES = {
|
|
21
|
+
claude_code: { kind: "claude_code_session", sourceProtocol: "anthropic_messages" },
|
|
22
|
+
codex: { kind: "codex_thread", sourceProtocol: "openai_responses" },
|
|
23
|
+
};
|
|
24
|
+
export async function handleGitEvents(request, routerId, activity) {
|
|
25
|
+
try {
|
|
26
|
+
if (activity === undefined)
|
|
27
|
+
throw new HttpError(404, "Not found", "not_found");
|
|
28
|
+
const apiKey = bearerToken(request.headers);
|
|
29
|
+
const body = await request.json().catch(() => null);
|
|
30
|
+
const harness = HARNESSES[String(body?.harness)];
|
|
31
|
+
if (harness === undefined)
|
|
32
|
+
throw new HttpError(400, "harness must be claude_code or codex.", "invalid_request_error", "harness");
|
|
33
|
+
const sessionId = typeof body?.session_id === "string" ? body.session_id.trim().toLowerCase() : "";
|
|
34
|
+
if (!UUID.test(sessionId))
|
|
35
|
+
throw new HttpError(400, "session_id must be a UUID.", "invalid_request_error", "session_id");
|
|
36
|
+
const commits = Array.isArray(body?.commits) ? body.commits : null;
|
|
37
|
+
if (commits === null || commits.length === 0 || commits.length > MAX_COMMITS) {
|
|
38
|
+
throw new HttpError(400, `commits must list 1 to ${MAX_COMMITS} commits.`, "invalid_request_error", "commits");
|
|
39
|
+
}
|
|
40
|
+
const events = commits.map(commitEvent);
|
|
41
|
+
const router = await resolveRouter({ routerId, apiKey, provisional: true });
|
|
42
|
+
const agentSessionId = scopedHarnessSessionId({
|
|
43
|
+
identity: { kind: harness.kind, value: sessionId },
|
|
44
|
+
sourceProtocol: harness.sourceProtocol,
|
|
45
|
+
scope: {
|
|
46
|
+
organizationId: router.organization_id,
|
|
47
|
+
routerId: router.router_id,
|
|
48
|
+
apiKeyId: router.api_key_id,
|
|
49
|
+
attributedUserId: router.attributed_user_id,
|
|
50
|
+
},
|
|
51
|
+
});
|
|
52
|
+
let session = agentSessionId;
|
|
53
|
+
if (harness.kind === "codex_thread") {
|
|
54
|
+
const found = await codexSession(activity.db, router.organization_id, agentSessionId, sessionId);
|
|
55
|
+
// A subagent can commit before its first request is recorded; the hook
|
|
56
|
+
// asks again, and on its last try (`final`) files it under the thread.
|
|
57
|
+
if (found === null && body?.final !== true) {
|
|
58
|
+
throw new HttpError(409, "No request names this Codex thread yet; report it again shortly.", "session_pending", "session_id");
|
|
59
|
+
}
|
|
60
|
+
session = found ?? agentSessionId;
|
|
61
|
+
}
|
|
62
|
+
await activity.saveSessionGitEvents({
|
|
63
|
+
organizationId: router.organization_id,
|
|
64
|
+
sourceProtocol: harness.sourceProtocol,
|
|
65
|
+
agentSessionId: session,
|
|
66
|
+
events,
|
|
67
|
+
});
|
|
68
|
+
return new Response(null, { status: 204 });
|
|
69
|
+
}
|
|
70
|
+
catch (error) {
|
|
71
|
+
return errorResponse(error);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
function commitEvent(value, ordinal) {
|
|
75
|
+
const commit = typeof value === "object" && value !== null ? value : {};
|
|
76
|
+
const field = (name, max) => {
|
|
77
|
+
const text = commit[name];
|
|
78
|
+
if (text === undefined || text === null)
|
|
79
|
+
return null;
|
|
80
|
+
if (typeof text !== "string" || text.length > max) {
|
|
81
|
+
throw new HttpError(400, `commits[${ordinal}].${name} must be a string of at most ${max} characters.`, "invalid_request_error", "commits");
|
|
82
|
+
}
|
|
83
|
+
return text;
|
|
84
|
+
};
|
|
85
|
+
const repository = field("repository", 200)?.toLowerCase() ?? "";
|
|
86
|
+
const branch = field("branch", 255) ?? "";
|
|
87
|
+
const sha = field("sha", 64)?.toLowerCase() ?? "";
|
|
88
|
+
if (!REPOSITORY.test(repository) || branch === "" || !SHA.test(sha)) {
|
|
89
|
+
throw new HttpError(400, `commits[${ordinal}] needs a GitHub repository (owner/name), a branch, and a full sha.`, "invalid_request_error", "commits");
|
|
90
|
+
}
|
|
91
|
+
const number = commit.pull_request ?? null;
|
|
92
|
+
if (number !== null && !(Number.isSafeInteger(number) && number >= 1)) {
|
|
93
|
+
throw new HttpError(400, `commits[${ordinal}].pull_request must be a pull request number.`, "invalid_request_error", "commits");
|
|
94
|
+
}
|
|
95
|
+
return {
|
|
96
|
+
kind: "commit",
|
|
97
|
+
repository,
|
|
98
|
+
branch,
|
|
99
|
+
commit_sha: sha,
|
|
100
|
+
number: number,
|
|
101
|
+
title: number === null ? null : field("title", 300),
|
|
102
|
+
ordinal,
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* The session a Codex thread belongs to, or null while no request names it.
|
|
107
|
+
* A subagent's thread is its own `CODEX_THREAD_ID`, but its requests are
|
|
108
|
+
* stamped with its parent's session, so a thread no request was stamped with
|
|
109
|
+
* is looked up among recent subagent requests, which name it as their agent.
|
|
110
|
+
*/
|
|
111
|
+
async function codexSession(db, organizationId, ownSession, threadId) {
|
|
112
|
+
const own = await db.all(sql `
|
|
113
|
+
select 1 as found
|
|
114
|
+
from routing_requests
|
|
115
|
+
where organization_id = ${organizationId}
|
|
116
|
+
and agent_session_id = ${ownSession}
|
|
117
|
+
limit 1`);
|
|
118
|
+
if (own.length > 0)
|
|
119
|
+
return ownSession;
|
|
120
|
+
const since = canonicalInstant(instantFromDate(new Date(Date.now() - SUBAGENT_LOOKBACK_MS)));
|
|
121
|
+
const [parent] = await db.all(db.dialect === "postgres"
|
|
122
|
+
? sql `
|
|
123
|
+
select agent_session_id
|
|
124
|
+
from routing_requests
|
|
125
|
+
where organization_id = ${organizationId}
|
|
126
|
+
and source_protocol = 'openai_responses'
|
|
127
|
+
and received_at >= ${since}::timestamptz
|
|
128
|
+
and agent_session_id is not null
|
|
129
|
+
and request_metadata -> 'agent_context' ->> 'agentId' = ${threadId}
|
|
130
|
+
order by received_at desc
|
|
131
|
+
limit 1`
|
|
132
|
+
: sql `
|
|
133
|
+
select agent_session_id
|
|
134
|
+
from routing_requests
|
|
135
|
+
where organization_id = ${organizationId}
|
|
136
|
+
and source_protocol = 'openai_responses'
|
|
137
|
+
and received_at >= ${since}
|
|
138
|
+
and agent_session_id is not null
|
|
139
|
+
and json_extract(request_metadata, '$.agent_context.agentId') = ${threadId}
|
|
140
|
+
order by received_at desc
|
|
141
|
+
limit 1`);
|
|
142
|
+
return parent === undefined ? null : String(parent.agent_session_id);
|
|
143
|
+
}
|
package/dist/link/budget.d.ts
CHANGED
|
@@ -1,13 +1,18 @@
|
|
|
1
|
-
import type { LinkBudget, LinkUsageTotals } from "../platform/platform.js";
|
|
1
|
+
import type { LinkBudget, LinkLimit, LinkSpend, LinkUsageTotals } from "../platform/platform.js";
|
|
2
2
|
/** The windows a budget can cap: five hours and one week. */
|
|
3
3
|
export declare const LINK_BUDGET_WINDOW_MINUTES: readonly [300, 10080];
|
|
4
4
|
/** The tokens a request used, as each kind is recorded. */
|
|
5
5
|
export type LinkTokenCounts = Pick<LinkUsageTotals, "inputTokens" | "outputTokens" | "cacheReadTokens" | "cacheWriteTokens">;
|
|
6
6
|
/** What a budget counts, and Connected Apps shows: every token, of every kind. */
|
|
7
7
|
export declare function linkTokens(counts: LinkTokenCounts): number;
|
|
8
|
-
/**
|
|
8
|
+
/**
|
|
9
|
+
* What one of a grant's requests used, when it was received, what it cost in
|
|
10
|
+
* US dollars, and the plan or key that served it (null when none did).
|
|
11
|
+
*/
|
|
9
12
|
export type BudgetUse = LinkTokenCounts & {
|
|
10
13
|
at: Date;
|
|
14
|
+
costUsd: number;
|
|
15
|
+
credentialId: string | null;
|
|
11
16
|
};
|
|
12
17
|
/** A budget window as it stands for a grant; `resetsAt` is set only at the cap. */
|
|
13
18
|
export type BudgetStanding = {
|
|
@@ -22,6 +27,26 @@ export declare function budgetStandings(budget: readonly LinkBudget[], uses: rea
|
|
|
22
27
|
export declare function overBudgetUntil(standings: readonly BudgetStanding[]): Date | undefined;
|
|
23
28
|
/** How far back a budget's windows reach, in milliseconds; 0 for none. */
|
|
24
29
|
export declare function budgetLookbackMs(budget: readonly LinkBudget[]): number;
|
|
30
|
+
/** The start of this calendar month, UTC. */
|
|
31
|
+
export declare function monthStart(now: Date): Date;
|
|
32
|
+
/** When this month's spend limits lift: the start of the next calendar month, UTC. */
|
|
33
|
+
export declare function nextMonthStart(now: Date): Date;
|
|
34
|
+
/** The earliest use a grant's budget and spend need: its windows, and this month. */
|
|
35
|
+
export declare function usesSince(budget: readonly LinkBudget[], now: Date): number;
|
|
36
|
+
/** Each granted plan or key's spend this month, with its limit when it has one. */
|
|
37
|
+
export declare function grantSpend(credentialIds: Iterable<string>, limits: readonly LinkLimit[], uses: readonly BudgetUse[], now: Date): LinkSpend[];
|
|
38
|
+
/** Limits from a request: `[{credential_id, monthly_usd}]`, each a distinct plan or key and a dollar amount of 0 or more. */
|
|
39
|
+
export declare function validLimits(value: unknown): LinkLimit[] | null;
|
|
40
|
+
export declare function limitsBody(limits: readonly LinkLimit[]): {
|
|
41
|
+
credential_id: string;
|
|
42
|
+
monthly_usd: number;
|
|
43
|
+
}[];
|
|
44
|
+
export declare function spendBody(spend: readonly LinkSpend[]): {
|
|
45
|
+
credential_id: string;
|
|
46
|
+
spent_usd: number;
|
|
47
|
+
monthly_usd: number | null;
|
|
48
|
+
reached: boolean;
|
|
49
|
+
}[];
|
|
25
50
|
/** A budget from a request: five-hour and weekly windows, each a positive whole token cap. */
|
|
26
51
|
export declare function validBudget(value: unknown): LinkBudget[] | null;
|
|
27
52
|
export declare function budgetBody(budget: readonly LinkBudget[]): {
|
package/dist/link/budget.js
CHANGED
|
@@ -8,7 +8,13 @@
|
|
|
8
8
|
served, so one in flight may take a window past its cap.
|
|
9
9
|
|
|
10
10
|
A window at its cap is back once enough of its oldest requests roll off to
|
|
11
|
-
bring it under the cap again: `resetsAt` is when that happens.
|
|
11
|
+
bring it under the cap again: `resetsAt` is when that happens.
|
|
12
|
+
|
|
13
|
+
A grant may also limit what it spends on each of its plans and API keys in
|
|
14
|
+
a calendar month (UTC): an API key's spend is what its provider charged,
|
|
15
|
+
and a plan's is what its requests would have cost at API prices. A plan or
|
|
16
|
+
key at its limit leaves the grant until the month ends; the grant serves on
|
|
17
|
+
the rest. */
|
|
12
18
|
/** The windows a budget can cap: five hours and one week. */
|
|
13
19
|
export const LINK_BUDGET_WINDOW_MINUTES = [300, 10080];
|
|
14
20
|
/** What a budget counts, and Connected Apps shows: every token, of every kind. */
|
|
@@ -43,6 +49,62 @@ export function overBudgetUntil(standings) {
|
|
|
43
49
|
export function budgetLookbackMs(budget) {
|
|
44
50
|
return Math.max(0, ...budget.map((entry) => entry.windowMinutes)) * 60_000;
|
|
45
51
|
}
|
|
52
|
+
/** The start of this calendar month, UTC. */
|
|
53
|
+
export function monthStart(now) {
|
|
54
|
+
return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1));
|
|
55
|
+
}
|
|
56
|
+
/** When this month's spend limits lift: the start of the next calendar month, UTC. */
|
|
57
|
+
export function nextMonthStart(now) {
|
|
58
|
+
return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1));
|
|
59
|
+
}
|
|
60
|
+
/** The earliest use a grant's budget and spend need: its windows, and this month. */
|
|
61
|
+
export function usesSince(budget, now) {
|
|
62
|
+
return Math.min(now.getTime() - budgetLookbackMs(budget), monthStart(now).getTime());
|
|
63
|
+
}
|
|
64
|
+
/** Each granted plan or key's spend this month, with its limit when it has one. */
|
|
65
|
+
export function grantSpend(credentialIds, limits, uses, now) {
|
|
66
|
+
const since = monthStart(now).getTime();
|
|
67
|
+
const spent = new Map();
|
|
68
|
+
for (const use of uses) {
|
|
69
|
+
if (use.credentialId === null || use.at.getTime() < since)
|
|
70
|
+
continue;
|
|
71
|
+
spent.set(use.credentialId, (spent.get(use.credentialId) ?? 0) + use.costUsd);
|
|
72
|
+
}
|
|
73
|
+
return [...credentialIds].map((credentialId) => {
|
|
74
|
+
const spentUsd = spent.get(credentialId) ?? 0;
|
|
75
|
+
const monthlyUsd = limits.find((limit) => limit.credentialId === credentialId)?.monthlyUsd ?? null;
|
|
76
|
+
return { credentialId, spentUsd, monthlyUsd, reached: monthlyUsd !== null && spentUsd >= monthlyUsd };
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
/** Limits from a request: `[{credential_id, monthly_usd}]`, each a distinct plan or key and a dollar amount of 0 or more. */
|
|
80
|
+
export function validLimits(value) {
|
|
81
|
+
if (!Array.isArray(value))
|
|
82
|
+
return null;
|
|
83
|
+
const limits = [];
|
|
84
|
+
for (const entry of value) {
|
|
85
|
+
if (typeof entry !== "object" || entry === null)
|
|
86
|
+
return null;
|
|
87
|
+
const { credential_id: credentialId, monthly_usd: monthlyUsd } = entry;
|
|
88
|
+
if (typeof credentialId !== "string" || credentialId.length === 0
|
|
89
|
+
|| typeof monthlyUsd !== "number" || !Number.isFinite(monthlyUsd) || monthlyUsd < 0
|
|
90
|
+
|| limits.some((other) => other.credentialId === credentialId)) {
|
|
91
|
+
return null;
|
|
92
|
+
}
|
|
93
|
+
limits.push({ credentialId, monthlyUsd });
|
|
94
|
+
}
|
|
95
|
+
return limits;
|
|
96
|
+
}
|
|
97
|
+
export function limitsBody(limits) {
|
|
98
|
+
return limits.map((limit) => ({ credential_id: limit.credentialId, monthly_usd: limit.monthlyUsd }));
|
|
99
|
+
}
|
|
100
|
+
export function spendBody(spend) {
|
|
101
|
+
return spend.map((entry) => ({
|
|
102
|
+
credential_id: entry.credentialId,
|
|
103
|
+
spent_usd: entry.spentUsd,
|
|
104
|
+
monthly_usd: entry.monthlyUsd,
|
|
105
|
+
reached: entry.reached,
|
|
106
|
+
}));
|
|
107
|
+
}
|
|
46
108
|
/** A budget from a request: five-hour and weekly windows, each a positive whole token cap. */
|
|
47
109
|
export function validBudget(value) {
|
|
48
110
|
if (!Array.isArray(value))
|