maka-agent 0.2.0-dev.14.20260902 → 0.2.0-dev.16.20260903

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 (160) hide show
  1. package/dist/cli-core.js +0 -1
  2. package/dist/pi-transcript.js +48 -0
  3. package/dist/pi-tui-form-interaction.js +497 -0
  4. package/dist/pi-tui-pickers.js +256 -55
  5. package/dist/pi-tui-runner.js +215 -12
  6. package/dist/runtime-host-cli.js +17 -42
  7. package/dist/runtime-host-lifecycle-transaction.js +31 -13
  8. package/dist/runtime-host-managed-lifecycle-manager.js +1 -1
  9. package/dist/runtime-host-onboarding.js +3 -1
  10. package/dist/runtime-host-openrc-service.js +469 -0
  11. package/dist/runtime-host-run-command.js +6 -2
  12. package/dist/runtime-host-service-command.js +3 -3
  13. package/dist/runtime-host-service-management-command.js +43 -15
  14. package/dist/runtime-host-session-channel.js +3 -0
  15. package/dist/runtime-host-session-driver.js +21 -6
  16. package/dist/runtime-host-setup-command.js +30 -31
  17. package/dist/tui-context-refresh.js +103 -0
  18. package/dist/tui-copy-catalog.js +73 -0
  19. package/native/runtime-host-peer/prebuilds/darwin-arm64/maka_runtime_host_peer.node +0 -0
  20. package/native/runtime-host-peer/prebuilds/linux-arm64/maka_runtime_host_peer.node +0 -0
  21. package/native/runtime-host-peer/prebuilds/linux-x64/maka_runtime_host_peer.node +0 -0
  22. package/native/runtime-host-peer/prebuilds/win32-x64/maka_runtime_host_peer.node +0 -0
  23. package/node_modules/@maka/core/dist/chat-model-choice.js +4 -0
  24. package/node_modules/@maka/core/dist/computer-use.js +27 -92
  25. package/node_modules/@maka/core/dist/interaction.js +577 -3
  26. package/node_modules/@maka/core/dist/llm-connections.js +4 -0
  27. package/node_modules/@maka/core/dist/local-memory.js +2 -2
  28. package/node_modules/@maka/core/dist/model-call-usage-projection.js +3 -0
  29. package/node_modules/@maka/core/dist/model-metadata.js +26 -7
  30. package/node_modules/@maka/core/dist/model-thinking.js +17 -0
  31. package/node_modules/@maka/core/dist/provider-registry.js +1 -0
  32. package/node_modules/@maka/core/dist/runtime-event.js +23 -1
  33. package/node_modules/@maka/core/dist/scheduled-task.js +4 -0
  34. package/node_modules/@maka/core/dist/session.js +95 -2
  35. package/node_modules/@maka/core/dist/text-sanitize.js +19 -0
  36. package/node_modules/@maka/core/dist/usage-ledger-merge.js +3 -0
  37. package/node_modules/@maka/core/dist/usage-record-schema.js +11 -5
  38. package/node_modules/@maka/core/dist/workhub-creation-intent.js +75 -9
  39. package/node_modules/@maka/core/dist/workhub-session-resolver.js +50 -0
  40. package/node_modules/@maka/core/package.json +2 -0
  41. package/node_modules/@maka/eval/dist/harbor-external-subject.js +2 -1
  42. package/node_modules/@maka/eval/dist/harness-executor.js +3 -2
  43. package/node_modules/@maka/eval/dist/install-preflight.js +39 -10
  44. package/node_modules/@maka/eval/dist/process-termination.js +83 -0
  45. package/node_modules/@maka/mcp/dist/sep-2243.js +3 -3
  46. package/node_modules/@maka/runtime/dist/agent-run.js +6 -3
  47. package/node_modules/@maka/runtime/dist/ai-sdk-backend.js +332 -118
  48. package/node_modules/@maka/runtime/dist/ai-sdk-compaction-contract.js +6 -1
  49. package/node_modules/@maka/runtime/dist/ai-sdk-compaction.js +171 -341
  50. package/node_modules/@maka/runtime/dist/bots/telegram-bridge.js +3 -26
  51. package/node_modules/@maka/runtime/dist/bundled-skill-catalog.generated.js +1 -1
  52. package/node_modules/@maka/runtime/dist/computer-use-codec.js +1 -141
  53. package/node_modules/@maka/runtime/dist/computer-use-tools.js +23 -105
  54. package/node_modules/@maka/runtime/dist/context-budget-policy.js +20 -26
  55. package/node_modules/@maka/runtime/dist/context-budget.js +18 -20
  56. package/node_modules/@maka/runtime/dist/conversation-copy.js +23 -19
  57. package/node_modules/@maka/runtime/dist/cua-frame-state.js +1 -69
  58. package/node_modules/@maka/runtime/dist/github-copilot-oauth-enrollment.js +267 -0
  59. package/node_modules/@maka/runtime/dist/history-compact-checkpoint.js +6 -9
  60. package/node_modules/@maka/runtime/dist/history-compact-summarizer.js +67 -23
  61. package/node_modules/@maka/runtime/dist/history-compact-summary-validation.js +11 -18
  62. package/node_modules/@maka/runtime/dist/history-compaction.js +66 -73
  63. package/node_modules/@maka/runtime/dist/interaction-authority.js +69 -0
  64. package/node_modules/@maka/runtime/dist/mcp-tools.js +13 -1
  65. package/node_modules/@maka/runtime/dist/memory-extraction.js +11 -11
  66. package/node_modules/@maka/runtime/dist/model-adapter.js +24 -6
  67. package/node_modules/@maka/runtime/dist/model-factory.js +14 -5
  68. package/node_modules/@maka/runtime/dist/oauth-provider-contracts.js +28 -1
  69. package/node_modules/@maka/runtime/dist/openai-codex-history-compactor.js +7 -6
  70. package/node_modules/@maka/runtime/dist/opencode-session-header.js +29 -0
  71. package/node_modules/@maka/runtime/dist/runtime-event-read-model.js +11 -1
  72. package/node_modules/@maka/runtime/dist/runtime-kernel.js +12 -11
  73. package/node_modules/@maka/runtime/dist/runtime-read-model.js +51 -13
  74. package/node_modules/@maka/runtime/dist/scheduled-task-tools.js +3 -0
  75. package/node_modules/@maka/runtime/dist/session-event-runtime-mapper.js +26 -0
  76. package/node_modules/@maka/runtime/dist/session-manager.js +1 -0
  77. package/node_modules/@maka/runtime/dist/session-projection-helpers.js +16 -1
  78. package/node_modules/@maka/runtime/dist/stream-graph-projection.js +6 -0
  79. package/node_modules/@maka/runtime/dist/stream-graph-read-model.js +5 -0
  80. package/node_modules/@maka/runtime/dist/stream-usage-fallback-fetch.js +74 -0
  81. package/node_modules/@maka/runtime/dist/subscription-credentials.js +51 -4
  82. package/node_modules/@maka/runtime/dist/subscription-model-fetch.js +47 -3
  83. package/node_modules/@maka/runtime/dist/system-prompt/main-session-prompt.js +20 -1
  84. package/node_modules/@maka/runtime/dist/test-connection.js +18 -11
  85. package/node_modules/@maka/runtime/dist/tool-runtime.js +183 -0
  86. package/node_modules/@maka/runtime/package.json +1 -0
  87. package/node_modules/@maka/runtime-host/dist/adapter/session-projector.js +14 -0
  88. package/node_modules/@maka/runtime-host/dist/client/client-capability-channel.js +84 -1
  89. package/node_modules/@maka/runtime-host/dist/client/host-profile.js +68 -51
  90. package/node_modules/@maka/runtime-host/dist/client/index.js +1 -1
  91. package/node_modules/@maka/runtime-host/dist/client/owner-connection-code.js +8 -5
  92. package/node_modules/@maka/runtime-host/dist/client/peer-client.js +342 -36
  93. package/node_modules/@maka/runtime-host/dist/client/reconnect-lifecycle.js +60 -4
  94. package/node_modules/@maka/runtime-host/dist/peer-mesh/index.js +3 -3
  95. package/node_modules/@maka/runtime-host/dist/peer-mesh/limits.js +1 -1
  96. package/node_modules/@maka/runtime-host/dist/peer-mesh/model.js +48 -60
  97. package/node_modules/@maka/runtime-host/dist/peer-mesh/node.js +847 -431
  98. package/node_modules/@maka/runtime-host/dist/peer-mesh/owner.js +33 -74
  99. package/node_modules/@maka/runtime-host/dist/peer-mesh/store.js +82 -69
  100. package/node_modules/@maka/runtime-host/dist/peer-reachability/index.js +21 -0
  101. package/node_modules/@maka/runtime-host/dist/peer-reachability/model.js +202 -0
  102. package/node_modules/@maka/runtime-host/dist/peer-reachability/owner.js +119 -0
  103. package/node_modules/@maka/runtime-host/dist/peer-reachability/publisher.js +245 -0
  104. package/node_modules/@maka/runtime-host/dist/protocol/agent-graph.js +4 -1
  105. package/node_modules/@maka/runtime-host/dist/protocol/client-capability.js +68 -0
  106. package/node_modules/@maka/runtime-host/dist/protocol/connection-effects.js +15 -8
  107. package/node_modules/@maka/runtime-host/dist/protocol/host-status.js +7 -23
  108. package/node_modules/@maka/runtime-host/dist/protocol/index.js +47 -1
  109. package/node_modules/@maka/runtime-host/dist/protocol/oauth.js +25 -1
  110. package/node_modules/@maka/runtime-host/dist/protocol/operations.js +1 -0
  111. package/node_modules/@maka/runtime-host/dist/protocol/peer-mesh.js +14 -31
  112. package/node_modules/@maka/runtime-host/dist/protocol/scheduled-task.js +19 -6
  113. package/node_modules/@maka/runtime-host/dist/protocol/session-collaboration.js +36 -1
  114. package/node_modules/@maka/runtime-host/dist/protocol/session-revision.js +11 -2
  115. package/node_modules/@maka/runtime-host/dist/protocol/usage-pricing.js +16 -2
  116. package/node_modules/@maka/runtime-host/dist/protocol/workhub-coordination.js +51 -2
  117. package/node_modules/@maka/runtime-host/dist/server/access-authority.js +35 -2
  118. package/node_modules/@maka/runtime-host/dist/server/access-credential-store.js +1 -0
  119. package/node_modules/@maka/runtime-host/dist/server/client-capability-coordinator.js +12 -10
  120. package/node_modules/@maka/runtime-host/dist/server/client-capability-invocation-broker.js +163 -30
  121. package/node_modules/@maka/runtime-host/dist/server/connection-effect-coordinator.js +38 -14
  122. package/node_modules/@maka/runtime-host/dist/server/daily-review-coordinator.js +45 -22
  123. package/node_modules/@maka/runtime-host/dist/server/execution-composition.js +78 -20
  124. package/node_modules/@maka/runtime-host/dist/server/execution-model-authority.js +4 -2
  125. package/node_modules/@maka/runtime-host/dist/server/execution-model-composition.js +2 -1
  126. package/node_modules/@maka/runtime-host/dist/server/execution-service.js +49 -28
  127. package/node_modules/@maka/runtime-host/dist/server/host-kernel.js +3 -6
  128. package/node_modules/@maka/runtime-host/dist/server/interaction-coordinator.js +130 -27
  129. package/node_modules/@maka/runtime-host/dist/server/interaction-projection.js +30 -1
  130. package/node_modules/@maka/runtime-host/dist/server/listener-set.js +2 -4
  131. package/node_modules/@maka/runtime-host/dist/server/message-coordinator.js +16 -3
  132. package/node_modules/@maka/runtime-host/dist/server/oauth-coordinator.js +66 -3
  133. package/node_modules/@maka/runtime-host/dist/server/oauth-execution-authority.js +20 -3
  134. package/node_modules/@maka/runtime-host/dist/server/peer-listener.js +8 -21
  135. package/node_modules/@maka/runtime-host/dist/server/peer-mesh-authority.js +1 -1
  136. package/node_modules/@maka/runtime-host/dist/server/root-turn-coordinator.js +6 -3
  137. package/node_modules/@maka/runtime-host/dist/server/scheduled-task-coordinator.js +72 -12
  138. package/node_modules/@maka/runtime-host/dist/server/session-revision-coordinator.js +48 -18
  139. package/node_modules/@maka/runtime-host/dist/server/session-turn-access-request-coordinator.js +43 -26
  140. package/node_modules/@maka/runtime-host/dist/server/usage-pricing-coordinator.js +15 -1
  141. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-action-gate.js +229 -4
  142. package/node_modules/@maka/runtime-host/dist/server/workhub-coordination-coordinator.js +146 -8
  143. package/node_modules/@maka/runtime-host/dist/transport/peer-native.js +32 -6
  144. package/node_modules/@maka/runtime-host/package.json +1 -0
  145. package/node_modules/@maka/storage/dist/agent-run-store.js +18 -5
  146. package/node_modules/@maka/storage/dist/codex-session-adapter.js +14 -0
  147. package/node_modules/@maka/storage/dist/execution-stores.js +5 -0
  148. package/node_modules/@maka/storage/dist/interaction-store.js +13 -1
  149. package/node_modules/@maka/storage/dist/runtime-policy/connection-catalog-document.js +9 -3
  150. package/node_modules/@maka/storage/dist/runtime-policy/coordinator.js +49 -19
  151. package/node_modules/@maka/storage/dist/runtime-policy/oauth-login-receipt-document.js +3 -1
  152. package/node_modules/@maka/storage/dist/runtime-policy/onboarding-transaction.js +13 -5
  153. package/node_modules/@maka/storage/dist/session-copy-cleanup.js +4 -2
  154. package/node_modules/@maka/storage/dist/session-store.js +39 -6
  155. package/node_modules/@maka/storage/dist/sqlite-runtime-store.js +16 -9
  156. package/node_modules/@maka/storage/dist/sqlite-session-metadata-schema.js +30 -3
  157. package/node_modules/@maka/storage/dist/sqlite-session-metadata-store.js +117 -0
  158. package/node_modules/@maka/storage/dist/sqlite-usage-store.js +29 -6
  159. package/node_modules/@maka/storage/dist/usage-stores.js +3 -1
  160. package/package.json +1 -1
