@mupt-ai/dari-gateway 1.0.306 → 1.0.307

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 (49) hide show
  1. package/README.md +2 -0
  2. package/dari-gateway.example.yaml +4 -0
  3. package/dist/context/interaction_fingerprint.js +3 -2
  4. package/dist/context/interaction_lease_depth.js +1 -1
  5. package/dist/context/routing_context.js +16 -2
  6. package/dist/ingress/anthropic_messages.js +14 -3
  7. package/dist/ingress/codex_models.d.ts +1 -1
  8. package/dist/ingress/codex_models.js +5 -2
  9. package/dist/ingress/models.js +3 -2
  10. package/dist/interaction/types.d.ts +12 -2
  11. package/dist/protocol/input/openai_responses.js +2 -2
  12. package/dist/protocol/output/anthropic_messages_output.js +3 -0
  13. package/dist/protocol/output/openai_responses_output.js +2 -0
  14. package/dist/protocol/output/openai_responses_stream.js +8 -5
  15. package/dist/providers/anthropic_safeguards.d.ts +3 -1
  16. package/dist/providers/anthropic_safeguards.js +17 -0
  17. package/dist/providers/model_capabilities.d.ts +1 -0
  18. package/dist/providers/model_capabilities.js +4 -0
  19. package/dist/providers/pi_context.js +13 -0
  20. package/dist/providers/pi_options.js +10 -1
  21. package/dist/providers/pi_output.js +2 -0
  22. package/dist/self_host/config.d.ts +2 -0
  23. package/dist/self_host/config.js +1 -0
  24. package/dist/self_host/resolve.js +1 -0
  25. package/dist/strategies/selector_projection.js +1 -1
  26. package/dist/telemetry/requests/interaction_observability.js +1 -1
  27. package/dist/types.d.ts +1 -0
  28. package/package.json +2 -2
  29. package/src/context/interaction_fingerprint.ts +3 -2
  30. package/src/context/interaction_lease_depth.ts +1 -1
  31. package/src/context/routing_context.ts +34 -1
  32. package/src/ingress/anthropic_messages.ts +20 -4
  33. package/src/ingress/codex_models.ts +7 -3
  34. package/src/ingress/models.ts +3 -2
  35. package/src/interaction/types.ts +19 -0
  36. package/src/protocol/input/openai_responses.ts +1 -2
  37. package/src/protocol/output/anthropic_messages_output.ts +2 -0
  38. package/src/protocol/output/openai_responses_output.ts +1 -0
  39. package/src/protocol/output/openai_responses_stream.ts +8 -6
  40. package/src/providers/anthropic_safeguards.ts +28 -1
  41. package/src/providers/model_capabilities.ts +5 -0
  42. package/src/providers/pi_context.ts +13 -0
  43. package/src/providers/pi_options.ts +15 -1
  44. package/src/providers/pi_output.ts +1 -0
  45. package/src/self_host/config.ts +3 -0
  46. package/src/self_host/resolve.ts +1 -0
  47. package/src/strategies/selector_projection.ts +1 -1
  48. package/src/telemetry/requests/interaction_observability.ts +1 -1
  49. package/src/types.ts +4 -0
package/README.md CHANGED
@@ -82,6 +82,7 @@ routers:
82
82
  codex: [openai/gpt-6.1-sol, openai/gpt-6.1-terra]
83
83
  subscriptions: true # prefer connected subscriptions over API keys
84
84
  sessionPinning: false # route each session and subagent once, then keep its model
85
+ nativeCompaction: false # let Codex compact server-side; compacted requests route only to supporting models
85
86
  local: # serves /local/v1/...
86
87
  models: [local/qwen3-coder]
87
88
 
@@ -129,6 +130,7 @@ Platforms can also:
129
130
  - implement `resolveProviderCredential({ provider, model, routerId, organizationId, apiKey, clientHarness? })` to supply a per-request `{ apiKey, baseUrl?, headers?, subscription? }`, such as a tenant's own key, in place of the router's resolved key. With `subscription` (`"openai_codex"`, `"anthropic_claude_code"`, or `"meta_muse"`), `apiKey` is that plan's access token: Codex's `auth.json` `tokens.access_token`, the token `claude setup-token` prints, or the Model API key a Meta sign-in mints. The platform keeps it fresh. Strict routers serve these supplied plans, but never subscriptions the gateway resolved itself. A plan serves only its own provider's models; a Claude Code plan serves only Claude Code clients, and a Muse Code plan only Muse Code clients (recognized by their `x-client-id`);
130
131
  - resolve routers with `strict: true` to serve only the requested `dari/model/<id>` at the requested thinking level, with no selector, lease, or personal subscription. Set `strict_providers: ["openai"]` on the resolved router to permit any bundled-catalog model from that provider without enumerating `enabled_models`. Use `dari/model/openai/gpt-6.1-sol`; bare IDs and unknown models remain refused. This grant is ignored on non-strict routers and does not discover uncatalogued models;
131
132
  - resolve routers with `session_pinning: true` to route each session once and serve that pair for the rest of the session. Each subagent (Claude Code agent id, Codex subagent thread, OpenCode child session) is routed once on its own. Pins are kept through `readSessionPin` and `writeSessionPin`, keyed by router and an opaque pin key; background requests and `dari/model/<id>` requests never use them;
133
+ - resolve routers with `native_compaction: true` to let Codex compact context server-side with the provider's native compaction. Requests carrying compaction state are routed only to models that support it;
132
134
  - read exact usage from `recordRequest`: the summary carries input, output, cache-read, and cache-write tokens and `total_cost_usd`, preferring the provider's billed cost (`cost_source: "provider"`, from OpenRouter and Vercel AI Gateway). Each record also carries the router's non-secret routing settings as `router` (enabled models, thinking levels, and the strict, speculative-routing, and session-pinning flags). Failed and aborted requests are recorded too;
133
135
  - attribute cost with `X-Dari-Tags: run=r1,trial=3`, which is parsed into `RequestRecord.tags` and the `recordUsage` payload's `tags`.
134
136
 
@@ -21,6 +21,10 @@ routers:
21
21
  # Route each session's first turn, then keep that model for the whole
22
22
  # session; each subagent is routed once on its own (default false).
23
23
  sessionPinning: false
24
+ # Let Codex compact context server-side with the provider's native
25
+ # compaction; requests carrying compaction state are routed only to
26
+ # models that support it (default false).
27
+ nativeCompaction: false
24
28
 
25
29
  local:
26
30
  models:
@@ -229,9 +229,10 @@ function fingerprintChatInputSteps(items, target, toolCallApi, policy) {
229
229
  pendingReasoningItemIndex = -1;
230
230
  continue;
231
231
  }
232
- if (item.type === "reasoning_configuration") {
232
+ if (item.type === "reasoning_configuration" || item.type === "compaction") {
233
233
  // Configuration updates change execution effort without becoming part
234
234
  // of the conversational identity, just like request-level effort.
235
+ // Native compaction state is opaque and replaced on every compaction.
235
236
  flushReasoning();
236
237
  continue;
237
238
  }
@@ -298,7 +299,7 @@ function fingerprintSteps(items, target, toolCallApi, policy) {
298
299
  });
299
300
  continue;
300
301
  }
