@vellumai/assistant 0.8.9 → 0.8.10-dev.202606092238.d04fd59

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 (147) hide show
  1. package/AGENTS.md +1 -1
  2. package/examples/plugins/echo/README.md +3 -3
  3. package/node_modules/@vellumai/skill-host-contracts/src/tool-types.ts +2 -0
  4. package/openapi.yaml +38 -12
  5. package/package.json +1 -1
  6. package/scripts/sync-llm-catalog.ts +2 -0
  7. package/src/__tests__/agent-loop-exit-reason.test.ts +19 -14
  8. package/src/__tests__/build-persisted-content.test.ts +75 -1
  9. package/src/__tests__/config-managed-gemini-defaults.test.ts +2 -46
  10. package/src/__tests__/context-overflow-reducer.test.ts +264 -124
  11. package/src/__tests__/context-window-manager-overflow-rung.test.ts +289 -0
  12. package/src/__tests__/conversation-agent-loop-overflow.test.ts +22 -22
  13. package/src/__tests__/conversation-agent-loop.test.ts +45 -37
  14. package/src/__tests__/conversation-fork-crud.test.ts +110 -0
  15. package/src/__tests__/conversation-provider-retry-repair.test.ts +16 -20
  16. package/src/__tests__/conversation-runtime-assembly.test.ts +118 -5
  17. package/src/__tests__/conversation-surfaces-app-control.test.ts +4 -1
  18. package/src/__tests__/conversation-tool-setup-app-refresh.test.ts +91 -142
  19. package/src/__tests__/conversation-tool-setup-skill-attribution.test.ts +116 -0
  20. package/src/__tests__/conversation-tool-setup-test-helpers.ts +98 -0
  21. package/src/__tests__/corrected-target.test.ts +93 -0
  22. package/src/__tests__/credential-execution-feature-gates.test.ts +3 -5
  23. package/src/__tests__/credential-security-invariants.test.ts +1 -0
  24. package/src/__tests__/embedding-managed-proxy-selection.test.ts +6 -40
  25. package/src/__tests__/external-plugin-loader.test.ts +0 -1
  26. package/src/__tests__/guardian-routing-invariants.test.ts +91 -0
  27. package/src/__tests__/history-repair-hook.test.ts +2 -0
  28. package/src/__tests__/host-app-control-proxy.test.ts +45 -0
  29. package/src/__tests__/llm-catalog-parity.test.ts +4 -0
  30. package/src/__tests__/memory-retrieval-hook.test.ts +29 -15
  31. package/src/__tests__/notification-decision-strategy.test.ts +3 -3
  32. package/src/__tests__/persistence-secret-redaction.test.ts +78 -0
  33. package/src/__tests__/plugin-bootstrap.test.ts +82 -73
  34. package/src/__tests__/plugin-tool-contribution.test.ts +7 -4
  35. package/src/__tests__/plugin-types.test.ts +0 -8
  36. package/src/__tests__/provider-catalog-visibility.test.ts +1 -9
  37. package/src/__tests__/retry-thinking-adaptive-only.test.ts +245 -0
  38. package/src/__tests__/server-history-render.test.ts +39 -0
  39. package/src/__tests__/skills.test.ts +123 -0
  40. package/src/__tests__/title-generate-hook.test.ts +2 -0
  41. package/src/__tests__/tool-audit-listener.test.ts +51 -0
  42. package/src/__tests__/tool-executor-lifecycle-events.test.ts +32 -0
  43. package/src/__tests__/tool-start-timestamp.test.ts +218 -0
  44. package/src/agent/loop.ts +26 -23
  45. package/src/api/events/tool-result.ts +9 -0
  46. package/src/api/events/tool-use-start.ts +7 -0
  47. package/src/api/responses/conversation-message.ts +91 -14
  48. package/src/approvals/guardian-request-resolvers.ts +26 -0
  49. package/src/cli/commands/channel-verification-sessions.ts +6 -6
  50. package/src/cli/commands/inference-providers.ts +0 -8
  51. package/src/cli/commands/plugins.ts +2 -2
  52. package/src/cli/lib/__tests__/install-from-github.test.ts +174 -18
  53. package/src/cli/lib/__tests__/plugin-catalog-cache.test.ts +1 -1
  54. package/src/cli/lib/__tests__/plugin-details.test.ts +1 -1
  55. package/src/cli/lib/__tests__/plugin-marketplace.test.ts +1 -1
  56. package/src/cli/lib/__tests__/search-plugins.test.ts +11 -11
  57. package/src/cli/lib/install-from-github.ts +130 -19
  58. package/src/cli/lib/plugin-catalog-cache.ts +1 -1
  59. package/src/cli/lib/plugin-details.ts +4 -4
  60. package/src/cli/lib/plugin-marketplace.ts +2 -2
  61. package/src/cli/lib/search-plugins.ts +6 -6
  62. package/src/config/bundled-skills/skill-management/SKILL.md +89 -1
  63. package/src/config/env-registry.ts +12 -0
  64. package/src/config/feature-flag-registry.json +0 -80
  65. package/src/config/loader.ts +5 -22
  66. package/src/config/seed-inference-profiles.ts +1 -1
  67. package/src/config/skills.ts +101 -47
  68. package/src/context/strip-injections.ts +7 -4
  69. package/src/daemon/conversation-agent-loop-handlers.ts +102 -6
  70. package/src/daemon/conversation-agent-loop.ts +134 -232
  71. package/src/daemon/conversation-runtime-assembly.ts +44 -8
  72. package/src/daemon/conversation-tool-setup.ts +9 -1
  73. package/src/daemon/external-plugins-bootstrap.ts +33 -87
  74. package/src/daemon/handlers/config-channels.ts +11 -2
  75. package/src/daemon/handlers/shared.ts +9 -1
  76. package/src/daemon/handlers/skills.ts +6 -2
  77. package/src/daemon/host-app-control-proxy.ts +72 -57
  78. package/src/daemon/message-protocol.ts +0 -7
  79. package/src/daemon/message-types/skills.ts +4 -0
  80. package/src/events/tool-audit-listener.ts +7 -1
  81. package/src/memory/__tests__/tool-invocation-test-helpers.ts +69 -0
  82. package/src/memory/conversation-crud.ts +44 -1
  83. package/src/memory/db-init.ts +4 -0
  84. package/src/memory/embedding-backend.ts +5 -22
  85. package/src/memory/memory-retrospective-startup-cleanup.ts +1 -1
  86. package/src/memory/migrations/275-tool-invocations-add-skill-id.test.ts +81 -0
  87. package/src/memory/migrations/275-tool-invocations-add-skill-id.ts +20 -0
  88. package/src/memory/migrations/276-tool-invocations-created-at-id-index.test.ts +68 -0
  89. package/src/memory/migrations/276-tool-invocations-created-at-id-index.ts +20 -0
  90. package/src/memory/migrations/index.ts +2 -0
  91. package/src/memory/schema/conversations.ts +3 -0
  92. package/src/memory/tool-execution-events-store.test.ts +162 -0
  93. package/src/memory/tool-execution-events-store.ts +73 -0
  94. package/src/memory/tool-usage-store.ts +4 -3
  95. package/src/memory/v2/__tests__/injected-block-slugs.test.ts +51 -0
  96. package/src/memory/v2/activation-store.ts +50 -1
  97. package/src/memory/v2/injected-block-slugs.ts +30 -0
  98. package/src/notifications/__tests__/copy-composer.test.ts +244 -0
  99. package/src/notifications/access-request-copy.ts +298 -0
  100. package/src/notifications/adapters/slack.ts +3 -3
  101. package/src/notifications/adapters/telegram.ts +2 -1
  102. package/src/notifications/copy-composer.ts +49 -267
  103. package/src/notifications/decision-engine.ts +16 -35
  104. package/src/notifications/home-feed-side-effect.ts +1 -6
  105. package/src/platform/client.ts +1 -3
  106. package/src/platform/feature-gate.ts +3 -12
  107. package/src/plugin-api/constants.ts +2 -0
  108. package/src/plugin-api/index.ts +34 -6
  109. package/src/plugin-api/types.ts +19 -0
  110. package/src/plugins/defaults/compaction/compact.ts +39 -1
  111. package/src/plugins/defaults/compaction/context-overflow-reducer.ts +240 -32
  112. package/src/plugins/defaults/compaction/corrected-target.ts +53 -0
  113. package/src/plugins/defaults/compaction/window-manager.ts +136 -0
  114. package/src/plugins/defaults/index.ts +24 -0
  115. package/src/plugins/defaults/memory-retrieval/hooks/post-compact.ts +68 -43
  116. package/src/plugins/defaults/memory-retrieval/hooks/{user-prompt-submit-temp.ts → user-prompt-submit.ts} +36 -67
  117. package/src/plugins/defaults/memory-retrieval/package.json +14 -0
  118. package/src/plugins/external-api.ts +1 -1
  119. package/src/plugins/types.ts +5 -51
  120. package/src/providers/inference/__tests__/base-url-route-validation.test.ts +1 -2
  121. package/src/providers/model-catalog.ts +57 -1
  122. package/src/providers/registry.ts +0 -8
  123. package/src/providers/retry.ts +35 -7
  124. package/src/runtime/routes/__tests__/acp-routes.test.ts +151 -0
  125. package/src/runtime/routes/__tests__/inference-provider-connection-routes.test.ts +0 -62
  126. package/src/runtime/routes/__tests__/plugins-routes.test.ts +4 -4
  127. package/src/runtime/routes/acp-routes.test.ts +106 -0
  128. package/src/runtime/routes/acp-routes.ts +248 -2
  129. package/src/runtime/routes/browser-tabs-routes.ts +1 -1
  130. package/src/runtime/routes/channel-verification-routes.ts +14 -5
  131. package/src/runtime/routes/chatgpt-subscription-auth-routes.ts +0 -14
  132. package/src/runtime/routes/inbound-stages/acl-enforcement.ts +33 -34
  133. package/src/runtime/routes/inference-provider-connection-routes.ts +0 -45
  134. package/src/runtime/routes/plugins-routes.ts +3 -3
  135. package/src/runtime/verification-outbound-actions.ts +147 -2
  136. package/src/runtime/verification-templates.ts +29 -3
  137. package/src/telemetry/types.ts +25 -1
  138. package/src/telemetry/usage-telemetry-reporter.test.ts +141 -7
  139. package/src/telemetry/usage-telemetry-reporter.ts +63 -7
  140. package/src/tools/executor.ts +4 -1
  141. package/src/tools/skills/load.ts +11 -6
  142. package/src/tools/terminal/safe-env.ts +1 -0
  143. package/src/tools/types.ts +10 -0
  144. package/src/__tests__/plugin-skill-contribution.test.ts +0 -355
  145. package/src/daemon/message-types/browser.ts +0 -10
  146. package/src/notifications/__tests__/emit-signal-home-feed.test.ts +0 -187
  147. package/src/plugins/plugin-skill-contributions.ts +0 -292
