@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.
Files changed (133) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +135 -2
  3. package/dari-gateway.example.yaml +28 -0
  4. package/package.json +42 -4
  5. package/src/bun.ts +4 -0
  6. package/src/context/eval_catalog.ts +11 -0
  7. package/src/context/interaction_fingerprint.ts +691 -0
  8. package/src/context/interaction_fingerprint_format.ts +189 -0
  9. package/src/context/interaction_lease_depth.ts +150 -0
  10. package/src/context/lease_history.ts +200 -0
  11. package/src/context/pricing.ts +30 -0
  12. package/src/context/provider_prompt_accounting.ts +241 -0
  13. package/src/context/routing_context.ts +337 -0
  14. package/src/http/auth.ts +43 -0
  15. package/src/http/errors.ts +114 -0
  16. package/src/http/handler.ts +110 -0
  17. package/src/http/http2_server.ts +122 -0
  18. package/src/http/serve.ts +119 -0
  19. package/src/index.ts +22 -0
  20. package/src/ingress/anthropic_messages.ts +162 -0
  21. package/src/ingress/anthropic_models.ts +28 -0
  22. package/src/ingress/chat_completions.ts +49 -0
  23. package/src/ingress/claude_code/request_context.ts +36 -0
  24. package/src/ingress/codex.ts +81 -0
  25. package/src/ingress/codex_models.ts +113 -0
  26. package/src/ingress/json.ts +113 -0
  27. package/src/ingress/models.ts +55 -0
  28. package/src/interaction/capabilities.ts +30 -0
  29. package/src/interaction/image.ts +12 -0
  30. package/src/interaction/portable_reasoning_state.ts +25 -0
  31. package/src/interaction/provider_continuation_state.ts +36 -0
  32. package/src/interaction/tool_identity.ts +65 -0
  33. package/src/interaction/types.ts +282 -0
  34. package/src/models/context_limits.ts +8 -0
  35. package/src/models/execution_provider.ts +22 -0
  36. package/src/models/gateways.ts +73 -0
  37. package/src/models/ids.ts +26 -0
  38. package/src/models/provider_defaults.ts +47 -0
  39. package/src/models/runtime_overrides.ts +221 -0
  40. package/src/observability/errors.ts +25 -0
  41. package/src/platform/platform.ts +204 -0
  42. package/src/platform/routing_contract.ts +6 -0
  43. package/src/protocol/input/anthropic_messages.ts +531 -0
  44. package/src/protocol/input/chat_completions.ts +255 -0
  45. package/src/protocol/input/chat_completions_validation.ts +293 -0
  46. package/src/protocol/input/openai_responses.ts +749 -0
  47. package/src/protocol/input/router_model.ts +53 -0
  48. package/src/protocol/output/anthropic_messages.ts +32 -0
  49. package/src/protocol/output/anthropic_messages_output.ts +129 -0
  50. package/src/protocol/output/anthropic_messages_stream.ts +281 -0
  51. package/src/protocol/output/chat_completions.ts +451 -0
  52. package/src/protocol/output/chat_reasoning_detail.ts +19 -0
  53. package/src/protocol/output/delivered_stream_snapshot.ts +31 -0
  54. package/src/protocol/output/openai_responses.ts +30 -0
  55. package/src/protocol/output/openai_responses_output.ts +159 -0
  56. package/src/protocol/output/openai_responses_stream.ts +631 -0
  57. package/src/protocol/output/sse_stream.ts +102 -0
  58. package/src/providers/anthropic_safeguards.ts +115 -0
  59. package/src/providers/aws_assume_role.ts +147 -0
  60. package/src/providers/cancel_estimate.ts +140 -0
  61. package/src/providers/execution.ts +800 -0
  62. package/src/providers/model_capabilities.ts +50 -0
  63. package/src/providers/pi.ts +499 -0
  64. package/src/providers/pi_context.ts +466 -0
  65. package/src/providers/pi_options.ts +416 -0
  66. package/src/providers/pi_output.ts +500 -0
  67. package/src/providers/provider_attempt_runner.ts +153 -0
  68. package/src/providers/provider_call.ts +433 -0
  69. package/src/providers/provider_reported_cost.ts +138 -0
  70. package/src/providers/reasoning.ts +59 -0
  71. package/src/providers/response_capture.ts +65 -0
  72. package/src/providers/stream_finalization.ts +264 -0
  73. package/src/providers/subscription_limits.ts +208 -0
  74. package/src/providers/subscription_usage.ts +99 -0
  75. package/src/runtime/claude_code/auxiliary_routing.ts +80 -0
  76. package/src/runtime/customer_disconnect.ts +66 -0
  77. package/src/runtime/explicit_model.ts +86 -0
  78. package/src/runtime/harness_identity/conversation.ts +87 -0
  79. package/src/runtime/harness_identity/extract.ts +323 -0
  80. package/src/runtime/harness_identity/index.ts +14 -0
  81. package/src/runtime/prepare_routed_completion.ts +224 -0
  82. package/src/runtime/provider_stream_lifecycle.ts +105 -0
  83. package/src/runtime/provider_stream_outcome.ts +83 -0
  84. package/src/runtime/request_tags.ts +34 -0
  85. package/src/runtime/routed_completion.ts +102 -0
  86. package/src/runtime/routed_protocol.ts +33 -0
  87. package/src/runtime/routed_runtime.ts +722 -0
  88. package/src/runtime/routing_lease.ts +273 -0
  89. package/src/runtime/runtime_reporter.ts +115 -0
  90. package/src/self_host/config.ts +173 -0
  91. package/src/self_host/main.ts +104 -0
  92. package/src/self_host/platform.ts +63 -0
  93. package/src/self_host/prefix_store.ts +315 -0
  94. package/src/self_host/resolve.ts +240 -0
  95. package/src/self_host/subscriptions/access.ts +43 -0
  96. package/src/self_host/subscriptions/http.ts +204 -0
  97. package/src/self_host/subscriptions/index.ts +43 -0
  98. package/src/self_host/subscriptions/oauth.ts +395 -0
  99. package/src/self_host/subscriptions/store.ts +339 -0
  100. package/src/strategies/auto_routing_selector.ts +72 -0
  101. package/src/strategies/eval_relevance.ts +57 -0
  102. package/src/strategies/fallback_decision.ts +30 -0
  103. package/src/strategies/priority_selector.ts +40 -0
  104. package/src/strategies/route_decision.ts +106 -0
  105. package/src/strategies/routing.ts +455 -0
  106. package/src/strategies/selector_projection.ts +207 -0
  107. package/src/telemetry/background.ts +40 -0
  108. package/src/telemetry/benchmark_replay.ts +160 -0
  109. package/src/telemetry/billing_finalization.ts +167 -0
  110. package/src/telemetry/ingest_values.ts +15 -0
  111. package/src/telemetry/model_cost.ts +14 -0
  112. package/src/telemetry/prefix_state.ts +183 -0
  113. package/src/telemetry/report.ts +832 -0
  114. package/src/telemetry/requests/interaction_observability.ts +258 -0
  115. package/src/telemetry/requests/retained_interaction_request.ts +20 -0
  116. package/src/telemetry/scrub.ts +38 -0
  117. package/src/telemetry/skills/claude/catalog.ts +119 -0
  118. package/src/telemetry/skills/claude/file_reads.ts +153 -0
  119. package/src/telemetry/skills/claude/observations.ts +450 -0
  120. package/src/telemetry/skills/codex/catalog.ts +171 -0
  121. package/src/telemetry/skills/codex/exec_file_reads.ts +55 -0
  122. package/src/telemetry/skills/codex/explicit.ts +116 -0
  123. package/src/telemetry/skills/codex/file_reads.ts +51 -0
  124. package/src/telemetry/skills/codex/identity.ts +21 -0
  125. package/src/telemetry/skills/observations.ts +94 -0
  126. package/src/telemetry/skills/paths.ts +82 -0
  127. package/src/telemetry/skills/pi.ts +276 -0
  128. package/src/telemetry/skills/shell_file_reads.ts +267 -0
  129. package/src/telemetry/skills/shell_words.ts +202 -0
  130. package/src/telemetry/tools/input.ts +16 -0
  131. package/src/telemetry/tools/observations.ts +349 -0
  132. package/src/telemetry/usage.ts +173 -0
  133. package/src/types.ts +150 -0
