@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
@@ -72,17 +72,13 @@ import {
72
72
  import { enqueueMemoryRetrospectiveOnCompaction } from "../memory/memory-retrospective-enqueue.js";
73
73
  import { HOOKS } from "../plugin-api/constants.js";
74
74
  import type { UserPromptSubmitContext } from "../plugin-api/types.js";
75
- import { defaultCompact } from "../plugins/defaults/compaction/compact.js";
76
75
  import {
77
76
  createInitialReducerState,
78
77
  reduceContextOverflow,
79
78
  type ReducerState,
80
79
  } from "../plugins/defaults/compaction/context-overflow-reducer.js";
81
- import type { ContextWindowCompactOptions } from "../plugins/defaults/compaction/window-manager.js";
80
+ import { computeCorrectedOverflowTarget } from "../plugins/defaults/compaction/corrected-target.js";
82
81
  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
82
  import { runHook } from "../plugins/pipeline.js";
87
83
  import type { ContentBlock, Message } from "../providers/types.js";
88
84
  import type { Provider } from "../providers/types.js";
@@ -124,6 +120,7 @@ import {
124
120
  getSlackCompactionWatermarkForPrefix,
125
121
  loadSlackChronologicalContext,
126
122
  resolveTurnInboundActorContext,
123
+ resolveTurnModelProfileLabel,
127
124
  type SlackChronologicalContext,
128
125
  stripInjectionsForCompaction,
129
126
  } from "./conversation-runtime-assembly.js";
@@ -802,9 +799,9 @@ export async function runAgentLoopImpl(
802
799
  // Unified `<turn_context>` actor input for this turn (model-facing grounding
803
800
  // metadata; the conversation runtime context remains the source for policy
804
801
  // 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.
802
+ // `modelProfileKey`) so post-compaction re-injection receives it as an
803
+ // explicit hook input rather than re-deriving it from live state that can
804
+ // flip mid-turn.
808
805
  const actorContext = resolveTurnInboundActorContext(
809
806
  ctx.trustContext,
810
807
  ctx.assistantId,
@@ -851,80 +848,65 @@ export async function runAgentLoopImpl(
851
848
  config.llm.activeProfile ??
852
849
  resolveDefaultProfileKey("mainAgent", config.llm);
853
850
  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;
851
+ const modelProfileKey =
852
+ effectiveProfileKey != null && effectiveProfileKey !== lastNotified
853
+ ? effectiveProfileKey
854
+ : null;
855
+ // The key is threaded as plain turn data to the user-prompt-submit and
856
+ // post-compaction hooks, which render the `Label (model)` line from it
857
+ // themselves. The post-rejection convergence re-injection further down is a
858
+ // direct assembly call rather than a hook, so its label is still rendered
859
+ // here from the same key.
860
+ const modelProfileStr = resolveTurnModelProfileLabel(
861
+ modelProfileKey,
862
+ turnCallSite,
863
+ config.llm,
864
+ ctx.conversationId,
865
+ );
866
+ if (modelProfileKey != null) {
862
867
  // Record the notification for persistence on delivery rather than here:
863
868
  // the model only "learns" the profile once it receives this turn
864
869
  // context, signalled by the first `message_complete`. Persisting inline
865
870
  // would mark the profile notified even if the turn is cancelled or fails
866
871
  // before the model ever sees the notice.
867
- state.pendingNotifiedInferenceProfile = effectiveProfileKey;
872
+ state.pendingNotifiedInferenceProfile = modelProfileKey;
868
873
  }
869
874
 
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.
875
+ // Trust class and injection mode, resolved once at turn start for the
876
+ // post-compaction re-injection sites further down, which re-apply the
877
+ // runtime injections (gated on trust) onto the compacted history.
882
878
  const isTrustedActor = resolveTrustClass(ctx.trustContext) === "guardian";
883
879
  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.
880
+
881
+ // user-prompt-submit hook chain. Fires once per user turn at the primary
882
+ // `agentLoop.run` (the re-entry / retry calls further down do not refire it
883
+ // — they're not new user submissions), before the loop runs so the
884
+ // hook-assembled messages are part of its input. Memory retrieval runs
885
+ // first — fetching PKB / NOW.md / memory-graph outputs, persisting its own
886
+ // side effects (injected-block metadata, recall log, `memory_recalled`
887
+ // event), and assembling the turn's runtime-injection blocks onto the
888
+ // history — followed by history repair and title generation, which see the
889
+ // fully injected history. Plugins may mutate `ctx.latestMessages` in place
890
+ // OR return a new context with a fresh array; `runHook` forwards whichever
891
+ // the chain settles on, in plugin registration order. The loop then reports
892
+ // its own appended output via `AgentLoopRunResult.newMessages`, which
893
+ // persistence consumes.
914
894
  const userPromptCtx: UserPromptSubmitContext = {
915
895
  conversationId: ctx.conversationId,
916
896
  userMessageId,
917
897
  requestId: reqId,
918
898
  prompt: options?.titleText ?? content,
919
899
  originalMessages: ctx.messages,
920
- latestMessages: runMessages,
900
+ latestMessages: ctx.messages,
921
901
  logger: rlog,
902
+ modelProfileKey,
903
+ isNonInteractive,
922
904
  };
923
905
  const finalUserPromptCtx = await runHook(
924
906
  HOOKS.USER_PROMPT_SUBMIT,
925
907
  userPromptCtx,
926
908
  );
927
- runMessages = finalUserPromptCtx.latestMessages;
909
+ let runMessages = finalUserPromptCtx.latestMessages;
928
910
 
929
911
  // Reducer state, tool-token budget, and calibration provider key consumed
930
912
  // by the post-rejection convergence loop further down. The tool-token
@@ -1005,7 +987,7 @@ export async function runAgentLoopImpl(
1005
987
  resolveContextWindow,
1006
988
  compactInPlace,
1007
989
  isNonInteractive,
1008
- modelProfile: modelProfileStr,
990
+ modelProfileKey,
1009
991
  actorContext,
1010
992
  });
1011
993
  lastRunAppendedNewMessages = appendedNewMessages;
@@ -1190,92 +1172,76 @@ export async function runAgentLoopImpl(
1190
1172
  },
1191
1173
  );
1192
1174
  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
- }
1175
+ const { targetTokens: correctedTarget, estimationErrorRatio } =
1176
+ computeCorrectedOverflowTarget({
1177
+ preflightBudget: convergenceBudget.preflightBudget,
1178
+ actualTokens,
1179
+ estimatedTokens: estimatedTokensAtOverflow,
1180
+ });
1181
+ if (estimationErrorRatio != null) {
1182
+ rlog.warn(
1183
+ {
1184
+ phase: "convergence",
1185
+ actualTokens,
1186
+ estimatedTokens: estimatedTokensAtOverflow,
1187
+ estimationErrorRatio: estimationErrorRatio.toFixed(2),
1188
+ preflightBudget: convergenceBudget.preflightBudget,
1189
+ correctedTarget,
1190
+ },
1191
+ "Adjusting compaction target based on observed estimation error",
1192
+ );
1212
1193
  }
1213
1194
 
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
- }
1195
+ // ── Bounded context-overflow convergence driver ─────────────────
1196
+ // The compaction plugin's reduction ladder owns every rung: the
1197
+ // emergency summarize-around-last-tool-pair, the middle tiers (forced
1198
+ // compaction, tool-result truncation, media stubbing, injection
1199
+ // downgrade), and the terminal auto-compress of the latest turn. This
1200
+ // driver applies one rung per iteration, re-injects, and re-runs the
1201
+ // agent loop until the context fits or the ladder is exhausted. The
1202
+ // overflow policy decides whether the terminal auto-compress rung is
1203
+ // permitted; the ladder never makes that policy call itself.
1204
+ const overflowAction = resolveOverflowAction({
1205
+ overflowRecovery: convergenceBudget.overflowRecovery,
1206
+ isInteractive: isInteractiveResolved,
1207
+ });
1208
+ const reducerConfig = {
1209
+ providerName: estimationProviderName,
1210
+ systemPrompt: ctx.systemPrompt,
1211
+ contextWindow: resolveCurrentContextWindowConfig(),
1212
+ targetTokens: correctedTarget,
1213
+ toolTokenBudget,
1214
+ conversationId: ctx.conversationId,
1215
+ overrideProfile: resolveCurrentOverrideProfile() ?? null,
1216
+ actorTrustClass: resolveTurnActorTrustClass(ctx),
1217
+ previousEstimatedInputTokens: estimatedTokensAtOverflow,
1218
+ maxMiddleTierAttempts: convergenceBudget.overflowRecovery.maxAttempts,
1219
+ allowAutoCompressLatestTurn:
1220
+ overflowAction === "auto_compress_latest_turn",
1221
+ };
1262
1222
 