@@ -9,11 +9,20 @@
9
9
  * messages is a no-op. Tiers are ordered so that less destructive
10
10
  * transformations are tried first.
11
11
  *
12
- * Tier progression:
13
- * 1. Forced compaction (emergency keep-boundary options)
12
+ * Rung progression:
13
+ * 0. Emergency summarize-around-last-tool-pair (preserves the most recent
14
+ * tool call/result while aggressively compressing earlier history)
15
+ * 1. Forced full-history compaction (emergency keep-boundary options)
14
16
  * 2. Aggressive tool-result text truncation across retained history
15
17
  * 3. Media/file payload stubbing (replace images/files with text stubs)
16
18
  * 4. Runtime injection downgrade to minimal mode
19
+ * terminal. Auto-compress the latest turn (policy-gated by the caller)
20
+ *
21
+ * Rungs 1–4 are the "middle tiers" and are bounded by `maxMiddleTierAttempts`.
22
+ * The emergency rung always runs first; the auto-compress rung runs last and
23
+ * only when the caller permits it. The caller invokes the reducer repeatedly,
24
+ * re-running the agent loop after each rung, until either the context fits or
25
+ * `state.exhausted` is true.
17
26
  */
18
27
 
19
28
  import type { ContextWindowConfig } from "../../../config/types.js";
