@mupt-ai/dari-gateway 1.0.333 → 1.0.335
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
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
skill events of that page. */
|
|
4
4
|
import { consecutivePath, contextRun, conversationSummary, decisionDetails, findRecord, groupsCondition, loadEntities, loadRecords, optionalFixed, pyRepr, recordKey, requestBlobFormat, selectedEffort, supported, } from "./conversation_records.js";
|
|
5
5
|
import { notFound } from "./params.js";
|
|
6
|
+
import { sessionCommits, withPullRequests } from "./pull_requests.js";
|
|
6
7
|
import { thinkingLevelValue } from "./shared.js";
|
|
7
8
|
import { sql } from "./sql.js";
|
|
8
9
|
import { formatInstant, readOptionalString } from "./values.js";
|
|
@@ -128,8 +129,10 @@ export const conversation = async (request) => {
|
|
|
128
129
|
route_path: routePath(records),
|
|
129
130
|
}));
|
|
130
131
|
const hasMore = start > 0;
|
|
132
|
+
const [summary] = await withPullRequests(db, organizationId, [conversationSummary(all, entities, undefined, null)]);
|
|
131
133
|
return {
|
|
132
|
-
conversation:
|
|
134
|
+
conversation: summary,
|
|
135
|
+
commits: await sessionCommits(db, organizationId, summary.source_protocol, summary.agent_session_id),
|
|
133
136
|
streams,
|
|
134
137
|
filtered_model_steps: filtered.length,
|
|
135
138
|
focused_request_class: focusedRequestClass,
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
import { conversationSummary, conversationTitles, findRecord, groupKeyText, groupsCondition, loadEntities, loadRecords, pyRepr, recordKey, requestBlobFormat, supported, } from "./conversation_records.js";
|
|
4
4
|
import { criteria, readActivityQuery, readSourceScope, sourceProtocols, validatedFilters } from "./filters.js";
|
|
5
5
|
import { notFound } from "./params.js";
|
|
6
|
+
import { withPullRequests } from "./pull_requests.js";
|
|
6
7
|
import { AGENT_SESSION_KEY } from "./shared.js";
|
|
7
8
|
import { likePattern, raw, sql } from "./sql.js";
|
|
8
9
|
import { readInt, readOptionalString } from "./values.js";
|
|
@@ -160,7 +161,7 @@ export const conversations = async (request) => {
|
|
|
160
161
|
}
|
|
161
162
|
}
|
|
162
163
|
return {
|
|
163
|
-
conversations: items,
|
|
164
|
+
conversations: await withPullRequests(db, organizationId, items),
|
|
164
165
|
conversation_count: readInt(totals.conversation_count),
|
|
165
166
|
model_switches: readInt(totals.total_model_switches),
|
|
166
167
|
conversations_with_model_switches: readInt(totals.conversations_with_model_switches),
|
package/dist/activity/http.d.ts
CHANGED
|
@@ -1,10 +1,20 @@
|
|
|
1
1
|
import { Params } from "./params.js";
|
|
2
|
+
import type { CommitEvent } from "../telemetry/tools/git_events.js";
|
|
2
3
|
import type { ActivityDb } from "./sql.js";
|
|
3
4
|
export declare const ACTIVITY_ROUTE: RegExp;
|
|
5
|
+
/** Commits an agent session made, as the Dari CLI's git hook reports them. */
|
|
6
|
+
export type SessionGitEvents = {
|
|
7
|
+
organizationId: string;
|
|
8
|
+
sourceProtocol: string;
|
|
9
|
+
agentSessionId: string;
|
|
10
|
+
events: CommitEvent[];
|
|
11
|
+
};
|
|
4
12
|
/** Activity as a platform provides it. */
|
|
5
13
|
export type ActivityPlatform = {
|
|
6
14
|
/** The database holding `routing_requests` and the tables Activity joins. */
|
|
7
15
|
db: ActivityDb;
|
|
16
|
+
/** Store a session's commits, now; a commit it already has is kept once. */
|
|
17
|
+
saveSessionGitEvents(write: SessionGitEvents): Promise<void>;
|
|
8
18
|
/**
|
|
9
19
|
* The organization a request may read. `organizationRef` is the path's
|
|
10
20
|
* organization: an ID, or `current` for the one the bearer key belongs to.
|
|
@@ -12,11 +22,22 @@ export type ActivityPlatform = {
|
|
|
12
22
|
* for one that is not an admin of the organization. Its message is the
|
|
13
23
|
* response's `detail`.
|
|
14
24
|
*/
|
|
15
|
-
authorize(request: Request, organizationRef: string): Promise<
|
|
16
|
-
organizationId: string;
|
|
17
|
-
}>;
|
|
25
|
+
authorize(request: Request, organizationRef: string): Promise<ActivityCaller>;
|
|
18
26
|
/** A retained payload's bytes, or null when nothing is stored there. */
|
|
19
27
|
readBlob(bucket: string, key: string): Promise<BodyInit | null>;
|
|
28
|
+
/**
|
|
29
|
+
* Optional. Store one imported request's report (imports.ts) under the
|
|
30
|
+
* organization's "Imported" router, creating the router when it has none.
|
|
31
|
+
* Resolves false when a request with the report's ID is already stored.
|
|
32
|
+
* Never bills, prices, or titles the request. Without it the import
|
|
33
|
+
* endpoint answers 404.
|
|
34
|
+
*/
|
|
35
|
+
importRequest?(caller: ActivityCaller, report: Record<string, unknown>): Promise<boolean>;
|
|
36
|
+
};
|
|
37
|
+
/** An admitted caller: its organization and, where the platform has users, who it is. */
|
|
38
|
+
export type ActivityCaller = {
|
|
39
|
+
organizationId: string;
|
|
40
|
+
userId?: string;
|
|
20
41
|
};
|
|
21
42
|
/** One Activity request, as a route reads it. */
|
|
22
43
|
export type ActivityRequest = {
|
|
@@ -25,6 +46,10 @@ export type ActivityRequest = {
|
|
|
25
46
|
params: Params;
|
|
26
47
|
/** The route's own path segments, such as `conversation_ref`. */
|
|
27
48
|
path: Record<string, string>;
|
|
49
|
+
/** The request's JSON body; fails with 422 when it is not JSON. */
|
|
50
|
+
body(): Promise<unknown>;
|
|
51
|
+
/** The caller's user, once `admitted`, where the platform has users. */
|
|
52
|
+
userId?: string;
|
|
28
53
|
/**
|
|
29
54
|
* The organization the caller may read. Routes call it after reading their
|
|
30
55
|
* parameters, so a malformed request fails with 422 or 400 before an
|
package/dist/activity/http.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
/* Activity's HTTP surface: `GET /v1/organizations/{organization}/routing/
|
|
2
|
-
activity/...`, the reads behind the Activity dashboard and `dari activity
|
|
3
|
-
|
|
4
|
-
|
|
2
|
+
activity/...`, the reads behind the Activity dashboard and `dari activity`,
|
|
3
|
+
and the import `dari traces import` posts to. Every platform serves the
|
|
4
|
+
same routes over its own database; the platform only says who is asking,
|
|
5
|
+
where retained payloads live, and how an imported request is stored. */
|
|
5
6
|
import { randomUUID } from "node:crypto";
|
|
6
7
|
import { HttpError } from "../http/errors.js";
|
|
7
8
|
import { activityError, Params } from "./params.js";
|
|
@@ -24,12 +25,12 @@ export async function handleActivityRequest(request, platform) {
|
|
|
24
25
|
const found = findRoute(match[2]);
|
|
25
26
|
if (found === null)
|
|
26
27
|
throw activityError(404, "Not Found");
|
|
27
|
-
if (request.method !==
|
|
28
|
+
if (request.method !== found.method)
|
|
28
29
|
throw activityError(405, "Method Not Allowed");
|
|
29
|
-
let
|
|
30
|
+
let caller = null;
|
|
30
31
|
let refused = null;
|
|
31
32
|
try {
|
|
32
|
-
|
|
33
|
+
caller = await platform.authorize(request, decodePathSegment(match[1]));
|
|
33
34
|
}
|
|
34
35
|
catch (error) {
|
|
35
36
|
if (!(error instanceof HttpError) || error.status === 401)
|
|
@@ -41,10 +42,14 @@ export async function handleActivityRequest(request, platform) {
|
|
|
41
42
|
platform,
|
|
42
43
|
params: new Params(url.searchParams),
|
|
43
44
|
path: found.path,
|
|
45
|
+
body: () => request.json().catch(() => {
|
|
46
|
+
throw activityError(422, "The body must be JSON.");
|
|
47
|
+
}),
|
|
48
|
+
userId: caller?.userId,
|
|
44
49
|
admitted() {
|
|
45
50
|
if (refused !== null)
|
|
46
51
|
throw refused;
|
|
47
|
-
return organizationId;
|
|
52
|
+
return caller.organizationId;
|
|
48
53
|
},
|
|
49
54
|
});
|
|
50
55
|
return withCors(result instanceof Response ? result : jsonResponse(result), requestId);
|
|
@@ -59,7 +64,7 @@ export async function handleActivityRequest(request, platform) {
|
|
|
59
64
|
}
|
|
60
65
|
function findRoute(rest) {
|
|
61
66
|
const segments = rest.split("/");
|
|
62
|
-
for (const [pattern, route] of ACTIVITY_ROUTES) {
|
|
67
|
+
for (const [pattern, route, method = "GET"] of ACTIVITY_ROUTES) {
|
|
63
68
|
const parts = pattern.split("/");
|
|
64
69
|
if (parts.length !== segments.length)
|
|
65
70
|
continue;
|
|
@@ -75,7 +80,7 @@ function findRoute(rest) {
|
|
|
75
80
|
return part === segment;
|
|
76
81
|
});
|
|
77
82
|
if (matches)
|
|
78
|
-
return { route, path };
|
|
83
|
+
return { route, method, path };
|
|
79
84
|
}
|
|
80
85
|
return null;
|
|
81
86
|
}
|
|
@@ -101,7 +106,7 @@ function withCors(response, requestId) {
|
|
|
101
106
|
if (requestId !== undefined)
|
|
102
107
|
response.headers.set("X-Request-Id", requestId);
|
|
103
108
|
response.headers.set("Access-Control-Allow-Origin", "*");
|
|
104
|
-
response.headers.set("Access-Control-Allow-Methods", "GET, OPTIONS");
|
|
109
|
+
response.headers.set("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
|
|
105
110
|
response.headers.set("Access-Control-Allow-Headers", "Authorization, Content-Type");
|
|
106
111
|
response.headers.set("Access-Control-Expose-Headers", "X-Dari-Request-Format, X-Request-Id");
|
|
107
112
|
response.headers.set("Access-Control-Max-Age", "600");
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { InteractionItem } from "../interaction/types.js";
|
|
2
|
+
import type { ActivityRequest } from "./http.js";
|
|
3
|
+
/** The router imported requests are filed under. */
|
|
4
|
+
export declare const IMPORTED_ROUTER_NAME = "Imported";
|
|
5
|
+
declare const STOP_REASONS: readonly ["stop", "length", "tool_use"];
|
|
6
|
+
declare const TOKEN_FIELDS: readonly ["input_tokens", "output_tokens", "cache_read_tokens", "cache_write_tokens"];
|
|
7
|
+
type ImportedTurn = {
|
|
8
|
+
request_id: string;
|
|
9
|
+
input_items: number;
|
|
10
|
+
output_items: number;
|
|
11
|
+
model: string;
|
|
12
|
+
provider: string;
|
|
13
|
+
received_at: string;
|
|
14
|
+
completed_at: string;
|
|
15
|
+
stop_reason: (typeof STOP_REASONS)[number];
|
|
16
|
+
usage: Record<(typeof TOKEN_FIELDS)[number], number>;
|
|
17
|
+
};
|
|
18
|
+
type ImportedSession = {
|
|
19
|
+
agent: string;
|
|
20
|
+
session_id: string;
|
|
21
|
+
agent_id?: string;
|
|
22
|
+
items: InteractionItem[];
|
|
23
|
+
turns: ImportedTurn[];
|
|
24
|
+
};
|
|
25
|
+
/** Store one session's model calls; answers how many were new. */
|
|
26
|
+
export declare function importSession(request: ActivityRequest): Promise<object>;
|
|
27
|
+
/** One imported model call as a request report, without a router. */
|
|
28
|
+
export declare function importedRequestReport(organizationId: string, session: ImportedSession, turn: ImportedTurn): Record<string, unknown>;
|
|
29
|
+
export {};
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
/* `POST .../routing/activity/imports`: sessions a coding agent kept on a
|
|
2
|
+
user's machine (`dari traces import`), stored as the requests Activity
|
|
3
|
+
shows. Each model call becomes a request under the organization's
|
|
4
|
+
"Imported" router with its token counts; none has a cost, a selector, or
|
|
5
|
+
billing facts, so nothing is billed for it. */
|
|
6
|
+
import { isRecord } from "@mupt-ai/dari-router/policy-engine";
|
|
7
|
+
import { anthropicContent, anthropicStopReason, anthropicUsage, } from "../protocol/output/anthropic_messages_output.js";
|
|
8
|
+
import { assistantMessagePayload } from "../protocol/output/chat_completions.js";
|
|
9
|
+
import { openAIResponsesOutputItems, openAIResponsesTerminal, openAIResponsesUsage, } from "../protocol/output/openai_responses_output.js";
|
|
10
|
+
import { extractInteractionObservability } from "../telemetry/requests/interaction_observability.js";
|
|
11
|
+
import { encodeRetainedInteractionRequest } from "../telemetry/requests/retained_interaction_request.js";
|
|
12
|
+
import { toolResultObservations, toolSkillEvents } from "../telemetry/tools/observations.js";
|
|
13
|
+
import { activityError, notFound } from "./params.js";
|
|
14
|
+
/** The router imported requests are filed under. */
|
|
15
|
+
export const IMPORTED_ROUTER_NAME = "Imported";
|
|
16
|
+
// The protocol each agent speaks, which Activity reads its responses in.
|
|
17
|
+
const AGENT_PROTOCOLS = {
|
|
18
|
+
claude: "anthropic_messages",
|
|
19
|
+
codex: "openai_responses",
|
|
20
|
+
opencode: "openai_chat",
|
|
21
|
+
pi: "openai_chat",
|
|
22
|
+
};
|
|
23
|
+
const MAX_TURNS = 100;
|
|
24
|
+
const SESSION_ID_MAX_CHARS = 64;
|
|
25
|
+
// An imported request's ID is the CLI's hash of its agent, session, and
|
|
26
|
+
// transcript entry; the prefix keeps it apart from a served request's.
|
|
27
|
+
const REQUEST_ID = /^imp_[0-9a-f]{32}$/;
|
|
28
|
+
const STOP_REASONS = ["stop", "length", "tool_use"];
|
|
29
|
+
const TOKEN_FIELDS = ["input_tokens", "output_tokens", "cache_read_tokens", "cache_write_tokens"];
|
|
30
|
+
/** Store one session's model calls; answers how many were new. */
|
|
31
|
+
export async function importSession(request) {
|
|
32
|
+
const store = request.platform.importRequest;
|
|
33
|
+
if (store === undefined)
|
|
34
|
+
throw notFound("Not Found");
|
|
35
|
+
const session = importedSession(await request.body());
|
|
36
|
+
const organizationId = request.admitted();
|
|
37
|
+
let imported = 0;
|
|
38
|
+
for (const turn of session.turns) {
|
|
39
|
+
const report = importedRequestReport(organizationId, session, turn);
|
|
40
|
+
if (await store({ organizationId, userId: request.userId }, report))
|
|
41
|
+
imported += 1;
|
|
42
|
+
}
|
|
43
|
+
return { imported, existing: session.turns.length - imported };
|
|
44
|
+
}
|
|
45
|
+
/** One imported model call as a request report, without a router. */
|
|
46
|
+
export function importedRequestReport(organizationId, session, turn) {
|
|
47
|
+
const sourceProtocol = AGENT_PROTOCOLS[session.agent];
|
|
48
|
+
const interaction = {
|
|
49
|
+
sourceProtocol,
|
|
50
|
+
...(session.agent_id === undefined
|
|
51
|
+
? {}
|
|
52
|
+
: { agentContext: { requestClass: "subagent", agentId: session.agent_id } }),
|
|
53
|
+
model: turn.model,
|
|
54
|
+
items: session.items.slice(0, turn.input_items),
|
|
55
|
+
tools: [],
|
|
56
|
+
generation: {},
|
|
57
|
+
stream: false,
|
|
58
|
+
};
|
|
59
|
+
const { usage } = turn;
|
|
60
|
+
const totalTokens = TOKEN_FIELDS.reduce((sum, field) => sum + usage[field], 0);
|
|
61
|
+
const output = {
|
|
62
|
+
createdAtMs: Date.parse(turn.completed_at),
|
|
63
|
+
source: { provider: turn.provider, api: sourceProtocol, model: turn.model },
|
|
64
|
+
items: session.items.slice(turn.input_items, turn.input_items + turn.output_items),
|
|
65
|
+
usage: {
|
|
66
|
+
input: usage.input_tokens,
|
|
67
|
+
output: usage.output_tokens,
|
|
68
|
+
cacheRead: usage.cache_read_tokens,
|
|
69
|
+
cacheWrite: usage.cache_write_tokens,
|
|
70
|
+
totalTokens,
|
|
71
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
|
72
|
+
},
|
|
73
|
+
stopReason: turn.stop_reason,
|
|
74
|
+
};
|
|
75
|
+
const observability = extractInteractionObservability(interaction);
|
|
76
|
+
const retained = encodeRetainedInteractionRequest(interaction);
|
|
77
|
+
// The tool events' context hash only pairs a call with its result, so any
|
|
78
|
+
// one name for the router serves.
|
|
79
|
+
const tools = { routerId: IMPORTED_ROUTER_NAME, request: interaction, zdr: false };
|
|
80
|
+
return {
|
|
81
|
+
request_id: turn.request_id,
|
|
82
|
+
client_request_id: null,
|
|
83
|
+
organization_id: organizationId,
|
|
84
|
+
api_key_id: null,
|
|
85
|
+
attributed_user_id: null,
|
|
86
|
+
source_protocol: sourceProtocol,
|
|
87
|
+
request_kind: observability.requestKind,
|
|
88
|
+
received_at: turn.received_at,
|
|
89
|
+
completed_at: turn.completed_at,
|
|
90
|
+
stream: false,
|
|
91
|
+
zdr: false,
|
|
92
|
+
status: "completed",
|
|
93
|
+
error_code: null,
|
|
94
|
+
error_message: null,
|
|
95
|
+
conversation_id: session.session_id,
|
|
96
|
+
agent_session_id: session.session_id,
|
|
97
|
+
message_count: observability.messageCount,
|
|
98
|
+
has_tools: observability.hasTools,
|
|
99
|
+
request_metadata: observability.metadata,
|
|
100
|
+
selected_model: turn.model,
|
|
101
|
+
selected_provider: turn.provider,
|
|
102
|
+
provider_key_source: null,
|
|
103
|
+
total_latency_ms: Date.parse(turn.completed_at) - Date.parse(turn.received_at),
|
|
104
|
+
client_request_json: retained.json,
|
|
105
|
+
client_request_format: retained.format,
|
|
106
|
+
client_response_json: JSON.stringify(responseBody(sourceProtocol, turn, output)),
|
|
107
|
+
// Token counts only: an imported request has no cost.
|
|
108
|
+
provider_call: {
|
|
109
|
+
stop_reason: turn.stop_reason,
|
|
110
|
+
usage: { ...usage, total_tokens: totalTokens, pricing_known: false },
|
|
111
|
+
},
|
|
112
|
+
tool_skill_events: toolSkillEvents({ ...tools, output }),
|
|
113
|
+
tool_result_observations: toolResultObservations(tools),
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
// The response as the agent's protocol would have carried it.
|
|
117
|
+
function responseBody(protocol, turn, output) {
|
|
118
|
+
if (protocol === "anthropic_messages") {
|
|
119
|
+
return {
|
|
120
|
+
id: turn.request_id,
|
|
121
|
+
type: "message",
|
|
122
|
+
role: "assistant",
|
|
123
|
+
model: turn.model,
|
|
124
|
+
content: anthropicContent(output),
|
|
125
|
+
stop_reason: anthropicStopReason(output),
|
|
126
|
+
stop_sequence: null,
|
|
127
|
+
usage: anthropicUsage(output),
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
if (protocol === "openai_responses") {
|
|
131
|
+
return {
|
|
132
|
+
id: turn.request_id,
|
|
133
|
+
object: "response",
|
|
134
|
+
created_at: Math.floor(output.createdAtMs / 1000),
|
|
135
|
+
...openAIResponsesTerminal(output),
|
|
136
|
+
model: turn.model,
|
|
137
|
+
output: openAIResponsesOutputItems(output),
|
|
138
|
+
usage: openAIResponsesUsage(output),
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
return {
|
|
142
|
+
id: turn.request_id,
|
|
143
|
+
object: "chat.completion",
|
|
144
|
+
created: Math.floor(output.createdAtMs / 1000),
|
|
145
|
+
model: turn.model,
|
|
146
|
+
choices: [{
|
|
147
|
+
index: 0,
|
|
148
|
+
message: assistantMessagePayload(output),
|
|
149
|
+
finish_reason: turn.stop_reason === "tool_use" ? "tool_calls" : turn.stop_reason,
|
|
150
|
+
}],
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
function importedSession(body) {
|
|
154
|
+
const invalid = (message) => activityError(422, message);
|
|
155
|
+
if (!isRecord(body))
|
|
156
|
+
throw invalid("The body must be a JSON object.");
|
|
157
|
+
const { agent, session_id: sessionId, agent_id: agentId, items, turns } = body;
|
|
158
|
+
if (typeof agent !== "string" || !Object.hasOwn(AGENT_PROTOCOLS, agent)) {
|
|
159
|
+
throw invalid(`agent must be one of ${Object.keys(AGENT_PROTOCOLS).join(", ")}.`);
|
|
160
|
+
}
|
|
161
|
+
if (typeof sessionId !== "string" || sessionId === "" || sessionId.length > SESSION_ID_MAX_CHARS) {
|
|
162
|
+
throw invalid(`session_id must be 1 to ${SESSION_ID_MAX_CHARS} characters.`);
|
|
163
|
+
}
|
|
164
|
+
if (agentId !== undefined && (typeof agentId !== "string" || agentId === "")) {
|
|
165
|
+
throw invalid("agent_id must be a non-empty string.");
|
|
166
|
+
}
|
|
167
|
+
if (!Array.isArray(items) || !items.every(isInteractionItem)) {
|
|
168
|
+
throw invalid("items must be messages, reasoning, tool calls, and tool results.");
|
|
169
|
+
}
|
|
170
|
+
if (!Array.isArray(turns) || turns.length === 0 || turns.length > MAX_TURNS) {
|
|
171
|
+
throw invalid(`turns must hold 1 to ${MAX_TURNS} model calls.`);
|
|
172
|
+
}
|
|
173
|
+
for (const turn of turns) {
|
|
174
|
+
if (!isRecord(turn) || typeof turn.request_id !== "string" || !REQUEST_ID.test(turn.request_id)) {
|
|
175
|
+
throw invalid("Each turn needs a request_id of imp_ and 32 hex digits.");
|
|
176
|
+
}
|
|
177
|
+
const invalidTurn = (message) => invalid(`Turn ${turn.request_id}: ${message}`);
|
|
178
|
+
const { input_items: input, output_items: count } = turn;
|
|
179
|
+
if (!isCount(input) || !isCount(count) || input + count > items.length) {
|
|
180
|
+
throw invalidTurn("input_items and output_items must lie within items.");
|
|
181
|
+
}
|
|
182
|
+
if (items.slice(input, input + count).some((item) => item.type === "tool_result")) {
|
|
183
|
+
throw invalidTurn("a response holds no tool results.");
|
|
184
|
+
}
|
|
185
|
+
if (typeof turn.model !== "string" || turn.model === "" || typeof turn.provider !== "string" || turn.provider === "") {
|
|
186
|
+
throw invalidTurn("model and provider are required.");
|
|
187
|
+
}
|
|
188
|
+
if (!isInstant(turn.received_at) || !isInstant(turn.completed_at) || Date.parse(turn.completed_at) < Date.parse(turn.received_at)) {
|
|
189
|
+
throw invalidTurn("received_at and completed_at must be timestamps with an offset, in order.");
|
|
190
|
+
}
|
|
191
|
+
if (!STOP_REASONS.includes(turn.stop_reason)) {
|
|
192
|
+
throw invalidTurn(`stop_reason must be one of ${STOP_REASONS.join(", ")}.`);
|
|
193
|
+
}
|
|
194
|
+
const { usage } = turn;
|
|
195
|
+
if (!isRecord(usage) || !TOKEN_FIELDS.every((field) => isCount(usage[field]))) {
|
|
196
|
+
throw invalidTurn(`usage needs ${TOKEN_FIELDS.join(", ")}.`);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
return body;
|
|
200
|
+
}
|
|
201
|
+
function isCount(value) {
|
|
202
|
+
return Number.isSafeInteger(value) && value >= 0;
|
|
203
|
+
}
|
|
204
|
+
// An RFC 3339 timestamp, whose offset the stored request needs.
|
|
205
|
+
function isInstant(value) {
|
|
206
|
+
return typeof value === "string" && /(Z|[+-]\d\d:\d\d)$/.test(value) && !Number.isNaN(Date.parse(value));
|
|
207
|
+
}
|
|
208
|
+
const isText = (value) => typeof value === "string";
|
|
209
|
+
// The items the CLI's transcript parsers write.
|
|
210
|
+
function isInteractionItem(item) {
|
|
211
|
+
if (!isRecord(item))
|
|
212
|
+
return false;
|
|
213
|
+
const toolKind = item.kind === "function" || item.kind === "custom";
|
|
214
|
+
switch (item.type) {
|
|
215
|
+
case "message":
|
|
216
|
+
return ["system", "developer", "user", "assistant"].includes(item.role)
|
|
217
|
+
&& Array.isArray(item.content)
|
|
218
|
+
&& item.content.every((part) => isRecord(part) && part.type === "text" && isText(part.text));
|
|
219
|
+
case "reasoning":
|
|
220
|
+
return Array.isArray(item.summary) && item.summary.every(isText)
|
|
221
|
+
&& Array.isArray(item.content) && item.content.every(isText);
|
|
222
|
+
case "tool_call":
|
|
223
|
+
return toolKind && isText(item.callId) && isText(item.name)
|
|
224
|
+
&& (item.namespace === undefined || isText(item.namespace));
|
|
225
|
+
case "tool_result":
|
|
226
|
+
return toolKind && isText(item.callId) && isText(item.output);
|
|
227
|
+
default:
|
|
228
|
+
return false;
|
|
229
|
+
}
|
|
230
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { ActivityRoute } from "./http.js";
|
|
2
|
+
import { type ActivityDb } from "./sql.js";
|
|
3
|
+
export type PullRequestRef = {
|
|
4
|
+
repository: string;
|
|
5
|
+
number: number;
|
|
6
|
+
url: string;
|
|
7
|
+
title: string | null;
|
|
8
|
+
};
|
|
9
|
+
/** The commits a session made that its git hook reported, oldest first. */
|
|
10
|
+
export declare function sessionCommits(db: ActivityDb, organizationId: string, sourceProtocol: string | null, agentSessionId: string | null): Promise<{
|
|
11
|
+
repository: string;
|
|
12
|
+
sha: string;
|
|
13
|
+
branch: string | null;
|
|
14
|
+
url: string;
|
|
15
|
+
reported_at: string;
|
|
16
|
+
}[]>;
|
|
17
|
+
type Summary = {
|
|
18
|
+
source_protocol: string | null;
|
|
19
|
+
agent_session_id: string | null;
|
|
20
|
+
};
|
|
21
|
+
/** The summaries, each with the pull requests its session worked on. */
|
|
22
|
+
export declare function withPullRequests<T extends Summary>(db: ActivityDb, organizationId: string, summaries: readonly T[]): Promise<(T & {
|
|
23
|
+
pull_requests: PullRequestRef[];
|
|
24
|
+
})[]>;
|
|
25
|
+
/** `GET pull-requests`: the organization's pull requests, latest activity first. */
|
|
26
|
+
export declare const pullRequests: ActivityRoute;
|
|
27
|
+
/** `GET pull-requests/{owner}/{repo}/{number}`: one pull request and its sessions. */
|
|
28
|
+
export declare const pullRequest: ActivityRoute;
|
|
29
|
+
export {};
|