301
- if (item.type === "reasoning_configuration") {
302
+ if (item.type === "reasoning_configuration" || item.type === "compaction") {
302
303
  continue;
303
304
  }
304
305
  if (item.type === "tool_result") {
@@ -40,7 +40,7 @@ export function interactionLeaseFenceDepth(request) {
40
40
  }
41
41
  continue;
42
42
  }
43
- if (item.type === "reasoning_configuration") {
43
+ if (item.type === "reasoning_configuration" || item.type === "compaction") {
44
44
  continue;
45
45
  }
46
46
  if (item.type === "tool_result") {
@@ -9,7 +9,7 @@ import { isBackgroundRequest } from "../interaction/types.js";
9
9
  import { requireCandidateModels } from "../models/ids.js";
10
10
  import { explicitModelId } from "../protocol/input/router_model.js";
11
11
  import { modelMetadataLookup } from "../providers/pi.js";
12
- import { modelSupportsDocumentInput, modelSupportsImageInput, modelSupportsHostedWebSearch, modelSupportsReasoningConfigurationUpdate, providerApiCanSerializeResponseFormat, } from "../providers/model_capabilities.js";
12
+ import { modelSupportsDocumentInput, modelSupportsImageInput, modelSupportsHostedWebSearch, modelSupportsNativeCompaction, modelSupportsReasoningConfigurationUpdate, providerApiCanSerializeResponseFormat, } from "../providers/model_capabilities.js";
13
13
  import { selectorMessagesForInteraction, } from "../strategies/selector_projection.js";
14
14
  import { interactionPrefixContext, interactionPrefixLookupHashes, } from "./interaction_fingerprint.js";
15
15
  import { pricingLookupForRouter } from "./pricing.js";
@@ -83,7 +83,7 @@ export async function buildRoutingContext(args) {
83
83
  const prefixHits = (background ? [] : args.credentials.prefix_hits ?? []).filter((hit) => args.explicitConversationId === undefined
84
84
  || hit.conversation_id === args.explicitConversationId);
85
85
  const prepared = prepareCandidates({
86
- candidateModels: documentCapableModels,
86
+ candidateModels: nativeCompactionCandidates(documentCapableModels, args.interaction, args.credentials.native_compaction === true, (model) => modelSupportsNativeCompaction(metadataLookup(model))),
87
87
  metadataLookup: capabilityLookup,
88
88
  requiredCapabilities: imageFilter.requiredCapabilities,
89
89
  requestedReasoningEffort: args.interaction.reasoning?.effort,
@@ -208,6 +208,20 @@ function documentCapableCandidates(candidateModels, hasDocument, supportsDocumen
208
208
  }
209
209
  return capable;
210
210
  }
211
+ // Native compaction state is opaque to every provider but OpenAI, so a
212
+ // conversation carrying it routes only among models that can read it.
213
+ function nativeCompactionCandidates(candidateModels, interaction, enabled, supportsNativeCompaction) {
214
+ if (!interaction.items.some((item) => item.type === "compaction"))
215
+ return candidateModels;
216
+ if (!enabled) {
217
+ throw new HttpError(400, "This conversation contains native compaction state, but native compaction is disabled on this router.", "native_compaction_disabled");
218
+ }
219
+ const capable = candidateModels.filter(supportsNativeCompaction);
220
+ if (capable.length === 0) {
221
+ throw new HttpError(400, "This conversation contains native compaction state, but no enabled model on this router supports native compaction.", "no_native_compaction_candidates");
222
+ }
223
+ return capable;
224
+ }
211
225
  function derivePrefixContext(args) {
212
226
  try {
213
227
  return interactionPrefixContext(args.routerId, args.interaction, args.targetsByModel);
@@ -13,6 +13,7 @@ import { claudeCodeConversationIdentity, } from "../runtime/harness_identity/ind
13
13
  import { parseJsonRequest } from "./json.js";
14
14
  const LEGACY_CLAUDE_CODE_BETA = "claude-code-20250219";
15
15
  const SAFEGUARDS_BETA_PREFIX = "dangerous-tool-use-";
16
+ const CONTEXT_MANAGEMENT_BETA_PREFIX = "context-management-";
16
17
  export async function handleAnthropicMessages(request, routerId, selectorBackend) {
17
18
  try {
18
19
  const apiKey = anthropicToken(request.headers);
@@ -20,9 +21,12 @@ export async function handleAnthropicMessages(request, routerId, selectorBackend
20
21
  const interaction = anthropicMessagesToInteraction(rawPayload);
21
22
  const isClaudeCode = isClaudeCodeRequest(request.headers);
22
23
  const anthropicSafeguards = safeguardsFrom(rawPayload, request.headers);
23
- const forwarded = anthropicSafeguards === undefined
24
- ? interaction
25
- : { ...interaction, anthropicSafeguards };
24
+ const anthropicContextManagement = contextManagementFrom(rawPayload, request.headers);
25
+ const forwarded = {
26
+ ...interaction,
27
+ ...(anthropicSafeguards === undefined ? {} : { anthropicSafeguards }),
28
+ ...(anthropicContextManagement === undefined ? {} : { anthropicContextManagement }),
29
+ };
26
30
  const payload = isClaudeCode
27
31
  ? {
28
32
  ...forwarded,
@@ -87,6 +91,13 @@ function safeguardsFrom(payload, headers) {
87
91
  const betas = [...anthropicBetas(headers)].filter((beta) => beta.startsWith(SAFEGUARDS_BETA_PREFIX));
88
92
  return betas.length === 0 ? undefined : { safeguards: payload.safeguards, betas };
89
93
  }
94
+ // Same pairing for server-side context editing.
95
+ function contextManagementFrom(payload, headers) {
96
+ if (!isRecord(payload.context_management))
97
+ return undefined;
98
+ const betas = [...anthropicBetas(headers)].filter((beta) => beta.startsWith(CONTEXT_MANAGEMENT_BETA_PREFIX));
99
+ return betas.length === 0 ? undefined : { contextManagement: payload.context_management, betas };
100
+ }
90
101
  function anthropicBetas(headers) {
91
102
  return new Set((headers.get("anthropic-beta") ?? "")
92
103
  .split(",")
@@ -1,2 +1,2 @@
1
1
  import type { ResolvedRouter } from "../types.js";
2
- export declare function codexModelsResponse(router: Pick<ResolvedRouter, "enabled_models" | "model_configs" | "allow_long_context" | "autorouting_enabled" | "routing_listed">, imageInputFor: (model: string) => boolean): Record<string, unknown>;
2
+ export declare function codexModelsResponse(router: Pick<ResolvedRouter, "enabled_models" | "model_configs" | "allow_long_context" | "autorouting_enabled" | "routing_listed" | "native_compaction">, imageInputFor: (model: string) => boolean, nativeCompactionFor?: (model: string) => boolean): Record<string, unknown>;
@@ -67,9 +67,12 @@ function codexCatalogEntry(args) {
67
67
  /* `dari/routing` comes first while the router may autoroute (the Codex
68
68
  launcher patches it); each enabled model follows as `dari/model/<id>` so
69
69
  Codex's /model menu can switch to it. The `dari` launchers build every
70
- agent's model menu from this list. */
71
- export function codexModelsResponse(router, imageInputFor) {
70
+ agent's model menu from this list. `remote_compaction` tells the
71
+ launcher which Codex provider compaction protocol the router accepts. */
72
+ export function codexModelsResponse(router, imageInputFor, nativeCompactionFor = () => false) {
73
+ const remoteCompaction = router.native_compaction === true && router.enabled_models.some(nativeCompactionFor);
72
74
  return {
75
+ remote_compaction: remoteCompaction ? "v2" : "unsupported",
73
76
  models: [
74
77
  ...(router.autorouting_enabled === false || router.routing_listed === false ? [] : [codexCatalogEntry({
75
78
  slug: CANONICAL_ROUTER_MODEL,
@@ -10,7 +10,7 @@ import { errorResponse } from "../http/errors.js";
10
10
  import { captureRequestError } from "../observability/errors.js";
11
11
  import { anthropicErrorResponse } from "./anthropic_messages.js";
12
12
  import { listModelCatalog } from "../models/catalog.js";
13
- import { modelSupportsImageInput } from "../providers/model_capabilities.js";
13
+ import { modelSupportsImageInput, modelSupportsNativeCompaction } from "../providers/model_capabilities.js";
14
14
  import { modelMetadataLookup } from "../providers/pi.js";
15
15
  import { resolveRouter } from "../strategies/routing.js";
16
16
  import { anthropicModelsResponse } from "./anthropic_models.js";
@@ -48,7 +48,8 @@ export async function handleModels(request, routerId) {
48
48
  }
49
49
  const metadataLookup = modelMetadataLookup(router.model_configs);
50
50
  const imageInputFor = (model) => modelSupportsImageInput(metadataLookup(model));
51
- return Response.json(codexModelsResponse(router, imageInputFor), {
51
+ const nativeCompactionFor = (model) => modelSupportsNativeCompaction(metadataLookup(model));
52
+ return Response.json(codexModelsResponse(router, imageInputFor, nativeCompactionFor), {
52
53
  headers: {
53
54
  "Cache-Control": "no-store",
54
55
  },
@@ -100,8 +100,13 @@ export type InteractionHostedToolCall = {
100
100
  serverToolInput?: Record<string, unknown>;
101
101
  serverToolResult?: InteractionToolReference[];
102
102
  };
103
- export type InteractionItem = InteractionMessage | InteractionReasoning | InteractionToolCall | InteractionToolResult | InteractionReasoningConfiguration | InteractionHostedToolCall;
104
- export type InteractionOutputItem = InteractionMessage | InteractionReasoning | InteractionToolCall | InteractionHostedToolCall;
103
+ export type InteractionCompaction = {
104
+ type: "compaction";
105
+ payload: Record<string, unknown>;
106
+ source?: ProviderIdentity;
107
+ };
108
+ export type InteractionItem = InteractionCompaction | InteractionMessage | InteractionReasoning | InteractionToolCall | InteractionToolResult | InteractionReasoningConfiguration | InteractionHostedToolCall;
109
+ export type InteractionOutputItem = InteractionCompaction | InteractionMessage | InteractionReasoning | InteractionToolCall | InteractionHostedToolCall;
105
110
  export type ServerToolKind = "bash_20250124" | "text_editor_20250124" | "tool_search_tool_20250919" | "tool_search_tool_regex_20250919" | "tool_search_tool_regex" | "tool_search_tool_regex_20251119" | "tool_search_tool_bm25" | "tool_search_tool_bm25_20251119";
106
111
  export type ClientTool = {
107
112
  kind: "client_tool";
@@ -162,6 +167,10 @@ export type AnthropicSafeguards = {
162
167
  safeguards: unknown[];
163
168
  betas: string[];
164
169
  };
170
+ export type AnthropicContextManagement = {
171
+ contextManagement: Record<string, unknown>;
172
+ betas: string[];
173
+ };
165
174
  export type InteractionRequest = {
166
175
  sourceProtocol: SourceProtocol;
167
176
  requestPurpose?: InteractionRequestPurpose;
@@ -169,6 +178,7 @@ export type InteractionRequest = {
169
178
  claudeCodeUserAgent?: string;
170
179
  museCodeClientId?: string;
171
180
  anthropicSafeguards?: AnthropicSafeguards;
181
+ anthropicContextManagement?: AnthropicContextManagement;
172
182
  model?: string;
173
183
  instructions?: string;
174
184
  items: InteractionItem[];
@@ -19,9 +19,7 @@ const UNSUPPORTED_INPUT_ITEM_TYPES = new Set([
19
19
  "local_shell_call_output",
20
20
  "tool_search_call",
21
21
  "tool_search_output",
22
- "compaction",
23
22
  "compaction_summary",
24
- "compaction_trigger",
25
23
  "context_compaction",
26
24
  ]);
27
25
  const CLIENT_TURN_ID_MAX_LENGTH = 200;
@@ -189,6 +187,8 @@ function responseItem(value, itemIndex, hostedReplayId) {
189
187
  if (UNSUPPORTED_INPUT_ITEM_TYPES.has(type)) {
190
188
  throw new HttpError(400, `Responses input item type '${type}' is not supported by this router MVP.`, "unsupported_response_item", "input");
191
189
  }
190
+ if (type === "compaction" || type === "compaction_trigger")
191
+ return { type: "compaction", payload: { ...value } };
192
192
  if (type === "reasoning")
193
193
  return reasoningItem(value);
194
194
  if (type === "configuration_update")
@@ -7,6 +7,9 @@ export function anthropicMessageId(requestId) {
7
7
  export function anthropicContent(output) {
8
8
  const content = [];
9
9
  for (const item of output.items) {
10
+ // Native compaction state is OpenAI Responses-only.
11
+ if (item.type === "compaction")
12
+ continue;
10
13
  if (item.type === "reasoning") {
11
14
  content.push(anthropicReasoningBlock(item));
12
15
  continue;
@@ -17,6 +17,8 @@ export function openAIResponsesOutputItem(output, item, index) {
17
17
  return responseReasoningItem(output, item, index);
18
18
  if (item.type === "hosted_tool_call")
19
19
  return responseHostedToolCallItem(item);
20
+ if (item.type === "compaction")
21
+ return item.payload;
20
22
  return responseToolCallItem(item);
21
23
  }
22
24
  export function openAIResponsesUsage(output) {
@@ -196,8 +196,8 @@ class ResponsesAccumulator {
196
196
  }
197
197
  if (type === "response.output_item.added" && isRecord(event.item)) {
198
198
  const index = providerOutputIndex(event);
199
- if (event.item.type === "web_search_call") {
200
- const item = providerHostedToolCall(event.item, this.args.source);
199
+ if (event.item.type === "web_search_call" || event.item.type === "compaction") {
200
+ const item = providerPassthroughItem(event.item, this.args.source);
201
201
  this.items.set(index, item);
202
202
  this.addedIndexes.add(index);
203
203
  send(type, providerEventPayload(event));
@@ -223,9 +223,9 @@ class ResponsesAccumulator {
223
223
  this.applyProviderMessageAnnotations(index, event.item);
224
224
  return;
225
225
  }
226
- if (event.item.type !== "web_search_call")
226
+ if (event.item.type !== "web_search_call" && event.item.type !== "compaction")
227
227
  return;
228
- this.items.set(index, providerHostedToolCall(event.item, this.args.source));
228
+ this.items.set(index, providerPassthroughItem(event.item, this.args.source));
229
229
  if (!this.addedIndexes.has(index)) {
230
230
  this.addedIndexes.add(index);
231
231
  send("response.output_item.added", { output_index: index, item: event.item });
@@ -492,7 +492,10 @@ function providerEventPayload(event) {
492
492
  const { type: _type, sequence_number: _sequenceNumber, ...payload } = event;
493
493
  return payload;
494
494
  }
495
- function providerHostedToolCall(item, source) {
495
+ // Provider output items the gateway relays verbatim instead of synthesizing.
496
+ function providerPassthroughItem(item, source) {
497
+ if (item.type === "compaction")
498
+ return { type: "compaction", payload: { ...item }, source };
496
499
  if (item.type !== "web_search_call" || typeof item.id !== "string" || !item.id) {
497
500
  throw new Error("OpenAI provider web search item is malformed.");
498
501
  }
@@ -1,6 +1,8 @@
1
- import type { AnthropicSafeguards, InteractionRequest } from "../interaction/types.js";
1
+ import type { AnthropicContextManagement, AnthropicSafeguards, InteractionRequest } from "../interaction/types.js";
2
2
  import type { ProviderFetch } from "./response_capture.js";
3
3
  export declare function forwardsAnthropicSafeguards(request: Pick<InteractionRequest, "anthropicSafeguards">, model: Record<string, unknown>): boolean;
4
+ export declare function forwardsAnthropicContextManagement(request: Pick<InteractionRequest, "anthropicContextManagement">, model: Record<string, unknown>): boolean;
5
+ export declare function payloadWithContextManagement(payload: Record<string, unknown>, contextManagement: AnthropicContextManagement): Record<string, unknown>;
4
6
  export declare function payloadWithSafeguards(payload: Record<string, unknown>, safeguards: AnthropicSafeguards): Record<string, unknown>;
5
7
  export type SafeguardResultsTap = {
6
8
  fetch: ProviderFetch;
@@ -10,6 +10,23 @@ export function forwardsAnthropicSafeguards(request, model) {
10
10
  model.provider === "anthropic" &&
11
11
  model.api === "anthropic-messages");
12
12
  }
13
+ // Claude Code's tool-result clearing (`context_management`) runs inside the
14
+ // Anthropic API. Only Anthropic's own Messages endpoint gets it; other
15
+ // providers serve the full history, as Claude Code expects when no
16
+ // `context_management` comes back.
17
+ export function forwardsAnthropicContextManagement(request, model) {
18
+ return (request.anthropicContextManagement !== undefined &&
19
+ model.provider === "anthropic" &&
20
+ model.api === "anthropic-messages");
21
+ }
22
+ export function payloadWithContextManagement(payload, contextManagement) {
23
+ const betas = Array.isArray(payload.betas) ? payload.betas : [];
24
+ return {
25
+ ...payload,
26
+ context_management: contextManagement.contextManagement,
27
+ betas: [...new Set([...betas, ...contextManagement.betas])],
28
+ };
29
+ }
13
30
  export function payloadWithSafeguards(payload, safeguards) {
14
31
  const betas = Array.isArray(payload.betas) ? payload.betas : [];
15
32
  return {
@@ -9,5 +9,6 @@ export declare function modelSupportsDocumentInput(modelId: string, metadata: Mo
9
9
  export declare function providerApiCanSerializeResponseFormat(metadata: ModelCapabilityMetadata): boolean;
10
10
  export declare function isOpenAIResponsesApi(api: unknown): boolean;
11
11
  export declare function modelSupportsReasoningConfigurationUpdate(metadata: ModelCapabilityMetadata): boolean;
12
+ export declare function modelSupportsNativeCompaction(metadata: ModelCapabilityMetadata): boolean;
12
13
  export declare function modelSupportsHostedWebSearch(metadata: ModelCapabilityMetadata): boolean;
13
14
  export {};
@@ -36,6 +36,10 @@ export function modelSupportsReasoningConfigurationUpdate(metadata) {
36
36
  return isRecord(metadata.model.compat)
37
37
  && metadata.model.compat.supportsReasoningConfigurationUpdate === true;
38
38
  }
39
+ // OpenAI's own Responses endpoints read and write native `compaction` items.
40
+ export function modelSupportsNativeCompaction(metadata) {
41
+ return modelSupportsHostedWebSearch(metadata);
42
+ }
39
43
  export function modelSupportsHostedWebSearch(metadata) {
40
44
  return ((metadata.model.provider === "openai" && metadata.model.api === "openai-responses")
41
45
  || (metadata.model.provider === "openai-codex"
@@ -146,6 +146,19 @@ export function buildContext(request, target) {
146
146
  toolCalls.set(item.callId, { id, name });
147
147
  continue;
148
148
  }
149
+ if (item.type === "compaction") {
150
+ // Routing narrows compaction-bearing requests to native-compaction targets.
151
+ if (!isOpenAIResponsesApi(target.api)) {
152
+ throw new HttpError(400, "Native compaction state can only be sent to OpenAI Responses models.", "unsupported_response_item", "input");
153
+ }
154
+ assistantFor(item.source ?? target).content.push({
155
+ type: "providerItem",
156
+ item: item.payload,
157
+ name: "providerItem",
158
+ arguments: item.payload,
159
+ });
160
+ continue;
161
+ }
149
162
  if (item.type === "hosted_tool_call") {
150
163
  if (item.tool === "server_tool_use" || item.tool === "tool_search") {
151
164
  // Server tool use and tool search results are Anthropic-specific.
@@ -5,7 +5,7 @@ import { gatewayFor, payloadWithGatewayFields } from "../models/gateways.js";
5
5
  import { offRequiresWireNone } from "../models/runtime_overrides.js";
6
6
  import { effectiveReasoningForModel, validateReasoningEffortForModel } from "./reasoning.js";
7
7
  import { isBedrockApi, isOpenAIResponsesApi } from "./model_capabilities.js";
8
- import { forwardsAnthropicSafeguards, payloadWithSafeguards } from "./anthropic_safeguards.js";
8
+ import { forwardsAnthropicContextManagement, forwardsAnthropicSafeguards, payloadWithContextManagement, payloadWithSafeguards, } from "./anthropic_safeguards.js";
9
9
  const ANTHROPIC_FAST_MODE_BETA = "fast-mode-2026-02-01";
10
10
  const ANTHROPIC_BINDING_CONTROLS_BETA = "thinking-binding-controls-2026-08-01";
11
11
  // Anthropic rejects newer models from older Claude Code versions, so forward
@@ -75,6 +75,15 @@ export function buildOptions(request, auth, selectedModel, model, pi, sessionId,
75
75
  if (safeguards !== undefined && forwardsAnthropicSafeguards(request, model)) {
76
76
  patches.push((payload) => payloadWithSafeguards(payload, safeguards));
77
77
  }
78
+ const contextManagement = request.anthropicContextManagement;
79
+ if (contextManagement !== undefined && forwardsAnthropicContextManagement(request, model)) {
80
+ patches.push((payload) => payloadWithContextManagement(payload, contextManagement));
81
+ }
82
+ // Pi keeps only the content it models, so native compaction output reaches
83
+ // the client from the provider's own output items.
84
+ if (isOpenAIResponsesApi(api) && request.items.some((item) => item.type === "compaction")) {
85
+ options.emitProviderEvents = true;
86
+ }
78
87
  if (isOpenAIResponsesApi(api) && requiredCapabilitiesFor(request).includes("openai_hosted_web_search")) {
79
88
  options.emitProviderEvents = true;
80
89
  const hosted = request.tools.flatMap((tool) => tool.kind === "hosted" ? [{ ...tool.config }] : []);
@@ -135,6 +135,8 @@ function openAIProviderResponseToInteractionOutput(response, message, source, re
135
135
  arguments: parsed,
136
136
  }, source, tools);
137
137
  }
138
+ if (value.type === "compaction")
139
+ return { type: "compaction", payload: { ...value }, source };
138
140
  if (value.type === "web_search_call") {
139
141
  return {
140
142
  type: "hosted_tool_call",
@@ -15,6 +15,7 @@ import type { ClientHarness } from "../types.js";
15
15
  * - openai/gpt-6.1-sol
16
16
  * subscriptions: true # serve with connected Claude Code / ChatGPT plans
17
17
  * sessionPinning: false # route each session and subagent once, then keep its model
18
+ * nativeCompaction: false # let Codex compact server-side with the provider's native compaction
18
19
  * providers: # optional: OpenAI-compatible or self-run endpoints
19
20
  * local:
20
21
  * baseUrl: http://localhost:8000/v1
@@ -42,6 +43,7 @@ export type RouterConfig = {
42
43
  retries: number;
43
44
  subscriptions: boolean;
44
45
  sessionPinning: boolean;
46
+ nativeCompaction: boolean;
45
47
  zdr: boolean;
46
48
  };
47
49
  export type RouterModelConfig = {
@@ -114,6 +114,7 @@ function parseRouter(id, raw) {
114
114
  retries: optionalRetries(raw.retries, `routers.${id}.retries`) ?? 1,
115
115
  subscriptions: optionalBoolean(raw.subscriptions, `routers.${id}.subscriptions`) ?? true,
116
116
  sessionPinning: optionalBoolean(raw.sessionPinning, `routers.${id}.sessionPinning`) ?? false,
117
+ nativeCompaction: optionalBoolean(raw.nativeCompaction, `routers.${id}.nativeCompaction`) ?? false,
117
118
  zdr: optionalBoolean(raw.zdr, `routers.${id}.zdr`) ?? false,
118
119
  };
119
120
  }
@@ -73,6 +73,7 @@ export async function resolveSelfHostedRouter(deps, request) {
73
73
  zdr: router.zdr,
74
74
  speculative_routing: false,
75
75
  session_pinning: router.sessionPinning,
76
+ native_compaction: router.nativeCompaction,
76
77
  primary_retries: router.retries,
77
78
  routing_strategy: "dari",
78
79
  custom_config: null,
@@ -50,7 +50,7 @@ export function selectorMessagesForInteraction(interaction, options = {}) {
50
50
  : selectorReasoning;
51
51
  continue;
52
52
  }
53
- if (item.type === "reasoning_configuration") {
53
+ if (item.type === "reasoning_configuration" || item.type === "compaction") {
54
54
  continue;
55
55
  }
56
56
  if (item.type === "tool_result") {
@@ -65,7 +65,7 @@ function interactionObservabilityMetadata(request) {
65
65
  addContentModalities(itemContentModalityCounts, item.output);
66
66
  continue;
67
67
  }
68
- if (item.type === "reasoning_configuration") {
68
+ if (item.type === "reasoning_configuration" || item.type === "compaction") {
69
69
  continue;
70
70
  }
71
71
  if (item.providerType === "tool_search_result") {
package/dist/types.d.ts CHANGED
@@ -78,6 +78,7 @@ export type ResolvedRouter = {
78
78
  allow_long_context?: boolean;
79
79
  speculative_routing?: boolean;
80
80
  session_pinning?: boolean;
81
+ native_compaction?: boolean;
81
82
  primary_retries?: number;
82
83
  strict?: boolean;
83
84
  strict_providers?: string[];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mupt-ai/dari-gateway",
3
- "version": "1.0.306",
3
+ "version": "1.0.307",
4
4
  "description": "Self-hostable LLM gateway for coding agents and APIs: one endpoint for Anthropic Messages, OpenAI Chat Completions, and OpenAI Responses, with subscription pooling, failover, and prompt-cache-aware routing.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -51,7 +51,7 @@
51
51
  },
52
52
  "dependencies": {
53
53
  "@aws-sdk/client-sts": "3.1063.0",
54
- "@mupt-ai/dari-router": "1.0.306",
54
+ "@mupt-ai/dari-router": "1.0.307",
55
55
  "@mupt-ai/pi-ai": "1.5.2-mupt.1"
56
56
  },
57
57
  "devDependencies": {
@@ -341,9 +341,10 @@ function fingerprintChatInputSteps(
341
341
  pendingReasoningItemIndex = -1;
342
342
  continue;
343
343
  }
344
- if (item.type === "reasoning_configuration") {
344
+ if (item.type === "reasoning_configuration" || item.type === "compaction") {
345
345
  // Configuration updates change execution effort without becoming part
346
346
  // of the conversational identity, just like request-level effort.
347
+ // Native compaction state is opaque and replaced on every compaction.
347
348
  flushReasoning();
348
349
  continue;
349
350
  }
@@ -424,7 +425,7 @@ function fingerprintSteps(
424
425
  });
425
426
  continue;
426
427
  }
427
- if (item.type === "reasoning_configuration") {
428
+ if (item.type === "reasoning_configuration" || item.type === "compaction") {
428
429
  continue;
429
430
  }
430
431
  if (item.type === "tool_result") {
@@ -71,7 +71,7 @@ export function interactionLeaseFenceDepth(
71
71
  continue;
72
72
  }
73
73
 
74
- if (item.type === "reasoning_configuration") {
74
+ if (item.type === "reasoning_configuration" || item.type === "compaction") {
75
75
  continue;
76
76
  }
77
77
 
@@ -30,6 +30,7 @@ import {
30
30
  modelSupportsDocumentInput,
31
31
  modelSupportsImageInput,
32
32
  modelSupportsHostedWebSearch,
33
+ modelSupportsNativeCompaction,
33
34
  modelSupportsReasoningConfigurationUpdate,
34
35
  providerApiCanSerializeResponseFormat,
35
36
  } from "../providers/model_capabilities.js";
@@ -180,7 +181,12 @@ export async function buildRoutingContext(args: {
180
181
  || hit.conversation_id === args.explicitConversationId,
181
182
  );
182
183
  const prepared = prepareCandidates({
183
- candidateModels: documentCapableModels,
184
+ candidateModels: nativeCompactionCandidates(
185
+ documentCapableModels,
186
+ args.interaction,
187
+ args.credentials.native_compaction === true,
188
+ (model) => modelSupportsNativeCompaction(metadataLookup(model)),
189
+ ),
184
190
  metadataLookup: capabilityLookup,
185
191
  requiredCapabilities: imageFilter.requiredCapabilities,
186
192
  requestedReasoningEffort: args.interaction.reasoning?.effort,
@@ -336,6 +342,33 @@ function documentCapableCandidates(
336
342
  return capable;
337
343
  }
338
344
 
345
+ // Native compaction state is opaque to every provider but OpenAI, so a
346
+ // conversation carrying it routes only among models that can read it.
347
+ function nativeCompactionCandidates(
348
+ candidateModels: string[],
349
+ interaction: InteractionRequest,
350
+ enabled: boolean,
351
+ supportsNativeCompaction: (model: string) => boolean,
352
+ ): string[] {
353
+ if (!interaction.items.some((item) => item.type === "compaction")) return candidateModels;
354
+ if (!enabled) {
355
+ throw new HttpError(
356
+ 400,
357
+ "This conversation contains native compaction state, but native compaction is disabled on this router.",
358
+ "native_compaction_disabled",
359
+ );
360
+ }
361
+ const capable = candidateModels.filter(supportsNativeCompaction);
362
+ if (capable.length === 0) {
363
+ throw new HttpError(
364
+ 400,
365
+ "This conversation contains native compaction state, but no enabled model on this router supports native compaction.",
366
+ "no_native_compaction_candidates",
367
+ );
368
+ }
369
+ return capable;
370
+ }
371
+
339
372
  function derivePrefixContext(args: {
340
373
  routerId: string;
341
374
  interaction: InteractionRequest;
@@ -14,7 +14,7 @@ import {
14
14
  claudeCodeConversationIdentity,
15
15
  } from "../runtime/harness_identity/index.js";
16
16
  import { parseJsonRequest } from "./json.js";
17
- import type { AnthropicSafeguards, ReasoningControls } from "../interaction/types.js";
17
+ import type { AnthropicContextManagement, AnthropicSafeguards, ReasoningControls } from "../interaction/types.js";
18
18
 
19
19
  type AnthropicErrorType =
20
20
  | "authentication_error"
@@ -26,6 +26,7 @@ type AnthropicErrorType =
26
26
 
27
27
  const LEGACY_CLAUDE_CODE_BETA = "claude-code-20250219";
28
28
  const SAFEGUARDS_BETA_PREFIX = "dangerous-tool-use-";
29
+ const CONTEXT_MANAGEMENT_BETA_PREFIX = "context-management-";
29
30
 
30
31
  export async function handleAnthropicMessages(
31
32
  request: Request,
@@ -38,9 +39,12 @@ export async function handleAnthropicMessages(
38
39
  const interaction = anthropicMessagesToInteraction(rawPayload);
39
40
  const isClaudeCode = isClaudeCodeRequest(request.headers);
40
41
  const anthropicSafeguards = safeguardsFrom(rawPayload, request.headers);
41
- const forwarded = anthropicSafeguards === undefined
42
- ? interaction
43
- : { ...interaction, anthropicSafeguards };
42
+ const anthropicContextManagement = contextManagementFrom(rawPayload, request.headers);
43
+ const forwarded = {
44
+ ...interaction,
45
+ ...(anthropicSafeguards === undefined ? {} : { anthropicSafeguards }),
46
+ ...(anthropicContextManagement === undefined ? {} : { anthropicContextManagement }),
47
+ };
44
48
  const payload = isClaudeCode
45
49
  ? {
46
50
  ...forwarded,
@@ -116,6 +120,18 @@ function safeguardsFrom(
116
120
  return betas.length === 0 ? undefined : { safeguards: payload.safeguards, betas };
117
121
  }
118
122
 
123
+ // Same pairing for server-side context editing.
124
+ function contextManagementFrom(
125
+ payload: Record<string, unknown>,
126
+ headers: Headers,
127
+ ): AnthropicContextManagement | undefined {
128
+ if (!isRecord(payload.context_management)) return undefined;
129
+ const betas = [...anthropicBetas(headers)].filter((beta) =>
130
+ beta.startsWith(CONTEXT_MANAGEMENT_BETA_PREFIX)
131
+ );
132
+ return betas.length === 0 ? undefined : { contextManagement: payload.context_management, betas };
133
+ }
134
+
119
135
  function anthropicBetas(headers: Headers): Set<string> {
120
136
  return new Set(
121
137
  (headers.get("anthropic-beta") ?? "")
@@ -88,12 +88,16 @@ function codexCatalogEntry(args: CodexCatalogEntry): Record<string, unknown> {
88
88
  /* `dari/routing` comes first while the router may autoroute (the Codex
89
89
  launcher patches it); each enabled model follows as `dari/model/<id>` so
90
90
  Codex's /model menu can switch to it. The `dari` launchers build every
91
- agent's model menu from this list. */
91
+ agent's model menu from this list. `remote_compaction` tells the
92
+ launcher which Codex provider compaction protocol the router accepts. */
92
93
  export function codexModelsResponse(
93
- router: Pick<ResolvedRouter, "enabled_models" | "model_configs" | "allow_long_context" | "autorouting_enabled" | "routing_listed">,
94
- imageInputFor: (model: string) => boolean
94
+ router: Pick<ResolvedRouter, "enabled_models" | "model_configs" | "allow_long_context" | "autorouting_enabled" | "routing_listed" | "native_compaction">,
95
+ imageInputFor: (model: string) => boolean,
96
+ nativeCompactionFor: (model: string) => boolean = () => false,
95
97
  ): Record<string, unknown> {
98
+ const remoteCompaction = router.native_compaction === true && router.enabled_models.some(nativeCompactionFor);
96
99
  return {
100
+ remote_compaction: remoteCompaction ? "v2" : "unsupported",
97
101
  models: [
98
102
  ...(router.autorouting_enabled === false || router.routing_listed === false ? [] : [codexCatalogEntry({
99
103
  slug: CANONICAL_ROUTER_MODEL,
@@ -11,7 +11,7 @@ import { errorResponse } from "../http/errors.js";
11
11
  import { captureRequestError } from "../observability/errors.js";
12
12
  import { anthropicErrorResponse } from "./anthropic_messages.js";
13
13
  import { listModelCatalog } from "../models/catalog.js";
14
- import { modelSupportsImageInput } from "../providers/model_capabilities.js";
14
+ import { modelSupportsImageInput, modelSupportsNativeCompaction } from "../providers/model_capabilities.js";
15
15
  import { modelMetadataLookup } from "../providers/pi.js";
16
16
  import { resolveRouter } from "../strategies/routing.js";
17
17
  import { anthropicModelsResponse } from "./anthropic_models.js";
@@ -51,7 +51,8 @@ export async function handleModels(request: Request, routerId: string): Promise<
51
51
  }
52
52
  const metadataLookup = modelMetadataLookup(router.model_configs);
53
53
  const imageInputFor = (model: string) => modelSupportsImageInput(metadataLookup(model));
54
- return Response.json(codexModelsResponse(router, imageInputFor), {
54
+ const nativeCompactionFor = (model: string) => modelSupportsNativeCompaction(metadataLookup(model));
55
+ return Response.json(codexModelsResponse(router, imageInputFor, nativeCompactionFor), {
55
56
  headers: {
56
57
  "Cache-Control": "no-store",
57
58
  },
@@ -131,7 +131,17 @@ export type InteractionHostedToolCall = {
131
131
  serverToolResult?: InteractionToolReference[];
132
132
  };
133
133
 
134
+ // OpenAI-native compaction state carried verbatim: a `compaction_trigger`
135
+ // request item or the opaque `compaction` item that replaces compacted
136
+ // history. Only OpenAI Responses targets can read it.
137
+ export type InteractionCompaction = {
138
+ type: "compaction";
139
+ payload: Record<string, unknown>;
140
+ source?: ProviderIdentity;
141
+ };
142
+
134
143
  export type InteractionItem =
144
+ | InteractionCompaction
135
145
  | InteractionMessage
136
146
  | InteractionReasoning
137
147
  | InteractionToolCall
@@ -140,6 +150,7 @@ export type InteractionItem =
140
150
  | InteractionHostedToolCall;
141
151
 
142
152
  export type InteractionOutputItem =
153
+ | InteractionCompaction
143
154
  | InteractionMessage
144
155
  | InteractionReasoning
145
156
  | InteractionToolCall
@@ -236,6 +247,13 @@ export type AnthropicSafeguards = {
236
247
  betas: string[];
237
248
  };
238
249
 
250
+ // Anthropic server-side context editing (`context_management`, e.g. Claude
251
+ // Code's tool-result clearing) with its paired beta.
252
+ export type AnthropicContextManagement = {
253
+ contextManagement: Record<string, unknown>;
254
+ betas: string[];
255
+ };
256
+
239
257
  export type InteractionRequest = {
240
258
  sourceProtocol: SourceProtocol;
241
259
  requestPurpose?: InteractionRequestPurpose;
@@ -245,6 +263,7 @@ export type InteractionRequest = {
245
263
  // Muse Code's own x-client-id, which Meta attributes its requests by.
246
264
  museCodeClientId?: string;
247
265
  anthropicSafeguards?: AnthropicSafeguards;
266
+ anthropicContextManagement?: AnthropicContextManagement;
248
267
  model?: string;
249
268
  instructions?: string;
250
269
  items: InteractionItem[];
@@ -36,9 +36,7 @@ const UNSUPPORTED_INPUT_ITEM_TYPES = new Set([
36
36
  "local_shell_call_output",
37
37
  "tool_search_call",
38
38
  "tool_search_output",
39
- "compaction",
40
39
  "compaction_summary",
41
- "compaction_trigger",
42
40
  "context_compaction",
43
41
  ]);
44
42
  const CLIENT_TURN_ID_MAX_LENGTH = 200;
@@ -232,6 +230,7 @@ function responseItem(value: unknown, itemIndex: number, hostedReplayId?: string
232
230
  if (UNSUPPORTED_INPUT_ITEM_TYPES.has(type)) {
233
231
  throw new HttpError(400, `Responses input item type '${type}' is not supported by this router MVP.`, "unsupported_response_item", "input");
234
232
  }
233
+ if (type === "compaction" || type === "compaction_trigger") return { type: "compaction", payload: { ...value } };
235
234
  if (type === "reasoning") return reasoningItem(value);
236
235
  if (type === "configuration_update") return reasoningConfigurationItem(value);
237
236
  if (type === "web_search_call") return hostedWebSearchCallItem(value, itemIndex, hostedReplayId);
@@ -11,6 +11,8 @@ export function anthropicMessageId(requestId: string): string {
11
11
  export function anthropicContent(output: InteractionOutput): Array<Record<string, unknown>> {
12
12
  const content: Array<Record<string, unknown>> = [];
13
13
  for (const item of output.items) {
14
+ // Native compaction state is OpenAI Responses-only.
15
+ if (item.type === "compaction") continue;
14
16
  if (item.type === "reasoning") {
15
17
  content.push(anthropicReasoningBlock(item));
16
18
  continue;
@@ -26,6 +26,7 @@ export function openAIResponsesOutputItem(
26
26
  if (item.type === "message") return responseMessageItem(output, item, index);
27
27
  if (item.type === "reasoning") return responseReasoningItem(output, item, index);
28
28
  if (item.type === "hosted_tool_call") return responseHostedToolCallItem(item);
29
+ if (item.type === "compaction") return item.payload;
29
30
  return responseToolCallItem(item);
30
31
  }
31
32
 
@@ -246,8 +246,8 @@ class ResponsesAccumulator {
246
246
 
247
247
  if (type === "response.output_item.added" && isRecord(event.item)) {
248
248
  const index = providerOutputIndex(event);
249
- if (event.item.type === "web_search_call") {
250
- const item = providerHostedToolCall(event.item, this.args.source);
249
+ if (event.item.type === "web_search_call" || event.item.type === "compaction") {
250
+ const item = providerPassthroughItem(event.item, this.args.source);
251
251
  this.items.set(index, item);
252
252
  this.addedIndexes.add(index);
253
253
  send(type, providerEventPayload(event));
@@ -277,8 +277,8 @@ class ResponsesAccumulator {
277
277
  this.applyProviderMessageAnnotations(index, event.item);
278
278
  return;
279
279
  }
280
- if (event.item.type !== "web_search_call") return;
281
- this.items.set(index, providerHostedToolCall(event.item, this.args.source));
280
+ if (event.item.type !== "web_search_call" && event.item.type !== "compaction") return;
281
+ this.items.set(index, providerPassthroughItem(event.item, this.args.source));
282
282
  if (!this.addedIndexes.has(index)) {
283
283
  this.addedIndexes.add(index);
284
284
  send("response.output_item.added", { output_index: index, item: event.item });
@@ -553,10 +553,12 @@ function providerEventPayload(event: Record<string, unknown>): Record<string, un
553
553
  return payload;
554
554
  }
555
555
 
556
- function providerHostedToolCall(
556
+ // Provider output items the gateway relays verbatim instead of synthesizing.
557
+ function providerPassthroughItem(
557
558
  item: Record<string, unknown>,
558
559
  source: ProviderIdentity
559
- ): Extract<InteractionOutputItem, { type: "hosted_tool_call" }> {
560
+ ): InteractionOutputItem {
561
+ if (item.type === "compaction") return { type: "compaction", payload: { ...item }, source };
560
562
  if (item.type !== "web_search_call" || typeof item.id !== "string" || !item.id) {
561
563
  throw new Error("OpenAI provider web search item is malformed.");
562
564
  }
@@ -1,6 +1,6 @@
1
1
  import { isRecord } from "@mupt-ai/dari-router/policy-engine";
2
2
 
3
- import type { AnthropicSafeguards, InteractionRequest } from "../interaction/types.js";
3
+ import type { AnthropicContextManagement, AnthropicSafeguards, InteractionRequest } from "../interaction/types.js";
4
4
  import type { ProviderFetch } from "./response_capture.js";
5
5
 
6
6
  // Claude Code's auto mode asks the Anthropic API to run its dangerous-tool-use
@@ -21,6 +21,33 @@ export function forwardsAnthropicSafeguards(
21
21
  );
22
22
  }
23
23
 
24
+ // Claude Code's tool-result clearing (`context_management`) runs inside the
25
+ // Anthropic API. Only Anthropic's own Messages endpoint gets it; other
26
+ // providers serve the full history, as Claude Code expects when no
27
+ // `context_management` comes back.
28
+ export function forwardsAnthropicContextManagement(
29
+ request: Pick<InteractionRequest, "anthropicContextManagement">,
30
+ model: Record<string, unknown>,
31
+ ): boolean {
32
+ return (
33
+ request.anthropicContextManagement !== undefined &&
34
+ model.provider === "anthropic" &&
35
+ model.api === "anthropic-messages"
36
+ );
37
+ }
38
+
39
+ export function payloadWithContextManagement(
40
+ payload: Record<string, unknown>,
41
+ contextManagement: AnthropicContextManagement,
42
+ ): Record<string, unknown> {
43
+ const betas = Array.isArray(payload.betas) ? payload.betas : [];
44
+ return {
45
+ ...payload,
46
+ context_management: contextManagement.contextManagement,
47
+ betas: [...new Set([...betas, ...contextManagement.betas])],
48
+ };
49
+ }
50
+
24
51
  export function payloadWithSafeguards(
25
52
  payload: Record<string, unknown>,
26
53
  safeguards: AnthropicSafeguards,
@@ -56,6 +56,11 @@ export function modelSupportsReasoningConfigurationUpdate(
56
56
  && metadata.model.compat.supportsReasoningConfigurationUpdate === true;
57
57
  }
58
58
 
59
+ // OpenAI's own Responses endpoints read and write native `compaction` items.
60
+ export function modelSupportsNativeCompaction(metadata: ModelCapabilityMetadata): boolean {
61
+ return modelSupportsHostedWebSearch(metadata);
62
+ }
63
+
59
64
  export function modelSupportsHostedWebSearch(metadata: ModelCapabilityMetadata): boolean {
60
65
  return (
61
66
  (metadata.model.provider === "openai" && metadata.model.api === "openai-responses")
@@ -186,6 +186,19 @@ export function buildContext(
186
186
  toolCalls.set(item.callId, { id, name });
187
187
  continue;
188
188
  }
189
+ if (item.type === "compaction") {
190
+ // Routing narrows compaction-bearing requests to native-compaction targets.
191
+ if (!isOpenAIResponsesApi(target.api)) {
192
+ throw new HttpError(400, "Native compaction state can only be sent to OpenAI Responses models.", "unsupported_response_item", "input");
193
+ }
194
+ assistantFor(item.source ?? target).content.push({
195
+ type: "providerItem",
196
+ item: item.payload,
197
+ name: "providerItem",
198
+ arguments: item.payload,
199
+ });
200
+ continue;
201
+ }
189
202
  if (item.type === "hosted_tool_call") {
190
203
  if (item.tool === "server_tool_use" || item.tool === "tool_search") {
191
204
  // Server tool use and tool search results are Anthropic-specific.
@@ -9,7 +9,12 @@ import { effectiveReasoningForModel, validateReasoningEffortForModel } from "./r
9
9
  import { isBedrockApi, isOpenAIResponsesApi } from "./model_capabilities.js";
10
10
  import type { ResolvedProviderAuth } from "../types.js";
11
11
  import type { ProviderFetch } from "./response_capture.js";
12
- import { forwardsAnthropicSafeguards, payloadWithSafeguards } from "./anthropic_safeguards.js";
12
+ import {
13
+ forwardsAnthropicContextManagement,
14
+ forwardsAnthropicSafeguards,
15
+ payloadWithContextManagement,
16
+ payloadWithSafeguards,
17
+ } from "./anthropic_safeguards.js";
13
18
 
14
19
  type PiOptionsSupport = {
15
20
  getSupportedThinkingLevels?: (model: Record<string, unknown>) => string[];
@@ -104,7 +109,16 @@ export function buildOptions(
104
109
  if (safeguards !== undefined && forwardsAnthropicSafeguards(request, model)) {
105
110
  patches.push((payload) => payloadWithSafeguards(payload, safeguards));
106
111
  }
112
+ const contextManagement = request.anthropicContextManagement;
113
+ if (contextManagement !== undefined && forwardsAnthropicContextManagement(request, model)) {
114
+ patches.push((payload) => payloadWithContextManagement(payload, contextManagement));
115
+ }
107
116
 
117
+ // Pi keeps only the content it models, so native compaction output reaches
118
+ // the client from the provider's own output items.
119
+ if (isOpenAIResponsesApi(api) && request.items.some((item) => item.type === "compaction")) {
120
+ options.emitProviderEvents = true;
121
+ }
108
122
  if (isOpenAIResponsesApi(api) && requiredCapabilitiesFor(request).includes("openai_hosted_web_search")) {
109
123
  options.emitProviderEvents = true;
110
124
  const hosted = request.tools.flatMap((tool) => tool.kind === "hosted" ? [{ ...tool.config }] : []);
@@ -154,6 +154,7 @@ function openAIProviderResponseToInteractionOutput(
154
154
  arguments: parsed,
155
155
  }, source, tools);
156
156
  }
157
+ if (value.type === "compaction") return { type: "compaction" as const, payload: { ...value }, source };
157
158
  if (value.type === "web_search_call") {
158
159
  return {
159
160
  type: "hosted_tool_call" as const,
@@ -22,6 +22,7 @@ import type { ClientHarness } from "../types.js";
22
22
  * - openai/gpt-6.1-sol
23
23
  * subscriptions: true # serve with connected Claude Code / ChatGPT plans
24
24
  * sessionPinning: false # route each session and subagent once, then keep its model
25
+ * nativeCompaction: false # let Codex compact server-side with the provider's native compaction
25
26
  * providers: # optional: OpenAI-compatible or self-run endpoints
26
27
  * local:
27
28
  * baseUrl: http://localhost:8000/v1
@@ -57,6 +58,7 @@ export type RouterConfig = {
57
58
  retries: number;
58
59
  subscriptions: boolean;
59
60
  sessionPinning: boolean;
61
+ nativeCompaction: boolean;
60
62
  zdr: boolean;
61
63
  };
62
64
 
@@ -191,6 +193,7 @@ function parseRouter(id: string, raw: unknown): RouterConfig {
191
193
  retries: optionalRetries(raw.retries, `routers.${id}.retries`) ?? 1,
192
194
  subscriptions: optionalBoolean(raw.subscriptions, `routers.${id}.subscriptions`) ?? true,
193
195
  sessionPinning: optionalBoolean(raw.sessionPinning, `routers.${id}.sessionPinning`) ?? false,
196
+ nativeCompaction: optionalBoolean(raw.nativeCompaction, `routers.${id}.nativeCompaction`) ?? false,
194
197
  zdr: optionalBoolean(raw.zdr, `routers.${id}.zdr`) ?? false,
195
198
  };
196
199
  }
@@ -128,6 +128,7 @@ export async function resolveSelfHostedRouter(
128
128
  zdr: router.zdr,
129
129
  speculative_routing: false,
130
130
  session_pinning: router.sessionPinning,
131
+ native_compaction: router.nativeCompaction,
131
132
  primary_retries: router.retries,
132
133
  routing_strategy: "dari",
133
134
  custom_config: null,
@@ -82,7 +82,7 @@ export function selectorMessagesForInteraction(
82
82
  continue;
83
83
  }
84
84
 
85
- if (item.type === "reasoning_configuration") {
85
+ if (item.type === "reasoning_configuration" || item.type === "compaction") {
86
86
  continue;
87
87
  }
88
88
 
@@ -131,7 +131,7 @@ function interactionObservabilityMetadata(
131
131
  addContentModalities(itemContentModalityCounts, item.output);
132
132
  continue;
133
133
  }
134
- if (item.type === "reasoning_configuration") {
134
+ if (item.type === "reasoning_configuration" || item.type === "compaction") {
135
135
  continue;
136
136
  }
137
137
  if (item.providerType === "tool_search_result") {
package/src/types.ts CHANGED
@@ -139,6 +139,10 @@ export type ResolvedRouter = {
139
139
  // Route each session's (and each subagent's) first turn, then serve that
140
140
  // pair for the rest of the session instead of selecting or leasing.
141
141
  session_pinning?: boolean;
142
+ // Let Codex compact context server-side with the provider's native
143
+ // compaction; requests carrying compaction state route only to models that
144
+ // support it.
145
+ native_compaction?: boolean;
142
146
  primary_retries?: number;
143
147
  // Serve only the requested `dari/model/<id>` at the requested thinking
144
148
  // level: no selector, lease, or personal subscription the platform did not