@@ -29,19 +38,38 @@ import {
29
38
  } from "../../../daemon/conversation-media-retry.js";
30
39
  import type { InjectionMode } from "../../../daemon/conversation-runtime-assembly.js";
31
40
  import type { Message } from "../../../providers/types.js";
41
+ import type { TrustClass } from "../../../runtime/actor-trust-resolver.js";
42
+ import { getLogger } from "../../../util/logger.js";
43
+ import { defaultCompact, defaultEmergencyCompact } from "./compact.js";
32
44
  import type {
33
45
  ContextWindowCompactOptions,
34
46
  ContextWindowResult,
35
47
  } from "./window-manager.js";
36
48
 
49
+ const log = getLogger("context-overflow-reducer");
50
+
37
51
  /**
38
52
  * Identifies which reduction tier was applied in a given step.
39
53
  */
40
54
  export type ReducerTier =
55
+ | "emergency_compaction"
41
56
  | "forced_compaction"
42
57
  | "tool_result_truncation"
43
58
  | "media_stubbing"
44
- | "injection_downgrade";
59
+ | "injection_downgrade"
60
+ | "auto_compress_latest_turn";
61
+
62
+ /**
63
+ * The "middle tiers" — the rungs bounded by `maxMiddleTierAttempts`. The
64
+ * emergency and auto-compress rungs are intentionally excluded so they remain
65
+ * reachable regardless of how small the middle-tier budget is.
66
+ */
67
+ const MIDDLE_TIERS: readonly ReducerTier[] = [
68
+ "forced_compaction",
69
+ "tool_result_truncation",
70
+ "media_stubbing",
71
+ "injection_downgrade",
72
+ ];
45
73
 
46
74
  /**
47
75
  * Tracks the cumulative state of the reducer across successive calls.
@@ -94,18 +122,35 @@ export interface ReducerConfig {
94
122
  targetTokens: number;
95
123
  /** Pre-computed tool token budget to include in estimations. */
96
124
  toolTokenBudget?: number;
