@mupt-ai/dari-gateway 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +135 -2
- package/dari-gateway.example.yaml +28 -0
- package/package.json +42 -4
- package/src/bun.ts +4 -0
- package/src/context/eval_catalog.ts +11 -0
- package/src/context/interaction_fingerprint.ts +691 -0
- package/src/context/interaction_fingerprint_format.ts +189 -0
- package/src/context/interaction_lease_depth.ts +150 -0
- package/src/context/lease_history.ts +200 -0
- package/src/context/pricing.ts +30 -0
- package/src/context/provider_prompt_accounting.ts +241 -0
- package/src/context/routing_context.ts +337 -0
- package/src/http/auth.ts +43 -0
- package/src/http/errors.ts +114 -0
- package/src/http/handler.ts +110 -0
- package/src/http/http2_server.ts +122 -0
- package/src/http/serve.ts +119 -0
- package/src/index.ts +22 -0
- package/src/ingress/anthropic_messages.ts +162 -0
- package/src/ingress/anthropic_models.ts +28 -0
- package/src/ingress/chat_completions.ts +49 -0
- package/src/ingress/claude_code/request_context.ts +36 -0
- package/src/ingress/codex.ts +81 -0
- package/src/ingress/codex_models.ts +113 -0
- package/src/ingress/json.ts +113 -0
- package/src/ingress/models.ts +55 -0
- package/src/interaction/capabilities.ts +30 -0
- package/src/interaction/image.ts +12 -0
- package/src/interaction/portable_reasoning_state.ts +25 -0
- package/src/interaction/provider_continuation_state.ts +36 -0
- package/src/interaction/tool_identity.ts +65 -0
- package/src/interaction/types.ts +282 -0
- package/src/models/context_limits.ts +8 -0
- package/src/models/execution_provider.ts +22 -0
- package/src/models/gateways.ts +73 -0
- package/src/models/ids.ts +26 -0
- package/src/models/provider_defaults.ts +47 -0
- package/src/models/runtime_overrides.ts +221 -0
- package/src/observability/errors.ts +25 -0
- package/src/platform/platform.ts +204 -0
- package/src/platform/routing_contract.ts +6 -0
- package/src/protocol/input/anthropic_messages.ts +531 -0
- package/src/protocol/input/chat_completions.ts +255 -0
- package/src/protocol/input/chat_completions_validation.ts +293 -0
- package/src/protocol/input/openai_responses.ts +749 -0
- package/src/protocol/input/router_model.ts +53 -0
- package/src/protocol/output/anthropic_messages.ts +32 -0
- package/src/protocol/output/anthropic_messages_output.ts +129 -0
- package/src/protocol/output/anthropic_messages_stream.ts +281 -0
- package/src/protocol/output/chat_completions.ts +451 -0
- package/src/protocol/output/chat_reasoning_detail.ts +19 -0
- package/src/protocol/output/delivered_stream_snapshot.ts +31 -0
- package/src/protocol/output/openai_responses.ts +30 -0
- package/src/protocol/output/openai_responses_output.ts +159 -0
- package/src/protocol/output/openai_responses_stream.ts +631 -0
- package/src/protocol/output/sse_stream.ts +102 -0
- package/src/providers/anthropic_safeguards.ts +115 -0
- package/src/providers/aws_assume_role.ts +147 -0
- package/src/providers/cancel_estimate.ts +140 -0
- package/src/providers/execution.ts +800 -0
- package/src/providers/model_capabilities.ts +50 -0
- package/src/providers/pi.ts +499 -0
- package/src/providers/pi_context.ts +466 -0
- package/src/providers/pi_options.ts +416 -0
- package/src/providers/pi_output.ts +500 -0
- package/src/providers/provider_attempt_runner.ts +153 -0
- package/src/providers/provider_call.ts +433 -0
- package/src/providers/provider_reported_cost.ts +138 -0
- package/src/providers/reasoning.ts +59 -0
- package/src/providers/response_capture.ts +65 -0
- package/src/providers/stream_finalization.ts +264 -0
- package/src/providers/subscription_limits.ts +208 -0
- package/src/providers/subscription_usage.ts +99 -0
- package/src/runtime/claude_code/auxiliary_routing.ts +80 -0
- package/src/runtime/customer_disconnect.ts +66 -0
- package/src/runtime/explicit_model.ts +86 -0
- package/src/runtime/harness_identity/conversation.ts +87 -0
- package/src/runtime/harness_identity/extract.ts +323 -0
- package/src/runtime/harness_identity/index.ts +14 -0
- package/src/runtime/prepare_routed_completion.ts +224 -0
- package/src/runtime/provider_stream_lifecycle.ts +105 -0
- package/src/runtime/provider_stream_outcome.ts +83 -0
- package/src/runtime/request_tags.ts +34 -0
- package/src/runtime/routed_completion.ts +102 -0
- package/src/runtime/routed_protocol.ts +33 -0
- package/src/runtime/routed_runtime.ts +722 -0
- package/src/runtime/routing_lease.ts +273 -0
- package/src/runtime/runtime_reporter.ts +115 -0
- package/src/self_host/config.ts +173 -0
- package/src/self_host/main.ts +104 -0
- package/src/self_host/platform.ts +63 -0
- package/src/self_host/prefix_store.ts +315 -0
- package/src/self_host/resolve.ts +240 -0
- package/src/self_host/subscriptions/access.ts +43 -0
- package/src/self_host/subscriptions/http.ts +204 -0
- package/src/self_host/subscriptions/index.ts +43 -0
- package/src/self_host/subscriptions/oauth.ts +395 -0
- package/src/self_host/subscriptions/store.ts +339 -0
- package/src/strategies/auto_routing_selector.ts +72 -0
- package/src/strategies/eval_relevance.ts +57 -0
- package/src/strategies/fallback_decision.ts +30 -0
- package/src/strategies/priority_selector.ts +40 -0
- package/src/strategies/route_decision.ts +106 -0
- package/src/strategies/routing.ts +455 -0
- package/src/strategies/selector_projection.ts +207 -0
- package/src/telemetry/background.ts +40 -0
- package/src/telemetry/benchmark_replay.ts +160 -0
- package/src/telemetry/billing_finalization.ts +167 -0
- package/src/telemetry/ingest_values.ts +15 -0
- package/src/telemetry/model_cost.ts +14 -0
- package/src/telemetry/prefix_state.ts +183 -0
- package/src/telemetry/report.ts +832 -0
- package/src/telemetry/requests/interaction_observability.ts +258 -0
- package/src/telemetry/requests/retained_interaction_request.ts +20 -0
- package/src/telemetry/scrub.ts +38 -0
- package/src/telemetry/skills/claude/catalog.ts +119 -0
- package/src/telemetry/skills/claude/file_reads.ts +153 -0
- package/src/telemetry/skills/claude/observations.ts +450 -0
- package/src/telemetry/skills/codex/catalog.ts +171 -0
- package/src/telemetry/skills/codex/exec_file_reads.ts +55 -0
- package/src/telemetry/skills/codex/explicit.ts +116 -0
- package/src/telemetry/skills/codex/file_reads.ts +51 -0
- package/src/telemetry/skills/codex/identity.ts +21 -0
- package/src/telemetry/skills/observations.ts +94 -0
- package/src/telemetry/skills/paths.ts +82 -0
- package/src/telemetry/skills/pi.ts +276 -0
- package/src/telemetry/skills/shell_file_reads.ts +267 -0
- package/src/telemetry/skills/shell_words.ts +202 -0
- package/src/telemetry/tools/input.ts +16 -0
- package/src/telemetry/tools/observations.ts +349 -0
- package/src/telemetry/usage.ts +173 -0
- package/src/types.ts +150 -0
|
@@ -0,0 +1,451 @@
|
|
|
1
|
+
import { isRecord, type ChatMessage, type RoutingDecision } from "@mupt-ai/dari-router/policy-engine";
|
|
2
|
+
|
|
3
|
+
import { piMessageToInteractionOutput } from "../../providers/pi_output";
|
|
4
|
+
import { providerToolCallIdentity } from "../../interaction/tool_identity";
|
|
5
|
+
import { encodeProviderContinuationState } from "../../interaction/provider_continuation_state";
|
|
6
|
+
import { chatReasoningDetailId } from "./chat_reasoning_detail";
|
|
7
|
+
import type { InteractionOutput, InteractionRequest, ProviderContinuationState, ProviderIdentity } from "../../interaction/types";
|
|
8
|
+
import {
|
|
9
|
+
isProviderFailureMessage,
|
|
10
|
+
providerFailureFromEvent,
|
|
11
|
+
providerFailureMessage,
|
|
12
|
+
type ProviderStreamOutcome,
|
|
13
|
+
} from "../../runtime/provider_stream_outcome";
|
|
14
|
+
import { sseStream } from "./sse_stream";
|
|
15
|
+
|
|
16
|
+
export function chatCompletionResponse(args: {
|
|
17
|
+
id: string;
|
|
18
|
+
model: string;
|
|
19
|
+
output: InteractionOutput;
|
|
20
|
+
modelCost?: number | null;
|
|
21
|
+
routing: RoutingDecision;
|
|
22
|
+
conversationId?: string;
|
|
23
|
+
}): Record<string, unknown> {
|
|
24
|
+
return {
|
|
25
|
+
id: completionId(args.id),
|
|
26
|
+
object: "chat.completion",
|
|
27
|
+
created: Math.floor(args.output.createdAtMs / 1000),
|
|
28
|
+
model: args.model,
|
|
29
|
+
choices: [
|
|
30
|
+
{
|
|
31
|
+
index: 0,
|
|
32
|
+
message: assistantMessagePayload(args.output),
|
|
33
|
+
finish_reason: interactionFinishReason(args.output),
|
|
34
|
+
},
|
|
35
|
+
],
|
|
36
|
+
usage: usagePayload(args.output, args.modelCost),
|
|
37
|
+
dari_routing: routingPayload(args.routing, args.conversationId),
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function chatCompletionsSseStream(args: {
|
|
42
|
+
id: string;
|
|
43
|
+
model: string;
|
|
44
|
+
routing: RoutingDecision;
|
|
45
|
+
events: AsyncIterable<Record<string, unknown>>;
|
|
46
|
+
source: ProviderIdentity;
|
|
47
|
+
request: InteractionRequest;
|
|
48
|
+
conversationId?: string;
|
|
49
|
+
onFinal?: (outcome: ProviderStreamOutcome) => void;
|
|
50
|
+
modelCost?: (message: Record<string, unknown>, failed: boolean) => number | null;
|
|
51
|
+
// Optional terminal barrier. Streaming deltas are unaffected, but [DONE]
|
|
52
|
+
// and EOF are held until this settles.
|
|
53
|
+
beforeClose?: (outcome: ProviderStreamOutcome) => Promise<void> | void;
|
|
54
|
+
clientSignal?: AbortSignal;
|
|
55
|
+
onAbort?: () => void;
|
|
56
|
+
}): ReadableStream<Uint8Array> {
|
|
57
|
+
const encoder = new TextEncoder();
|
|
58
|
+
const completion = completionId(args.id);
|
|
59
|
+
const created = Math.floor(Date.now() / 1000);
|
|
60
|
+
return sseStream({
|
|
61
|
+
protocol: "openai_chat",
|
|
62
|
+
lifecycle: args,
|
|
63
|
+
start: ({ controller, snapshot, lifecycle, settle, observeTerminal }) => {
|
|
64
|
+
const send = (value: unknown) => {
|
|
65
|
+
if (!lifecycle.canWrite) return;
|
|
66
|
+
snapshot.record({ data: value });
|
|
67
|
+
controller.enqueue(encoder.encode(`data: ${JSON.stringify(value)}\n\n`));
|
|
68
|
+
};
|
|
69
|
+
const done = () => {
|
|
70
|
+
if (!lifecycle.canWrite) return;
|
|
71
|
+
controller.enqueue(encoder.encode("data: [DONE]\n\n"));
|
|
72
|
+
};
|
|
73
|
+
const sendProviderError = (message: Record<string, unknown>) => {
|
|
74
|
+
send({ ...errorChunk({ completion, created, model: args.model, message: providerFailureMessage(message) }),
|
|
75
|
+
usage: usagePayload(message, args.modelCost?.(message, true)) });
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
send(chunk({ completion, created, model: args.model, delta: {}, finishReason: null, routing: args.routing, conversationId: args.conversationId }));
|
|
79
|
+
send(chunk({ completion, created, model: args.model, delta: { role: "assistant" }, finishReason: null }));
|
|
80
|
+
|
|
81
|
+
const argumentDeltaSeen = new Set<string>();
|
|
82
|
+
const toolCallIdsSeen = new Set<string>();
|
|
83
|
+
const emittedToolCallIds = new Set<string>();
|
|
84
|
+
const toolCallNamesSeen = new Set<string>();
|
|
85
|
+
const toolCallIndexes = new Map<string, number>();
|
|
86
|
+
let reasoningDeltaSeen = false;
|
|
87
|
+
let nextToolCallIndex = 0;
|
|
88
|
+
const streamIndexFor = (event: Record<string, unknown>): number => {
|
|
89
|
+
const keys = toolCallStreamKeys(event);
|
|
90
|
+
for (const key of keys) {
|
|
91
|
+
const existing = toolCallIndexes.get(key);
|
|
92
|
+
if (existing !== undefined) return existing;
|
|
93
|
+
}
|
|
94
|
+
const index = typeof event.index === "number" ? event.index : nextToolCallIndex++;
|
|
95
|
+
nextToolCallIndex = Math.max(nextToolCallIndex, index + 1);
|
|
96
|
+
for (const key of keys) toolCallIndexes.set(key, index);
|
|
97
|
+
return index;
|
|
98
|
+
};
|
|
99
|
+
const markKeys = (event: Record<string, unknown>, target: Set<string>) => {
|
|
100
|
+
for (const key of toolCallStreamKeys(event)) target.add(key);
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
return {
|
|
104
|
+
consume: async () => {
|
|
105
|
+
for await (const event of args.events) {
|
|
106
|
+
if (lifecycle.shouldStopConsuming) break;
|
|
107
|
+
const type = event.type;
|
|
108
|
+
if (type === "text_delta" && typeof event.delta === "string" && event.delta) {
|
|
109
|
+
send(chunk({ completion, created, model: args.model, delta: { content: event.delta }, finishReason: null }));
|
|
110
|
+
} else if (type === "thinking_delta" && typeof event.delta === "string" && event.delta) {
|
|
111
|
+
reasoningDeltaSeen = true;
|
|
112
|
+
send(chunk({ completion, created, model: args.model, delta: { reasoning_content: event.delta }, finishReason: null }));
|
|
113
|
+
} else if (type === "toolcall_start") {
|
|
114
|
+
const index = streamIndexFor(event);
|
|
115
|
+
const delta = toolCallStartDelta(event, index, args.source);
|
|
116
|
+
if (typeof delta.id === "string" && delta.id) {
|
|
117
|
+
markKeys(event, toolCallIdsSeen);
|
|
118
|
+
emittedToolCallIds.add(delta.id);
|
|
119
|
+
}
|
|
120
|
+
if (toolCallNameFromEvent(event)) markKeys(event, toolCallNamesSeen);
|
|
121
|
+
send(chunk({ completion, created, model: args.model, delta: { tool_calls: [delta] }, finishReason: null }));
|
|
122
|
+
} else if (type === "toolcall_delta" && typeof event.delta === "string" && event.delta) {
|
|
123
|
+
const index = streamIndexFor(event);
|
|
124
|
+
markKeys(event, argumentDeltaSeen);
|
|
125
|
+
send(chunk({ completion, created, model: args.model, delta: { tool_calls: [toolCallArgumentsDelta(event, index)] }, finishReason: null }));
|
|
126
|
+
} else if (type === "toolcall_end" && isRecord(event.toolCall)) {
|
|
127
|
+
const index = streamIndexFor(event);
|
|
128
|
+
const keys = toolCallStreamKeys(event);
|
|
129
|
+
const delta = toolCallEndDelta(event, index, args.source, {
|
|
130
|
+
includeArguments: !keys.some((key) => argumentDeltaSeen.has(key)),
|
|
131
|
+
includeId: !keys.some((key) => toolCallIdsSeen.has(key)),
|
|
132
|
+
includeName: !keys.some((key) => toolCallNamesSeen.has(key)),
|
|
133
|
+
});
|
|
134
|
+
if (typeof delta.id === "string" && delta.id) emittedToolCallIds.add(delta.id);
|
|
135
|
+
if (toolCallDeltaHasPayload(delta)) {
|
|
136
|
+
send(chunk({ completion, created, model: args.model, delta: { tool_calls: [delta] }, finishReason: null }));
|
|
137
|
+
}
|
|
138
|
+
} else if (type === "done") {
|
|
139
|
+
if (!isRecord(event.message)) throw new Error("Provider stream ended without a terminal message.");
|
|
140
|
+
observeTerminal(event.message);
|
|
141
|
+
if (isProviderFailureMessage(event.message)) {
|
|
142
|
+
settle({ status: "provider_error", message: event.message });
|
|
143
|
+
sendProviderError(event.message);
|
|
144
|
+
} else {
|
|
145
|
+
const output = piMessageToInteractionOutput(event.message, args.source, args.request);
|
|
146
|
+
settle({ status: "completed", message: event.message, output });
|
|
147
|
+
const assistant = assistantMessagePayload(output);
|
|
148
|
+
if (!reasoningDeltaSeen && typeof assistant.reasoning_content === "string" && assistant.reasoning_content) {
|
|
149
|
+
send(chunk({
|
|
150
|
+
completion,
|
|
151
|
+
created,
|
|
152
|
+
model: args.model,
|
|
153
|
+
delta: { reasoning_content: assistant.reasoning_content },
|
|
154
|
+
finishReason: null,
|
|
155
|
+
}));
|
|
156
|
+
}
|
|
157
|
+
if (Array.isArray(assistant.reasoning_details) && assistant.reasoning_details.length > 0) {
|
|
158
|
+
send(chunk({
|
|
159
|
+
completion,
|
|
160
|
+
created,
|
|
161
|
+
model: args.model,
|
|
162
|
+
delta: { reasoning_details: assistant.reasoning_details },
|
|
163
|
+
finishReason: null,
|
|
164
|
+
}));
|
|
165
|
+
}
|
|
166
|
+
const terminalToolCalls = Array.isArray(assistant.tool_calls)
|
|
167
|
+
? assistant.tool_calls.flatMap((toolCall, index) => {
|
|
168
|
+
if (!isRecord(toolCall) || typeof toolCall.id !== "string" || emittedToolCallIds.has(toolCall.id)) {
|
|
169
|
+
return [];
|
|
170
|
+
}
|
|
171
|
+
return [{ index, ...toolCall }];
|
|
172
|
+
})
|
|
173
|
+
: [];
|
|
174
|
+
if (terminalToolCalls.length > 0) {
|
|
175
|
+
send(chunk({
|
|
176
|
+
completion,
|
|
177
|
+
created,
|
|
178
|
+
model: args.model,
|
|
179
|
+
delta: { tool_calls: terminalToolCalls },
|
|
180
|
+
finishReason: null,
|
|
181
|
+
}));
|
|
182
|
+
}
|
|
183
|
+
send(chunk({
|
|
184
|
+
completion,
|
|
185
|
+
created,
|
|
186
|
+
model: args.model,
|
|
187
|
+
delta: {},
|
|
188
|
+
finishReason: interactionFinishReason(output),
|
|
189
|
+
usage: usagePayload(event.message, args.modelCost?.(event.message, false)),
|
|
190
|
+
}));
|
|
191
|
+
}
|
|
192
|
+
break;
|
|
193
|
+
} else if (type === "error") {
|
|
194
|
+
const message = providerFailureFromEvent(event);
|
|
195
|
+
settle({ status: "provider_error", message });
|
|
196
|
+
sendProviderError(message);
|
|
197
|
+
break;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
},
|
|
201
|
+
emitProviderError: sendProviderError,
|
|
202
|
+
close: () => {
|
|
203
|
+
done();
|
|
204
|
+
controller.close();
|
|
205
|
+
},
|
|
206
|
+
};
|
|
207
|
+
},
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
function routingPayload(decision: RoutingDecision, conversationId?: string): Record<string, unknown> {
|
|
212
|
+
return {
|
|
213
|
+
requested_model: "dari/routing",
|
|
214
|
+
selected_model: decision.selectedModel,
|
|
215
|
+
reasoning_effort: decision.reasoningEffort,
|
|
216
|
+
reason: decision.reason,
|
|
217
|
+
...(conversationId ? { conversation_id: conversationId } : {}),
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
function chunk(args: {
|
|
222
|
+
completion: string;
|
|
223
|
+
created: number;
|
|
224
|
+
model: string;
|
|
225
|
+
delta: Record<string, unknown>;
|
|
226
|
+
finishReason: string | null;
|
|
227
|
+
routing?: RoutingDecision;
|
|
228
|
+
usage?: Record<string, unknown>;
|
|
229
|
+
conversationId?: string;
|
|
230
|
+
}): Record<string, unknown> {
|
|
231
|
+
return {
|
|
232
|
+
id: args.completion,
|
|
233
|
+
object: "chat.completion.chunk",
|
|
234
|
+
created: args.created,
|
|
235
|
+
model: args.model,
|
|
236
|
+
choices: [{ index: 0, delta: args.delta, finish_reason: args.finishReason }],
|
|
237
|
+
...(args.routing ? { dari_routing: routingPayload(args.routing, args.conversationId) } : {}),
|
|
238
|
+
...(args.usage ? { usage: args.usage } : {}),
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
function errorChunk(args: { completion: string; created: number; model: string; message: string }): Record<string, unknown> {
|
|
243
|
+
return {
|
|
244
|
+
id: args.completion,
|
|
245
|
+
object: "chat.completion.chunk",
|
|
246
|
+
created: args.created,
|
|
247
|
+
model: args.model,
|
|
248
|
+
choices: [{ index: 0, delta: {}, finish_reason: "error" }],
|
|
249
|
+
error: { message: args.message, type: "server_error", code: "provider_execution_failed" },
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
export function assistantMessagePayload(output: InteractionOutput): ChatMessage {
|
|
254
|
+
const textParts: string[] = [];
|
|
255
|
+
const reasoningParts: string[] = [];
|
|
256
|
+
const continuations: ProviderContinuationState[] = [];
|
|
257
|
+
const toolCalls: Array<Record<string, unknown>> = [];
|
|
258
|
+
const toolCallIds: string[] = [];
|
|
259
|
+
const reasoningDetailIds = new Set<string>();
|
|
260
|
+
for (const item of output.items) {
|
|
261
|
+
if (item.type === "message") {
|
|
262
|
+
textParts.push(...item.content.filter((part) => part.type === "text").map((part) => part.text));
|
|
263
|
+
}
|
|
264
|
+
if (item.type === "reasoning") {
|
|
265
|
+
reasoningParts.push(...item.summary, ...item.content);
|
|
266
|
+
if (item.continuation) continuations.push(item.continuation);
|
|
267
|
+
}
|
|
268
|
+
if (item.type === "tool_call") {
|
|
269
|
+
toolCalls.push(toolCallMessage(item, toolCalls.length));
|
|
270
|
+
toolCallIds.push(item.callId || `call_${toolCallIds.length}`);
|
|
271
|
+
}
|
|
272
|
+
if (item.type === "hosted_tool_call") {
|
|
273
|
+
toolCalls.push(hostedToolCallMessage(item));
|
|
274
|
+
toolCallIds.push(item.id);
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
return {
|
|
278
|
+
role: "assistant",
|
|
279
|
+
content: toolCalls.length > 0 && textParts.length === 0 ? null : textParts.join(""),
|
|
280
|
+
...(reasoningParts.length > 0 ? { reasoning_content: reasoningParts.join("\n") } : {}),
|
|
281
|
+
...(toolCalls.length > 0 ? { tool_calls: toolCalls } : {}),
|
|
282
|
+
...(continuations.length > 0
|
|
283
|
+
? {
|
|
284
|
+
reasoning_details: continuations.map((continuation, index) => ({
|
|
285
|
+
type: "reasoning.encrypted",
|
|
286
|
+
id: chatReasoningDetailId(continuation, index, toolCallIds, reasoningDetailIds),
|
|
287
|
+
data: encodeProviderContinuationState(continuation),
|
|
288
|
+
})),
|
|
289
|
+
}
|
|
290
|
+
: {}),
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
function hostedToolCallMessage(
|
|
295
|
+
item: Extract<InteractionOutput["items"][number], { type: "hosted_tool_call" }>
|
|
296
|
+
): Record<string, unknown> {
|
|
297
|
+
const replayPayload = chatHostedToolReplayPayload(item);
|
|
298
|
+
return {
|
|
299
|
+
id: item.id,
|
|
300
|
+
type: "function",
|
|
301
|
+
function: {
|
|
302
|
+
name: item.tool,
|
|
303
|
+
arguments: JSON.stringify(replayPayload),
|
|
304
|
+
},
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
export function chatHostedToolReplayPayload(
|
|
309
|
+
item: Extract<InteractionOutput["items"][number], { type: "hosted_tool_call" }>
|
|
310
|
+
): Record<string, unknown> {
|
|
311
|
+
const payload: Record<string, unknown> = {
|
|
312
|
+
...item.payload,
|
|
313
|
+
type: item.providerType,
|
|
314
|
+
id: item.id,
|
|
315
|
+
};
|
|
316
|
+
if (item.status) payload.status = item.status;
|
|
317
|
+
else delete payload.status;
|
|
318
|
+
return payload;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
function toolCallMessage(item: Extract<InteractionOutput["items"][number], { type: "tool_call" }>, index: number): Record<string, unknown> {
|
|
322
|
+
const name = item.namespace ? `${item.namespace}__${item.name}` : item.name;
|
|
323
|
+
return {
|
|
324
|
+
id: item.callId || `call_${index}`,
|
|
325
|
+
type: "function",
|
|
326
|
+
function: {
|
|
327
|
+
name,
|
|
328
|
+
arguments: typeof item.input === "string" ? item.input : JSON.stringify(item.input ?? {}),
|
|
329
|
+
},
|
|
330
|
+
};
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
function usagePayload(message: { usage?: unknown }, cost?: number | null): Record<string, unknown> {
|
|
334
|
+
const usage = isRecord(message.usage) ? message.usage : {};
|
|
335
|
+
const input = numeric(usage.input);
|
|
336
|
+
const cacheRead = numeric(usage.cacheRead);
|
|
337
|
+
const cacheWrite = numeric(usage.cacheWrite);
|
|
338
|
+
const prompt = input + cacheRead + cacheWrite;
|
|
339
|
+
const completion = numeric(usage.output);
|
|
340
|
+
return {
|
|
341
|
+
// Same field as OpenRouter. Null means unpriced, never a fabricated free request.
|
|
342
|
+
cost: cost ?? null,
|
|
343
|
+
prompt_tokens: prompt,
|
|
344
|
+
completion_tokens: completion,
|
|
345
|
+
// OpenAI counts cached tokens inside prompt_tokens; once cache tokens are
|
|
346
|
+
// folded in, recompute the total rather than trusting upstream totalTokens.
|
|
347
|
+
total_tokens: cacheRead || cacheWrite
|
|
348
|
+
? prompt + completion
|
|
349
|
+
: numeric(usage.totalTokens) || prompt + completion,
|
|
350
|
+
...(cacheRead || cacheWrite
|
|
351
|
+
? { prompt_tokens_details: { cached_tokens: cacheRead, cache_write_tokens: cacheWrite } }
|
|
352
|
+
: {}),
|
|
353
|
+
};
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
function interactionFinishReason(output: InteractionOutput): string {
|
|
357
|
+
if (output.stopReason === "length") return "length";
|
|
358
|
+
if (output.stopReason === "tool_use") return "tool_calls";
|
|
359
|
+
if (output.stopReason === "error" || output.stopReason === "aborted") return "error";
|
|
360
|
+
return "stop";
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
function completionId(id: string): string {
|
|
364
|
+
return `chatcmpl-${id}`;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
function toolCallStartDelta(
|
|
368
|
+
event: Record<string, unknown>,
|
|
369
|
+
index: number,
|
|
370
|
+
source: ProviderIdentity
|
|
371
|
+
): Record<string, unknown> {
|
|
372
|
+
const toolCall = toolCallFromEvent(event);
|
|
373
|
+
const providerId = stringValue(event.toolCallId) ?? stringValue(toolCall.id);
|
|
374
|
+
const id = providerId ? providerToolCallIdentity(providerId, source).callId : undefined;
|
|
375
|
+
const name = toolCallNameFromEvent(event) ?? "tool";
|
|
376
|
+
return {
|
|
377
|
+
index,
|
|
378
|
+
...(id ? { id } : {}),
|
|
379
|
+
type: "function",
|
|
380
|
+
function: { name, arguments: "" },
|
|
381
|
+
};
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
function toolCallArgumentsDelta(event: Record<string, unknown>, index: number): Record<string, unknown> {
|
|
385
|
+
return { index, function: { arguments: String(event.delta ?? "") } };
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
function toolCallEndDelta(
|
|
389
|
+
event: Record<string, unknown>,
|
|
390
|
+
index: number,
|
|
391
|
+
source: ProviderIdentity,
|
|
392
|
+
options: { includeArguments: boolean; includeId: boolean; includeName: boolean },
|
|
393
|
+
): Record<string, unknown> {
|
|
394
|
+
const toolCall = toolCallFromEvent(event);
|
|
395
|
+
const providerId = stringValue(toolCall.id);
|
|
396
|
+
const id = providerId ? providerToolCallIdentity(providerId, source).callId : undefined;
|
|
397
|
+
const name = stringValue(toolCall.name);
|
|
398
|
+
const functionDelta: Record<string, unknown> = {};
|
|
399
|
+
if (options.includeName && name) functionDelta.name = name;
|
|
400
|
+
if (options.includeArguments) {
|
|
401
|
+
functionDelta.arguments = JSON.stringify(isRecord(toolCall.arguments) ? toolCall.arguments : {});
|
|
402
|
+
}
|
|
403
|
+
return {
|
|
404
|
+
index,
|
|
405
|
+
...(options.includeId && id ? { id } : {}),
|
|
406
|
+
...((options.includeId && id) || (options.includeName && name) ? { type: "function" } : {}),
|
|
407
|
+
...(Object.keys(functionDelta).length > 0 ? { function: functionDelta } : {}),
|
|
408
|
+
};
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
function toolCallDeltaHasPayload(delta: Record<string, unknown>): boolean {
|
|
412
|
+
return Boolean(delta.id || delta.type || (isRecord(delta.function) && Object.keys(delta.function).length > 0));
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
function toolCallStreamKeys(event: Record<string, unknown>): string[] {
|
|
416
|
+
const keys: string[] = [];
|
|
417
|
+
const toolCall = toolCallFromEvent(event);
|
|
418
|
+
if (typeof event.index === "number") keys.push(`index:${event.index}`);
|
|
419
|
+
if (typeof event.contentIndex === "number") keys.push(`content:${event.contentIndex}`);
|
|
420
|
+
if (typeof event.toolCallId === "string" && event.toolCallId) keys.push(`id:${event.toolCallId}`);
|
|
421
|
+
if (typeof toolCall.id === "string" && toolCall.id) keys.push(`id:${toolCall.id}`);
|
|
422
|
+
return keys.length > 0 ? keys : ["unknown"];
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
function toolCallFromEvent(event: Record<string, unknown>): Record<string, unknown> {
|
|
426
|
+
if (isRecord(event.toolCall)) return event.toolCall;
|
|
427
|
+
const partial = isRecord(event.partial) ? event.partial : {};
|
|
428
|
+
const content = Array.isArray(partial.content) ? partial.content : [];
|
|
429
|
+
const contentIndex = eventContentIndex(event);
|
|
430
|
+
const item = contentIndex === undefined ? undefined : content[contentIndex];
|
|
431
|
+
return isRecord(item) && item.type === "toolCall" ? item : {};
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
function eventContentIndex(event: Record<string, unknown>): number | undefined {
|
|
435
|
+
if (typeof event.contentIndex === "number") return event.contentIndex;
|
|
436
|
+
if (typeof event.index === "number") return event.index;
|
|
437
|
+
return undefined;
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
function toolCallNameFromEvent(event: Record<string, unknown>): string | undefined {
|
|
441
|
+
const toolCall = toolCallFromEvent(event);
|
|
442
|
+
return stringValue(event.toolName) ?? stringValue(toolCall.name);
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
function stringValue(value: unknown): string | undefined {
|
|
446
|
+
return typeof value === "string" && value ? value : undefined;
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
function numeric(value: unknown): number {
|
|
450
|
+
return typeof value === "number" && Number.isFinite(value) ? Math.trunc(value) : 0;
|
|
451
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { ProviderContinuationState } from "../../interaction/types";
|
|
2
|
+
|
|
3
|
+
export function chatReasoningDetailId(
|
|
4
|
+
continuation: ProviderContinuationState,
|
|
5
|
+
index: number,
|
|
6
|
+
toolCallIds: readonly string[],
|
|
7
|
+
usedIds: Set<string>
|
|
8
|
+
): string {
|
|
9
|
+
let candidate = toolCallIds[index];
|
|
10
|
+
if (
|
|
11
|
+
!candidate
|
|
12
|
+
&& continuation.kind === "openai_reasoning"
|
|
13
|
+
&& continuation.providerItemId
|
|
14
|
+
) candidate = continuation.providerItemId;
|
|
15
|
+
if (!candidate || usedIds.has(candidate)) candidate = `reasoning_${index}`;
|
|
16
|
+
while (usedIds.has(candidate)) candidate = `${candidate}_${index}`;
|
|
17
|
+
usedIds.add(candidate);
|
|
18
|
+
return candidate;
|
|
19
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
const MAX_SNAPSHOT_BYTES = 256 * 1024;
|
|
2
|
+
|
|
3
|
+
/** Bounded record of protocol frames actually handed to the client stream. */
|
|
4
|
+
export class DeliveredStreamSnapshot {
|
|
5
|
+
private readonly events: unknown[] = [];
|
|
6
|
+
private encodedBytes = 0;
|
|
7
|
+
private truncated = false;
|
|
8
|
+
|
|
9
|
+
constructor(private readonly protocol: string) {}
|
|
10
|
+
|
|
11
|
+
record(event: unknown): void {
|
|
12
|
+
if (this.truncated) return;
|
|
13
|
+
const encoded = JSON.stringify(event);
|
|
14
|
+
const bytes = Buffer.byteLength(encoded, "utf8");
|
|
15
|
+
if (this.encodedBytes + bytes > MAX_SNAPSHOT_BYTES) {
|
|
16
|
+
this.truncated = true;
|
|
17
|
+
return;
|
|
18
|
+
}
|
|
19
|
+
this.events.push(event);
|
|
20
|
+
this.encodedBytes += bytes;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
body(): Record<string, unknown> {
|
|
24
|
+
return {
|
|
25
|
+
type: "dari.stream_partial",
|
|
26
|
+
protocol: this.protocol,
|
|
27
|
+
events: this.events,
|
|
28
|
+
truncated: this.truncated,
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import {
|
|
2
|
+
openAIResponsesOutputItems,
|
|
3
|
+
openAIResponsesResponseId,
|
|
4
|
+
openAIResponsesRouting,
|
|
5
|
+
openAIResponsesTerminal,
|
|
6
|
+
openAIResponsesUsage,
|
|
7
|
+
} from "./openai_responses_output";
|
|
8
|
+
import type { InteractionOutput, InteractionRequest } from "../../interaction/types";
|
|
9
|
+
|
|
10
|
+
export function openAIResponsesResponse(args: {
|
|
11
|
+
id: string;
|
|
12
|
+
model: string;
|
|
13
|
+
output: InteractionOutput;
|
|
14
|
+
request: InteractionRequest;
|
|
15
|
+
routing: RoutingDecision;
|
|
16
|
+
conversationId?: string;
|
|
17
|
+
}): Record<string, unknown> {
|
|
18
|
+
return {
|
|
19
|
+
id: openAIResponsesResponseId(args.id),
|
|
20
|
+
object: "response",
|
|
21
|
+
created_at: Math.floor(args.output.createdAtMs / 1000),
|
|
22
|
+
...openAIResponsesTerminal(args.output),
|
|
23
|
+
model: args.model,
|
|
24
|
+
output: openAIResponsesOutputItems(args.output),
|
|
25
|
+
usage: openAIResponsesUsage(args.output),
|
|
26
|
+
parallel_tool_calls: args.request.parallelToolCalls ?? true,
|
|
27
|
+
dari_routing: openAIResponsesRouting(args.routing, args.conversationId),
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
import type { RoutingDecision } from "@mupt-ai/dari-router/policy-engine";
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import { encodeProviderContinuationState } from "../../interaction/provider_continuation_state";
|
|
2
|
+
import type { InteractionOutput } from "../../interaction/types";
|
|
3
|
+
|
|
4
|
+
export function openAIResponsesResponseId(requestId: string): string {
|
|
5
|
+
return `resp_${requestId}`;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export function openAIResponsesTerminal(output: Pick<InteractionOutput, "stopReason">): {
|
|
9
|
+
status: "completed" | "incomplete";
|
|
10
|
+
incomplete_details: { reason: "max_output_tokens" } | null;
|
|
11
|
+
} {
|
|
12
|
+
return output.stopReason === "length"
|
|
13
|
+
? { status: "incomplete", incomplete_details: { reason: "max_output_tokens" } }
|
|
14
|
+
: { status: "completed", incomplete_details: null };
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function openAIResponsesOutputItems(output: InteractionOutput): Array<Record<string, unknown>> {
|
|
18
|
+
return output.items.map((item, index) => openAIResponsesOutputItem(output, item, index));
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function openAIResponsesOutputItem(
|
|
22
|
+
output: InteractionOutput,
|
|
23
|
+
item: InteractionOutput["items"][number],
|
|
24
|
+
index: number
|
|
25
|
+
): Record<string, unknown> {
|
|
26
|
+
if (item.type === "message") return responseMessageItem(output, item, index);
|
|
27
|
+
if (item.type === "reasoning") return responseReasoningItem(output, item, index);
|
|
28
|
+
if (item.type === "hosted_tool_call") return responseHostedToolCallItem(item);
|
|
29
|
+
return responseToolCallItem(item);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function openAIResponsesUsage(output: Pick<InteractionOutput, "usage">): Record<string, unknown> {
|
|
33
|
+
const inputTokens = output.usage.input + output.usage.cacheRead + output.usage.cacheWrite;
|
|
34
|
+
return {
|
|
35
|
+
input_tokens: inputTokens,
|
|
36
|
+
input_tokens_details: output.usage.cacheRead || output.usage.cacheWrite
|
|
37
|
+
? { cached_tokens: output.usage.cacheRead, cache_write_tokens: output.usage.cacheWrite }
|
|
38
|
+
: null,
|
|
39
|
+
output_tokens: output.usage.output,
|
|
40
|
+
output_tokens_details: null,
|
|
41
|
+
total_tokens: output.usage.totalTokens || inputTokens + output.usage.output,
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function openAIResponsesRouting(
|
|
46
|
+
decision: RoutingDecision,
|
|
47
|
+
conversationId?: string
|
|
48
|
+
): Record<string, unknown> {
|
|
49
|
+
return {
|
|
50
|
+
requested_model: "dari/routing",
|
|
51
|
+
selected_model: decision.selectedModel,
|
|
52
|
+
reasoning_effort: decision.reasoningEffort,
|
|
53
|
+
reason: decision.reason,
|
|
54
|
+
...(conversationId ? { conversation_id: conversationId } : {}),
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function responseMessageOutputItem(id: string, text: string): Record<string, unknown> {
|
|
59
|
+
return {
|
|
60
|
+
type: "message",
|
|
61
|
+
role: "assistant",
|
|
62
|
+
id,
|
|
63
|
+
status: "completed",
|
|
64
|
+
content: [{ type: "output_text", text, annotations: [] }],
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function responseMessageItem(
|
|
69
|
+
output: InteractionOutput,
|
|
70
|
+
item: Extract<InteractionOutput["items"][number], { type: "message" }>,
|
|
71
|
+
index: number
|
|
72
|
+
): Record<string, unknown> {
|
|
73
|
+
const content = item.content.flatMap((part) =>
|
|
74
|
+
part.type === "text"
|
|
75
|
+
? [{
|
|
76
|
+
type: "output_text",
|
|
77
|
+
text: part.text,
|
|
78
|
+
annotations: part.annotations ?? [],
|
|
79
|
+
}]
|
|
80
|
+
: []
|
|
81
|
+
);
|
|
82
|
+
return {
|
|
83
|
+
...responseMessageOutputItem(item.id ?? fallbackItemId("msg", output, index), ""),
|
|
84
|
+
content,
|
|
85
|
+
status: outputItemStatus(output),
|
|
86
|
+
...(item.phase ? { phase: item.phase } : {}),
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function responseHostedToolCallItem(
|
|
91
|
+
item: Extract<InteractionOutput["items"][number], { type: "hosted_tool_call" }>
|
|
92
|
+
): Record<string, unknown> {
|
|
93
|
+
return {
|
|
94
|
+
...item.payload,
|
|
95
|
+
type: item.providerType,
|
|
96
|
+
id: item.id,
|
|
97
|
+
...(item.status ? { status: item.status } : {}),
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function responseReasoningItem(
|
|
102
|
+
output: InteractionOutput,
|
|
103
|
+
item: Extract<InteractionOutput["items"][number], { type: "reasoning" }>,
|
|
104
|
+
index: number
|
|
105
|
+
): Record<string, unknown> {
|
|
106
|
+
return {
|
|
107
|
+
type: "reasoning",
|
|
108
|
+
id: item.id ?? fallbackItemId("rs", output, index),
|
|
109
|
+
status: outputItemStatus(output),
|
|
110
|
+
summary: item.summary.map((text) => ({ type: "summary_text", text })),
|
|
111
|
+
...(item.content.length
|
|
112
|
+
? { content: item.content.map((text) => ({ type: "reasoning_text", text })) }
|
|
113
|
+
: {}),
|
|
114
|
+
...(item.continuation
|
|
115
|
+
? { encrypted_content: encodeProviderContinuationState(item.continuation) }
|
|
116
|
+
: {}),
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function responseToolCallItem(
|
|
121
|
+
item: Extract<InteractionOutput["items"][number], { type: "tool_call" }>
|
|
122
|
+
): Record<string, unknown> {
|
|
123
|
+
const id = item.id ?? item.callId;
|
|
124
|
+
if (item.kind === "custom") {
|
|
125
|
+
return {
|
|
126
|
+
type: "custom_tool_call",
|
|
127
|
+
id,
|
|
128
|
+
call_id: item.callId,
|
|
129
|
+
...(item.namespace ? { namespace: item.namespace } : {}),
|
|
130
|
+
name: item.name,
|
|
131
|
+
input: typeof item.input === "string" ? item.input : "",
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
return {
|
|
135
|
+
type: "function_call",
|
|
136
|
+
id,
|
|
137
|
+
call_id: item.callId,
|
|
138
|
+
...(item.namespace ? { namespace: item.namespace } : {}),
|
|
139
|
+
name: item.name,
|
|
140
|
+
arguments: toolArgumentsString(item.input),
|
|
141
|
+
...(item.status ? { status: item.status } : {}),
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function outputItemStatus(output: InteractionOutput): "completed" | "incomplete" {
|
|
146
|
+
return output.stopReason === "length" ? "incomplete" : "completed";
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function fallbackItemId(prefix: "msg" | "rs", output: InteractionOutput, index: number): string {
|
|
150
|
+
const responseId = output.responseId?.replace(/[^A-Za-z0-9_-]/g, "_") || "routing";
|
|
151
|
+
return `${prefix}_${responseId}_${index}`.slice(0, 64);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function toolArgumentsString(value: unknown): string {
|
|
155
|
+
if (typeof value === "string") return value;
|
|
156
|
+
if (value === undefined || value === null) return "{}";
|
|
157
|
+
return JSON.stringify(value);
|
|
158
|
+
}
|
|
159
|
+
import type { RoutingDecision } from "@mupt-ai/dari-router/policy-engine";
|