@@ -17,8 +17,8 @@
17
17
  * under the License.
18
18
  */
19
19
  import { compactionDecisionDiagnosticPatch } from './compaction-boundary.js';
20
- import { buildContextBudgetDiagnosticShell, estimateRuntimeEventsTokens, mergeContextBudgetDiagnostic, } from './context-budget.js';
21
- import { evaluateHistoryCompactCheckpointReplay, isHistoryCompactContentEvent, } from './history-compaction.js';
20
+ import { buildContextBudgetDiagnosticShell, mergeContextBudgetDiagnostic, } from './context-budget.js';
21
+ import { isHistoryCompactContentEvent } from './history-compaction.js';
22
22
  import { canContinueHistoryCompactCheckpointForModel, canReplayHistoryCompactCheckpointForModel, matchHistoryCompactCheckpointPrefix, projectHistoryCompactCheckpointReplay, } from './history-compact-checkpoint.js';
23
23
  import { HistoryCompactSummarizerError, isMalformedHistoryCompactSummaryReason, } from './history-compact-error.js';
24
24
  import { createHash } from 'node:crypto';
@@ -27,11 +27,9 @@ import { archiveToolResultAsTransition, collectStaleToolResultArchiveCandidates,
27
27
  import { estimateTokens } from './context-budget-helpers.js';
28
28
  import { baseToolResultProjection, reduceEffectiveModelProjections, } from './model-projection-transition-ledger.js';
29
29
  import { buildRuntimeEventModelReplayPlan, collectToolActivityTurnIds, compatibleProviderReasoningReplayEventIds, } from './model-history.js';
30
- import { toolSchemaCharsForDiagnostics } from './request-shape.js';
31
- import { estimateNextRequestTokens, exceedsHighWater, planHistoryCompaction, } from './history-compaction.js';
32
- import { resolveSelectedModelContextWindow } from './context-budget-policy.js';
33
- import { MATERIALIZED_IMAGE_TOKENS } from '@maka/core/attachments';
34
- import { collectHistoricalImageToolResults, isInlineImageFilePart, omitHistoricalImageToolResults, } from './provider-image-overflow-recovery.js';
30
+ import { planHistoryCompaction } from './history-compaction.js';
31
+ import { resolveDeclaredContextWindow } from './context-budget-policy.js';
32
+ import { collectHistoricalImageToolResults, omitHistoricalImageToolResults, } from './provider-image-overflow-recovery.js';
35
33
  export class AiSdkCompaction {
36
34
  input;
37
35
  sessionId;
@@ -125,7 +123,6 @@ export class AiSdkCompaction {
125
123
  return { outcome: { kind: 'unchanged', reason: 'empty_history' } };
126
124
  }
127
125
  const charsPerToken = policy.charsPerToken ?? 4;
128
- const estimatedTokensBefore = Math.max(1, estimateRuntimeEventsTokens(runtimeContext, charsPerToken));
129
126
  let previousCheckpoint;
130
127
  try {
131
128
  const loaded = await Promise.resolve(this.input.loadHistoryCompactCheckpoint?.());
@@ -140,8 +137,7 @@ export class AiSdkCompaction {
140
137
  if (previousCheckpoint) {
141
138
  const match = matchHistoryCompactCheckpointPrefix(previousCheckpoint, runtimeContext);
142
139
  if (!match.reason && match.successorRuntimeEvents.length === 0) {
143
- const fit = evaluateHistoryCompactCheckpointReplay(previousCheckpoint, [], charsPerToken, policy.maxHistoryEstimatedTokens, { sourceReplayEvents: runtimeContext });
144
- if (fit.fits) {
140
+ {
145
141
  const projectedEvents = projectHistoryCompactCheckpointReplay(previousCheckpoint, match.coveredRuntimeEvents, []);
146
142
  return {
147
143
  outcome: { kind: 'unchanged', reason: 'already_compacted' },
@@ -173,6 +169,13 @@ export class AiSdkCompaction {
173
169
  sessionId: this.sessionId,
174
170
  phase: 'standalone',
175
171
  orderedEvents: runtimeContext,
172
+ ...(input.runtimeContextRunHeaders ? { runHeaders: input.runtimeContextRunHeaders } : {}),
173
+ acceptedRoute: {
174
+ modelId: this.input.modelId,
175
+ ...(this.targetConnectionId !== undefined
176
+ ? { connectionId: this.targetConnectionId }
177
+ : {}),
178
+ },
176
179
  reserveTailEvents: 0,
177
180
  charsPerToken,
178
181
  now: this.now(),
@@ -193,10 +196,6 @@ export class AiSdkCompaction {
193
196
  },
194
197
  newlyFoldedRuntimeEvents: [...newlyFoldedRuntimeEvents],
195
198
  ...(previousCheckpoint ? { previousCheckpoint } : {}),
196
- inputBudget: {
197
- maxEstimatedTokens: policy.maxHistoryEstimatedTokens ?? estimatedTokensBefore,
198
- charsPerToken,
199
- },
200
199
  abortSignal: historyCompactAbortController.signal,
201
200
  ...(tracker ? { providerRequestTracker: tracker } : {}),
202
201
  }),
@@ -221,22 +220,6 @@ export class AiSdkCompaction {
221
220
  }),
222
221
  };
223
222
  }
224
- const replayFit = evaluateHistoryCompactCheckpointReplay(plan.checkpoint, plan.tailRuntimeEvents, charsPerToken, policy.maxHistoryEstimatedTokens, { sourceReplayEvents: runtimeContext });
225
- if (!replayFit.fits) {
226
- return {
227
- outcome: { kind: 'failed', reason: replayFit.reason },
228
- contextBudget: mergeContextBudgetDiagnostic(diagnosticShell(runtimeContext), {
229
- ...compactionDecisionDiagnosticPatch({
230
- stage: 'priorReplay',
231
- sourceKind: 'runtimeEvents',
232
- decision: 'failedOpen',
233
- phase: 'pre_turn',
234
- boundaryKind: 'historyCompact',
235
- failOpenReason: replayFit.reason,
236
- }),
237
- }),
238
- };
239
- }
240
223
  try {
241
224
  await Promise.resolve(recorder(plan.checkpoint, input.turnId));
242
225
  }
@@ -303,7 +286,7 @@ export class AiSdkCompaction {
303
286
  modelId: this.input.modelId,
304
287
  historyCompactRoute: this.input.historyCompactRoute,
305
288
  contextBudget: this.input.contextBudget,
306
- inputBudget: input.inputBudget,
289
+ maxOutputTokens: input.maxOutputTokens,
307
290
  previousCheckpoint: input.previousCheckpoint,
308
291
  currentRunEventIds: input.runId
309
292
  ? input.source.foldedRuntimeEvents
@@ -562,39 +545,39 @@ export class AiSdkCompaction {
562
545
  const priorContentEvents = (input.runtimeContext ?? [])
563
546
  .filter((event) => event.turnId !== input.turnId)
564
547
  .filter(isHistoryCompactContentEvent);
565
- const state = new MidTurnCapacityCompactState(headAnchor, priorContentEvents, input.runtimeContextRunHeaders ?? [], resolveSelectedModelContextWindow(this.input.connection, this.input.modelId));
548
+ const state = new MidTurnCapacityCompactState(headAnchor, priorContentEvents, input.runtimeContextRunHeaders ?? [], resolveDeclaredContextWindow(this.input.connection, this.input.modelId));
566
549
  // Seed the turn's FIRST request with the last request the provider
567
- // actually counted, so step 0 is estimated like every later step instead
568
- // of guessing the whole payload at char/4.
550
+ // actually counted, so step 0 is judged by the same real number as every
551
+ // later step. No anchor means no proactive fold on step 0; the provider
552
+ // decides, and its rejection is recovered from.
569
553
  const persisted = persistedRequestAnchor(input.runtimeContext ?? [], state.priorRunHeaders, this.input.modelId, this.targetConnectionId);
570
554
  if (persisted) {
571
- state.lastRequestInputTokens = persisted.inputTokens;
572
- state.lastRequestPayloadChars = persisted.payloadChars;
555
+ state.baselineTokens = persisted.inputTokens + (persisted.outputTokens ?? 0);
556
+ state.lastAcceptedTotalTokens = state.baselineTokens;
557
+ state.priorAcceptedInputTokens = persisted.inputTokens;
573
558
  }
559
+ if (persisted)
560
+ state.replyReserveTokens = replyReserveTokens(persisted.outputTokens);
574
561
  return state;
575
562
  }
576
563
  /**
577
- * Request-projection stage for the mid-turn capacity invariant: between
578
- * steps of one turn, estimate the next provider request (last step's real
579
- * usage + a signed char/4 payload delta, tool schemas included) against
580
- * `contextWindow - reserve`; over the high-water, fold a safe completed
581
- * prefix into a durable mid_turn checkpoint and continue the same turn on
582
- * `[compact block, verbatim head anchor]`.
564
+ * Request-projection stage for proactive compaction: before each request of
565
+ * one turn, compare the baseline — the last provider-accepted request's real
566
+ * input plus real output tokens — against the context window the user
567
+ * declared, and over it fold a safe completed prefix into a durable
568
+ * checkpoint, continuing the turn on `[compact block, verbatim head anchor]`.
583
569
  *
584
- * This hook never terminates the turn: every failure fails open with a
585
- * diagnostic and the request goes out. The trigger threshold is approximate
586
- * on purpose — a missed or spurious trigger costs at most one compaction,
587
- * and whether the request actually fits is the provider's answer, not a
588
- * local estimate's.
570
+ * Nothing here estimates whether a request fits: the baseline is the
571
+ * provider's own count, the window is the user's own number, and the part of
572
+ * the next request neither describes (tool results, user text, images
573
+ * appended since) is judged by the provider when the request goes out. This
574
+ * hook never terminates the turn: every failure fails open with a diagnostic
575
+ * and the request is sent; a rejection is recovered by one reactive fold
576
+ * (#4559).
589
577
  */
590
578
  buildMidTurnCapacityCompactProjection(turnId, state, queue, providerTools, onDiagnosticPatch, origin, memoryCompactionDecision, onMemoryCompaction, abortSignal) {
591
579
  if (!state)
592
580
  return undefined;
593
- const policy = this.input.contextBudget;
594
- const compactPolicy = policy.historyCompact;
595
- const midTurn = compactPolicy.midTurn;
596
- const charsPerToken = policy.charsPerToken ?? 4;
597
- const reserveTokens = midTurn.reserveTokens ?? 16_384;
598
581
  let acceptedProjection;
599
582
  return async (options) => {
600
583
  const incomingMessages = options.messages;
@@ -602,37 +585,20 @@ export class AiSdkCompaction {
602
585
  projectedMessages =
603
586
  projectHistoricalImageOmissions(projectedMessages ?? incomingMessages, state.omittedImageToolResults) ?? projectedMessages;
604
587
  const keepProjection = () => projectedMessages ? { messages: projectedMessages } : undefined;
605
- // Real usage for the last finished step, read synchronously from the
606
- // SDK's own step results (the same numbers the finish-step chunk
607
- // carries) — no coupling to how far the stream consumer has advanced.
608
- // Baseline = the last request's INPUT tokens only (see the state field
609
- // doc: the payload delta already carries the step's output). The
610
- // adapter fails closed on missing token counts (undefined, #972), and a
611
- // provider can still report a zero input outright — either way a
612
- // non-positive input count is unusable for estimation, so clear the
613
- // baseline and let the estimate fall back to the whole-payload cold
614
- // start instead of "0 + delta".
615
- //
616
- // The usage anchor is only meaningful PAIRED with the payload baseline
617
- // of the request it was reported for (`lastRequestPayloadChars`). A
618
- // successful overflow recovery restructures the request and resets that
619
- // baseline to undefined: the send-global steps view still carries the
620
- // dead attempt's last usage, but anchoring on it against the rejected
621
- // request's chars would under-estimate the retry by the whole previous
622
- // step growth — so a missing baseline forces the whole-payload cold
623
- // start, exactly like a missing usage sample.
624
- //
625
- // Before the first step finishes nothing in-send has overwritten the
626
- // seeded pair, so leave it alone rather than clearing a coherent anchor.
588
+ // Baseline = the last accepted request's REAL input tokens plus its REAL
589
+ // output tokens, read synchronously from the SDK's own step results.
590
+ // Everything the model produced last step is re-sent as input this step,
591
+ // so both halves are already in the next request; the only part no
592
+ // number describes yet is what was appended from outside the model,
593
+ // and that part is the provider's to judge. A missing or non-positive
594
+ // input count is no baseline at all — unknown, never zero.
627
595
  if (options.completedSteps.length > 0) {
628
- const lastStepInputTokens = options.completedSteps.at(-1)?.usage?.inputTokens;
629
- state.lastRequestInputTokens =
630
- state.lastRequestPayloadChars !== undefined &&
631
- lastStepInputTokens !== undefined &&
632
- Number.isFinite(lastStepInputTokens) &&
633
- lastStepInputTokens > 0
634
- ? lastStepInputTokens
635
- : undefined;
596
+ const lastUsage = options.completedSteps.at(-1)?.usage;
597
+ state.baselineTokens = usageBaselineTokens(lastUsage);
598
+ if (state.baselineTokens !== undefined) {
599
+ state.lastAcceptedTotalTokens = state.baselineTokens;
600
+ state.replyReserveTokens = replyReserveTokens(lastUsage?.outputTokens);
601
+ }
636
602
  }
637
603
  // The turn's first request folds as a pre_turn boundary, like the
638
604
  // reactive step-0 recovery; later steps fold mid_turn.
@@ -654,44 +620,24 @@ export class AiSdkCompaction {
654
620
  });
655
621
  return keepProjection();
656
622
  };
657
- // A shaping failure records the step so the rescue re-entry does not
658
- // re-run a shaper that already attempted and failed this step.
659
- const shapeFailure = (diagnosticReason) => {
660
- state.lastShapeFailure = { stepNumber: options.stepNumber };
661
- return failOpen(diagnosticReason);
662
- };
663
- // Trigger estimate: the last request's input tokens plus a SIGNED char/4 delta of
664
- // this step's payload (system prompt + projected messages + active tool
665
- // schemas) against the previous request's measured payload. Measured synchronously from
666
- // the SDK's own projection — no ledger dependency — so a same-turn
667
- // `tool_search` schema expansion or a large tool result both count. This
668
- // position measures BEFORE later shapers (prune) run, so it can
669
- // over-trigger; that is the recoverable direction, and the verdict owner
670
- // re-measures the post-shaping payload.
671
- const measuredMessages = projectedMessages ?? incomingMessages;
672
- // Price the request dispatch will actually build, not the pre-dispatch
673
- // inputs: a finalization step adds prompt fragments and sends no tools.
674
- const dispatch = options.resolveDispatch(options.activeTools);
675
- const activeToolsForStep = dispatch.activeTools;
676
- const payloadChars = midTurnRequestPayloadChars(measuredMessages, providerTools, activeToolsForStep, dispatch.systemPromptChars, charsPerToken);
677
- const forcedEstimate = state.forcedTriggerEstimate;
678
- state.forcedTriggerEstimate = undefined;
679
- const anchored = requestEstimateAnchor(state, payloadChars);
680
- // The turn's FIRST request only gets a trigger when a previous turn left
681
- // a usable anchor. Without one the estimate is the whole payload at
682
- // chars/4 — the same guess the pre_turn gate already spends, and far too
683
- // crude to start a summarizer on. With one, step 0 is judged exactly like
684
- // every later step.
685
- if (options.stepNumber < 1 &&
686
- forcedEstimate === undefined &&
687
- anchored.priorUsageTokens === undefined) {
688
- return keepProjection();
689
- }
690
- const estimate = forcedEstimate ?? estimateNextRequestTokens({ ...anchored, charsPerToken });
691
- if (forcedEstimate === undefined &&
692
- (state.capacity === undefined || !exceedsHighWater(estimate, state.capacity, reserveTokens))) {
623
+ // One trigger, one real signal: the baseline plus the room the next reply
624
+ // needs crossed the window the user declared. A cut reply is deliberately
625
+ // not a trigger — see the note on `finishReason: length` in the backend.
626
+ // The next request is at least the baseline, and its reply needs room on
627
+ // top of it. The room is measured from the last reply the model actually
628
+ // wrote, not from the largest one it could write: on a model whose
629
+ // output limit is a large fraction of its window (k3-256k reports
630
+ // 131,072 against 262,144) reserving the limit would fold at half the
631
+ // declared window, while a reply twice the size of the last one is the
632
+ // margin the session's own behaviour supports (#4634).
633
+ const overWindow = state.capacity !== undefined &&
634
+ state.baselineTokens !== undefined &&
635
+ state.baselineTokens + state.replyReserveTokens >= state.capacity;
636
+ if (!overWindow || state.compactionAttemptedThisSend) {
693
637
  return keepProjection();
694
638
  }
639
+ state.compactionAttemptedThisSend = true;
640
+ const activeToolsForStep = options.resolveDispatch(options.activeTools).activeTools;
695
641
  // Fold a safe completed prefix of the durable turn ledger into a
696
642
  // replacement projection (validate → persist), shared with the reactive
697
643
  // overflow path. This stage maps the outcome to the request-projection contract:
@@ -703,17 +649,18 @@ export class AiSdkCompaction {
703
649
  state,
704
650
  queue,
705
651
  minFlushedSteps: options.stepNumber,
706
- referencePayloadChars: payloadChars,
707
- providerTools,
708
652
  activeToolsForStep,
709
- systemPromptChars: dispatch.systemPromptChars,
710
653
  memoryCompactionDecision,
711
654
  onMemoryCompaction,
712
655
  abortSignal,
713
656
  });
714
657
  if (outcome.decision === 'fail') {
715
- return shapeFailure(outcome.diagnosticReason);
658
+ return failOpen(outcome.diagnosticReason);
716
659
  }
660
+ // The fold replaced the request; the baseline described the old one.
661
+ // The next accepted request is the first measurement of the new shape.
662
+ state.compactionAppliedThisSend = true;
663
+ state.baselineTokens = undefined;
717
664
  acceptedProjection = {
718
665
  sourceSignatures: incomingMessages.map(modelMessageSignature),
719
666
  projectedMessages: outcome.replacementMessages,
@@ -740,11 +687,11 @@ export class AiSdkCompaction {
740
687
  * the pass/terminate verdict and the diagnostic emission are the caller's.
741
688
  */
742
689
  async compactActiveRequestHistory(input) {
743
- const { turnId, state, queue, providerTools, activeToolsForStep, systemPromptChars, abortSignal, } = input;
744
- if (state.malformedSummaryFailure) {
690
+ const { turnId, state, queue, activeToolsForStep, abortSignal } = input;
691
+ if (state.summarizerFailure) {
745
692
  return {
746
693
  decision: 'fail',
747
- diagnosticReason: state.malformedSummaryFailure,
694
+ diagnosticReason: state.summarizerFailure,
748
695
  };
749
696
  }
750
697
  const summarizer = this.input.summarizeHistoryCompact;
@@ -761,9 +708,7 @@ export class AiSdkCompaction {
761
708
  const loadTurnRuntimeEvents = this.input.loadTurnRuntimeEvents;
762
709
  const policy = this.input.contextBudget;
763
710
  const compactPolicy = policy.historyCompact;
764
- const midTurn = compactPolicy.midTurn;
765
711
  const charsPerToken = policy.charsPerToken ?? 4;
766
- const reserveTokens = midTurn.reserveTokens ?? 16_384;
767
712
  // Coverage pool = the durable run ledger, read through the injected
768
713
  // seam. Covered events are persisted by construction (no crash window
769
714
  // between checkpoint and source), and their bytes are exactly what a
@@ -832,6 +777,11 @@ export class AiSdkCompaction {
832
777
  phase: input.phase ?? 'mid_turn',
833
778
  orderedEvents,
834
779
  headAnchor: { runtimeEventId: state.headAnchor.id, turnId },
780
+ runHeaders: state.priorRunHeaders,
781
+ acceptedRoute: {
782
+ modelId: this.input.modelId,
783
+ ...(this.targetConnectionId !== undefined ? { connectionId: this.targetConnectionId } : {}),
784
+ },
835
785
  reserveTailEvents: 1,
836
786
  charsPerToken,
837
787
  now: this.now(),
@@ -860,12 +810,6 @@ export class AiSdkCompaction {
860
810
  },
861
811
  ...(previousCheckpoint ? { previousCheckpoint } : {}),
862
812
  newlyFoldedRuntimeEvents: [...newlyFoldedRuntimeEvents],
863
- inputBudget: {
864
- ...(state.capacity !== undefined
865
- ? { maxEstimatedTokens: Math.max(1, state.capacity - reserveTokens) }
866
- : {}),
867
- charsPerToken,
868
- },
869
813
  ...(abortSignal ? { abortSignal } : {}),
870
814
  ...(midTurnTracker ? { providerRequestTracker: midTurnTracker } : {}),
871
815
  });
@@ -873,20 +817,22 @@ export class AiSdkCompaction {
873
817
  });
874
818
  if (plan.decision === 'fail_open') {
875
819
  const diagnosticReason = plan.diagnosticReason ?? plan.reason;
876
- if (isMalformedHistoryCompactSummaryReason(diagnosticReason)) {
877
- state.malformedSummaryFailure = diagnosticReason;
878
- }
820
+ // Latch every fail-open reason, not only the malformed ones. The baseline
821
+ // that fired this trigger survives a fail-open, so without the latch the
822
+ // next step evaluates the same condition and dispatches the same doomed
823
+ // summarizer call: a provider that answers slowly and fails (kimi's HTTP
824
+ // 200 with an error body) produced 15 such calls over 47 minutes before
825
+ // one main request (#4634). One attempt per send, then fail open (#4559).
826
+ state.summarizerFailure = diagnosticReason;
879
827
  return {
880
828
  decision: 'fail',
881
829
  diagnosticReason,
882
830
  };
883
831
  }
884
- // Lifecycle order is validate → persist → apply, where validate =
885
- // materializable ∧ smaller ∧ replay-admissible. Replay applies the
886
- // session's latest checkpoint BEFORE any high-water check, so a
887
- // checkpoint that fails ANY of the three must never be persisted — it
888
- // would poison every later projection even though this step correctly
889
- // refused it.
832
+ // Lifecycle order is validate → persist → apply, where validate is
833
+ // materializable and replay-admissible. A checkpoint that fails either
834
+ // check must never be persisted because it would poison every later
835
+ // projection.
890
836
  const replayPlan = buildRuntimeEventModelReplayPlan(plan.replacementEvents, {
891
837
  toolActivityTurnIds: collectToolActivityTurnIds(orderedEvents),
892
838
  });
@@ -899,28 +845,9 @@ export class AiSdkCompaction {
899
845
  };
900
846
  }
901
847
  const replacementMessages = await this.materializeRuntimeReplayPlan(replayPlan, input.origin.imageBudget, plan.checkpoint, compatibleProviderReasoningReplayEventIds(plan.replacementEvents, state.priorRunHeaders, this.targetProviderStateIdentity, this.input.modelId, input.origin.runId));
902
- // Apply the shape only when it actually shrinks the request versus the
903
- // reference payload (the incoming request for the proactive hook, the
904
- // request that overflowed for reactive recovery): a materialized
905
- // replacement that is not smaller proves the summarizer's OUTPUT is
906
- // unusable, reported as summarizer_failed via replacement_not_smaller.
907
- const replacedPayloadChars = midTurnRequestPayloadChars(replacementMessages, providerTools, activeToolsForStep, systemPromptChars, charsPerToken);
908
- if (replacedPayloadChars >= input.referencePayloadChars) {
909
- return {
910
- decision: 'fail',
911
- diagnosticReason: 'replacement_not_smaller',
912
- };
913
- }
914
- // Replay admissibility uses the same complete-prefix capacity gate as
915
- // recovery. Actual payload shrinkage was already checked above because
916
- // only this owner can measure the fully materialized provider request.
917
- const replayFit = evaluateHistoryCompactCheckpointReplay(plan.checkpoint, plan.checkpoint.version === 3 ? plan.replacementEvents : plan.replacementEvents.slice(1), policy?.charsPerToken, policy?.maxHistoryEstimatedTokens);
918
- if (!replayFit.fits) {
919
- return {
920
- decision: 'fail',
921
- diagnosticReason: `replay_rejected_${replayFit.reason}`,
922
- };
923
- }
848
+ // Whether the replacement fits is the provider's answer once it goes out;
849
+ // no local measure stands between a materializable fold and dispatch
850
+ // (#4559).
924
851
  // The replacement is valid: durably persist the checkpoint BEFORE
925
852
  // applying the projection — the same order as the pre_turn path. A
926
853
  // persistence failure keeps raw messages and records write_failed.
@@ -979,21 +906,13 @@ export class AiSdkCompaction {
979
906
  const image = eligibleImages.get(toolCallId);
980
907
  return image ? [[toolCallId, image]] : [];
981
908
  }));
982
- state.lastRequestPayloadChars = undefined;
983
- state.lastRequestInputTokens = undefined;
909
+ state.baselineTokens = undefined;
984
910
  return { messages: imageOmission.messages };
985
911
  }
986
- // The shrink baseline is the request the provider actually rejected. Its
987
- // single owner is the verdict owner's per-request payload measure
988
- // (state.lastRequestPayloadChars), recorded at the end of every
989
- // request-projection run — the attempt-INITIAL messages undercount the rejected
990
- // request by every same-turn tool step, and a baseline anchored there
991
- // refuses folds that genuinely shrink the real request (review P1-1).
992
- // The cold-start fallback only covers a send whose verdict owner never
993
- // ran request projection (defensive; step 0 records the baseline too).
994
- const referencePayloadChars = state.lastRequestPayloadChars ??
995
- midTurnRequestPayloadChars(input.currentMessages, input.providerTools, input.activeTools, input.systemPromptChars, this.input.contextBudget?.charsPerToken ?? 4);
996
912
  const phase = input.stepNumber === 0 ? 'pre_turn' : 'mid_turn';
913
+ // Entering the module spends the send's one attempt whether or not a fold
914
+ // comes out of it; only a selected projection sets `applied`.
915
+ state.compactionAttemptedThisSend = true;
997
916
  const outcome = await this.compactActiveRequestHistory({
998
917
  turnId: input.turnId,
999
918
  phase,
@@ -1003,10 +922,7 @@ export class AiSdkCompaction {
1003
922
  // The stream has ended, so every completed step is already flushed; wait
1004
923
  // only for the consumer to drain the durable ledger up to date.
1005
924
  minFlushedSteps: state.flushedSteps,
1006
- referencePayloadChars,
1007
- providerTools: input.providerTools,
1008
925
  activeToolsForStep: input.activeTools,
1009
- systemPromptChars: input.systemPromptChars,
1010
926
  memoryCompactionDecision: input.memoryCompactionDecision,
1011
927
  onMemoryCompaction: input.onMemoryCompaction,
1012
928
  abortSignal: input.abortSignal,
@@ -1039,92 +955,11 @@ export class AiSdkCompaction {
1039
955
  estimatedTokensAfter: outcome.estimatedTokensAfter,
1040
956
  reason: 'overflow',
1041
957
  }));
1042
- // A successful recovery restructures the request, so the rejected
1043
- // request's payload measure no longer describes what the retry sends.
1044
- // Reset the baseline: the capacity hook's usage anchor is only coherent
1045
- // paired with the payload chars of the SAME request, and a missing
1046
- // baseline forces the whole-payload cold-start estimate instead of a
1047
- // stale pairing against the dead attempt. The cross-turn seed goes with
1048
- // it: falling back to an even older request's anchor pairs worse, not
1049
- // better.
1050
- state.lastRequestPayloadChars = undefined;
1051
- state.lastRequestInputTokens = undefined;
958
+ // The fold replaced the request; the baseline described the rejected one.
959
+ state.compactionAppliedThisSend = true;
960
+ state.baselineTokens = undefined;
1052
961
  return { messages: outcome.replacementMessages };
1053
962
  }
1054
- /**
1055
- * The single end-of-pipeline estimate owner for the mid-turn capacity
1056
- * invariant. Every request-projection stage only shapes; this wrapper measures the
1057
- * FINAL outgoing (messages, tools) payload — the bytes the provider will
1058
- * actually see, after capacity compaction, active tool-result pruning, and
1059
- * semantic/active-full compaction have all run — and spends the last
1060
- * chance to shrink it:
1061
- *
1062
- * - estimate = the last request's real INPUT tokens + signed char/4 delta
1063
- * against the previous request's measured payload (recorded here on
1064
- * every step, including step 0's baseline); the delta already carries
1065
- * the step's fresh output, so an output-inclusive baseline would count
1066
- * it twice, and an unusable usage sample falls back to the whole-payload
1067
- * cold start rather than a zero baseline;
1068
- * - over the window with no capacity attempt this step (the approximate
1069
- * trigger missed, e.g. growth the trigger under-weighted), force ONE
1070
- * capacity re-entry.
1071
- *
1072
- * Still over afterwards, the request goes out anyway: only the provider
1073
- * knows whether it fits, and a rejection is recovered from.
1074
- */
1075
- buildMidTurnFinalRequestRescue(input) {
1076
- const { shaped, reentry, state, providerTools, charsPerToken } = input;
1077
- return async (options) => {
1078
- let result = await Promise.resolve(shaped(options));
1079
- const omissionProjection = projectHistoricalImageOmissions(result?.messages ?? options.messages, state.omittedImageToolResults);
1080
- if (omissionProjection) {
1081
- result = { ...(result ?? {}), messages: omissionProjection };
1082
- }
1083
- const finalPayloadChars = () => {
1084
- // Measure the dispatched shape, so the payload recorded as the anchor's
1085
- // pair describes the same request the provider counts.
1086
- const dispatch = options.resolveDispatch(result?.activeTools ?? options.activeTools);
1087
- return midTurnRequestPayloadChars(result?.messages ?? options.messages, providerTools, dispatch.activeTools, dispatch.systemPromptChars, charsPerToken);
1088
- };
1089
- let payloadChars = finalPayloadChars();
1090
- // Same rule as the trigger: the turn's first request is measured only
1091
- // when a previous turn left a usable anchor to measure it against.
1092
- const anchoredAtStepZero = requestEstimateAnchor(state, payloadChars).priorUsageTokens !== undefined;
1093
- if (state.capacity !== undefined && (options.stepNumber >= 1 || anchoredAtStepZero)) {
1094
- const estimateFinal = () => estimateNextRequestTokens({
1095
- ...requestEstimateAnchor(state, payloadChars),
1096
- charsPerToken,
1097
- });
1098
- const estimate = estimateFinal();
1099
- const capacityAttemptedThisStep = state.replacedStepNumber === options.stepNumber ||
1100
- state.lastShapeFailure?.stepNumber === options.stepNumber;
1101
- if (estimate > state.capacity && !capacityAttemptedThisStep) {
1102
- // One bounded capacity re-entry. Re-run only the capacity + prune
1103
- // shapers over the already-shaped projection; a second attempt
1104
- // after a same-step failure is pointless (the failure was not a
1105
- // trigger miss) and would double recorder counters and summarizer
1106
- // calls.
1107
- state.forcedTriggerEstimate = estimate;
1108
- const reshaped = await Promise.resolve(reentry({
1109
- ...options,
1110
- messages: result?.messages ?? options.messages,
1111
- ...(result?.activeTools ? { activeTools: result.activeTools } : {}),
1112
- }));
1113
- state.forcedTriggerEstimate = undefined;
1114
- if (reshaped) {
1115
- result = {
1116
- ...(result ?? {}),
1117
- ...reshaped,
1118
- activeTools: reshaped.activeTools ?? result?.activeTools,
1119
- };
1120
- }
1121
- payloadChars = finalPayloadChars();
1122
- }
1123
- }
1124
- state.lastRequestPayloadChars = payloadChars;
1125
- return result;
1126
- };
1127
- }
1128
963
  }
1129
964
  // -- moved helpers (defined in ai-sdk-backend, used only by cache write) -------
1130
965
  function incrementRecord(counts, key) {
@@ -1221,28 +1056,28 @@ export class MidTurnCapacityCompactState {
1221
1056
  priorRunHeaders;
1222
1057
  capacity;
1223
1058
  /**
1224
- * Raw serialized chars of the final provider request. Overflow recovery
1225
- * uses this as its shrink-reference baseline because it must compare the
1226
- * actual rejected projection with a candidate replacement.
1227
- *
1228
- * Seeded before the turn's first request from the anchor a previous turn
1229
- * persisted, so it can describe a request from an earlier send.
1059
+ * The last provider-accepted request's real input tokens plus its real
1060
+ * output tokens, as the provider counted them — everything already in the
1061
+ * next request that a number describes. Seeded from the previous turn's
1062
+ * persisted anchor, refreshed at every step boundary, and cleared by any
1063
+ * fold (the checkpoint changed the request; the next accepted one is the
1064
+ * first measurement). Undefined is "no baseline", never zero.
1230
1065
  */
1231
- lastRequestPayloadChars;
1066
+ baselineTokens;
1232
1067
  /**
1233
- * The last request's REAL input size: the inputTokens the provider reported
1234
- * for the last finished step. Never input+output — the signed payload delta
1235
- * already carries the step's freshly generated output (assistant text/tool
1236
- * calls) and its tool results, so an output-inclusive baseline would count
1237
- * them twice. Undefined when the last step's usage is missing or unusable
1238
- * (no positive input count); estimates then fall back to the whole-payload
1239
- * cold-start path — an unusable sample is unknown, never zero.
1240
- *
1241
- * Written and cleared as a pair with `lastRequestPayloadChars`, seeded from
1242
- * the previous turn's persisted anchor — see `LastRequestAnchor` for why the
1243
- * two only mean anything together.
1068
+ * Input plus output of the last request the provider accepted, as it
1069
+ * counted them. Unlike `baselineTokens` it survives a fold: it is not a
1070
+ * trigger input but the number a rejected user can declare as their window,
1071
+ * proven to fit because the provider already accepted it (#4559).
1244
1072
  */
1245
- lastRequestInputTokens;
1073
+ lastAcceptedTotalTokens;
1074
+ /**
1075
+ * Room the next reply may need: the model's declared output limit when the
1076
+ * connection or metadata states one, else 0. A provider fact, never an
1077
+ * estimate; it lets the trigger fire before a request that would otherwise
1078
+ * be accepted but leave the reply no room (#4559).
1079
+ */
1080
+ replyReserveTokens = 0;
1246
1081
  /** Latest durable checkpoint (loaded or written) for roll-forward summaries. */
1247
1082
  previousCheckpoint;
1248
1083
  /** Checkpoint accepted during this send; pins every later durable projection. */
@@ -1260,24 +1095,40 @@ export class MidTurnCapacityCompactState {
1260
1095
  * events enqueued at all.
1261
1096
  */
1262
1097
  flushedSteps = 0;
1263
- /**
1264
- * Set by the final-request estimate owner to force one capacity re-entry on
1265
- * the current step, bypassing the (deliberately approximate) high-water
1266
- * trigger. Consumed by the capacity hook on its next invocation.
1267
- */
1268
- forcedTriggerEstimate;
1269
1098
  /** Exact historical image results omitted after a provider overflow. */
1270
1099
  omittedImageToolResults = new Map();
1100
+ /** Malformed summaries spend one bounded repair budget for this whole Turn. */
1101
+ summarizerFailure;
1271
1102
  /**
1272
- * The step of the capacity hook's most recent shaping failure. The rescue
1273
- * re-entry reads it so it never re-runs a shaper that already attempted and
1274
- * failed on the same step.
1103
+ * The compaction module has been entered in this send.
1104
+ *
1105
+ * One attempt per send, whatever its outcome: the summarizer's own failure
1106
+ * circuit already latches for the rest of the send, so a second entry would
1107
+ * dispatch nothing new. This is the budget, and only the budget (#4559).
1275
1108
  */
1276
- lastShapeFailure;
1277
- /** Malformed summaries spend one bounded repair budget for this whole Turn. */
1278
- malformedSummaryFailure;
1109
+ compactionAttemptedThisSend = false;
1110
+ /**
1111
+ * A folded projection was actually selected in this send.
1112
+ *
1113
+ * Distinct from the attempt: a fold that fails open leaves the request
1114
+ * carrying its full raw history, so nothing may be concluded from a later
1115
+ * rejection about what remains in it.
1116
+ */
1117
+ compactionAppliedThisSend = false;
1118
+ /**
1119
+ * Input tokens of the last request a provider accepted before this send.
1120
+ *
1121
+ * Input against input, across the send boundary: the first request of a send
1122
+ * has no earlier step to compare with, and `baselineTokens` counts the reply
1123
+ * too, which the next request does not always carry.
1124
+ */
1125
+ priorAcceptedInputTokens;
1279
1126
  constructor(headAnchor, priorContentEvents, priorRunHeaders,
1280
- /** The model's declared context window, absent when it declares none. */
1127
+ /**
1128
+ * The Maka window: the context window the USER declared for this model,
1129
+ * a compaction target and nothing else. Absent when none is declared,
1130
+ * and then no proactive fold ever runs — the provider decides (#4559).
1131
+ */
1281
1132
  capacity) {
1282
1133
  this.headAnchor = headAnchor;
1283
1134
  this.priorContentEvents = priorContentEvents;
@@ -1286,37 +1137,33 @@ export class MidTurnCapacityCompactState {
1286
1137
  }
1287
1138
  }
1288
1139
  /**
1289
- * Char measure of the FULL provider-visible request input: the system prompt
1290
- * (sent through the separate `system` field), the (projected) messages, and
1291
- * the serialized schemas of the active tool subset. Media is billed in tokens
1292
- * converted to chars, so the whole measure stays in one unit. The capacity
1293
- * trigger and the rescue re-entry both measure with this ONE function, so
1294
- * their comparisons against `lastRequestPayloadChars` are commensurable and
1295
- * same-turn tool-schema growth (a `tool_search` activation) is counted like
1296
- * any other payload growth. The system prompt is constant between adjacent
1297
- * requests — signed deltas cancel it — but the cold-start estimate (no usable
1298
- * usage sample) is the whole payload, so omitting it would under-estimate by
1299
- * exactly the system prompt.
1140
+ * The baseline one accepted request leaves for the next: its real input plus
1141
+ * its real output tokens. Output is counted whole, reasoning included — a wire
1142
+ * that does not resend reasoning makes this err high, and high is the safe
1143
+ * direction for a trigger that can only ask for a compaction (#4559).
1144
+ */
1145
+ /**
1146
+ * Room to leave for the next reply, from the size of the last real one.
1300
1147
  *
1301
- * A media part is worth what the provider charges for it, not what it
1302
- * serializes to: materialized bytes reach the request as base64 or a byte map,
1303
- * where a 500 KB screenshot serializes to ~667K chars. Measuring that string
1304
- * makes one image look like a whole context window, which is how an affordable
1305
- * request became a terminal verdict (#4458). Billing it at the same constant
1306
- * the ledger's ruler uses keeps the two measures commensurable.
1148
+ * Two real numbers and one bound: twice the last reply absorbs an answer that
1149
+ * grows, and the cap keeps a single long reply from turning the reserve into
1150
+ * the window. No previous reply means no reserve, never a guessed one.
1307
1151
  */
1308
- function midTurnRequestPayloadChars(messages, providerTools, activeTools, systemPromptChars, charsPerToken) {
1309
- let mediaParts = 0;
1310
- const serializedMessages = JSON.stringify(messages, (_key, value) => {
1311
- if (!isInlineImageFilePart(value))
1312
- return value;
1313
- mediaParts += 1;
1314
- return { type: value.type, mediaType: value.mediaType };
1315
- });
1316
- return (Math.max(0, Math.floor(systemPromptChars)) +
1317
- (serializedMessages?.length ?? 0) +
1318
- mediaParts * MATERIALIZED_IMAGE_TOKENS * Math.max(1, charsPerToken) +
1319
- toolSchemaCharsForDiagnostics(providerTools, activeTools));
1152
+ const MAX_REPLY_RESERVE_TOKENS = 8_000;
1153
+ function replyReserveTokens(lastReplyTokens) {
1154
+ if (lastReplyTokens === undefined || !Number.isFinite(lastReplyTokens) || lastReplyTokens <= 0) {
1155
+ return 0;
1156
+ }
1157
+ return Math.min(lastReplyTokens * 2, MAX_REPLY_RESERVE_TOKENS);
1158
+ }
1159
+ function usageBaselineTokens(usage) {
1160
+ if (!usage)
1161
+ return undefined;
1162
+ const input = usage.inputTokens;
1163
+ if (!Number.isFinite(input) || input <= 0)
1164
+ return undefined;
1165
+ const output = Number.isFinite(usage.outputTokens) ? Math.max(0, usage.outputTokens) : 0;
1166
+ return input + output;
1320
1167
  }
1321
1168
  /**
1322
1169
  * The newest `LastRequestAnchor` persisted in the prior context.
@@ -1344,23 +1191,6 @@ function persistedRequestAnchor(events, runHeaders, modelId, connectionId) {
1344
1191
  }
1345
1192
  return undefined;
1346
1193
  }
1347
- /**
1348
- * The estimate inputs for the request about to go out: the paired anchor and
1349
- * the signed char delta against the payload that anchor was reported for.
1350
- *
1351
- * A delta wider than the whole payload means the pairing has already failed, so
1352
- * drop it and cold start: the whole payload against a zero anchor.
1353
- */
1354
- function requestEstimateAnchor(state, payloadChars) {
1355
- const anchor = state.lastRequestInputTokens;
1356
- const baseline = state.lastRequestPayloadChars;
1357
- if (anchor === undefined || baseline === undefined)
1358
- return { appendedChars: payloadChars };
1359
- const appendedChars = payloadChars - baseline;
1360
- if (Math.abs(appendedChars) > payloadChars)
1361
- return { appendedChars: payloadChars };
1362
- return { priorUsageTokens: anchor, appendedChars };
1363
- }
1364
1194
  /**
1365
1195
  * The `decision: 'replaced'` diagnostic patch for a durable active-send fold,
1366
1196
  * shared by the proactive (`reason: 'context_limit'`) and reactive