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