@linxiraos/pi-agent-core 1.4.4 → 1.4.7

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.
@@ -11,11 +11,9 @@ import type { Api, CodexCompactionContext, FetchImpl, Model, ProviderSessionStat
11
11
  import * as AIError from "@linxiraos/pi-ai/error";
12
12
  import { createOpenAICodexCompactionRequestContext } from "@linxiraos/pi-ai/providers/openai-codex-compaction";
13
13
  import { applyCodexResponsesLiteShape } from "@linxiraos/pi-ai/providers/openai-codex/request-transformer";
14
- import {
15
- createOpenAICodexCompatibilityMetadata,
16
- openCodexCompactionEventStream,
17
- type OpenAICodexCompactionBody,
18
- type OpenAICodexCompatibilityMetadata,
14
+ import type {
15
+ OpenAICodexCompactionBody,
16
+ OpenAICodexCompatibilityMetadata,
19
17
  } from "@linxiraos/pi-ai/providers/openai-codex-responses";
20
18
  import {
21
19
  getOpenAIPromptCacheKey,
@@ -24,6 +22,7 @@ import {
24
22
  resolveOpenAIRequestSetup,
25
23
  } from "@linxiraos/pi-ai/providers/openai-shared";
26
24
  import { captureOpenAIHttpError } from "@linxiraos/pi-ai/utils/openai-http";
25
+ import type { CatalogPolicyInputs } from "@linxiraos/pi-catalog/types";
27
26
  import { isBedrockOpenAIUrl } from "@linxiraos/pi-catalog/hosts";
28
27
  import {
29
28
  applyCodexResidencyHeader,
@@ -131,7 +130,8 @@ export function shouldUseCompactionV2Streaming(
131
130
  return getCompactionV2Endpoint(model) !== undefined;
132
131
  }
133
132
 
134
- function compactionV2Api(model: Model): Api | undefined {
133
+ /** Effective compaction request adapter: the `remoteCompaction.api` override, else the model's own API. Always defined — `Model.api` is required. */
134
+ function compactionV2Api(model: Model): Api {
135
135
  return model.remoteCompaction?.api ?? model.api;
136
136
  }
137
137
 
@@ -171,6 +171,23 @@ function resolveCompactionV2Model(model: Model): string {
171
171
  return mappedDeployment ?? requestModel;
172
172
  }
173
173
 
174
+ /**
175
+ * Catalog-policy view of a remote compaction request (V1 and V2): the
176
+ * effective adapter (`remoteCompaction.api`) and the wire id the body sends
177
+ * (`remoteCompaction.model`). Under a model override the active lane's
178
+ * `requestModelId` and thinking classification describe a model that never
179
+ * reaches the wire, so they are dropped; `reasoning` stays because the
180
+ * compaction body derives its reasoning config from the active model.
181
+ */
182
+ export function remoteCompactionPolicyModel(model: Model): CatalogPolicyInputs {
183
+ const api = compactionV2Api(model);
184
+ const overrideId = model.remoteCompaction?.model;
185
+ const base = { provider: model.provider, providerType: model.providerType, api, reasoning: model.reasoning };
186
+ return overrideId == null
187
+ ? { ...base, id: model.id, requestModelId: model.requestModelId, thinking: model.thinking }
188
+ : { ...base, id: overrideId };
189
+ }
190
+
174
191
  // ============================================================================
175
192
  // Request Building
176
193
  // ============================================================================
@@ -274,18 +291,21 @@ export async function requestCompactionV2Streaming(
274
291
 
275
292
  const retryWait = options?.retryWait ?? ((delayMs: number) => Bun.sleep(delayMs));
276
293
  const isCodexResponses = compactionV2Api(model) === "openai-codex-responses" || model.provider === "openai-codex";
277
- const codexMetadata =
278
- isCodexResponses && !shouldUseCodexProviderTransport(model)
279
- ? createOpenAICodexCompatibilityMetadata({
280
- sessionId: request.sessionId,
281
- providerSessionState: options?.providerSessionState,
282
- requestKind: "compaction",
283
- compaction: createOpenAICodexCompactionRequestContext({
284
- context: options?.codexCompaction,
285
- implementation: "responses_compaction_v2",
286
- }),
287
- })
288
- : undefined;
294
+ let codexMetadata: OpenAICodexCompatibilityMetadata | undefined;
295
+ if (isCodexResponses && !shouldUseCodexProviderTransport(model)) {
296
+ // Metadata generation is request work; importing compaction policy must not load the Codex transport.
297
+ const { createOpenAICodexCompatibilityMetadata } =
298
+ await import("@linxiraos/pi-ai/providers/openai-codex-responses");
299
+ codexMetadata = createOpenAICodexCompatibilityMetadata({
300
+ sessionId: request.sessionId,
301
+ providerSessionState: options?.providerSessionState,
302
+ requestKind: "compaction",
303
+ compaction: createOpenAICodexCompactionRequestContext({
304
+ context: options?.codexCompaction,
305
+ implementation: "responses_compaction_v2",
306
+ }),
307
+ });
308
+ }
289
309
  let lastError: Error | undefined;
290
310
 
291
311
  for (let attempt = 0; attempt <= V2_COMPACTION_MAX_RETRIES; attempt++) {
@@ -348,6 +368,8 @@ async function attemptCompactionV2Streaming(
348
368
  }
349
369
 
350
370
  if (shouldUseCodexProviderTransport(model)) {
371
+ // The native transport is only needed when sending a Codex compaction request.
372
+ const { openCodexCompactionEventStream } = await import("@linxiraos/pi-ai/providers/openai-codex-responses");
351
373
  const eventStream = await openCodexCompactionEventStream(model, body, {
352
374
  apiKey,
353
375
  signal,
@@ -413,8 +435,9 @@ function buildCompactionV2Headers(
413
435
  "content-type": "application/json",
414
436
  ...resolveOpenAIRequestSetup(
415
437
  {
416
- provider: model.provider,
417
- id: model.id,
438
+ // `on-api` scoped cache policy must see the request this
439
+ // compaction actually sends, not the active lane.
440
+ ...remoteCompactionPolicyModel(model),
418
441
  baseUrl: model.baseUrl,
419
442
  headers: model.headers,
420
443
  compat: {
@@ -422,7 +445,16 @@ function buildCompactionV2Headers(
422
445
  model.compat && "sessionHeader" in model.compat ? model.compat.sessionHeader : undefined,
423
446
  },
424
447
  },
425
- { apiKey, messages: [], sessionId: request.sessionId ?? routingSessionId, promptCacheSessionId },
448
+ {
449
+ apiKey,
450
+ messages: [],
451
+ sessionId: request.sessionId ?? routingSessionId,
452
+ promptCacheSessionId,
453
+ // The family affinity key rides only an explicit
454
+ // prompt-cache identity; the sessionId-derived cache-id
455
+ // fallback never does.
456
+ promptCacheAffinityKey: request.promptCacheKey ? promptCacheSessionId : undefined,
457
+ },
426
458
  ).headers,
427
459
  };
428
460
  if (api === "openai-codex-responses" || model.provider === "openai-codex") {
@@ -27,12 +27,8 @@ import {
27
27
  import type { Dialect } from "@linxiraos/pi-ai/dialect";
28
28
  import * as AIError from "@linxiraos/pi-ai/error";
29
29
  import { createOpenAICodexCompactionRequestContext } from "@linxiraos/pi-ai/providers/openai-codex-compaction";
30
+ import type { OpenAICodexCompactionBody } from "@linxiraos/pi-ai/providers/openai-codex-responses";
30
31
  import type { InputItem as CodexInputItem } from "@linxiraos/pi-ai/providers/openai-codex/request-transformer";
31
- import {
32
- buildTransformedCodexRequestBody,
33
- type OpenAICodexCompactionBody,
34
- } from "@linxiraos/pi-ai/providers/openai-codex-responses";
35
- import { convertTools } from "@linxiraos/pi-ai/providers/openai-responses";
36
32
  import { buildResponsesInput, resolveOpenAICompatPolicy } from "@linxiraos/pi-ai/providers/openai-shared";
37
33
  import { isSurvivingAssistant } from "@linxiraos/pi-ai/providers/transform-messages";
38
34
  import { stripOpenAIResponsesOutputOnlyStatusesForReplay } from "@linxiraos/pi-ai/utils";
@@ -200,6 +196,19 @@ export interface CompactionSettings {
200
196
  /** Reserve applied when {@link CompactionSettings.reserveTokens} is unset. */
201
197
  export const DEFAULT_RESERVE_TOKENS = 16384;
202
198
 
199
+ /**
200
+ * Hysteresis band under the compaction trigger. Maintenance counts as having
201
+ * resolved threshold pressure only when residual context lands at or below
202
+ * `COMPACTION_RECOVERY_BAND × threshold`. Re-checking against the raw threshold
203
+ * lets a pass keep reclaiming a trickle of the previous turn's output and land
204
+ * just under the line every turn, sustaining the auto-continue dead loop
205
+ * reported in #2275; the same band stops the context-full / snapcompact tail
206
+ * from re-firing on a history whose single most-recent kept turn already
207
+ * exceeds the threshold. {@link prepareCompaction} sizes the kept tail to land
208
+ * inside it.
209
+ */
210
+ export const COMPACTION_RECOVERY_BAND = 0.8;
211
+
203
212
  /**
204
213
  * Hard ceiling on a generated compaction summary.
205
214
  *
@@ -728,8 +737,15 @@ export interface SummaryOptions {
728
737
  thinkingLevel?: ThinkingLevel;
729
738
  /** Session routing key for remote compaction transports with sticky provider sessions. */
730
739
  sessionId?: string;
731
- /** Prompt-cache key for remote compaction transports that support provider prefix caching. */
740
+ /** Prompt-cache key for conventional summary requests, gated against the summarizing model. */
732
741
  promptCacheKey?: string;
742
+ /**
743
+ * Prompt-cache key for remote compaction requests, gated against the request
744
+ * they send (`remoteCompaction.api`/`model` override, see
745
+ * `remoteCompactionPolicyModel`). Defaults to {@link promptCacheKey} only when
746
+ * omitted; an explicit `undefined` means the remote target gets no key.
747
+ */
748
+ remotePromptCacheKey?: string;
733
749
  /** Mutable provider state used to keep Codex compaction on the live session identity. */
734
750
  providerSessionState?: Map<string, ProviderSessionState>;
735
751
  /** Whether Codex remote compaction should prefer the provider WebSocket transport. */
@@ -1205,6 +1221,14 @@ export async function generateHandoff(
1205
1221
  );
1206
1222
  }
1207
1223
 
1224
+ /** Result of the short-summary request before it is mapped to the optional field. */
1225
+ type ShortSummaryOutcome = { kind: "text"; text: string } | { kind: "failed"; error: string } | { kind: "aborted" };
1226
+
1227
+ /**
1228
+ * Generate the optional display summary. Cancellation propagates as an
1229
+ * `AbortError`; every other failure or an empty answer yields `undefined`, so
1230
+ * a completed full summary is never discarded for this display-only field.
1231
+ */
1208
1232
  async function generateShortSummary(
1209
1233
  recentMessages: AgentMessage[],
1210
1234
  historySummary: string | undefined,
@@ -1213,7 +1237,7 @@ async function generateShortSummary(
1213
1237
  apiKey: ApiKey,
1214
1238
  signal?: AbortSignal,
1215
1239
  options?: SummaryOptions,
1216
- ): Promise<string> {
1240
+ ): Promise<string | undefined> {
1217
1241
  const maxTokens = Math.min(512, Math.floor(0.2 * reserveTokens));
1218
1242
  const llmMessages = (options?.convertToLlm ?? defaultConvertToLlm)(recentMessages);
1219
1243
  const conversationText = serializeConversationForSummary(
@@ -1229,57 +1253,97 @@ async function generateShortSummary(
1229
1253
  promptText += formatAdditionalContext(options?.extraContext);
1230
1254
  promptText += SHORT_SUMMARY_PROMPT;
1231
1255
 
1232
- if (options?.remoteEndpoint) {
1233
- const endpoint = options.remoteEndpoint;
1234
- const remote = await withAuth(
1235
- apiKey,
1236
- key =>
1237
- requestRemoteCompaction(
1238
- endpoint,
1239
- { systemPrompt: SUMMARIZATION_SYSTEM_PROMPT, prompt: promptText, maxTokens },
1256
+ let outcome: ShortSummaryOutcome;
1257
+ try {
1258
+ if (options?.remoteEndpoint) {
1259
+ const endpoint = options.remoteEndpoint;
1260
+ const remote = await withAuth(
1261
+ apiKey,
1262
+ key =>
1263
+ requestRemoteCompaction(
1264
+ endpoint,
1265
+ { systemPrompt: SUMMARIZATION_SYSTEM_PROMPT, prompt: promptText, maxTokens },
1266
+ signal,
1267
+ { fetch: options?.fetch, model, apiKey: key },
1268
+ ),
1269
+ { signal, missingKeyMessage: "Remote compaction credentials unavailable" },
1270
+ );
1271
+ outcome = { kind: "text", text: remote.summary };
1272
+ } else {
1273
+ const response = await instrumentedCompleteSimple(
1274
+ model,
1275
+ {
1276
+ systemPrompt: [SUMMARIZATION_SYSTEM_PROMPT],
1277
+ messages: [{ role: "user", content: [{ type: "text", text: promptText }], timestamp: Date.now() }],
1278
+ },
1279
+ {
1280
+ maxTokens,
1240
1281
  signal,
1241
- { fetch: options?.fetch, model, apiKey: key },
1242
- ),
1243
- { signal, missingKeyMessage: "Remote compaction credentials unavailable" },
1244
- );
1245
- return remote.summary;
1282
+ apiKey,
1283
+ reasoning: resolveCompactionEffort(model, options?.thinkingLevel),
1284
+ initiatorOverride: options?.initiatorOverride,
1285
+ metadata: options?.metadata,
1286
+ fetch: options?.fetch,
1287
+ sessionId: options?.sessionId,
1288
+ promptCacheKey: options?.promptCacheKey,
1289
+ providerSessionState: options?.providerSessionState,
1290
+ codexCompaction: localCodexCompaction(options),
1291
+ },
1292
+ {
1293
+ telemetry: options?.telemetry,
1294
+ oneshotKind: "compaction_short_summary",
1295
+ completeImpl: options?.completeImpl,
1296
+ retry: summaryOneshotRetry(options),
1297
+ },
1298
+ );
1299
+ switch (response.stopReason) {
1300
+ case "aborted":
1301
+ outcome = { kind: "aborted" };
1302
+ break;
1303
+ case "error":
1304
+ outcome = { kind: "failed", error: response.errorMessage || "Unknown error" };
1305
+ break;
1306
+ case "stop":
1307
+ case "length":
1308
+ case "toolUse":
1309
+ outcome = {
1310
+ kind: "text",
1311
+ text: response.content
1312
+ .filter((c): c is { type: "text"; text: string } => c.type === "text")
1313
+ .map(c => c.text)
1314
+ .join("\n"),
1315
+ };
1316
+ break;
1317
+ }
1318
+ }
1319
+ } catch (err) {
1320
+ outcome = signal?.aborted
1321
+ ? { kind: "aborted" }
1322
+ : { kind: "failed", error: err instanceof Error ? err.message : String(err) };
1246
1323
  }
1247
1324
 
1248
- const response = await instrumentedCompleteSimple(
1249
- model,
1250
- {
1251
- systemPrompt: [SUMMARIZATION_SYSTEM_PROMPT],
1252
- messages: [{ role: "user", content: [{ type: "text", text: promptText }], timestamp: Date.now() }],
1253
- },
1254
- {
1255
- maxTokens,
1256
- signal,
1257
- apiKey,
1258
- reasoning: resolveCompactionEffort(model, options?.thinkingLevel),
1259
- initiatorOverride: options?.initiatorOverride,
1260
- metadata: options?.metadata,
1261
- fetch: options?.fetch,
1262
- sessionId: options?.sessionId,
1263
- promptCacheKey: options?.promptCacheKey,
1264
- providerSessionState: options?.providerSessionState,
1265
- codexCompaction: localCodexCompaction(options),
1266
- },
1267
- {
1268
- telemetry: options?.telemetry,
1269
- oneshotKind: "compaction_short_summary",
1270
- completeImpl: options?.completeImpl,
1271
- retry: summaryOneshotRetry(options),
1272
- },
1273
- );
1274
-
1275
- if (response.stopReason === "error") {
1276
- throw createSummarizationError("Short summary failed", response);
1325
+ if (signal?.aborted) outcome = { kind: "aborted" };
1326
+ switch (outcome.kind) {
1327
+ case "aborted":
1328
+ throw new AIError.AbortError("Short summary aborted", { cause: signal?.reason });
1329
+ case "failed":
1330
+ logger.warn("Compaction short summary skipped", {
1331
+ error: outcome.error,
1332
+ model: model.id,
1333
+ provider: model.provider,
1334
+ });
1335
+ return undefined;
1336
+ case "text":
1337
+ if (outcome.text.trim() === "") {
1338
+ logger.warn("Compaction short summary skipped", {
1339
+ error: "empty answer",
1340
+ model: model.id,
1341
+ provider: model.provider,
1342
+ });
1343
+ return undefined;
1344
+ }
1345
+ return outcome.text;
1277
1346
  }
1278
-
1279
- return response.content
1280
- .filter((c): c is { type: "text"; text: string } => c.type === "text")
1281
- .map(c => c.text)
1282
- .join("\n");
1283
1347
  }
1284
1348
 
1285
1349
  // ============================================================================
@@ -1457,9 +1521,27 @@ export function prepareCompaction(
1457
1521
  compactionMessages.push(message);
1458
1522
  }
1459
1523
 
1460
- const lastUsage = getLastAssistantUsage(pathEntries);
1524
+ const postCompactionStart = Math.max(prevCompactionIndex, resetBoundaryIndex) + 1;
1525
+ const lastUsage = getLastAssistantUsage(
1526
+ postCompactionStart > 0 ? pathEntries.slice(postCompactionStart) : pathEntries,
1527
+ );
1461
1528
  const tokensBefore = lastUsage ? calculateContextTokens(lastUsage) : 0;
1462
1529
  let keepRecentTokens = settings.keepRecentTokens;
1530
+ if (activeModel?.contextWindow && activeModel.contextWindow > 0) {
1531
+ // The compacted context (kept tail + summary/prompt overhead) must land in
1532
+ // the recovery band under the configured trigger, or it fires again at once.
1533
+ // The trigger is the user's choice, so the kept tail gives way, not the trigger:
1534
+ // it gets what the band leaves after the reserve floor (an upper bound on the
1535
+ // summary), or half the band when the floor alone fills it.
1536
+ const contextWindow = activeModel.contextWindow;
1537
+ const recoveryBand = Math.floor(resolveThresholdTokens(contextWindow, settings) * COMPACTION_RECOVERY_BAND);
1538
+ const reserveFloor = Math.min(
1539
+ resolveBudgetReserveTokens(contextWindow, settings),
1540
+ settings.reserveTokens ?? DEFAULT_RESERVE_TOKENS,
1541
+ );
1542
+ const tailBudget = recoveryBand > reserveFloor ? recoveryBand - reserveFloor : Math.floor(recoveryBand / 2);
1543
+ keepRecentTokens = Math.min(keepRecentTokens, Math.max(1, tailBudget));
1544
+ }
1463
1545
  if (lastUsage) {
1464
1546
  const estimatedTokens = tokenizer.countMessages(compactionMessages);
1465
1547
  const promptTokens = calculatePromptTokens(lastUsage);
@@ -1677,6 +1759,10 @@ export async function compact(
1677
1759
  thinkingLevel: options?.thinkingLevel,
1678
1760
  sessionId: options?.sessionId,
1679
1761
  promptCacheKey: options?.promptCacheKey,
1762
+ remotePromptCacheKey:
1763
+ options && Object.hasOwn(options, "remotePromptCacheKey")
1764
+ ? options.remotePromptCacheKey
1765
+ : options?.promptCacheKey,
1680
1766
  providerSessionState: options?.providerSessionState,
1681
1767
  preferWebsockets: options?.preferWebsockets,
1682
1768
  codexCompaction: options?.codexCompaction,
@@ -1800,6 +1886,9 @@ export async function compact(
1800
1886
  let codexBody: OpenAICodexCompactionBody | undefined;
1801
1887
  let remoteHistory: Array<Record<string, unknown>>;
1802
1888
  if (isCodexResponsesModel(model)) {
1889
+ // Load the serializer only when building a Codex compaction request, not session policy setup.
1890
+ const { buildTransformedCodexRequestBody } =
1891
+ await import("@linxiraos/pi-ai/providers/openai-codex-responses");
1803
1892
  const previousCodexInput: CodexInputItem[] = [];
1804
1893
  for (const item of previousReplacementHistory ?? []) {
1805
1894
  if (!isCodexInputItem(item)) {
@@ -1815,7 +1904,7 @@ export async function compact(
1815
1904
  forceReasoningOff: summaryOptions.thinkingLevel === ThinkingLevel.Off,
1816
1905
  responsesLite: model.useResponsesLite,
1817
1906
  sessionId: summaryOptions.sessionId,
1818
- promptCacheKey: summaryOptions.promptCacheKey,
1907
+ promptCacheKey: summaryOptions.remotePromptCacheKey,
1819
1908
  providerSessionState: summaryOptions.providerSessionState,
1820
1909
  codexCompaction: createOpenAICodexCompactionRequestContext({
1821
1910
  context: summaryOptions.codexCompaction,
@@ -1860,12 +1949,17 @@ export async function compact(
1860
1949
  ? codexBody.instructions
1861
1950
  : ""
1862
1951
  : remoteSystemPrompt.join("\n\n");
1952
+ // Responses serialization is needed only for this native compaction request.
1863
1953
  const tools = codexBody
1864
1954
  ? Array.isArray(codexBody.tools)
1865
1955
  ? codexBody.tools
1866
1956
  : undefined
1867
1957
  : summaryOptions.tools
1868
- ? convertTools(summaryOptions.tools, model.compat.supportsStrictMode, model)
1958
+ ? (await import("@linxiraos/pi-ai/providers/openai-responses")).convertTools(
1959
+ summaryOptions.tools,
1960
+ model.compat.supportsStrictMode,
1961
+ model,
1962
+ )
1869
1963
  : undefined;
1870
1964
  const trimmed = trimRemoteCompactionInputToContextWindow(
1871
1965
  remoteHistory,
@@ -1888,7 +1982,7 @@ export async function compact(
1888
1982
  assertRemoteCompactionInputFits(trimmed, model);
1889
1983
  const requestOptions = {
1890
1984
  sessionId: summaryOptions.sessionId,
1891
- promptCacheKey: summaryOptions.promptCacheKey,
1985
+ promptCacheKey: summaryOptions.remotePromptCacheKey,
1892
1986
  retainedMessageBudget: settings.v2RetainedMessageBudget,
1893
1987
  retainedUserItems,
1894
1988
  };
@@ -1970,6 +2064,7 @@ export async function compact(
1970
2064
  {
1971
2065
  fetch: summaryOptions.fetch,
1972
2066
  sessionId: summaryOptions.sessionId,
2067
+ promptCacheKey: summaryOptions.remotePromptCacheKey,
1973
2068
  providerSessionState: summaryOptions.providerSessionState,
1974
2069
  codexCompaction: summaryOptions.codexCompaction,
1975
2070
  rewriteOutputs,
@@ -2272,7 +2367,7 @@ export async function compact(
2272
2367
 
2273
2368
  return {
2274
2369
  summary,
2275
- shortSummary,
2370
+ ...(shortSummary !== undefined ? { shortSummary } : {}),
2276
2371
  firstKeptEntryId: nativeSummary !== undefined ? nativeFirstKeptEntryId : firstKeptEntryId,
2277
2372
  tokensBefore,
2278
2373
  details: { readFiles, modifiedFiles } as CompactionDetails,
@@ -2300,7 +2395,7 @@ async function generateTurnPrefixSummary(
2300
2395
  preferredDialect(model.id),
2301
2396
  resolveCatalogPolicy(model).classifierCotExtraction === true,
2302
2397
  );
2303
- const promptText = `<conversation>\n${conversationText}\n</conversation>\n\n${TURN_PREFIX_SUMMARIZATION_PROMPT}`;
2398
+ const promptText = `<conversation>\n${conversationText}\n</conversation>\n\n${formatAdditionalContext(options?.extraContext)}${TURN_PREFIX_SUMMARIZATION_PROMPT}`;
2304
2399
  const summarizationMessages = [
2305
2400
  {
2306
2401
  role: "user" as const,
@@ -19,10 +19,14 @@ import { attach, create, Flag, ProviderHttpError } from "@linxiraos/pi-ai/error"
19
19
  import { getCodexAttestationHeader } from "@linxiraos/pi-ai/providers/openai-codex-attestation";
20
20
  import { createOpenAICodexCompactionRequestContext } from "@linxiraos/pi-ai/providers/openai-codex-compaction";
21
21
  import { applyCodexResponsesLiteShape } from "@linxiraos/pi-ai/providers/openai-codex/request-transformer";
22
- import { createOpenAICodexCompatibilityMetadata } from "@linxiraos/pi-ai/providers/openai-codex-responses";
23
- import { applySessionHeader } from "@linxiraos/pi-ai/providers/inference-headers";
22
+ import {
23
+ applyInferenceHeaders,
24
+ applySessionHeader,
25
+ resolveOpenCodeGoCacheAffinity,
26
+ } from "@linxiraos/pi-ai/providers/inference-headers";
24
27
  import {
25
28
  encodeResponsesToolResultOutput,
29
+ getOpenAIPromptCacheKey,
26
30
  hoistInterleavedResponsesToolBatchMessages,
27
31
  parseAzureDeploymentNameMap,
28
32
  parseTextSignature,
@@ -59,7 +63,7 @@ import { dataUrlImageSize } from "../image-tokens";
59
63
  import { Tokenizer } from "../tokenizer";
60
64
  import { appendAzureApiVersion, resolveAzureOpenAiBaseUrl } from "./azure-openai-endpoint";
61
65
  import { prepareBedrockCompactionRequest } from "./bedrock";
62
- import { isOpenAiRemoteCompactionApi } from "./compaction-v2-streaming";
66
+ import { isOpenAiRemoteCompactionApi, remoteCompactionPolicyModel } from "./compaction-v2-streaming";
63
67
  import contextWindowTruncatedOutputPrompt from "./prompts/context-window-truncated-output.md" with { type: "text" };
64
68
 
65
69
  export * from "./compaction-v2-streaming";
@@ -100,18 +104,13 @@ interface RemoteEstimateParts {
100
104
  imageTokens: number;
101
105
  }
102
106
 
103
- function collectRemoteCompactionEstimate(
104
- value: unknown,
105
- tokenizer: Tokenizer,
106
- dropEncrypted: boolean,
107
- parts: RemoteEstimateParts,
108
- ): void {
107
+ function collectRemoteCompactionEstimate(value: unknown, tokenizer: Tokenizer, parts: RemoteEstimateParts): void {
109
108
  if (typeof value === "string") {
110
109
  if (value) parts.fragments.push(value);
111
110
  return;
112
111
  }
113
112
  if (Array.isArray(value)) {
114
- for (const item of value) collectRemoteCompactionEstimate(item, tokenizer, dropEncrypted, parts);
113
+ for (const item of value) collectRemoteCompactionEstimate(item, tokenizer, parts);
115
114
  return;
116
115
  }
117
116
  if (value === null || typeof value !== "object") {
@@ -141,9 +140,9 @@ function collectRemoteCompactionEstimate(
141
140
  // Opaque encrypted reasoning/compaction state: its local base64 size far
142
141
  // exceeds what the provider bills, so it stays out of the fit estimate
143
142
  // (same policy as `MessageCountOptions.excludeEncryptedReasoning`).
144
- if (item === undefined || (dropEncrypted && key === "encrypted_content" && typeof item === "string")) continue;
143
+ if (item === undefined || (key === "encrypted_content" && typeof item === "string")) continue;
145
144
  parts.framing.push(key);
146
- collectRemoteCompactionEstimate(item, tokenizer, dropEncrypted, parts);
145
+ collectRemoteCompactionEstimate(item, tokenizer, parts);
147
146
  }
148
147
  }
149
148
 
@@ -155,21 +154,20 @@ function collectRemoteCompactionEstimate(
155
154
  function remoteCompactionEstimateParts(
156
155
  value: unknown,
157
156
  tokenizer: Tokenizer,
158
- dropEncrypted: boolean,
159
157
  ): { fragments: string[]; imageTokens: number } {
160
158
  const parts: RemoteEstimateParts = { fragments: [], framing: [], imageTokens: 0 };
161
- collectRemoteCompactionEstimate(value, tokenizer, dropEncrypted, parts);
159
+ collectRemoteCompactionEstimate(value, tokenizer, parts);
162
160
  if (parts.framing.length > 0) parts.fragments.push(parts.framing.join(" "));
163
161
  return { fragments: parts.fragments, imageTokens: parts.imageTokens };
164
162
  }
165
163
 
166
164
  /**
167
165
  * Tokens of stored Responses replacement history. Retained `input_image` parts
168
- * count at their image estimate rather than as base64 text; everything else,
169
- * opaque compaction state included, counts as decoded text.
166
+ * count at their image estimate, not their base64 size. Opaque encrypted state
167
+ * stays excluded, matching ordinary message estimates and remote fit checks.
170
168
  */
171
169
  export function countResponsesHistoryTokens(items: unknown[], tokenizer: Tokenizer): number {
172
- const { fragments, imageTokens } = remoteCompactionEstimateParts(items, tokenizer, false);
170
+ const { fragments, imageTokens } = remoteCompactionEstimateParts(items, tokenizer);
173
171
  return (fragments.length === 0 ? 0 : tokenizer.countTokens(fragments)) + imageTokens;
174
172
  }
175
173
 
@@ -214,7 +212,6 @@ function probeRemoteCompactionInputBudget(
214
212
  const { fragments, imageTokens } = remoteCompactionEstimateParts(
215
213
  { instructions, input, ...(tools ? { tools } : {}) },
216
214
  tokenizer,
217
- true,
218
215
  );
219
216
  const flatTokens = imageTokens + REMOTE_COMPACTION_REQUEST_OVERHEAD_TOKENS;
220
217
  if (!contextWindow || contextWindow <= 0) {
@@ -360,6 +357,13 @@ export interface OpenAiRemoteCompactionRequest {
360
357
  model: string;
361
358
  input: Array<Record<string, unknown>>;
362
359
  instructions: string;
360
+ /**
361
+ * Responses body cache identity. Mirrors the V2 body: the explicit
362
+ * prompt-cache key when supplied (normalized to the 64-char wire limit),
363
+ * else the session-derived cache id — retention-gated through
364
+ * `getOpenAIPromptCacheKey`; absent when it resolves to nothing.
365
+ */
366
+ prompt_cache_key?: string;
363
367
  reasoning?: {
364
368
  context?: string;
365
369
  [key: string]: unknown;
@@ -858,6 +862,13 @@ export async function requestOpenAiRemoteCompaction(
858
862
  fetch?: FetchImpl;
859
863
  timeoutMs?: number;
860
864
  sessionId?: string;
865
+ /**
866
+ * Explicit prompt-cache identity. Feeds the Go family affinity header
867
+ * (`x-opencode-session`) and the Responses body `prompt_cache_key`
868
+ * under the same KDL gate as the V2 request; an absent/empty key keeps
869
+ * the child conversation id.
870
+ */
871
+ promptCacheKey?: string;
861
872
  providerSessionState?: Map<string, ProviderSessionState>;
862
873
  codexCompaction?: CodexCompactionContext;
863
874
  /** Forwarded to {@link trimRemoteCompactionInputToContextWindow}. */
@@ -889,6 +900,12 @@ export async function requestOpenAiRemoteCompaction(
889
900
  });
890
901
  }
891
902
  assertRemoteCompactionInputFits(trimmed, model);
903
+ // Same cache identity as the V2 request: the resolved id prefers the
904
+ // explicit prompt-cache key and falls back to the session id, all
905
+ // retention-gated by getOpenAIPromptCacheKey (PI_CACHE_RETENTION=none
906
+ // resolves to nothing here, which then also drops the affinity below).
907
+ const cacheOptions = { sessionId: opts?.sessionId, promptCacheKey: opts?.promptCacheKey };
908
+ const promptCacheSessionId = getOpenAIPromptCacheKey(cacheOptions);
892
909
  const request: OpenAiRemoteCompactionRequest = {
893
910
  model: requestModel,
894
911
  // Preserve the native transcript. Only oversized trailing tool outputs are
@@ -896,6 +913,7 @@ export async function requestOpenAiRemoteCompaction(
896
913
  // reasoning, or call/result pairing.
897
914
  input: trimmed.input,
898
915
  instructions,
916
+ ...(promptCacheSessionId ? { prompt_cache_key: promptCacheSessionId } : {}),
899
917
  };
900
918
  const isAzureOpenAiResponses = (model.remoteCompaction?.api ?? model.api) === "azure-openai-responses";
901
919
  const isCodexResponses =
@@ -911,10 +929,29 @@ export async function requestOpenAiRemoteCompaction(
911
929
  Authorization: `Bearer ${apiKey}`,
912
930
  ...model.headers,
913
931
  };
932
+ // Same gate as the V2 request, against the request this compaction actually
933
+ // sends. Azure keeps its plain header shape (V2 skips the cascade there too).
934
+ // Only an EXPLICIT prompt-cache key feeds the affinity; the sessionId-derived
935
+ // cache id never does. `promptCacheSessionId` is already retention-gated.
936
+ if (!isAzureOpenAiResponses) {
937
+ applyInferenceHeaders(headers, {
938
+ provider: model.provider,
939
+ providerType: model.providerType,
940
+ protocol: "openai",
941
+ sessionId: opts?.sessionId,
942
+ cacheAffinity: resolveOpenCodeGoCacheAffinity(
943
+ remoteCompactionPolicyModel(model),
944
+ opts?.promptCacheKey ? promptCacheSessionId : undefined,
945
+ ),
946
+ });
947
+ }
914
948
  applySessionHeader(headers, model.compat, opts?.sessionId);
915
949
 
916
950
  // Codex endpoints require additional auth headers
917
951
  if (isCodexResponses) {
952
+ // Keep transport loading on the actual Codex request path, not compaction policy inspection.
953
+ const { createOpenAICodexCompatibilityMetadata } =
954
+ await import("@linxiraos/pi-ai/providers/openai-codex-responses");
918
955
  const accountId = getCodexAccountId(apiKey);
919
956
  if (accountId) {
920
957
  headers[OPENAI_HEADERS.ACCOUNT_ID] = accountId;
@@ -2,7 +2,6 @@ The conversation above is the complete history to summarize. The API replaces ev
2
2
 
3
3
  {{#if extraContext}}
4
4
  {{extraContext}}
5
-
6
5
  {{/if}}
7
6
  {{basePrompt}}
8
7
  {{#if customInstructions}}
@@ -10,4 +9,4 @@ The conversation above is the complete history to summarize. The API replaces ev
10
9
  Additional focus: {{customInstructions}}
11
10
  {{/if}}
12
11
 
13
- You MUST NOT call any tools while writing the summary; respond with the summary text only.
12
+ You MUST NOT call any tools while writing the summary; respond with the summary text only.
package/src/index.ts CHANGED
@@ -32,5 +32,3 @@ export * from "./tokenizer";
32
32
  export * from "./tool-arguments";
33
33
  // Types
34
34
  export * from "./types";
35
- // Yield utilities for Bun event-loop busy-wait prevention
36
- export * from "./utils/yield";
@@ -239,6 +239,12 @@ export class SpeculativeOperationCoordinator {
239
239
  #closed = false;
240
240
  #admissionsFinalized = false;
241
241
  #running = 0;
242
+ /** Observer of existing speculative execution draining; no separate work ledger. */
243
+ onIdle?: () => void;
244
+
245
+ get isRunning(): boolean {
246
+ return this.#running > 0;
247
+ }
242
248
 
243
249
  constructor(
244
250
  readonly config: SpeculativeToolExecutionConfig,
@@ -955,6 +961,7 @@ export class SpeculativeOperationCoordinator {
955
961
  } finally {
956
962
  this.#running--;
957
963
  this.#drain();
964
+ if (this.#running === 0) this.onIdle?.();
958
965
  }
959
966
  })();
960
967
  }