@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
@@ -32,15 +32,10 @@ import {
32
32
  } from "../config/llm-resolver.js";
33
33
  import { getConfig } from "../config/loader.js";
34
34
  import type { LLMCallSite } from "../config/schemas/llm.js";
35
- import type { ContextWindowConfig } from "../config/types.js";
36
35
  import {
37
36
  derefToolResultReReads,
38
37
  postTurnTruncateToolResults,
39
38
  } from "../context/post-turn-tool-result-truncation.js";
40
- import {
41
- estimatePromptTokens,
42
- getCalibrationProviderKey,
43
- } from "../context/token-estimator.js";
44
39
  import { writeRelationshipState } from "../home/relationship-state-writer.js";
45
40
  import {
46
41
  clearSentryConversationContext,
@@ -72,17 +67,11 @@ import {
72
67
  import { enqueueMemoryRetrospectiveOnCompaction } from "../memory/memory-retrospective-enqueue.js";
73
68
  import { HOOKS } from "../plugin-api/constants.js";
74
69
  import type { UserPromptSubmitContext } from "../plugin-api/types.js";
75
- import { defaultCompact } from "../plugins/defaults/compaction/compact.js";
76
70
  import {
77
71
  createInitialReducerState,
78
- reduceContextOverflow,
79
72
  type ReducerState,
80
73
  } from "../plugins/defaults/compaction/context-overflow-reducer.js";
81
- import type { ContextWindowCompactOptions } from "../plugins/defaults/compaction/window-manager.js";
82
74
  import { deepRepairHistory } from "../plugins/defaults/history-repair/terminal.js";
83
- import userPromptSubmitMemoryRetrieval, {
84
- type MemoryRetrievalHookContext,
85
- } from "../plugins/defaults/memory-retrieval/hooks/user-prompt-submit-temp.js";
86
75
  import { runHook } from "../plugins/pipeline.js";
87
76
  import type { ContentBlock, Message } from "../providers/types.js";
88
77
  import type { Provider } from "../providers/types.js";
@@ -124,6 +113,7 @@ import {
124
113
  getSlackCompactionWatermarkForPrefix,
125
114
  loadSlackChronologicalContext,
126
115
  resolveTurnInboundActorContext,
116
+ resolveTurnModelProfileLabel,
127
117
  type SlackChronologicalContext,
128
118
  stripInjectionsForCompaction,
129
119
  } from "./conversation-runtime-assembly.js";
@@ -429,10 +419,6 @@ export async function runAgentLoopImpl(
429
419
  refreshCurrentProfileState();
430
420
  return currentEffectiveContextWindow.maxInputTokens;
431
421
  };
432
- const resolveCurrentContextWindowConfig = (): ContextWindowConfig => {
433
- refreshCurrentProfileState();
434
- return currentContextWindowConfig;
435
- };
436
422
  const resolveCurrentContextBudget = (): {
437
423
  overflowRecovery: EffectiveContextWindow["overflowRecovery"];
438
424
  providerMaxTokens: number;
@@ -801,14 +787,16 @@ export async function runAgentLoopImpl(
801
787
 
802
788
  // Unified `<turn_context>` actor input for this turn (model-facing grounding
803
789
  // metadata; the conversation runtime context remains the source for policy
804
- // gating). Resolved once at turn start and threaded per call site (like
805
- // `modelProfile`) so post-compaction re-injection receives it as an explicit
806
- // hook input rather than re-deriving it from live state that can flip
807
- // mid-turn.
790
+ // gating). Resolved once at turn start and reused by the orchestrator's
791
+ // post-rejection convergence re-injection rather than re-derived from live
792
+ // state that can flip mid-turn. Frozen onto the conversation so the
793
+ // post-compaction hook re-emits this same value instead of re-resolving
794
+ // against contact/member registry state that may have drifted mid-turn.
808
795
  const actorContext = resolveTurnInboundActorContext(
809
796
  ctx.trustContext,
810
797
  ctx.assistantId,
811
798
  );
799
+ ctx.currentTurnInboundActorContext = actorContext;
812
800
 
813
801
  // Surface long gaps between user messages so the model can acknowledge
814
802
  // the absence naturally. Gated at >12h to avoid noisy injection during
@@ -851,90 +839,72 @@ export async function runAgentLoopImpl(
851
839
  config.llm.activeProfile ??
852
840
  resolveDefaultProfileKey("mainAgent", config.llm);
853
841
  const lastNotified = ctx.lastNotifiedInferenceProfile;
854
- let modelProfileStr: string | null = null;
855
- if (effectiveProfileKey != null && effectiveProfileKey !== lastNotified) {
856
- const profileEntry = config.llm.profiles?.[effectiveProfileKey];
857
- const resolved = resolveCallSiteConfig(turnCallSite, config.llm, {
858
- overrideProfile: turnOverrideProfile ?? undefined,
859
- });
860
- const label = profileEntry?.label ?? effectiveProfileKey;
861
- modelProfileStr = resolved.model ? `${label} (${resolved.model})` : label;
842
+ const modelProfileKey =
843
+ effectiveProfileKey != null && effectiveProfileKey !== lastNotified
844
+ ? effectiveProfileKey
845
+ : null;
846
+ // The key is threaded as plain turn data to the user-prompt-submit and
847
+ // post-compaction hooks, which render the `Label (model)` line from it
848
+ // themselves. The post-rejection convergence re-injection further down is a
849
+ // direct assembly call rather than a hook, so its label is still rendered
850
+ // here from the same key.
851
+ const modelProfileStr = resolveTurnModelProfileLabel(
852
+ modelProfileKey,
853
+ turnCallSite,
854
+ config.llm,
855
+ ctx.conversationId,
856
+ );
857
+ if (modelProfileKey != null) {
862
858
  // Record the notification for persistence on delivery rather than here:
863
859
  // the model only "learns" the profile once it receives this turn
864
860
  // context, signalled by the first `message_complete`. Persisting inline
865
861
  // would mark the profile notified even if the turn is cancelled or fails
866
862
  // before the model ever sees the notice.
867
- state.pendingNotifiedInferenceProfile = effectiveProfileKey;
863
+ state.pendingNotifiedInferenceProfile = modelProfileKey;
868
864
  }
869
865
 
870
- // Memory retrieval + runtime injection — fetches PKB / NOW.md / memory-graph
871
- // outputs, persists the retrieval's own side effects (injected-block
872
- // metadata, recall log, `memory_recalled` event), and assembles the turn's
873
- // runtime-injection blocks onto the history (persisting those blocks too).
874
- // Runs at the early "prompt submitted, before context assembly" moment so
875
- // its injected output is what the agent loop receives. It is shaped as the
876
- // `user-prompt-submit-temp` hook handler but invoked directly for now,
877
- // separate from the canonical late `user-prompt-submit` hook (history
878
- // repair, title) that fires just before the loop.
879
- // The injection inputs (`isNonInteractive`, `modelProfile`) are resolved
880
- // once at turn start and threaded in so post-compaction re-injection reuses
881
- // the same snapshot rather than live state that can flip mid-turn.
866
+ // Trust class and injection mode, resolved once at turn start for the
867
+ // post-compaction re-injection sites further down, which re-apply the
868
+ // runtime injections (gated on trust) onto the compacted history.
882
869
  const isTrustedActor = resolveTrustClass(ctx.trustContext) === "guardian";
883
870
  let currentInjectionMode: InjectionMode = "full";
884
- const memoryCtx: MemoryRetrievalHookContext = {
885
- onEvent,
886
- conversationId: ctx.conversationId,
887
- userMessageId,
888
- logger: rlog,
889
- latestMessages: ctx.messages,
890
- requestId: reqId,
891
- isNonInteractive,
892
- modelProfile: modelProfileStr,
893
- };
894
- await userPromptSubmitMemoryRetrieval(memoryCtx);
895
-
896
- // The hook owns its side effects (injected-block metadata, recall log,
897
- // `memory_recalled` event, and the runtime-injection metadata persist) and
898
- // records the dense/sparse PKB query pair on the graph handle for the
899
- // PKB-reminder injector to read back; the loop reuses the fully injected
900
- // message list downstream.
901
- let runMessages = memoryCtx.latestMessages;
902
-
903
- // user-prompt-submit hook: plugins may transform `runMessages` right
904
- // before the agent loop receives them. Fires once per user turn at the
905
- // primary `agentLoop.run` only — the re-entry / retry calls further down
906
- // in this function do not refire it (they're not new user submissions).
907
- // Plugins may mutate `ctx.latestMessages` in place OR return a new
908
- // context with a fresh array; `runHook` forwards whichever the chain
909
- // settles on. Order is plugin registration order.
910
- //
911
- // Fires BEFORE the agent loop runs so the hook-emitted messages are part
912
- // of the loop's input; the loop then reports its own appended output via
913
- // `AgentLoopRunResult.newMessages`, which is what persistence consumes.
871
+
872
+ // user-prompt-submit hook chain. Fires once per user turn at the primary
873
+ // `agentLoop.run` (the re-entry / retry calls further down do not refire it
874
+ // — they're not new user submissions), before the loop runs so the
875
+ // hook-assembled messages are part of its input. Memory retrieval runs
876
+ // first — fetching PKB / NOW.md / memory-graph outputs, persisting its own
877
+ // side effects (injected-block metadata, recall log, `memory_recalled`
878
+ // event), and assembling the turn's runtime-injection blocks onto the
879
+ // history — followed by history repair and title generation, which see the
880
+ // fully injected history. Plugins may mutate `ctx.latestMessages` in place
881
+ // OR return a new context with a fresh array; `runHook` forwards whichever
882
+ // the chain settles on, in plugin registration order. The loop then reports
883
+ // its own appended output via `AgentLoopRunResult.newMessages`, which
884
+ // persistence consumes.
914
885
  const userPromptCtx: UserPromptSubmitContext = {
915
886
  conversationId: ctx.conversationId,
916
887
  userMessageId,
917
888
  requestId: reqId,
918
889
  prompt: options?.titleText ?? content,
919
890
  originalMessages: ctx.messages,
920
- latestMessages: runMessages,
891
+ latestMessages: ctx.messages,
921
892
  logger: rlog,
893
+ modelProfileKey,
894
+ isNonInteractive,
922
895
  };
923
896
  const finalUserPromptCtx = await runHook(
924
897
  HOOKS.USER_PROMPT_SUBMIT,
925
898
  userPromptCtx,
926
899
  );
927
- runMessages = finalUserPromptCtx.latestMessages;
928
-
929
- // Reducer state, tool-token budget, and calibration provider key consumed
930
- // by the post-rejection convergence loop further down. The tool-token
931
- // budget is resolved once per turn (the resolved tool set is stable across
932
- // the turn); the calibration key matches the key recorded by `handleUsage`
933
- // for wrapper providers (OpenRouter routing to Anthropic → key is
934
- // `"anthropic"`).
900
+ let runMessages = finalUserPromptCtx.latestMessages;
901
+
902
+ // Mirror of the manager's turn-scoped overflow-recovery ladder state, used
903
+ // by the post-rejection convergence driver below to gate its bounded rung
904
+ // loop. Reset at the turn boundary so a new turn starts the ladder fresh
905
+ // from the emergency rung.
935
906
  let reducerState: ReducerState | undefined;
936
- const toolTokenBudget = ctx.agentLoop.getToolTokenBudget(runMessages);
937
- const estimationProviderName = getCalibrationProviderKey(ctx.provider);
907
+ ctx.contextWindowManager.resetOverflowRecovery();
938
908
 
939
909
  const shouldGenerateTitle = isReplaceableTitle(
940
910
  getConversation(ctx.conversationId)?.title ?? null,
@@ -1005,8 +975,7 @@ export async function runAgentLoopImpl(
1005
975
  resolveContextWindow,
1006
976
  compactInPlace,
1007
977
  isNonInteractive,
1008
- modelProfile: modelProfileStr,
1009
- actorContext,
978
+ modelProfileKey,
1010
979
  });
1011
980
  lastRunAppendedNewMessages = appendedNewMessages;
1012
981
  lastRunNewMessages = newMessages;
@@ -1172,135 +1141,71 @@ export async function runAgentLoopImpl(
1172
1141
  }
1173
1142
 
1174
1143
  // When the provider reveals the actual token count in its error
1175
- // message (e.g. "242201 tokens > 200000"), use it to correct the
1176
- // compaction target. The estimator may significantly underestimate
1177
- // (e.g. estimated 185k but actual was 242k), so using the
1178
- // uncorrected preflightBudget would still be too high. Passes the raw
1179
- // error so ContextOverflowError.actualTokens can short-circuit the
1180
- // string-regex path for proxy-rewrapped untyped errors.
1144
+ // message (e.g. "242201 tokens > 200000"), the manager uses it to
1145
+ // correct the compaction target — the estimator can significantly
1146
+ // undercount, so the uncorrected preflight budget would still be too
1147
+ // high. Passes the raw error so `ContextOverflowError.actualTokens` can
1148
+ // short-circuit the string-regex path for proxy-rewrapped untyped
1149
+ // errors.
1181
1150
  const actualTokens = parseActualTokensFromError(
1182
1151
  state.contextTooLargeError,
1183
1152
  );
1184
- const estimatedTokensAtOverflow = estimatePromptTokens(
1185
- ctx.messages,
1186
- ctx.systemPrompt,
1187
- {
1188
- providerName: estimationProviderName,
1189
- toolTokenBudget,
1190
- },
1191
- );
1192
- const convergenceBudget = resolveCurrentContextBudget();
1193
- let correctedTarget = convergenceBudget.preflightBudget;
1194
- if (actualTokens && estimatedTokensAtOverflow > 0) {
1195
- const estimationErrorRatio = actualTokens / estimatedTokensAtOverflow;
1196
- if (estimationErrorRatio > 1.0) {
1197
- correctedTarget = Math.floor(
1198
- convergenceBudget.preflightBudget / estimationErrorRatio,
1199
- );
1200
- rlog.warn(
1201
- {
1202
- phase: "convergence",
1203
- actualTokens,
1204
- estimatedTokens: estimatedTokensAtOverflow,
1205
- estimationErrorRatio: estimationErrorRatio.toFixed(2),
1206
- preflightBudget: convergenceBudget.preflightBudget,
1207
- correctedTarget,
1208
- },
1209
- "Adjusting compaction target based on observed estimation error",
1210
- );
1211
- }
1212
- }
1213
-
1214
- // ── Emergency mid-turn compaction ────────────────────────────
1215
- // Before entering the reducer tier loop, attempt a targeted
1216
- // emergency compaction: summarize everything before the last
1217
- // tool_use + tool_result pair and let the agent continue with
1218
- // [summary, last_tool_call, last_tool_result]. This preserves
1219
- // the agent's most recent action context while aggressively
1220
- // compressing history. Falls through to reducer tiers on failure.
1221
- {
1222
- try {
1223
- const emergencyResult =
1224
- await ctx.contextWindowManager.emergencyCompact(
1225
- ctx.messages,
1226
- {
1227
- previousEstimatedInputTokens: estimatedTokensAtOverflow,
1228
- overrideProfile: resolveCurrentOverrideProfile() ?? null,
1229
- },
1230
- abortController.signal,
1231
- );
1232
- if (emergencyResult.compacted) {
1233
- rlog.info(
1234
- {
1235
- phase: "convergence",
1236
- compactedMessages: emergencyResult.compactedMessages,
1237
- summaryChars: emergencyResult.summaryText.length,
1238
- },
1239
- "Emergency mid-turn compaction succeeded — bypassing reducer tiers",
1240
- );
1241
- if (emergencyResult.summaryFailed !== undefined) {
1242
- await ctx.agentLoop.compactionCircuit.recordOutcome(
1243
- emergencyResult.summaryFailed,
1244
- onEvent,
1245
- );
1246
- }
1247
- if (emergencyResult.compacted) {
1248
- await applySuccessfulCompaction(emergencyResult, ctx.messages);
1249
- }
1250
- // Clear the overflow flag and re-run the agent loop with
1251
- // the compacted context.
1252
- state.contextTooLargeDetected = false;
1253
- }
1254
- } catch (err) {
1255
- rlog.warn(
1256
- { phase: "convergence", err },
1257
- "Emergency mid-turn compaction failed; continuing to reducer tiers",
1258
- );
1259
- }
1260
- // If emergency compaction failed, fall through to reducer tiers.
1261
- }
1262
1153
 
1263
- let convergenceAttempts = 0;
1264
- const maxAttempts = convergenceBudget.overflowRecovery.maxAttempts;
1154
+ // ── Bounded context-overflow convergence driver ─────────────────
1155
+ // The compaction plugin's reduction ladder owns every rung: the
1156
+ // emergency summarize-around-last-tool-pair, the middle tiers (forced
1157
+ // compaction, tool-result truncation, media stubbing, injection
1158
+ // downgrade), and the terminal auto-compress of the latest turn. The
1159
+ // manager owns the rung selection, the reducer state, and the corrected
1160
+ // target it derives from its own calibrated estimate; this driver only
1161
+ // applies one rung per iteration, re-injects, and re-runs the agent loop
1162
+ // until the context fits or the ladder is exhausted. The overflow policy
1163
+ // decides whether the terminal auto-compress rung is permitted; the
1164
+ // ladder never makes that policy call itself.
1165
+ const { overflowRecovery } = resolveCurrentContextBudget();
1166
+ const overflowAction = resolveOverflowAction({
1167
+ overflowRecovery,
1168
+ isInteractive: isInteractiveResolved,
1169
+ });
1170
+ const allowAutoCompressLatestTurn =
1171
+ overflowAction === "auto_compress_latest_turn";
1172
+
1173
+ // Safety backstop against a reduction ladder that never reports
1174
+ // exhaustion: the ladder can apply at most the emergency rung, the
1175
+ // middle-tier attempt budget, and the terminal auto-compress rung, so a
1176
+ // well-behaved reducer always sets `exhausted` within this many steps.
1177
+ // The cap only guards against a misbehaving reducer; it never truncates a
1178
+ // legitimate escalation.
1179
+ const maxConvergenceRungs = overflowRecovery.maxAttempts + 2;
1180
+ let convergenceRungs = 0;
1265
1181
 
1266
1182
  while (
1267
1183
  state.contextTooLargeDetected &&
1268
- convergenceAttempts < maxAttempts &&
1269
- !reducerState.exhausted
1184
+ !reducerState.exhausted &&
1185
+ convergenceRungs < maxConvergenceRungs
1270
1186
  ) {
1271
- convergenceAttempts++;
1187
+ convergenceRungs++;
1272
1188
  rlog.warn(
1273
1189
  {
1274
1190
  phase: "convergence",
1275
- attempt: convergenceAttempts,
1191
+ rung: convergenceRungs,
1276
1192
  appliedTiers: reducerState.appliedTiers,
1277
1193
  },
1278
- "Context too large — applying next reducer tier",
1194
+ "Context too large — applying next reduction rung",
1279
1195
  );
1280
1196
 
1281
1197
  ctx.emitActivityState("thinking", "context_compacting", {
1282
1198
  requestId: reqId,
1283
1199
  });
1284
1200
  const convergenceCompactionBasis = ctx.messages;
1285
- const step = await reduceContextOverflow(
1201
+ const step = await ctx.contextWindowManager.reduceOverflowOneRung(
1286
1202
  convergenceCompactionBasis,
1287
1203
  {
1288
- providerName: estimationProviderName,
1289
- systemPrompt: ctx.systemPrompt,
1290
- contextWindow: resolveCurrentContextWindowConfig(),
1291
- targetTokens: correctedTarget,
1292
- toolTokenBudget,
1204
+ actualTokens,
1205
+ allowAutoCompressLatestTurn,
1206
+ overrideProfile: resolveCurrentOverrideProfile() ?? null,
1207
+ actorTrustClass: resolveTurnActorTrustClass(ctx),
1293
1208
  },
1294
- reducerState,
1295
- (msgs, signal, opts) =>
1296
- defaultCompact({
1297
- conversationId: ctx.conversationId,
1298
- messages: msgs,
1299
- signal,
1300
- ...((opts ?? {}) as ContextWindowCompactOptions),
1301
- overrideProfile: resolveCurrentOverrideProfile() ?? null,
1302
- actorTrustClass: resolveTurnActorTrustClass(ctx),
1303
- }),
1304
1209
  abortController.signal,
1305
1210
  );
1306
1211
 
@@ -1308,10 +1213,9 @@ export async function runAgentLoopImpl(
1308
1213
  ctx.messages = step.messages;
1309
1214
  currentInjectionMode = step.state.injectionMode;
1310
1215
 
1311
- // See the preflight reducer call above for rationale. Only track when
1312
- // the summary LLM actually ran — `summaryFailed === undefined`
1313
- // indicates the reducer's forced compaction took an early-return path
1314
- // without calling the summary LLM.
1216
+ // Only track when the summary LLM actually ran — `summaryFailed
1217
+ // === undefined` indicates a forced-compaction early-return path that
1218
+ // never called the summary LLM.
1315
1219
  if (
1316
1220
  step.compactionResult &&
1317
1221
  step.compactionResult.summaryFailed !== undefined
@@ -1351,87 +1255,39 @@ export async function runAgentLoopImpl(
1351
1255
 
1352
1256
  updatedHistory = await runAgentLoop(runMessages);
1353
1257
 
1354
- // If the rerun still yields at checkpoint, the turn is still
1355
- // incomplete — continue reducing through the remaining tiers
1356
- // instead of silently dropping the incomplete state.
1357
1258
  if (yieldedForBudget && !abortController.signal.aborted) {
1358
- rlog.warn(
1359
- {
1360
- phase: "convergence",
1361
- attempt: convergenceAttempts,
1362
- appliedTiers: reducerState.appliedTiers,
1363
- },
1364
- "Post-convergence rerun still yielded at checkpoint — continuing reduction",
1365
- );
1366
- state.contextTooLargeDetected = true;
1367
-
1368
- // Fold rerun progress into ctx.messages so the next reducer
1369
- // tier operates on up-to-date history instead of stale
1370
- // pre-rerun messages.
1371
- if (lastRunAppendedNewMessages) {
1372
- ctx.messages = stripInjectionsForCompaction(updatedHistory);
1373
- markHistoryStrippedBestEffort(ctx.conversationId);
1374
- }
1375
- }
1376
- }
1377
-
1378
- // All reducer tiers exhausted but provider still rejects —
1379
- // consult the overflow policy for latest-turn compression.
1380
- // The policy either auto-compresses the latest turn or falls
1381
- // through to the final graceful-error fallback below.
1382
- if (state.contextTooLargeDetected) {
1383
- const action = resolveOverflowAction({
1384
- overflowRecovery: convergenceBudget.overflowRecovery,
1385
- isInteractive: isInteractiveResolved,
1386
- });
1387
-
1388
- if (action === "auto_compress_latest_turn") {
1389
- // Auto-compress without asking — users opt out via the "drop" policy.
1390
- ctx.emitActivityState("thinking", "context_compacting", {
1391
- requestId: reqId,
1392
- });
1393
- const emergencyCompact = await defaultCompact({
1394
- conversationId: ctx.conversationId,
1395
- messages: ctx.messages,
1396
- signal: abortController.signal,
1397
- force: true,
1398
- minKeepRecentUserTurns: 0,
1399
- overrideProfile: resolveCurrentOverrideProfile() ?? null,
1400
- });
1401
- // Only track when the summary LLM actually ran; `force: true`
1402
- // bypasses the auto-threshold gate but not the early-return paths.
1403
- if (emergencyCompact.summaryFailed !== undefined) {
1404
- await ctx.agentLoop.compactionCircuit.recordOutcome(
1405
- emergencyCompact.summaryFailed,
1406
- onEvent,
1259
+ if (!reducerState.exhausted) {
1260
+ // The rerun still yields and the ladder has a rung left — the turn
1261
+ // is incomplete, so continue reducing instead of silently dropping
1262
+ // the incomplete state.
1263
+ rlog.warn(
1264
+ {
1265
+ phase: "convergence",
1266
+ appliedTiers: reducerState.appliedTiers,
1267
+ },
1268
+ "Post-convergence rerun still yielded at checkpoint — continuing reduction",
1407
1269
  );
1408
- }
1409
- if (emergencyCompact.compacted) {
1410
- await applySuccessfulCompaction(emergencyCompact, ctx.messages);
1411
- }
1270
+ state.contextTooLargeDetected = true;
1412
1271
 
1413
- // Only re-inject the memory-static block when ctx.messages was
1414
- // actually stripped; otherwise the existing block is still present.
1415
- // (The `<knowledge_base>`, NOW.md, and v2 static `<info>` blocks
1416
- // self-gate inside their injectors on whether they are already
1417
- // present in `ctx.messages`.)
1418
- const injection = await applyRuntimeInjections(ctx.messages, {
1419
- isNonInteractive,
1420
- modelProfile: modelProfileStr,
1421
- actorContext,
1422
- mode: currentInjectionMode,
1423
- requestId: reqId,
1424
- conversationId: ctx.conversationId,
1425
- });
1426
- runMessages = injection.messages;
1427
- if (isTrustedActor && currentInjectionMode !== "minimal") {
1428
- ctx.graphMemory.retrackCachedNodes();
1272
+ // Fold rerun progress into ctx.messages so the next rung operates
1273
+ // on up-to-date history instead of stale pre-rerun messages.
1274
+ if (lastRunAppendedNewMessages) {
1275
+ ctx.messages = stripInjectionsForCompaction(updatedHistory);
1276
+ markHistoryStrippedBestEffort(ctx.conversationId);
1277
+ }
1278
+ } else if (
1279
+ !reducerState.appliedTiers.includes("auto_compress_latest_turn")
1280
+ ) {
1281
+ // The ladder is exhausted without the terminal auto-compress rung
1282
+ // (the overflow policy disallowed it, or the middle tiers ran out)
1283
+ // and the turn is still over budget. This is a genuine
1284
+ // unrecoverable overflow — surface `context_too_large` via the
1285
+ // fallback below. The terminal auto-compress rung instead leaves
1286
+ // this false so its post-rerun yield reads as
1287
+ // `budget_yield_unrecovered`.
1288
+ state.contextTooLargeDetected = true;
1429
1289
  }
1430
- state.contextTooLargeDetected = false;
1431
-
1432
- updatedHistory = await runAgentLoop(runMessages);
1433
1290
  }
1434
- // action === "fail_gracefully" falls through to the final error below
1435
1291
  }
1436
1292
 
1437
1293
  // Final fallback: all recovery paths exhausted
@@ -10,9 +10,13 @@ import { join } from "node:path";
10
10
 
11
11
  import { type ChannelId, parseInterfaceId } from "../channels/types.js";
12
12
  import { isAssistantFeatureFlagEnabled } from "../config/assistant-feature-flags.js";
13
+ import { resolveCallSiteConfig } from "../config/llm-resolver.js";
13
14
  import { getConfig } from "../config/loader.js";
14
- import type { LLMCallSite } from "../config/schemas/llm.js";
15
- import { stripUserTextBlocksByPrefix } from "../context/strip-injections.js";
15
+ import type { LLMCallSite, LLMConfig } from "../config/schemas/llm.js";
16
+ import {
17
+ NOW_SCRATCHPAD_STRIP_PREFIXES,
18
+ stripUserTextBlocksByPrefix,
19
+ } from "../context/strip-injections.js";
16
20
  import { getDocumentsForConversation } from "../documents/document-store.js";
17
21
  import {
18
22
  getApp,
@@ -210,6 +214,43 @@ export function resolveTurnInboundActorContext(
210
214
  return resolved.trustClass === "guardian" ? null : resolved;
211
215
  }
212
216
 
217
+ /**
218
+ * Render the `model_profile:` turn-context label for a turn from its resolved
219
+ * inference profile key, for the unified `<turn_context>` block.
220
+ *
221
+ * Returns `null` when there is no key to announce (the caller gates this to the
222
+ * turns where the active profile changed since the one last delivered to the
223
+ * model). Otherwise the human-readable label comes from the profile's
224
+ * configured `label` (falling back to the key) and the model id from the
225
+ * call-site resolution keyed on that profile, yielding `Label (model)` — or
226
+ * just `Label` when no model resolves. Derives purely from the passed key,
227
+ * call site, and config, so callers thread the key (plain turn data) rather
228
+ * than the rendered string and self-resolve the call site from the live
229
+ * conversation.
230
+ *
231
+ * `selectionSeed` is the conversation id, threaded so that a key naming a `mix`
232
+ * profile expands to the same arm the turn's provider calls run on (which seed
233
+ * expansion with the same id). Without it the announced model would be a fresh
234
+ * random arm that can disagree with the model actually serving the turn.
235
+ */
236
+ export function resolveTurnModelProfileLabel(
237
+ modelProfileKey: string | null,
238
+ callSite: LLMCallSite,
239
+ llm: LLMConfig,
240
+ selectionSeed?: string,
241
+ ): string | null {
242
+ if (modelProfileKey == null) {
243
+ return null;
244
+ }
245
+ const profileEntry = llm.profiles?.[modelProfileKey];
246
+ const resolved = resolveCallSiteConfig(callSite, llm, {
247
+ overrideProfile: modelProfileKey,
248
+ selectionSeed,
249
+ });
250
+ const label = profileEntry?.label ?? modelProfileKey;
251
+ return resolved.model ? `${label} (${resolved.model})` : label;
252
+ }
253
+
213
254
  /** Derive channel capabilities from source channel + interface identifiers. */
214
255
  export function resolveChannelCapabilities(
215
256
  sourceChannel?: string | null,
@@ -631,12 +672,7 @@ function injectVoiceCallControlContext(
631
672
 
632
673
  /** Strip `<NOW.md>` blocks injected by the `now-md` default injector. */
633
674
  export function stripNowScratchpad(messages: Message[]): Message[] {
634
- return stripUserTextBlocksByPrefix(messages, [
635
- // Shared prefix catches both the current tag and any pre-line-limit
636
- // variant that may linger in in-flight histories during a rolling deploy.
637
- "<NOW.md Always keep this up to date",
638
- "<now_scratchpad>", // backward-compat: strip legacy blocks from pre-rename history
639
- ]);
675
+ return stripUserTextBlocksByPrefix(messages, NOW_SCRATCHPAD_STRIP_PREFIXES);
640
676
  }
641
677
 
642
678
  /**
@@ -20,7 +20,7 @@ import type { Message, ToolDefinition } from "../providers/types.js";
20
20
  import { assistantEventHub } from "../runtime/assistant-event-hub.js";
21
21
  import { registerConversationSender } from "../tools/browser/browser-screencast.js";
22
22
  import type { ToolExecutor } from "../tools/executor.js";
23
- import { getMcpToolDefinitions } from "../tools/registry.js";
23
+ import { getMcpToolDefinitions, getToolOwner } from "../tools/registry.js";
24
24
  import {
25
25
  ACTIVITY_SKIP_SET,
26
26
  injectActivityField,
@@ -236,6 +236,14 @@ export function createToolExecutor(
236
236
  };
237
237
  }
238
238
 
239
+ // Attribute the invocation to the skill that owns the dispatched tool
240
+ // so lifecycle events (and the tool_invocations audit row) carry the
241
+ // triggering skill id.
242
+ const owner = getToolOwner(toolName);
243
+ if (owner?.kind === "skill") {
244
+ toolContext.skillId = owner.id;
245
+ }
246
+
239
247
  const result = await executor.execute(toolName, toolInput, toolContext);
240
248
  if (toolContext.approvedViaPrompt) {
241
249
  ctx.approvedViaPromptThisTurn = true;
@@ -129,6 +129,7 @@ import { MessageQueue } from "./conversation-queue-manager.js";
129
129
  import {
130
130
  type ChannelCapabilities,
131
131
  getSlackCompactionWatermarkForPrefix,
132
+ type InboundActorContext,
132
133
  loadSlackChronologicalContext,
133
134
  stripInjectionsForCompaction,
134
135
  } from "./conversation-runtime-assembly.js";
@@ -269,6 +270,18 @@ export class Conversation {
269
270
  * another actor's persona mid-turn.
270
271
  */
271
272
  /** @internal */ currentTurnTrustContext?: TrustContext;
273
+ /**
274
+ * The model-facing inbound actor context resolved once at turn start from
275
+ * {@link currentTurnTrustContext}. Frozen here because resolving it reads the
276
+ * live contact/member registry (member status/policy, contact notes,
277
+ * interaction count), which a contact tool or the guardian can mutate
278
+ * mid-turn; post-compaction re-injection reads this snapshot so it re-emits
279
+ * the actor context the turn's initial assembly saw rather than re-resolving
280
+ * against drifted registry state. `null` on guardian turns and when there is
281
+ * no trust context (the actor section is suppressed).
282
+ * @internal
283
+ */
284
+ currentTurnInboundActorContext?: InboundActorContext | null;
272
285
  /** @internal */ currentTurnChannelCapabilities?: ChannelCapabilities;
273
286
  /** @internal */ currentTurnOverrideProfile?: string;
274
287
  /** @internal */ toolRoutedProfile?: string;