@@ -0,0 +1,66 @@
1
+ import { HttpError } from "../http/errors";
2
+
3
+ const CUSTOMER_DISCONNECTED_MESSAGE = "Client disconnected.";
4
+
5
+ export class CustomerDisconnectedError extends HttpError {
6
+ readonly name = "CustomerDisconnectedError";
7
+
8
+ constructor() {
9
+ // 499 is the conventional server-side classification for a client that
10
+ // closed the request before a response could be delivered.
11
+ super(499, CUSTOMER_DISCONNECTED_MESSAGE, "client_disconnected");
12
+ }
13
+ }
14
+
15
+ export type ProviderAttemptAbort = {
16
+ readonly signal: AbortSignal;
17
+ readonly aborted: boolean;
18
+ abort(): void;
19
+ dispose(): void;
20
+ };
21
+
22
+ /**
23
+ * Give every provider attempt its own cancellation boundary tied to the
24
+ * client's disconnect. A cancelled request stops paying the provider at once;
25
+ * its usage is estimated from what was delivered instead of drained.
26
+ */
27
+ export function createProviderAttemptAbort(args: {
28
+ clientSignal?: AbortSignal;
29
+ }): ProviderAttemptAbort {
30
+ const controller = new AbortController();
31
+ const abort = () => {
32
+ if (!controller.signal.aborted) {
33
+ controller.abort(new CustomerDisconnectedError());
34
+ }
35
+ };
36
+ const clientSignal = args.clientSignal;
37
+ if (clientSignal?.aborted) {
38
+ abort();
39
+ } else {
40
+ clientSignal?.addEventListener("abort", abort, { once: true });
41
+ }
42
+
43
+ return {
44
+ signal: controller.signal,
45
+ get aborted() {
46
+ return controller.signal.aborted;
47
+ },
48
+ abort,
49
+ dispose() {
50
+ clientSignal?.removeEventListener("abort", abort);
51
+ },
52
+ };
53
+ }
54
+
55
+ export function customerCanceledProviderMessage(
56
+ usage?: Record<string, unknown>,
57
+ responseId?: string,
58
+ ): Record<string, unknown> {
59
+ return {
60
+ stopReason: "aborted",
61
+ errorMessage: CUSTOMER_DISCONNECTED_MESSAGE,
62
+ content: [],
63
+ ...(usage ? { usage, usage_estimated: usage.estimated === true } : {}),
64
+ ...(responseId ? { responseId } : {}),
65
+ };
66
+ }
@@ -0,0 +1,86 @@
1
+ import type { RoutingCandidate, RoutingDecision } from "@mupt-ai/dari-router/policy-engine";
2
+
3
+ import { HttpError } from "../http/errors";
4
+ import { explicitModelId } from "../protocol/input/router_model";
5
+ import type { RoutedDecision } from "../strategies/route_decision";
6
+ import type { PreparedRoutedCompletion } from "./prepare_routed_completion";
7
+
8
+ /* A request for `dari/model/<id>` is served by exactly that enabled model,
9
+ with no selector, lease, or fallback: the user chose it, like picking a
10
+ model in their agent's /model menu. The client's thinking level is kept
11
+ when the model supports it; otherwise the model's default level is used. */
12
+ export function explicitModelDecision(
13
+ prepared: PreparedRoutedCompletion,
14
+ ): RoutedDecision | null {
15
+ const modelId = explicitModelId(prepared.interaction.model);
16
+ if (modelId === null) return null;
17
+ if (!prepared.credentials.enabled_models.includes(modelId)) {
18
+ throw new HttpError(
19
+ 400,
20
+ `Model '${modelId}' is not enabled on this router.`,
21
+ "model_not_enabled",
22
+ "model",
23
+ );
24
+ }
25
+ const candidates = prepared.routing.candidateResolution.candidates.filter(
26
+ (candidate) => candidate.model === modelId,
27
+ );
28
+ if (candidates.length === 0) {
29
+ throw new HttpError(
30
+ 400,
31
+ `Model '${modelId}' cannot serve this request.`,
32
+ "model_unavailable",
33
+ "model",
34
+ );
35
+ }
36
+ const candidate = pickCandidate(prepared, modelId, candidates);
37
+ const decision: RoutingDecision = {
38
+ selectedModel: candidate.model,
39
+ reasoningEffort: candidate.reasoningEffort,
40
+ reason: `Requested model ${modelId} served without selection.`,
41
+ };
42
+ return { decision };
43
+ }
44
+
45
+ function pickCandidate(
46
+ prepared: PreparedRoutedCompletion,
47
+ modelId: string,
48
+ candidates: RoutingCandidate[],
49
+ ): RoutingCandidate {
50
+ const preferred = [
51
+ prepared.interaction.reasoning?.effort,
52
+ prepared.credentials.model_configs?.[modelId]?.default_thinking_level,
53
+ ];
54
+ for (const effort of preferred) {
55
+ const match = candidates.find((candidate) => candidate.reasoningEffort === effort);
56
+ if (match) return match;
57
+ }
58
+ return candidates[0]!;
59
+ }
60
+
61
+ /* A strict router serves only the pinned `dari/model/<id>` at exactly the
62
+ requested thinking level (the model's default when none is sent), and
63
+ refuses everything else instead of substituting. */
64
+ export function strictModelDecision(prepared: PreparedRoutedCompletion): RoutedDecision {
65
+ const modelId = explicitModelId(prepared.interaction.model);
66
+ if (modelId === null) {
67
+ throw new HttpError(
68
+ 400,
69
+ "This router is strict: request a pinned model as 'dari/model/<id>'.",
70
+ "strict_model_required",
71
+ "model",
72
+ );
73
+ }
74
+ const { decision } = explicitModelDecision(prepared)!;
75
+ const requested = prepared.interaction.reasoning?.effort
76
+ ?? prepared.credentials.model_configs?.[modelId]?.default_thinking_level;
77
+ if (requested !== undefined && requested !== null && decision.reasoningEffort !== requested) {
78
+ throw new HttpError(
79
+ 400,
80
+ `Model '${modelId}' cannot serve thinking level '${requested}' on this router.`,
81
+ "thinking_level_unavailable",
82
+ "reasoning_effort",
83
+ );
84
+ }
85
+ return { decision };
86
+ }
@@ -0,0 +1,87 @@
1
+ import { createHash } from "node:crypto";
2
+
3
+ import type { SourceProtocol } from "../../interaction/types";
4
+
5
+ export type HarnessConversationIdentity =
6
+ | {
7
+ kind: "codex_thread";
8
+ value: string;
9
+ parentThreadId?: string;
10
+ qualifiers?: string[];
11
+ userTurnId?: string;
12
+ }
13
+ | {
14
+ kind: "claude_code_session";
15
+ value: string;
16
+ qualifiers?: string[];
17
+ }
18
+ | {
19
+ kind: "openai_chat_session";
20
+ value: string;
21
+ qualifiers?: string[];
22
+ };
23
+
24
+ export type HarnessConversationScope = {
25
+ organizationId: string;
26
+ routerId: string;
27
+ apiKeyId: string | null;
28
+ attributedUserId: string | null;
29
+ };
30
+
31
+ const PREFIX = "hconv_";
32
+ // The conversation id is the fallback provider prompt_cache_key for callers
33
+ // that send none (Codex sends thread metadata, not a cache key). OpenAI rejects
34
+ // a prompt_cache_key longer than 64 characters, so the id must fit that budget.
35
+ const MAX_CONVERSATION_ID_CHARS = 64;
36
+ const DIGEST_CHARS = MAX_CONVERSATION_ID_CHARS - PREFIX.length;
37
+
38
+ export function scopedHarnessSessionId(args: {
39
+ identity: HarnessConversationIdentity;
40
+ sourceProtocol: SourceProtocol;
41
+ scope: HarnessConversationScope;
42
+ }): string {
43
+ const identity = args.identity.kind === "codex_thread" && args.identity.parentThreadId
44
+ ? { ...args.identity, value: args.identity.parentThreadId }
45
+ : args.identity;
46
+ return scopedHarnessId({ ...args, identity });
47
+ }
48
+
49
+ export function scopedHarnessConversationId(args: {
50
+ identity: HarnessConversationIdentity;
51
+ sourceProtocol: SourceProtocol;
52
+ scope: HarnessConversationScope;
53
+ conversationPrefix: string;
54
+ }): string {
55
+ return scopedHarnessId(args, args.conversationPrefix);
56
+ }
57
+
58
+ function scopedHarnessId(
59
+ args: {
60
+ identity: HarnessConversationIdentity;
61
+ sourceProtocol: SourceProtocol;
62
+ scope: HarnessConversationScope;
63
+ },
64
+ conversationPrefix?: string,
65
+ ): string {
66
+ const subject = args.scope.apiKeyId !== null
67
+ ? ["api_key", args.scope.apiKeyId]
68
+ : args.scope.attributedUserId !== null
69
+ ? ["user", args.scope.attributedUserId]
70
+ : ["organization_runtime", args.scope.organizationId];
71
+ const identity = [
72
+ args.identity.kind,
73
+ args.identity.value,
74
+ ...(args.identity.qualifiers ?? []),
75
+ ];
76
+ const digest = createHash("sha256")
77
+ .update(JSON.stringify([
78
+ args.scope.organizationId,
79
+ args.scope.routerId,
80
+ subject,
81
+ args.sourceProtocol,
82
+ ...identity,
83
+ ...(conversationPrefix === undefined ? [] : [conversationPrefix]),
84
+ ]))
85
+ .digest("hex");
86
+ return `${PREFIX}${digest.slice(0, DIGEST_CHARS)}`;
87
+ }
@@ -0,0 +1,323 @@
1
+ import { isRecord } from "@mupt-ai/dari-router/policy-engine";
2
+
3
+ import { HttpError } from "../../http/errors";
4
+ import type {
5
+ AgentRequestClass,
6
+ AgentRequestContext,
7
+ InteractionRequestPurpose,
8
+ } from "../../interaction/types";
9
+ import type { HarnessConversationIdentity } from "./conversation";
10
+
11
+ const MAX_ID_CHARS = 200;
12
+
13
+ export function chatCompletionsConversationIdentity(
14
+ headers: Headers,
15
+ promptCacheKey?: string,
16
+ ): HarnessConversationIdentity | undefined {
17
+ // x-session-affinity is the authoritative Chat Completions identity.
18
+ // Fall back to prompt_cache_key from the request body for callers that
19
+ // send a stable cache key without the affinity header, so append-only
20
+ // sessions (growing message history) stay grouped under one conversation.
21
+ const sessionId = boundedIdentity(
22
+ headers.get("x-session-affinity"),
23
+ "x-session-affinity",
24
+ ) ?? boundedIdentity(promptCacheKey, "prompt_cache_key");
25
+ if (sessionId === undefined) return undefined;
26
+ // OpenCode sends a subagent's parent session as its affinity, so subagents
27
+ // share the parent's session. Scope each one to its own composite identity,
28
+ // as Claude Code subagents are, so it keeps its own conversation and lease.
29
+ const subagentId = openCodeSubagentId(headers);
30
+ return {
31
+ kind: "openai_chat_session",
32
+ value: sessionId,
33
+ ...(subagentId === undefined ? {} : { qualifiers: [subagentId] }),
34
+ };
35
+ }
36
+
37
+ // OpenCode names the session behind every request, and a subagent's parent
38
+ // session too. The `dari opencode` plugin adds the request kind and agent,
39
+ // which OpenCode does not send itself. Like Claude Code's headers, these are
40
+ // client-supplied routing hints, never inferred from prompt text.
41
+ export function openCodeRequestContext(headers: Headers): AgentRequestContext | undefined {
42
+ if (boundedIdentity(headers.get("x-opencode-session-id"), "x-opencode-session-id") === undefined) {
43
+ return undefined;
44
+ }
45
+ const kind = headers.get("x-opencode-request-kind")?.trim();
46
+ const subagentId = openCodeSubagentId(headers);
47
+ const requestClass: AgentRequestClass = kind === "compaction" ? "compaction"
48
+ : kind === "title" || kind === "generate" ? "auxiliary"
49
+ : subagentId === undefined ? "main" : "subagent";
50
+ return {
51
+ requestClass,
52
+ ...(subagentId === undefined ? {} : {
53
+ agentId: subagentId,
54
+ parentAgentId: boundedIdentity(
55
+ headers.get("x-opencode-parent-session-id"),
56
+ "x-opencode-parent-session-id",
57
+ ),
58
+ }),
59
+ agentType: boundedIdentity(headers.get("x-opencode-agent"), "x-opencode-agent"),
60
+ };
61
+ }
62
+
63
+ function openCodeSubagentId(headers: Headers): string | undefined {
64
+ const parent = boundedIdentity(
65
+ headers.get("x-opencode-parent-session-id"),
66
+ "x-opencode-parent-session-id",
67
+ );
68
+ return parent === undefined
69
+ ? undefined
70
+ : boundedIdentity(headers.get("x-opencode-session-id"), "x-opencode-session-id");
71
+ }
72
+
73
+ export function codexConversationIdentity(
74
+ headers: Headers,
75
+ payload: Record<string, unknown>,
76
+ ): HarnessConversationIdentity | undefined {
77
+ const clientMetadata = isRecord(payload.client_metadata)
78
+ ? payload.client_metadata
79
+ : undefined;
80
+ const turnMetadata = codexTurnMetadataCollection(headers, payload);
81
+ if (turnMetadata.length === 0) {
82
+ return undefined;
83
+ }
84
+ const candidates = [
85
+ ...turnMetadata.map((metadata) => uuidIdentity(
86
+ metadata.thread_id,
87
+ "x-codex-turn-metadata.thread_id",
88
+ )),
89
+ uuidIdentity(headers.get("thread-id"), "thread-id"),
90
+ uuidIdentity(clientMetadata?.thread_id, "client_metadata.thread_id"),
91
+ ].filter((value): value is string => value !== undefined);
92
+ if (candidates.length === 0) {
93
+ return undefined;
94
+ }
95
+ const [threadId] = candidates;
96
+ if (candidates.some((candidate) => candidate !== threadId)) {
97
+ throw new HttpError(
98
+ 400,
99
+ "Codex thread identity fields must agree.",
100
+ "invalid_request_error",
101
+ "thread-id",
102
+ );
103
+ }
104
+ const userTurnIds = turnMetadata
105
+ .map((metadata) => uuidIdentity(
106
+ metadata.turn_id,
107
+ "x-codex-turn-metadata.turn_id",
108
+ ))
109
+ .filter((value): value is string => value !== undefined);
110
+ const [userTurnId] = userTurnIds;
111
+ if (userTurnIds.some((candidate) => candidate !== userTurnId)) {
112
+ throw new HttpError(
113
+ 400,
114
+ "Codex turn identity fields must agree.",
115
+ "invalid_request_error",
116
+ "x-codex-turn-metadata.turn_id",
117
+ );
118
+ }
119
+ const parentThreadIds = turnMetadata
120
+ .map((metadata) => uuidIdentity(metadata.parent_thread_id,
121
+ "x-codex-turn-metadata.parent_thread_id"))
122
+ .filter((value): value is string => value !== undefined);
123
+ const [parentThreadId] = parentThreadIds;
124
+ if (parentThreadIds.some((candidate) => candidate !== parentThreadId)) {
125
+ throw new HttpError(400, "Codex parent thread identity fields must agree.",
126
+ "invalid_request_error", "x-codex-turn-metadata.parent_thread_id");
127
+ }
128
+ return {
129
+ kind: "codex_thread",
130
+ value: threadId,
131
+ ...(parentThreadId === undefined ? {} : { parentThreadId }),
132
+ ...(userTurnId === undefined ? {} : { userTurnId }),
133
+ };
134
+ }
135
+
136
+ export function codexRequestPurpose(
137
+ headers: Headers,
138
+ payload: Record<string, unknown>,
139
+ ): InteractionRequestPurpose | undefined {
140
+ const turnMetadata = codexTurnMetadataCollection(headers, payload);
141
+ return turnMetadata.length > 0 && turnMetadata.every(isCodexMemoryExtraction)
142
+ ? "memory_extraction"
143
+ : undefined;
144
+ }
145
+
146
+ export function codexRequestContext(
147
+ headers: Headers,
148
+ payload: Record<string, unknown>,
149
+ ): AgentRequestContext | undefined {
150
+ const metadata = codexTurnMetadataCollection(headers, payload);
151
+ if (metadata.length === 0) return undefined;
152
+ // HTTP and body projections must agree before either can classify a turn.
153
+ const kinds = new Set(metadata.map((entry) => entry.request_kind));
154
+ const agents = new Set(metadata.map((entry) => entry.subagent_kind));
155
+ if (kinds.size > 1 || agents.size > 1) {
156
+ throw new HttpError(400, "Codex request classification fields must agree.",
157
+ "invalid_request_error", "x-codex-turn-metadata");
158
+ }
159
+ const [kind] = kinds;
160
+ const [agentKind] = agents;
161
+ const entry = metadata[0]!;
162
+ const agentId = uuidIdentity(entry.thread_id, "x-codex-turn-metadata.thread_id");
163
+ const requestClass = kind === "compaction" ? "compaction"
164
+ : kind === "memory" || kind === "prewarm" ? "auxiliary"
165
+ : kind === "turn" && agentKind === "memory_consolidation" ? "auxiliary"
166
+ : kind === "turn" && agentKind === "compact" ? "compaction"
167
+ : kind === "turn" && agentKind !== undefined ? "subagent"
168
+ : kind === "turn" ? "main" : "unknown";
169
+ return {
170
+ requestClass,
171
+ ...(requestClass === "subagent" && agentId !== undefined ? { agentId } : {}),
172
+ parentAgentId: uuidIdentity(entry.parent_thread_id, "x-codex-turn-metadata.parent_thread_id"),
173
+ agentType: boundedIdentity(agentKind, "x-codex-turn-metadata.subagent_kind"),
174
+ };
175
+ }
176
+
177
+ export function claudeCodeConversationIdentity(
178
+ headers: Headers,
179
+ metadataSessionId?: string,
180
+ ): HarnessConversationIdentity | undefined {
181
+ const candidates = [
182
+ uuidIdentity(
183
+ headers.get("x-claude-code-session-id"),
184
+ "x-claude-code-session-id",
185
+ ),
186
+ uuidIdentity(
187
+ metadataSessionId,
188
+ "metadata.user_id.session_id",
189
+ ),
190
+ ].filter((value): value is string => value !== undefined);
191
+ if (candidates.length === 0) return undefined;
192
+ const [sessionId] = candidates;
193
+ if (candidates.some((candidate) => candidate !== sessionId)) {
194
+ throw new HttpError(
195
+ 400,
196
+ "Claude Code session identity fields must agree.",
197
+ "invalid_request_error",
198
+ "x-claude-code-session-id",
199
+ );
200
+ }
201
+ // Claude Code reuses the parent session UUID for every subagent, but gives
202
+ // each subagent a stable agent header. Keep the parent thread on the bare
203
+ // session identity and scope each subagent to its own composite identity.
204
+ // Treat this as an opaque Claude identifier. Besides ordinary subagent IDs,
205
+ // Claude may send labeled agents or Agent Teams identities such as
206
+ // `reviewer@backend`; Dari only needs a stable, bounded value to hash.
207
+ const agentId = boundedIdentity(
208
+ headers.get("x-claude-code-agent-id"),
209
+ "x-claude-code-agent-id",
210
+ );
211
+ return {
212
+ kind: "claude_code_session",
213
+ value: sessionId,
214
+ ...(agentId === undefined ? {} : { qualifiers: [agentId] }),
215
+ };
216
+ }
217
+
218
+ function isCodexMemoryExtraction(
219
+ metadata: Record<string, unknown>,
220
+ ): boolean {
221
+ if (
222
+ metadata.request_kind !== "memory" ||
223
+ metadata.thread_source !== "memory_consolidation"
224
+ ) {
225
+ return false;
226
+ }
227
+ // Codex deliberately omits canonical turn identity for detached phase-1
228
+ // memory jobs, while compatibility projections still carry the live root
229
+ // thread UUID. Phase-2 consolidation agents use ordinary turn metadata and
230
+ // their own thread identities, so they do not match this shape.
231
+ return [
232
+ "session_id",
233
+ "thread_id",
234
+ "turn_id",
235
+ "root_turn_id",
236
+ "window_id",
237
+ "forked_from_thread_id",
238
+ ].every((field) => metadata[field] === undefined);
239
+ }
240
+
241
+ function codexTurnMetadataCollection(
242
+ headers: Headers,
243
+ payload: Record<string, unknown>,
244
+ ): Record<string, unknown>[] {
245
+ const clientMetadata = isRecord(payload.client_metadata)
246
+ ? payload.client_metadata
247
+ : undefined;
248
+ return [
249
+ codexTurnMetadata(
250
+ headers.get("x-codex-turn-metadata"),
251
+ "x-codex-turn-metadata",
252
+ ),
253
+ codexTurnMetadata(
254
+ clientMetadata?.["x-codex-turn-metadata"],
255
+ "client_metadata.x-codex-turn-metadata",
256
+ ),
257
+ ].filter((value): value is Record<string, unknown> => value !== undefined);
258
+ }
259
+
260
+ function boundedIdentity(value: unknown, field: string): string | undefined {
261
+ if (value === undefined || value === null) return undefined;
262
+ if (typeof value !== "string") {
263
+ throw new HttpError(
264
+ 400,
265
+ `${field} must be a string.`,
266
+ "invalid_request_error",
267
+ field,
268
+ );
269
+ }
270
+ const normalized = value.trim();
271
+ if (!normalized) return undefined;
272
+ if (normalized.length > MAX_ID_CHARS) {
273
+ throw new HttpError(
274
+ 400,
275
+ `${field} must not exceed ${MAX_ID_CHARS} characters.`,
276
+ "invalid_request_error",
277
+ field,
278
+ );
279
+ }
280
+ return normalized;
281
+ }
282
+
283
+ function uuidIdentity(value: unknown, field: string): string | undefined {
284
+ const normalized = boundedIdentity(value, field);
285
+ if (normalized === undefined) return undefined;
286
+ const canonical = normalized.toLowerCase();
287
+ if (!/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(canonical)) {
288
+ throw new HttpError(
289
+ 400,
290
+ `${field} must be a UUID.`,
291
+ "invalid_request_error",
292
+ field,
293
+ );
294
+ }
295
+ return canonical;
296
+ }
297
+
298
+ function codexTurnMetadata(
299
+ raw: unknown,
300
+ field: string,
301
+ ): Record<string, unknown> | undefined {
302
+ if (raw === undefined || raw === null) return undefined;
303
+ if (typeof raw !== "string") {
304
+ throw new HttpError(
305
+ 400,
306
+ `${field} must be a JSON string.`,
307
+ "invalid_request_error",
308
+ field,
309
+ );
310
+ }
311
+ try {
312
+ const parsed: unknown = JSON.parse(raw);
313
+ if (!isRecord(parsed)) throw new Error("not an object");
314
+ return parsed;
315
+ } catch {
316
+ throw new HttpError(
317
+ 400,
318
+ `${field} must contain a JSON object.`,
319
+ "invalid_request_error",
320
+ field,
321
+ );
322
+ }
323
+ }
@@ -0,0 +1,14 @@
1
+ export {
2
+ scopedHarnessConversationId,
3
+ scopedHarnessSessionId,
4
+ type HarnessConversationIdentity,
5
+ type HarnessConversationScope,
6
+ } from "./conversation";
7
+ export {
8
+ chatCompletionsConversationIdentity,
9
+ claudeCodeConversationIdentity,
10
+ codexConversationIdentity,
11
+ codexRequestPurpose,
12
+ codexRequestContext,
13
+ openCodeRequestContext,
14
+ } from "./extract";