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