@vellumai/assistant 0.8.9 → 0.8.10-dev.202606092334.09948c8

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 (161) 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 +21 -15
  8. package/src/__tests__/approval-cascade.test.ts +1 -0
  9. package/src/__tests__/build-persisted-content.test.ts +75 -1
  10. package/src/__tests__/compaction-events.test.ts +1 -0
  11. package/src/__tests__/config-managed-gemini-defaults.test.ts +2 -46
  12. package/src/__tests__/context-overflow-reducer.test.ts +264 -124
  13. package/src/__tests__/context-window-manager-overflow-rung.test.ts +351 -0
  14. package/src/__tests__/conversation-abort-tool-results.test.ts +1 -0
  15. package/src/__tests__/conversation-agent-loop-inference-profile.test.ts +11 -0
  16. package/src/__tests__/conversation-agent-loop-overflow.test.ts +90 -49
  17. package/src/__tests__/conversation-agent-loop.test.ts +113 -64
  18. package/src/__tests__/conversation-confirmation-signals.test.ts +1 -0
  19. package/src/__tests__/conversation-fork-crud.test.ts +110 -0
  20. package/src/__tests__/conversation-process-callsite.test.ts +1 -0
  21. package/src/__tests__/conversation-provider-retry-repair.test.ts +48 -48
  22. package/src/__tests__/conversation-queue.test.ts +1 -0
  23. package/src/__tests__/conversation-runtime-assembly.test.ts +119 -8
  24. package/src/__tests__/conversation-slash-queue.test.ts +1 -0
  25. package/src/__tests__/conversation-slash-unknown.test.ts +1 -0
  26. package/src/__tests__/conversation-speed-override.test.ts +1 -0
  27. package/src/__tests__/conversation-surfaces-app-control.test.ts +4 -1
  28. package/src/__tests__/conversation-tool-setup-app-refresh.test.ts +91 -142
  29. package/src/__tests__/conversation-tool-setup-skill-attribution.test.ts +116 -0
  30. package/src/__tests__/conversation-tool-setup-test-helpers.ts +98 -0
  31. package/src/__tests__/conversation-workspace-cache-state.test.ts +1 -0
  32. package/src/__tests__/conversation-workspace-injection.test.ts +1 -0
  33. package/src/__tests__/conversation-workspace-tool-tracking.test.ts +1 -0
  34. package/src/__tests__/corrected-target.test.ts +93 -0
  35. package/src/__tests__/credential-execution-feature-gates.test.ts +3 -5
  36. package/src/__tests__/credential-security-invariants.test.ts +1 -0
  37. package/src/__tests__/embedding-managed-proxy-selection.test.ts +6 -40
  38. package/src/__tests__/external-plugin-loader.test.ts +0 -1
  39. package/src/__tests__/guardian-routing-invariants.test.ts +91 -0
  40. package/src/__tests__/history-repair-hook.test.ts +2 -0
  41. package/src/__tests__/host-app-control-proxy.test.ts +45 -0
  42. package/src/__tests__/llm-catalog-parity.test.ts +4 -0
  43. package/src/__tests__/memory-retrieval-hook.test.ts +29 -15
  44. package/src/__tests__/notification-decision-strategy.test.ts +3 -3
  45. package/src/__tests__/persistence-secret-redaction.test.ts +78 -0
  46. package/src/__tests__/plugin-bootstrap.test.ts +82 -73
  47. package/src/__tests__/plugin-tool-contribution.test.ts +7 -4
  48. package/src/__tests__/plugin-types.test.ts +0 -8
  49. package/src/__tests__/provider-catalog-visibility.test.ts +1 -9
  50. package/src/__tests__/retry-thinking-adaptive-only.test.ts +245 -0
  51. package/src/__tests__/server-history-render.test.ts +39 -0
  52. package/src/__tests__/skills.test.ts +123 -0
  53. package/src/__tests__/title-generate-hook.test.ts +2 -0
  54. package/src/__tests__/tool-audit-listener.test.ts +51 -0
  55. package/src/__tests__/tool-executor-lifecycle-events.test.ts +32 -0
  56. package/src/__tests__/tool-start-timestamp.test.ts +218 -0
  57. package/src/agent/loop.ts +26 -39
  58. package/src/api/events/tool-result.ts +9 -0
  59. package/src/api/events/tool-use-start.ts +7 -0
  60. package/src/api/responses/conversation-message.ts +91 -14
  61. package/src/approvals/guardian-request-resolvers.ts +26 -0
  62. package/src/cli/commands/channel-verification-sessions.ts +6 -6
  63. package/src/cli/commands/inference-providers.ts +0 -8
  64. package/src/cli/commands/plugins.ts +2 -2
  65. package/src/cli/lib/__tests__/install-from-github.test.ts +174 -18
  66. package/src/cli/lib/__tests__/plugin-catalog-cache.test.ts +1 -1
  67. package/src/cli/lib/__tests__/plugin-details.test.ts +1 -1
  68. package/src/cli/lib/__tests__/plugin-marketplace.test.ts +1 -1
  69. package/src/cli/lib/__tests__/search-plugins.test.ts +11 -11
  70. package/src/cli/lib/install-from-github.ts +130 -19
  71. package/src/cli/lib/plugin-catalog-cache.ts +1 -1
  72. package/src/cli/lib/plugin-details.ts +4 -4
  73. package/src/cli/lib/plugin-marketplace.ts +2 -2
  74. package/src/cli/lib/search-plugins.ts +6 -6
  75. package/src/config/bundled-skills/skill-management/SKILL.md +89 -1
  76. package/src/config/env-registry.ts +12 -0
  77. package/src/config/feature-flag-registry.json +0 -80
  78. package/src/config/loader.ts +5 -22
  79. package/src/config/seed-inference-profiles.ts +1 -1
  80. package/src/config/skills.ts +101 -47
  81. package/src/context/strip-injections.ts +7 -4
  82. package/src/daemon/conversation-agent-loop-handlers.ts +102 -6
  83. package/src/daemon/conversation-agent-loop.ts +126 -270
  84. package/src/daemon/conversation-runtime-assembly.ts +44 -8
  85. package/src/daemon/conversation-tool-setup.ts +9 -1
  86. package/src/daemon/conversation.ts +13 -0
  87. package/src/daemon/external-plugins-bootstrap.ts +33 -87
  88. package/src/daemon/handlers/config-channels.ts +11 -2
  89. package/src/daemon/handlers/shared.ts +9 -1
  90. package/src/daemon/handlers/skills.ts +6 -2
  91. package/src/daemon/host-app-control-proxy.ts +72 -57
  92. package/src/daemon/message-protocol.ts +0 -7
  93. package/src/daemon/message-types/skills.ts +4 -0
  94. package/src/events/tool-audit-listener.ts +7 -1
  95. package/src/memory/__tests__/tool-invocation-test-helpers.ts +69 -0
  96. package/src/memory/conversation-crud.ts +44 -1
  97. package/src/memory/db-init.ts +4 -0
  98. package/src/memory/embedding-backend.ts +5 -22
  99. package/src/memory/memory-retrospective-startup-cleanup.ts +1 -1
  100. package/src/memory/migrations/275-tool-invocations-add-skill-id.test.ts +81 -0
  101. package/src/memory/migrations/275-tool-invocations-add-skill-id.ts +20 -0
  102. package/src/memory/migrations/276-tool-invocations-created-at-id-index.test.ts +68 -0
  103. package/src/memory/migrations/276-tool-invocations-created-at-id-index.ts +20 -0
  104. package/src/memory/migrations/index.ts +2 -0
  105. package/src/memory/schema/conversations.ts +3 -0
  106. package/src/memory/tool-execution-events-store.test.ts +162 -0
  107. package/src/memory/tool-execution-events-store.ts +73 -0
  108. package/src/memory/tool-usage-store.ts +4 -3
  109. package/src/memory/v2/__tests__/injected-block-slugs.test.ts +51 -0
  110. package/src/memory/v2/activation-store.ts +50 -1
  111. package/src/memory/v2/injected-block-slugs.ts +30 -0
  112. package/src/notifications/__tests__/copy-composer.test.ts +244 -0
  113. package/src/notifications/access-request-copy.ts +298 -0
  114. package/src/notifications/adapters/slack.ts +3 -3
  115. package/src/notifications/adapters/telegram.ts +2 -1
  116. package/src/notifications/copy-composer.ts +49 -267
  117. package/src/notifications/decision-engine.ts +16 -35
  118. package/src/notifications/home-feed-side-effect.ts +1 -6
  119. package/src/platform/client.ts +1 -3
  120. package/src/platform/feature-gate.ts +3 -12
  121. package/src/plugin-api/constants.ts +2 -0
  122. package/src/plugin-api/index.ts +37 -6
  123. package/src/plugin-api/types.ts +75 -0
  124. package/src/plugins/defaults/compaction/compact.ts +39 -1
  125. package/src/plugins/defaults/compaction/context-overflow-reducer.ts +240 -32
  126. package/src/plugins/defaults/compaction/corrected-target.ts +53 -0
  127. package/src/plugins/defaults/compaction/window-manager.ts +195 -1
  128. package/src/plugins/defaults/index.ts +24 -0
  129. package/src/plugins/defaults/memory-retrieval/hooks/post-compact.ts +76 -112
  130. package/src/plugins/defaults/memory-retrieval/hooks/{user-prompt-submit-temp.ts → user-prompt-submit.ts} +36 -67
  131. package/src/plugins/defaults/memory-retrieval/package.json +14 -0
  132. package/src/plugins/external-api.ts +1 -1
  133. package/src/plugins/types.ts +5 -51
  134. package/src/providers/inference/__tests__/base-url-route-validation.test.ts +1 -2
  135. package/src/providers/model-catalog.ts +57 -1
  136. package/src/providers/registry.ts +0 -8
  137. package/src/providers/retry.ts +35 -7
  138. package/src/runtime/routes/__tests__/acp-routes.test.ts +151 -0
  139. package/src/runtime/routes/__tests__/inference-provider-connection-routes.test.ts +0 -62
  140. package/src/runtime/routes/__tests__/plugins-routes.test.ts +4 -4
  141. package/src/runtime/routes/acp-routes.test.ts +106 -0
  142. package/src/runtime/routes/acp-routes.ts +248 -2
  143. package/src/runtime/routes/browser-tabs-routes.ts +1 -1
  144. package/src/runtime/routes/channel-verification-routes.ts +14 -5
  145. package/src/runtime/routes/chatgpt-subscription-auth-routes.ts +0 -14
  146. package/src/runtime/routes/inbound-stages/acl-enforcement.ts +33 -34
  147. package/src/runtime/routes/inference-provider-connection-routes.ts +0 -45
  148. package/src/runtime/routes/plugins-routes.ts +3 -3
  149. package/src/runtime/verification-outbound-actions.ts +147 -2
  150. package/src/runtime/verification-templates.ts +29 -3
  151. package/src/telemetry/types.ts +25 -1
  152. package/src/telemetry/usage-telemetry-reporter.test.ts +141 -7
  153. package/src/telemetry/usage-telemetry-reporter.ts +63 -7
  154. package/src/tools/executor.ts +4 -1
  155. package/src/tools/skills/load.ts +11 -6
  156. package/src/tools/terminal/safe-env.ts +1 -0
  157. package/src/tools/types.ts +10 -0
  158. package/src/__tests__/plugin-skill-contribution.test.ts +0 -355
  159. package/src/daemon/message-types/browser.ts +0 -10
  160. package/src/notifications/__tests__/emit-signal-home-feed.test.ts +0 -187
  161. package/src/plugins/plugin-skill-contributions.ts +0 -292