125
+ /**
126
+ * Conversation whose {@link ContextWindowManager} the compaction rungs
127
+ * resolve from the compaction store to run the summary call.
128
+ */
129
+ conversationId: string;
130
+ /** Per-conversation inference-profile override for the summary call. */
131
+ overrideProfile?: string | null;
132
+ /** Trust class of the actor whose turn triggered overflow recovery. */
133
+ actorTrustClass?: TrustClass;
134
+ /**
135
+ * The provider-reported estimate at the overflow that triggered recovery.
136
+ * Sizes the emergency summarize-around-last-tool-pair cut.
137
+ */
138
+ previousEstimatedInputTokens: number;
139
+ /**
140
+ * Maximum number of middle-tier reductions (forced compaction, tool-result
141
+ * truncation, media stubbing, injection downgrade) to apply before
142
+ * escalating to the terminal auto-compress rung. The emergency and
143
+ * auto-compress rungs are not counted against this budget.
144
+ */
145
+ maxMiddleTierAttempts: number;
146
+ /**
147
+ * Whether the terminal auto-compress-latest-turn rung is permitted. The
148
+ * caller resolves this from the overflow policy; when false, the ladder ends
149
+ * once the middle tiers are exhausted.
150
+ */
151
+ allowAutoCompressLatestTurn: boolean;
97
152
  }
98
153
 
99
- /**
100
- * Compaction callback — the reducer does not own the ContextWindowManager
101
- * instance, so the caller provides a function that performs compaction.
102
- */
103
- export type CompactFn = (
104
- messages: Message[],
105
- signal: AbortSignal | undefined,
106
- options: ContextWindowCompactOptions,
107
- ) => Promise<ContextWindowResult>;
108
-
109
154
  // Aggressive truncation cap for tool results during overflow recovery.
110
155
  // Much tighter than the normal per-result budget.
111
156
  const OVERFLOW_TOOL_RESULT_MAX_CHARS = 4_000;
@@ -121,53 +166,163 @@ export async function reduceContextOverflow(
121
166
  messages: Message[],
122
167
  config: ReducerConfig,
123
168
  state: ReducerState | undefined,
124
- compactFn: CompactFn,
125
169
  signal?: AbortSignal,
126
170
  ): Promise<ReducerStepResult> {
127
171
  const applied = state?.appliedTiers ?? [];
172
+ const step = await selectNextRung(messages, config, state, applied, signal);
128
173
 
129
- // Tier 1: forced compaction
130
- if (!applied.includes("forced_compaction")) {
131
- return applyForcedCompaction(messages, config, applied, compactFn, signal);
132
- }
174
+ // Exhaustion is decided centrally from the rungs applied so far so the last
175
+ // rung that actually runs sets `exhausted`, avoiding a wasted no-op rerun.
176
+ step.state.exhausted = isLadderExhausted(step.state.appliedTiers, config);
177
+ return step;
178
+ }
133
179
 