1263
- let convergenceAttempts = 0;
1264
- const maxAttempts = convergenceBudget.overflowRecovery.maxAttempts;
1223
+ // Safety backstop against a reduction ladder that never reports
1224
+ // exhaustion: the ladder can apply at most the emergency rung, the
1225
+ // middle-tier attempt budget, and the terminal auto-compress rung, so a
1226
+ // well-behaved reducer always sets `exhausted` within this many steps.
1227
+ // The cap only guards against a misbehaving reducer; it never truncates a
1228
+ // legitimate escalation.
1229
+ const maxConvergenceRungs = reducerConfig.maxMiddleTierAttempts + 2;
1230
+ let convergenceRungs = 0;
1265
1231
 
1266
1232
  while (
1267
1233
  state.contextTooLargeDetected &&
1268
- convergenceAttempts < maxAttempts &&
1269
- !reducerState.exhausted
1234
+ !reducerState.exhausted &&
1235
+ convergenceRungs < maxConvergenceRungs
1270
1236
  ) {
1271
- convergenceAttempts++;
1237
+ convergenceRungs++;
1272
1238
  rlog.warn(
1273
1239
  {
1274
1240
  phase: "convergence",
1275
- attempt: convergenceAttempts,
1241
+ rung: convergenceRungs,
1276
1242
  appliedTiers: reducerState.appliedTiers,
1277
1243
  },
1278
- "Context too large — applying next reducer tier",
1244
+ "Context too large — applying next reduction rung",
1279
1245
  );
1280
1246
 
1281
1247
  ctx.emitActivityState("thinking", "context_compacting", {
@@ -1284,23 +1250,8 @@ export async function runAgentLoopImpl(
1284
1250
  const convergenceCompactionBasis = ctx.messages;
1285
1251
  const step = await reduceContextOverflow(
1286
1252
  convergenceCompactionBasis,
1287
- {
1288
- providerName: estimationProviderName,
1289
- systemPrompt: ctx.systemPrompt,
1290
- contextWindow: resolveCurrentContextWindowConfig(),
1291
- targetTokens: correctedTarget,
1292
- toolTokenBudget,
1293
- },
1253
+ reducerConfig,
1294
1254
  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
1255
  abortController.signal,
1305
1256
  );
1306
1257
 
@@ -1308,10 +1259,9 @@ export async function runAgentLoopImpl(
1308
1259
  ctx.messages = step.messages;
1309
1260
  currentInjectionMode = step.state.injectionMode;
1310
1261
 
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.
1262
+ // Only track when the summary LLM actually ran — `summaryFailed
1263
+ // === undefined` indicates a forced-compaction early-return path that
1264
+ // never called the summary LLM.
1315
1265
  if (
1316
1266
  step.compactionResult &&
1317
1267
  step.compactionResult.summaryFailed !== undefined
@@ -1351,87 +1301,39 @@ export async function runAgentLoopImpl(
1351
1301
 
1352
1302
  updatedHistory = await runAgentLoop(runMessages);
1353
1303
 
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
1304
  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,
1305
+ if (!reducerState.exhausted) {
1306
+ // The rerun still yields and the ladder has a rung left — the turn
1307
+ // is incomplete, so continue reducing instead of silently dropping
1308
+ // the incomplete state.
1309
+ rlog.warn(
1310
+ {
1311
+ phase: "convergence",
1312
+ appliedTiers: reducerState.appliedTiers,
1313
+ },
1314
+ "Post-convergence rerun still yielded at checkpoint — continuing reduction",
1407
1315
  );
1408
- }
1409
- if (emergencyCompact.compacted) {
1410
- await applySuccessfulCompaction(emergencyCompact, ctx.messages);
1411
- }
1316
+ state.contextTooLargeDetected = true;
1412
1317
 
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();
1318
+ // Fold rerun progress into ctx.messages so the next rung operates
1319
+ // on up-to-date history instead of stale pre-rerun messages.
1320
+ if (lastRunAppendedNewMessages) {
1321
+ ctx.messages = stripInjectionsForCompaction(updatedHistory);
1322
+ markHistoryStrippedBestEffort(ctx.conversationId);
1323
+ }
1324
+ } else if (
1325
+ !reducerState.appliedTiers.includes("auto_compress_latest_turn")
1326
+ ) {
1327
+ // The ladder is exhausted without the terminal auto-compress rung
1328
+ // (the overflow policy disallowed it, or the middle tiers ran out)
1329
+ // and the turn is still over budget. This is a genuine
1330
+ // unrecoverable overflow — surface `context_too_large` via the
1331
+ // fallback below. The terminal auto-compress rung instead leaves
1332
+ // this false so its post-rerun yield reads as
1333
+ // `budget_yield_unrecovered`.
1334
+ state.contextTooLargeDetected = true;
1429
1335
  }
1430
- state.contextTooLargeDetected = false;
1431
-
1432
- updatedHistory = await runAgentLoop(runMessages);
1433
1336
  }
1434
- // action === "fail_gracefully" falls through to the final error below
1435
1337
  }
1436
1338
 
1437
1339
  // 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;