@@ -24,7 +24,10 @@ import {
24
24
  runAssistantDrivenCompaction,
25
25
  runEmergencyCompaction,
26
26
  } from "../../../context/compactor.js";
27
- import { estimatePromptTokens } from "../../../context/token-estimator.js";
27
+ import {
28
+ estimatePromptTokens,
29
+ estimateToolsTokens,
30
+ } from "../../../context/token-estimator.js";
28
31
  import type {
29
32
  ContentBlock,
30
33
  Message,
@@ -33,6 +36,14 @@ import type {
33
36
  } from "../../../providers/types.js";
34
37
  import type { TrustClass } from "../../../runtime/actor-trust-resolver.js";
35
38
  import { getLogger } from "../../../util/logger.js";
39
+ import {
40
+ createInitialReducerState,
41
+ reduceContextOverflow,
42
+ type ReducerConfig,
43
+ type ReducerState,
44
+ type ReducerStepResult,
45
+ } from "./context-overflow-reducer.js";
46
+ import { computeCorrectedOverflowTarget } from "./corrected-target.js";
36
47
 
37
48
  const log = getLogger("context-window");
38
49
 
@@ -135,6 +146,33 @@ export interface EmergencyCompactOptions {
135
146
  overrideProfile?: string | null;
136
147
  }
137
148
 
149
+ /**
150
+ * Turn-specific inputs for {@link ContextWindowManager.reduceOverflowOneRung}.
151
+ * The manager owns everything the reduction ladder derives from its own state
152
+ * (provider, system prompt, token budgets, conversation id, config, and the
153
+ * running reducer state); the caller supplies only what is specific to the
154
+ * overflow that triggered recovery.
155
+ */
156
+ export interface OverflowRecoveryRungOptions {
157
+ /**
158
+ * Provider-reported token count from the overflow rejection, or `null` when
159
+ * it could not be parsed. Lowers the compaction target in proportion to the
160
+ * estimator's under-count so the reduced history lands under the provider's
161
+ * true ceiling rather than the under-counted estimate.
162
+ */
163
+ actualTokens: number | null;
164
+ /**
165
+ * Whether the terminal auto-compress-latest-turn rung is permitted. The
166
+ * caller resolves this from the overflow policy; the manager never makes the
167
+ * policy call itself.
168
+ */
169
+ allowAutoCompressLatestTurn: boolean;
170
+ /** Per-conversation inference-profile override for the summary call. */
171
+ overrideProfile?: string | null;
172
+ /** Trust class of the actor whose turn triggered overflow recovery. */
173
+ actorTrustClass?: TrustClass;
174
+ }
175
+
138
176
  export interface ContextWindowManagerOptions {
139
177
  provider: Provider;
140
178
  systemPrompt: string | (() => string);
@@ -218,6 +256,26 @@ export class ContextWindowManager {
218
256
  */
219
257
  private _nonPersistedPrefixCount = 0;
220
258
  private _resolvedSystemPrompt: string | undefined;
259
+ /**
260
+ * Reducer state for the in-progress overflow-recovery ladder, held across
261
+ * the successive {@link reduceOverflowOneRung} calls of a single turn so the
262
+ * ladder advances one rung per call. Reset to `undefined` at each turn
263
+ * boundary via {@link resetOverflowRecovery} so a new turn starts the ladder
264
+ * from the emergency rung.
265
+ */
266
+ private _overflowReducerState: ReducerState | undefined;
267
+ /**
268
+ * The corrected compaction target and the prompt-token estimate it was
269
+ * derived from, computed once against the overflowing prompt on the first
270
+ * rung of a turn and reused across that turn's later rungs. The correction
271
+ * captures the estimator error the provider's actual token count revealed at
272
+ * the moment of overflow; re-deriving it against an already-reduced prompt
273
+ * would divide the original actual-token count by a smaller estimate and
274
+ * drive the target ever lower. Reset with {@link resetOverflowRecovery}.
275
+ */
276
+ private _overflowTurnTarget:
277
+ | { targetTokens: number; estimatedInputTokens: number }
278
+ | undefined;
221
279
 
222
280
  constructor(options: ContextWindowManagerOptions) {
223
281
  this.provider = options.provider;
@@ -232,6 +290,16 @@ export class ContextWindowManager {
232
290
  this.config = config;
233
291
  }
234
292
 
293
+ /**
294
+ * Clear the overflow-recovery ladder so the next {@link reduceOverflowOneRung}
295
+ * call starts a fresh ladder from the emergency rung. Called at the turn
296
+ * boundary.
297
+ */
298
+ resetOverflowRecovery(): void {
299
+ this._overflowReducerState = undefined;
300
+ this._overflowTurnTarget = undefined;
301
+ }
302
+
235
303
  /** Leading non-persisted inherited-context messages the compactor preserves. */
236
304
  get nonPersistedPrefixCount(): number {
237
305
  return this._nonPersistedPrefixCount;
@@ -325,6 +393,132 @@ export class ContextWindowManager {
325
393
  }
326
394
  }
327
395
 
396
+ /**
397
+ * Advance the context-overflow reduction ladder by one rung against
398
+ * `messages`, holding the reducer state across the successive calls of a
399
+ * single turn (reset via {@link resetOverflowRecovery}). The compaction
400
+ * target is the manager's overflow preflight budget, lowered in proportion
401
+ * to the estimator error the provider's actual token count reveals, so the
402
+ * reduced history lands under the provider's true ceiling rather than the
403
+ * under-counted estimate.
404
+ */
405
+ async reduceOverflowOneRung(
406
+ messages: Message[],
407
+ options: OverflowRecoveryRungOptions,
408
+ signal?: AbortSignal,
409
+ ): Promise<ReducerStepResult> {
410
+ try {
411
+ return await this._reduceOverflowOneRung(messages, options, signal);
412
+ } finally {
413
+ this.clearSystemPromptCache();
414
+ }
415
+ }
416
+
417
+ private async _reduceOverflowOneRung(
418
+ messages: Message[],
419
+ options: OverflowRecoveryRungOptions,
420
+ signal?: AbortSignal,
421
+ ): Promise<ReducerStepResult> {
422
+ if (this.conversationId == null) {
423
+ throw new Error(
424
+ "ContextWindowManager has no conversationId — cannot run overflow recovery",
425
+ );
426
+ }
427
+ if (!this._overflowReducerState) {
428
+ this._overflowReducerState = createInitialReducerState();
429
+ this._overflowTurnTarget = this.deriveOverflowTurnTarget(
430
+ messages,
431
+ options.actualTokens,
432
+ );
433
+ }
434
+ const { targetTokens, estimatedInputTokens } = this._overflowTurnTarget!;
435
+
436
+ const config: ReducerConfig = {
437
+ providerName: this.estimationProviderName,
438
+ systemPrompt: this.systemPrompt,
439
+ contextWindow: this.config,
440
+ targetTokens,
441
+ toolTokenBudget: this.resolveTurnToolTokenBudget(),
442
+ conversationId: this.conversationId,
443
+ overrideProfile: options.overrideProfile ?? null,
444
+ actorTrustClass: options.actorTrustClass,
445
+ previousEstimatedInputTokens: estimatedInputTokens,
446
+ maxMiddleTierAttempts: this.config.overflowRecovery.maxAttempts,
447
+ allowAutoCompressLatestTurn: options.allowAutoCompressLatestTurn,
448
+ };
449
+
450
+ const step = await reduceContextOverflow(
451
+ messages,
452
+ config,
453
+ this._overflowReducerState,
454
+ signal,
455
+ );
456
+ this._overflowReducerState = step.state;
457
+ return step;
458
+ }
459
+
460
+ /**
461
+ * Compute the corrected compaction target for a turn's overflow recovery:
462
+ * the overflow preflight budget lowered in proportion to the estimator error
463
+ * the provider's actual token count reveals, so the reduced history lands
464
+ * under the provider's true ceiling rather than the under-counted estimate.
465
+ */
466
+ private deriveOverflowTurnTarget(
467
+ messages: Message[],
468
+ actualTokens: number | null,
469
+ ): { targetTokens: number; estimatedInputTokens: number } {
470
+ const estimatedInputTokens = estimatePromptTokens(
471
+ messages,
472
+ this.systemPrompt,
473
+ {
474
+ providerName: this.estimationProviderName,
475
+ toolTokenBudget: this.resolveTurnToolTokenBudget(),
476
+ },
477
+ );
478
+ const { targetTokens, estimationErrorRatio } =
479
+ computeCorrectedOverflowTarget({
480
+ preflightBudget: this.resolveOverflowPreflightBudget(messages.length),
481
+ actualTokens,
482
+ estimatedTokens: estimatedInputTokens,
483
+ });
484
+ if (estimationErrorRatio != null) {
485
+ log.warn(
486
+ {
487
+ actualTokens,
488
+ estimatedTokens: estimatedInputTokens,
489
+ estimationErrorRatio: estimationErrorRatio.toFixed(2),
490
+ targetTokens,
491
+ },
492
+ "Adjusting overflow compaction target based on observed estimation error",
493
+ );
494
+ }
495
+ return { targetTokens, estimatedInputTokens };
496
+ }
497
+
498
+ /**
499
+ * The token budget overflow recovery compacts below, derived from the
500
+ * manager's configured max-input cap and overflow-recovery safety margin.
501
+ * Long histories (> 50 messages) get a wider margin so the reduced prompt
502
+ * keeps clearance under the provider's true ceiling.
503
+ */
504
+ /**
505
+ * Tool-token budget for the current turn's overflow recovery. Prefers the
506
+ * live tool set resolved for the turn — matching what the loop sends to the
507
+ * provider — and falls back to the constructor-time snapshot when no
508
+ * resolver is wired (legacy test paths, ad-hoc instantiation).
509
+ */
510
+ private resolveTurnToolTokenBudget(): number {
511
+ const tools = this.resolveTools?.();
512
+ return tools ? estimateToolsTokens(tools) : this.toolTokenBudget;
513
+ }
514
+
515
+ private resolveOverflowPreflightBudget(messageCount: number): number {
516
+ const baseSafetyMargin = this.config.overflowRecovery.safetyMarginRatio;
517
+ const safetyMargin =
518
+ messageCount > 50 ? Math.max(baseSafetyMargin, 0.15) : baseSafetyMargin;
519
+ return Math.floor(this.config.maxInputTokens * (1 - safetyMargin));
520
+ }
521
+
328
522
  private async _maybeCompact(
329
523
  messages: Message[],
330
524
  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,
@@ -4,136 +4,100 @@
4
4
  * After the agent loop compacts a conversation mid-turn it must re-apply the
5
5
  * runtime injections compaction stripped — the NOW.md scratchpad, PKB context,
6
6
  * memory-v2 static block, workspace top-level context, and Slack chronological
7
- * snapshot — onto the compacted history before the turn continues. This hook
8
- * is the memory system's home for that transform: it receives the message
9
- * history plus the resolved runtime-injection options and returns the edited
10
- * history (and the blocks it captured), with no dependency on the agent loop's
11
- * closure state.
7
+ * snapshot — onto the compacted history before the turn continues. This hook is
8
+ * the memory system's home for that transform: it re-applies the injections via
9
+ * {@link applyRuntimeInjections}, writes the edited history back onto the
10
+ * context, and re-tracks the memory graph's cached nodes against the re-injected
11
+ * history. The injection blocks the transform captures are not needed by the
12
+ * re-injection caller, so only the messages propagate.
12
13
  *
13
- * It re-applies the runtime injections via {@link applyRuntimeInjections} and
14
- * re-tracks the memory graph's cached nodes against the re-injected history.
15
- * The remaining orchestrator-side step (the post-injection bookkeeping the
16
- * loop records) is expected to migrate here as the hook subsumes the loop's
17
- * re-injection ceremony.
14
+ * Every per-turn input the live conversation can supply is self-resolved from
15
+ * it (looked up by id) rather than threaded in by the loop:
16
+ * - The trust snapshot comes from the conversation's turn-start trust snapshot
17
+ * ({@link Conversation.currentTurnTrustContext}), and the inbound actor
18
+ * context from the turn-start actor snapshot
19
+ * ({@link Conversation.currentTurnInboundActorContext}) — both frozen at turn
20
+ * start, not read live. Post-compaction runs mid-turn in a later tool
21
+ * iteration, where the live trust can be overwritten by a concurrent
22
+ * request's actor and the contact/member registry the actor context derives
23
+ * from can be mutated by contact tools; reading the frozen snapshots re-emits
24
+ * the values the turn's initial assembly resolved.
25
+ * - The memory graph handle comes from the plugin's own conversation-keyed
26
+ * registry ({@link getLiveGraphMemory}).
27
+ * - The call site and transcript inputs self-resolve inside
28
+ * {@link applyRuntimeInjections}.
18
29
  *
19
- * The memory graph handle is sourced internally from the plugin's own
20
- * conversation-keyed registry ({@link getLiveGraphMemory}) rather than being
21
- * threaded in by the loop — it is memory-retrieval-specific state, not
22
- * something the generic loop should carry.
30
+ * The loop supplies only the irreducible turn-identity fields on the public
31
+ * {@link PostCompactContext}.
23
32
  */
24
33
 
34
+ import type { PluginHookFn, PostCompactContext } from "@vellumai/plugin-api";
35
+
36
+ import { getConfig } from "../../../../config/loader.js";
37
+ import { findConversationOrSubagent } from "../../../../daemon/conversation-registry.js";
25
38
  import {
26
39
  applyRuntimeInjections,
27
- type InboundActorContext,
28
- type InjectionMode,
29
- type RuntimeInjectionResult,
40
+ resolveTurnModelProfileLabel,
30
41
  } from "../../../../daemon/conversation-runtime-assembly.js";
31
42
  import {
43
+ FALLBACK_TURN_TRUST,
32
44
  resolveTrustClass,
33
- type TrustContext,
34
45
  } from "../../../../daemon/trust-context.js";
35
46
  import { getLiveGraphMemory } from "../../../../memory/graph/conversation-graph-memory.js";
36
- import type { Message } from "../../../../providers/types.js";
37
-
38
- /**
39
- * Everything the post-compaction hook needs, supplied by the agent loop from
40
- * its own working state. Re-injection inputs migrate loop-ward by growing this
41
- * type; the loop hands the hook an object of this shape when it calls
42
- * {@link postCompact} directly.
43
- *
44
- * The turn-identity fields are flat here: `conversationId` is the key the
45
- * re-injection resolves the live conversation through (and the only one that,
46
- * together with `requestId` and `trust`, cannot be recovered from that live
47
- * conversation), while `turnIndex` and `callSite` are intentionally omitted so
48
- * {@link applyRuntimeInjections} self-resolves them from the live conversation.
49
- * The memory graph handle is likewise sourced internally via
50
- * {@link getLiveGraphMemory} rather than threaded in.
51
- */
52
- export interface PostCompactContext {
53
- /** Compacted message history to re-inject onto. */
54
- history: Message[];
55
- /**
56
- * Stable ID for the current request, forwarded onto the injector turn
57
- * context. The one turn-identity field that cannot be recovered from the
58
- * live conversation, so the loop supplies it.
59
- */
60
- requestId: string | undefined;
61
- /**
62
- * Conversation the turn is scoped to. The key the re-injection resolves the
63
- * live conversation (and its channel/trust/transcript state) through, so the
64
- * loop always supplies it.
65
- */
66
- conversationId: string;
67
- /**
68
- * Trust classification and channel identity for the inbound actor, forwarded
69
- * onto the injector turn context and used to gate the memory-graph re-track.
70
- * Supplied by the loop as the turn-start snapshot rather than re-resolved
71
- * mid-turn.
72
- */
73
- trust: TrustContext;
74
- /**
75
- * Whether the in-flight turn has no human present to answer clarification
76
- * questions. Resolved once by the agent loop at turn start (from its
77
- * `isInteractive` option, which can fall back to mutable client/headless
78
- * state that flips mid-turn on SSE reconnect) and handed to the hook here, so
79
- * re-injection uses the loop's turn-start snapshot rather than re-reading
80
- * live conversation state.
81
- */
82
- isNonInteractive: boolean;
83
- /**
84
- * Injection volume for the re-applied blocks. Owned by the agent loop, which
85
- * drops to `"minimal"` when overflow reduction trims the prompt; handed to
86
- * the hook here so re-injection matches the loop's committed decision instead
87
- * of re-deriving it.
88
- */
89
- mode: InjectionMode;
90
- /**
91
- * The `model_profile:` turn-context label, or `null` when the active
92
- * inference profile is unchanged since the last notified one. The agent loop
93
- * resolves it once at turn start from config and the turn's profile override,
94
- * and notifies the model only on change — a decision that flips mid-turn once
95
- * the notification is persisted, so it cannot be re-derived. Handed to the
96
- * hook here so re-injection re-emits the loop's turn-start value.
97
- */
98
- modelProfile: string | null;
99
- /**
100
- * Inbound actor identity and trust fields for the unified `<turn_context>`
101
- * block, or `null` on guardian turns (which suppress the actor section). The
102
- * agent loop resolves it once at turn start via the actor-trust resolver,
103
- * whose contact/member registry inputs can be mutated mid-turn by contact
104
- * tools, so it cannot be re-derived. Handed to the hook here so re-injection
105
- * re-emits the loop's turn-start value.
106
- */
107
- actorContext: InboundActorContext | null;
108
- }
109
47
 
110
- export default async function postCompact(
111
- ctx: PostCompactContext,
112
- ): Promise<RuntimeInjectionResult> {
113
- const { history, requestId, conversationId, trust, ...options } = ctx;
114
- // The remaining `options` carry the non-identity injection inputs
115
- // (`isNonInteractive`, `mode`, `modelProfile`, `actorContext`). Forward the
116
- // turn-identity fields the live conversation can't supply (`requestId`,
117
- // `conversationId`, `trust`); `turnIndex` and `callSite` self-resolve from
118
- // the live conversation so the re-injection matches the turn's initial
119
- // assembly.
48
+ const postCompact: PluginHookFn<PostCompactContext> = async (ctx) => {
49
+ const {
50
+ history,
51
+ requestId,
52
+ conversationId,
53
+ isNonInteractive,
54
+ modelProfileKey,
55
+ } = ctx;
56
+ const config = getConfig();
57
+ const conversation = findConversationOrSubagent(conversationId);
58
+ // Trust and the inbound actor context are read from the conversation's
59
+ // turn-start snapshots rather than live state: post-compaction runs mid-turn
60
+ // in a later tool iteration, where the live trust can be overwritten by a
61
+ // concurrent request's actor and the contact/member registry the actor
62
+ // context derives from can be mutated by contact tools. The snapshots are the
63
+ // values the turn's initial assembly resolved.
64
+ const trust =
65
+ conversation?.currentTurnTrustContext ??
66
+ conversation?.trustContext ??
67
+ FALLBACK_TURN_TRUST;
68
+ const actorContext = conversation?.currentTurnInboundActorContext ?? null;
69
+ // Render the `model_profile:` label from the turn's resolved profile key,
70
+ // using the call site self-resolved from the live conversation — the same
71
+ // derivation the first-call user-prompt-submit assembly uses. Mid-loop
72
+ // re-injection always runs at `"full"` volume; only the orchestrator's
73
+ // post-rejection convergence re-injection ever downgrades the mode.
74
+ const modelProfile = resolveTurnModelProfileLabel(
75
+ modelProfileKey,
76
+ conversation?.currentCallSite ?? "mainAgent",
77
+ config.llm,
78
+ conversationId,
79
+ );
120
80
  const result = await applyRuntimeInjections(history, {
121
- ...options,
81
+ isNonInteractive,
82
+ modelProfile,
83
+ actorContext,
84
+ mode: "full",
122
85
  requestId,
123
86
  conversationId,
124
87
  trust,
125
88
  });
89
+ // Write the re-injected history back onto the threaded context; the loop
90
+ // reads it from there once the hook settles.
91
+ ctx.history = result.messages;
126
92
  // Re-track the nodes the memory graph last injected so they survive against
127
- // the re-injected history. Untrusted actors and minimal-mode turns never
128
- // received a memory-graph injection, so there is nothing to re-track. The
129
- // actor's trust class is derived from the turn's own trust context (the same
130
- // value the injector chain resolves). The live graph handle is looked up
131
- // from the plugin's own registry by the turn's conversation id — the same
132
- // instance the turn's retrieval mutated, so re-tracking sees the real
133
- // cached-node state.
93
+ // the re-injected history. Untrusted actors never received a memory-graph
94
+ // injection, so there is nothing to re-track. The live graph handle is looked
95
+ // up from the plugin's own registry by the turn's conversation id — the same
96
+ // instance the turn's retrieval mutated.
134
97
  const isTrustedActor = resolveTrustClass(trust) === "guardian";
135
- if (isTrustedActor && options.mode !== "minimal") {
98
+ if (isTrustedActor) {
136
99
  getLiveGraphMemory(conversationId)?.retrackCachedNodes();
137
100
  }
138
- return result;
139
- }
101
+ };
102
+
103
+ export default postCompact;