134
- // Tier 2: aggressive tool-result truncation
135
- if (!applied.includes("tool_result_truncation")) {
136
- return applyToolResultTruncation(messages, config, applied, state);
180
+ async function selectNextRung(
181
+ messages: Message[],
182
+ config: ReducerConfig,
183
+ state: ReducerState | undefined,
184
+ applied: ReducerTier[],
185
+ signal?: AbortSignal,
186
+ ): Promise<ReducerStepResult> {
187
+ // Rung 0: emergency summarize-around-last-tool-pair (uncounted, runs first).
188
+ if (!applied.includes("emergency_compaction")) {
189
+ return applyEmergencyCompaction(messages, config, applied, signal);
137
190
  }
138
191
 
139
- // Tier 3: media/file payload stubbing
140
- if (!applied.includes("media_stubbing")) {
141
- return applyMediaStubbing(messages, config, applied, state);
192
+ // Middle tiers (rungs 1–4), bounded by the configured attempt budget.
193
+ const middleApplied = applied.filter((t) => MIDDLE_TIERS.includes(t)).length;
194
+ if (
195
+ middleApplied < config.maxMiddleTierAttempts &&
196
+ hasUnappliedMiddleTier(applied)
197
+ ) {
198
+ if (!applied.includes("forced_compaction")) {
199
+ return applyForcedCompaction(messages, config, applied, signal);
200
+ }
201
+ if (!applied.includes("tool_result_truncation")) {
202
+ return applyToolResultTruncation(messages, config, applied, state);
203
+ }
204
+ if (!applied.includes("media_stubbing")) {
205
+ return applyMediaStubbing(messages, config, applied, state);
206
+ }
207
+ return applyInjectionDowngrade(messages, config, applied, state);
142
208
  }
143
209
 
144
- // Tier 4: injection downgrade
145
- if (!applied.includes("injection_downgrade")) {
146
- return applyInjectionDowngrade(messages, config, applied, state);
210
+ // Terminal rung: auto-compress the latest turn (uncounted, policy-gated).
211
+ if (
212
+ config.allowAutoCompressLatestTurn &&
213
+ !applied.includes("auto_compress_latest_turn")
214
+ ) {
215
+ return applyAutoCompressLatestTurn(
216
+ messages,
217
+ config,
218
+ applied,
219
+ state,
220
+ signal,
221
+ );
147
222
  }
148
223
 
149
- // All tiers exhausted
224
+ // No rung left to apply — return a no-op step. `reduceContextOverflow`
225
+ // marks it exhausted via `isLadderExhausted`.
150
226
  const estimatedTokens = estimatePromptTokens(messages, config.systemPrompt, {
151
227
  providerName: config.providerName,
152
228
  toolTokenBudget: config.toolTokenBudget,
153
229
  });
154
230
  return {
155
231
  messages,
156
- tier: "injection_downgrade",
232
+ tier: applied[applied.length - 1] ?? "forced_compaction",
157
233
  state: {
158
234
  appliedTiers: [...applied],
159
235
  injectionMode: state?.injectionMode ?? "minimal",
236
+ toolResultMaxChars: state?.toolResultMaxChars,
237
+ compactionOptions: state?.compactionOptions,
160
238
  exhausted: true,
161
239
  },
162
240
  estimatedTokens,
163
241
  };
164
242
  }
165
243
 
244
+ /** Whether any middle tier remains unapplied. */
245
+ function hasUnappliedMiddleTier(applied: ReducerTier[]): boolean {
246
+ return MIDDLE_TIERS.some((tier) => !applied.includes(tier));
247
+ }
248
+
249
+ /**
250
+ * Decide whether the ladder has nothing more to try after the given rungs.
251
+ * The terminal auto-compress rung is the last; before it, the middle tiers
252
+ * are exhausted once the attempt budget is spent or every middle tier ran.
253
+ */
254
+ function isLadderExhausted(
255
+ applied: ReducerTier[],
256
+ config: ReducerConfig,
257
+ ): boolean {
258
+ if (applied.includes("auto_compress_latest_turn")) {
259
+ return true;
260
+ }
261
+ const middleApplied = applied.filter((t) => MIDDLE_TIERS.includes(t)).length;
262
+ const middleExhausted =
263
+ middleApplied >= config.maxMiddleTierAttempts ||
264
+ !hasUnappliedMiddleTier(applied);
265
+ if (!middleExhausted) {
266
+ return false;
267
+ }
268
+ // Middle tiers are done — the ladder continues only if the terminal
269
+ // auto-compress rung is permitted and has not run yet.
270
+ return !config.allowAutoCompressLatestTurn;
271
+ }
272
+
273
+ async function applyEmergencyCompaction(
274
+ messages: Message[],
275
+ config: ReducerConfig,
276
+ applied: ReducerTier[],
277
+ signal?: AbortSignal,
278
+ ): Promise<ReducerStepResult> {
279
+ let result: ContextWindowResult | null = null;
280
+ try {
281
+ result = await defaultEmergencyCompact({
282
+ conversationId: config.conversationId,
283
+ messages,
284
+ previousEstimatedInputTokens: config.previousEstimatedInputTokens,
285
+ overrideProfile: config.overrideProfile ?? null,
286
+ signal,
287
+ });
288
+ } catch (err) {
289
+ // No tool pair to split on, an unparseable summary, or a provider error.
290
+ // Fall through to forced compaction below rather than failing recovery.
291
+ log.warn(
292
+ { err },
293
+ "Emergency mid-turn compaction failed; falling through to forced compaction",
294
+ );
295
+ }
296
+
297
+ if (result?.compacted) {
298
+ return {
299
+ messages: result.messages,
300
+ tier: "emergency_compaction",
301
+ state: {
302
+ appliedTiers: [...applied, "emergency_compaction"],
303
+ injectionMode: "full",
304
+ exhausted: false,
305
+ },
306
+ estimatedTokens: result.estimatedInputTokens,
307
+ compactionResult: result,
308
+ };
309
+ }
310
+
311
+ // Emergency compaction produced no reduction; continue straight to forced
312
+ // compaction in the same step so the caller does not waste a provider rerun
313
+ // on unchanged messages.
314
+ return applyForcedCompaction(
315
+ messages,
316
+ config,
317
+ [...applied, "emergency_compaction"],
318
+ signal,
319
+ );
320
+ }
321
+
166
322
  async function applyForcedCompaction(
167
323
  messages: Message[],
168
324
  config: ReducerConfig,
169
325
  applied: ReducerTier[],
170
- compactFn: CompactFn,
171
326
  signal?: AbortSignal,
172
327
  ): Promise<ReducerStepResult> {
173
328
  const compactionOptions: ContextWindowCompactOptions = {
@@ -175,7 +330,14 @@ async function applyForcedCompaction(
175
330
  minKeepRecentUserTurns: 0,
176
331
  };
177
332
 
178
- const result = await compactFn(messages, signal, compactionOptions);
333
+ const result = await defaultCompact({
334
+ conversationId: config.conversationId,
335
+ messages,
336
+ signal,
337
+ ...compactionOptions,
338
+ overrideProfile: config.overrideProfile ?? null,
339
+ actorTrustClass: config.actorTrustClass,
340
+ });
179
341
  const nextMessages = result.compacted ? result.messages : messages;
180
342
  const estimatedTokens = result.compacted
181
343
  ? result.estimatedInputTokens
@@ -339,12 +501,58 @@ function applyInjectionDowngrade(
339
501
  injectionMode: "minimal",
340
502
  toolResultMaxChars: prevState?.toolResultMaxChars,
341
503
  compactionOptions: prevState?.compactionOptions,
342
- exhausted: true,
504
+ exhausted: false,
343
505
  },
344
506
  estimatedTokens,
345
507
  };
346
508
  }
347
509
 
510
+ async function applyAutoCompressLatestTurn(
511
+ messages: Message[],
512
+ config: ReducerConfig,
513
+ applied: ReducerTier[],
514
+ prevState: ReducerState | undefined,
515
+ signal?: AbortSignal,
516
+ ): Promise<ReducerStepResult> {
517
+ // Force-compress the latest turn as a last resort. Shares the forced
518
+ // compaction options, but runs after the middle tiers have been spent.
519
+ const compactionOptions: ContextWindowCompactOptions = {
520
+ force: true,
521
+ minKeepRecentUserTurns: 0,
522
+ };
523
+
524
+ const result = await defaultCompact({
525
+ conversationId: config.conversationId,
526
+ messages,
527
+ signal,
528
+ ...compactionOptions,
529
+ overrideProfile: config.overrideProfile ?? null,
530
+ actorTrustClass: config.actorTrustClass,
531
+ });
532
+ const nextMessages = result.compacted ? result.messages : messages;
533
+ const estimatedTokens = result.compacted
534
+ ? result.estimatedInputTokens
535
+ : estimatePromptTokens(nextMessages, config.systemPrompt, {
536
+ providerName: config.providerName,
537
+ toolTokenBudget: config.toolTokenBudget,
538
+ });
539
+
540
+ const nextApplied: ReducerTier[] = [...applied, "auto_compress_latest_turn"];
541
+ return {
542
+ messages: nextMessages,
543
+ tier: "auto_compress_latest_turn",
544
+ state: {
545
+ appliedTiers: nextApplied,
546
+ injectionMode: prevState?.injectionMode ?? "full",
547
+ toolResultMaxChars: prevState?.toolResultMaxChars,
548
+ compactionOptions,
549
+ exhausted: false,
550
+ },
551
+ estimatedTokens,
552
+ compactionResult: result,
553
+ };
554
+ }
555
+
348
556
  /**
349
557
  * Create the initial (empty) reducer state.
350
558
  */
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Corrected compaction target for reactive context-overflow recovery.
3
+ *
4
+ * When the provider rejects a request as context-too-large, the rejection
5
+ * reveals the *actual* token count it measured (e.g. "242201 tokens > 200000").
6
+ * The local estimator that gated the call may have significantly under-counted,
7
+ * so compacting to the nominal preflight budget would still overshoot the
8
+ * provider's real limit and re-reject. Scaling the preflight budget down by the
9
+ * observed estimator error yields a target that, once the estimator re-measures
10
+ * the reduced history, lands under the provider's true ceiling.
11
+ */
12
+
13
+ /** The compaction target plus the estimator-error context used to derive it. */
14
+ export interface CorrectedOverflowTarget {
15
+ /**
16
+ * Token budget the reducer should compact below. Equal to `preflightBudget`
17
+ * when the estimator did not under-count, and lower otherwise.
18
+ */
19
+ targetTokens: number;
20
+ /**
21
+ * The provider-actual / estimator ratio when the estimator under-counted
22
+ * (> 1), otherwise `null`. Exposed so callers can log the adjustment without
23
+ * recomputing it.
24
+ */
25
+ estimationErrorRatio: number | null;
26
+ }
27
+
28
+ /**
29
+ * Compute the compaction target for an overflow rejection, lowering the
30
+ * preflight budget in proportion to how badly the estimator under-counted.
31
+ *
32
+ * @param preflightBudget The nominal target the estimator gates against.
33
+ * @param actualTokens Provider-reported token count from the rejection, or
34
+ * `null` when it could not be parsed.
35
+ * @param estimatedTokens The estimator's count for the same history at overflow.
36
+ */
37
+ export function computeCorrectedOverflowTarget(params: {
38
+ preflightBudget: number;
39
+ actualTokens: number | null;
40
+ estimatedTokens: number;
41
+ }): CorrectedOverflowTarget {
42
+ const { preflightBudget, actualTokens, estimatedTokens } = params;
43
+ if (actualTokens != null && actualTokens > 0 && estimatedTokens > 0) {
44
+ const estimationErrorRatio = actualTokens / estimatedTokens;
45
+ if (estimationErrorRatio > 1.0) {
46
+ return {
47
+ targetTokens: Math.floor(preflightBudget / estimationErrorRatio),
48
+ estimationErrorRatio,
49
+ };
50
+ }
51
+ }
52
+ return { targetTokens: preflightBudget, estimationErrorRatio: null };
53
+ }
@@ -33,6 +33,14 @@ import type {
33
33
  } from "../../../providers/types.js";
34
34
  import type { TrustClass } from "../../../runtime/actor-trust-resolver.js";
35
35
  import { getLogger } from "../../../util/logger.js";
36
+ import {
37
+ createInitialReducerState,
38
+ reduceContextOverflow,
39
+ type ReducerConfig,
40
+ type ReducerState,
41
+ type ReducerStepResult,
42
+ } from "./context-overflow-reducer.js";
43
+ import { computeCorrectedOverflowTarget } from "./corrected-target.js";
36
44
 
37
45
  const log = getLogger("context-window");
38
46
 
@@ -135,6 +143,33 @@ export interface EmergencyCompactOptions {
135
143
  overrideProfile?: string | null;
136
144
  }
137
145
 
146
+ /**
147
+ * Turn-specific inputs for {@link ContextWindowManager.reduceOverflowOneRung}.
148
+ * The manager owns everything the reduction ladder derives from its own state
149
+ * (provider, system prompt, token budgets, conversation id, config, and the
150
+ * running reducer state); the caller supplies only what is specific to the
151
+ * overflow that triggered recovery.
152
+ */
153
+ export interface OverflowRecoveryRungOptions {
154
+ /**
155
+ * Provider-reported token count from the overflow rejection, or `null` when
156
+ * it could not be parsed. Lowers the compaction target in proportion to the
157
+ * estimator's under-count so the reduced history lands under the provider's
158
+ * true ceiling rather than the under-counted estimate.
159
+ */
160
+ actualTokens: number | null;
161
+ /**
162
+ * Whether the terminal auto-compress-latest-turn rung is permitted. The
163
+ * caller resolves this from the overflow policy; the manager never makes the
164
+ * policy call itself.
165
+ */
166
+ allowAutoCompressLatestTurn: boolean;
167
+ /** Per-conversation inference-profile override for the summary call. */
168
+ overrideProfile?: string | null;
169
+ /** Trust class of the actor whose turn triggered overflow recovery. */
170
+ actorTrustClass?: TrustClass;
171
+ }
172
+
138
173
  export interface ContextWindowManagerOptions {
139
174
  provider: Provider;
140
175
  systemPrompt: string | (() => string);
@@ -218,6 +253,14 @@ export class ContextWindowManager {
218
253
  */
219
254
  private _nonPersistedPrefixCount = 0;
220
255
  private _resolvedSystemPrompt: string | undefined;
256
+ /**
257
+ * Reducer state for the in-progress overflow-recovery ladder, held across
258
+ * the successive {@link reduceOverflowOneRung} calls of a single turn so the
259
+ * ladder advances one rung per call. Reset to `undefined` at each turn
260
+ * boundary via {@link resetOverflowRecovery} so a new turn starts the ladder
261
+ * from the emergency rung.
262
+ */
263
+ private _overflowReducerState: ReducerState | undefined;
221
264
 
222
265
  constructor(options: ContextWindowManagerOptions) {
223
266
  this.provider = options.provider;
@@ -232,6 +275,15 @@ export class ContextWindowManager {
232
275
  this.config = config;
233
276
  }
234
277
 
278
+ /**
279
+ * Clear the overflow-recovery ladder so the next {@link reduceOverflowOneRung}
280
+ * call starts a fresh ladder from the emergency rung. Called at the turn
281
+ * boundary.
282
+ */
283
+ resetOverflowRecovery(): void {
284
+ this._overflowReducerState = undefined;
285
+ }
286
+
235
287
  /** Leading non-persisted inherited-context messages the compactor preserves. */
236
288
  get nonPersistedPrefixCount(): number {
237
289
  return this._nonPersistedPrefixCount;
@@ -325,6 +377,90 @@ export class ContextWindowManager {
325
377
  }
326
378
  }
327
379
 
380
+ /**
381
+ * Advance the context-overflow reduction ladder by one rung against
382
+ * `messages`, holding the reducer state across the successive calls of a
383
+ * single turn (reset via {@link resetOverflowRecovery}). The compaction
384
+ * target is the manager's overflow preflight budget, lowered in proportion
385
+ * to the estimator error the provider's actual token count reveals, so the
386
+ * reduced history lands under the provider's true ceiling rather than the
387
+ * under-counted estimate.
388
+ */
389
+ async reduceOverflowOneRung(
390
+ messages: Message[],
391
+ options: OverflowRecoveryRungOptions,
392
+ signal?: AbortSignal,
393
+ ): Promise<ReducerStepResult> {
394
+ try {
395
+ return await this._reduceOverflowOneRung(messages, options, signal);
396
+ } finally {
397
+ this.clearSystemPromptCache();
398
+ }
399
+ }
400
+
401
+ private async _reduceOverflowOneRung(
402
+ messages: Message[],
403
+ options: OverflowRecoveryRungOptions,
404
+ signal?: AbortSignal,
405
+ ): Promise<ReducerStepResult> {
406
+ if (this.conversationId == null) {
407
+ throw new Error(
408
+ "ContextWindowManager has no conversationId — cannot run overflow recovery",
409
+ );
410
+ }
411
+ this._overflowReducerState ??= createInitialReducerState();
412
+
413
+ const estimatedTokensAtOverflow = estimatePromptTokens(
414
+ messages,
415
+ this.systemPrompt,
416
+ {
417
+ providerName: this.estimationProviderName,
418
+ toolTokenBudget: this.toolTokenBudget,
419
+ },
420
+ );
421
+ const { targetTokens } = computeCorrectedOverflowTarget({
422
+ preflightBudget: this.resolveOverflowPreflightBudget(messages.length),
423
+ actualTokens: options.actualTokens,
424
+ estimatedTokens: estimatedTokensAtOverflow,
425
+ });
426
+
427
+ const config: ReducerConfig = {
428
+ providerName: this.estimationProviderName,
429
+ systemPrompt: this.systemPrompt,
430
+ contextWindow: this.config,
431
+ targetTokens,
432
+ toolTokenBudget: this.toolTokenBudget,
433
+ conversationId: this.conversationId,
434
+ overrideProfile: options.overrideProfile ?? null,
435
+ actorTrustClass: options.actorTrustClass,
436
+ previousEstimatedInputTokens: estimatedTokensAtOverflow,
437
+ maxMiddleTierAttempts: this.config.overflowRecovery.maxAttempts,
438
+ allowAutoCompressLatestTurn: options.allowAutoCompressLatestTurn,
439
+ };
440
+
441
+ const step = await reduceContextOverflow(
442
+ messages,
443
+ config,
444
+ this._overflowReducerState,
445
+ signal,
446
+ );
447
+ this._overflowReducerState = step.state;
448
+ return step;
449
+ }
450
+
451
+ /**
452
+ * The token budget overflow recovery compacts below, derived from the
453
+ * manager's configured max-input cap and overflow-recovery safety margin.
454
+ * Long histories (> 50 messages) get a wider margin so the reduced prompt
455
+ * keeps clearance under the provider's true ceiling.
456
+ */
457
+ private resolveOverflowPreflightBudget(messageCount: number): number {
458
+ const baseSafetyMargin = this.config.overflowRecovery.safetyMarginRatio;
459
+ const safetyMargin =
460
+ messageCount > 50 ? Math.max(baseSafetyMargin, 0.15) : baseSafetyMargin;
461
+ return Math.floor(this.config.maxInputTokens * (1 - safetyMargin));
462
+ }
463
+
328
464
  private async _maybeCompact(
329
465
  messages: Message[],
330
466
  signal?: AbortSignal,
@@ -31,6 +31,9 @@ import emptyResponseStop from "./empty-response/hooks/stop.js";
31
31
  import emptyResponsePkg from "./empty-response/package.json" with { type: "json" };
32
32
  import historyRepairUserPromptSubmit from "./history-repair/hooks/user-prompt-submit.js";
33
33
  import historyRepairPkg from "./history-repair/package.json" with { type: "json" };
34
+ import memoryRetrievalPostCompact from "./memory-retrieval/hooks/post-compact.js";
35
+ import memoryRetrievalUserPromptSubmit from "./memory-retrieval/hooks/user-prompt-submit.js";
36
+ import memoryRetrievalPkg from "./memory-retrieval/package.json" with { type: "json" };
34
37
  import memoryV3PostCompact from "./memory-v3-shadow/hooks/post-compact.js";
35
38
  import memoryV3UserPromptSubmit from "./memory-v3-shadow/hooks/user-prompt-submit.js";
36
39
  import memoryV3Pkg from "./memory-v3-shadow/package.json" with { type: "json" };
@@ -70,6 +73,26 @@ export const defaultEmptyResponsePlugin: Plugin = {
70
73
  },
71
74
  };
72
75
 
76
+ /**
77
+ * `memory-retrieval` — assembles the turn's runtime injections (the unified
78
+ * `<turn_context>` block, Slack chronological transcript, NOW.md / PKB /
79
+ * memory-v2 / workspace blocks) via two hooks: `user-prompt-submit` runs
80
+ * memory-graph retrieval and the initial injection, and `post-compact`
81
+ * re-applies the injections onto the compacted history after a mid-turn
82
+ * compaction. Registered first in the chain so later `user-prompt-submit`
83
+ * hooks (history repair, title) see the fully memory-injected history.
84
+ */
85
+ export const defaultMemoryRetrievalPlugin: Plugin = {
86
+ manifest: {
87
+ name: memoryRetrievalPkg.name,
88
+ version: memoryRetrievalPkg.version,
89
+ },
90
+ hooks: {
91
+ "user-prompt-submit": memoryRetrievalUserPromptSubmit,
92
+ "post-compact": memoryRetrievalPostCompact,
93
+ },
94
+ };
95
+
73
96
  /**
74
97
  * `history-repair` — a `user-prompt-submit` hook that normalizes the working
75
98
  * message history (tool-use/tool-result pairing, role alternation) before the
@@ -156,6 +179,7 @@ export const defaultToolResultTruncatePlugin: Plugin = {
156
179
  */
157
180
  function getAllDefaultPlugins(): readonly Plugin[] {
158
181
  return [
182
+ defaultMemoryRetrievalPlugin,
159
183
  defaultToolResultTruncatePlugin,
160
184
  defaultEmptyResponsePlugin,
161
185
  defaultToolErrorPlugin,