@memberjunction/ai-agents 6.2.0-edge.7 → 6.2.0

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 (38) hide show
  1. package/README.md +15 -0
  2. package/dist/MemoryWriteManager.d.ts +12 -0
  3. package/dist/MemoryWriteManager.d.ts.map +1 -1
  4. package/dist/MemoryWriteManager.js +18 -3
  5. package/dist/MemoryWriteManager.js.map +1 -1
  6. package/dist/agent-types/loop-agent-prompt-params.d.ts +20 -0
  7. package/dist/agent-types/loop-agent-prompt-params.d.ts.map +1 -1
  8. package/dist/agent-types/loop-agent-prompt-params.js +4 -1
  9. package/dist/agent-types/loop-agent-prompt-params.js.map +1 -1
  10. package/dist/base-agent.d.ts +85 -5
  11. package/dist/base-agent.d.ts.map +1 -1
  12. package/dist/base-agent.js +296 -50
  13. package/dist/base-agent.js.map +1 -1
  14. package/dist/client-tool-results.d.ts +12 -0
  15. package/dist/client-tool-results.d.ts.map +1 -1
  16. package/dist/client-tool-results.js +21 -0
  17. package/dist/client-tool-results.js.map +1 -1
  18. package/dist/index.d.ts +2 -0
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.js +2 -0
  21. package/dist/index.js.map +1 -1
  22. package/dist/realtime/bridge-realtime-session-factory.d.ts +3 -3
  23. package/dist/realtime/bridge-realtime-session-factory.d.ts.map +1 -1
  24. package/dist/realtime/bridge-realtime-session-factory.js +12 -6
  25. package/dist/realtime/bridge-realtime-session-factory.js.map +1 -1
  26. package/dist/realtime/realtime-client-session-service.d.ts +50 -23
  27. package/dist/realtime/realtime-client-session-service.d.ts.map +1 -1
  28. package/dist/realtime/realtime-client-session-service.js +84 -44
  29. package/dist/realtime/realtime-client-session-service.js.map +1 -1
  30. package/dist/realtime/realtime-platform-credentials.d.ts +65 -0
  31. package/dist/realtime/realtime-platform-credentials.d.ts.map +1 -0
  32. package/dist/realtime/realtime-platform-credentials.js +148 -0
  33. package/dist/realtime/realtime-platform-credentials.js.map +1 -0
  34. package/dist/realtime/realtime-vendor-resolution.d.ts +41 -2
  35. package/dist/realtime/realtime-vendor-resolution.d.ts.map +1 -1
  36. package/dist/realtime/realtime-vendor-resolution.js +86 -4
  37. package/dist/realtime/realtime-vendor-resolution.js.map +1 -1
  38. package/package.json +20 -20
@@ -37,7 +37,8 @@ import { CrushCode } from '@memberjunction/context-crush/code';
37
37
  import { RealtimeSessionRunner } from './realtime/realtime-session-runner.js';
38
38
  import { ResolveNarrationInstructionsTemplate } from './realtime/realtime-narration.js';
39
39
  import { BuildRealtimeOverridesJson, BuildVoiceMannerSection, GetNarrationPaceMs, GetProviderVoiceSettings, GetSessionTuningSettings, GetModelCatalogSessionSettings, DeepMergeConfigs, ResolveEffectiveRealtimeConfig } from './realtime/realtime-coagent-config.js';
40
- import { ListRealtimeVendorsForModel, SelectRealtimeVendorForModel } from './realtime/realtime-vendor-resolution.js';
40
+ import { ListRealtimeVendorsForModel, RealtimeKeyFixHint, SelectRealtimeVendorForModel } from './realtime/realtime-vendor-resolution.js';
41
+ import { ResolveRealtimePlatformCredentials } from './realtime/realtime-platform-credentials.js';
41
42
  import { ChooseRealtimeVendorForAvatar, RealtimeModelShowsAvatar } from './realtime/realtime-video-output-gate.js';
42
43
  import { RealtimeSessionCanShowAvatar } from './realtime/realtime-avatar-resolution.js';
43
44
  import { RealtimeClientSessionService, WarnOnUnmatchedProviderVoice } from './realtime/realtime-client-session-service.js';
@@ -56,7 +57,7 @@ import { PriorTurnToolResultCache } from './prior-turn-tool-result-cache.js';
56
57
  import { PromptComponentResolver, InjectScopedPromptParts } from './prompt-component-resolver.js';
57
58
  import { ScopedPromptConfigResolver, ApplyScopedPromptConfig } from './scoped-prompt-config-resolver.js';
58
59
  import { StringifyForPersistence, AIPromptParams, ChildPromptParam, ConversationUtility, ParseFileOutputRef, parseAssignmentStrategy, ResolveClientTools, initAgentRunStep, finalizeAgentRunStep, AgentRunStepSaveQueue, ExtractPromptResultText, GetTaskGraphSubmitter, SummarizeDecisionAnswers, SystemPlaceholderManager, WithoutHostOnlyAgentRunDataKeys, WithAgentRunDataTrustApplied, AgentUserPolicyEngine, ApplyOutputMapping, BuildActionOutputObject, ConfigOf, ResolveLoopBodyParams, ValidateLoopOperationStructure } from '@memberjunction/ai-core-plus';
59
- import { ActionResult, RunActionParams, AUDIENCE_UNSUPPORTED_RESULT_CODE, ActionRunScopeIsBounded } from '@memberjunction/actions-base';
60
+ import { ActionEngineBase, ActionResult, RunActionParams, AUDIENCE_UNSUPPORTED_RESULT_CODE, ActionRunScopeIsBounded } from '@memberjunction/actions-base';
60
61
  import { UserCache } from '@memberjunction/generic-database-provider';
61
62
  import { AgentAudienceAddsReader, AgentAudienceProblem, AgentAudienceReaderIDs, MatchAudienceUsers } from './agent-audience.js';
62
63
  import { TemplateEngineServer } from '@memberjunction/templates';
@@ -82,7 +83,7 @@ import { PipelineExecutor, PipelineToolRegistry, ActionInvocable, ArtifactToolIn
82
83
  import { GetValueFromPath, SetMappedValue } from '@memberjunction/ai-core-plus';
83
84
  import { AgentDataPreloader } from './AgentDataPreloader.js';
84
85
  import { ClientToolRequestManager } from './ClientToolRequestManager.js';
85
- import { BuildClientToolResultMessage, ResolveClientToolResultMaxChars, ReplaceMediaBlocksWithStubs, IsMediaBlock, IMAGE_BLOCK_TOKEN_ESTIMATE } from './client-tool-results.js';
86
+ import { BuildClientToolResultMessage, ResolveClientToolResultMaxChars, ReplaceMediaBlocksWithStubs, IsMediaBlock, IMAGE_BLOCK_TOKEN_ESTIMATE, WrapUntrustedExternalData } from './client-tool-results.js';
86
87
  import { CanAgentOwnSubAgentConsults, DEFAULT_MAX_SUB_AGENT_CONSULT_ROUNDS, FormatReloadedConsultsMessage, FormatResponseFormSummary, FormatSubAgentConsultMessage, LoadOpenSubAgentConsults } from './sub-agent-consult.js';
87
88
  import { ConversationMessageResolver } from './utils/ConversationMessageResolver.js';
88
89
  import _ from 'lodash';
@@ -135,6 +136,11 @@ import _ from 'lodash';
135
136
  * one) from saturating the model API / DB pool with N concurrent runs.
136
137
  */
137
138
  const PARALLEL_SUBAGENT_CONCURRENCY_LIMIT = 5;
139
+ /** Result codes that are structurally non-retryable (permission or run-scope refusals). */
140
+ export const NON_RETRYABLE_RESULT_CODES = new Set([
141
+ 'PERMISSION_DENIED',
142
+ 'RUN_SCOPE_UNSUPPORTED',
143
+ ]);
138
144
  /** Result code of a call the user's agent policy denies outright (`checkUserActionPolicy`). */
139
145
  export const POLICY_DENIED_RESULT_CODE = 'POLICY_DENIED';
140
146
  /** Result code of a call the user's agent policy allows only with the user's approval. */
@@ -220,6 +226,13 @@ export class BaseAgent {
220
226
  * @private
221
227
  */
222
228
  this._audienceLockedActions = new Set();
229
+ /**
230
+ * External/untrusted data sources ingested during the current agent run (Primitive 2).
231
+ * Once non-empty, {@link IsRunTainted} is true for the remainder of the run and any memory
232
+ * notes written by the run land as `Status = 'Pending'` with taint provenance in `Comments`.
233
+ * @protected
234
+ */
235
+ this._taintedSources = [];
223
236
  /**
224
237
  * Parameter-aware failure tracking per action name for the current agent run.
225
238
  * Differentiates identical retries (which trip quickly) from parameter modifications (which allow self-correction).
@@ -660,6 +673,19 @@ export class BaseAgent {
660
673
  get TreeBudget() {
661
674
  return this._treeBudget;
662
675
  }
676
+ /**
677
+ * True when the current agent run has ingested at least one `'Untrusted'` or `'SemiTrusted'`
678
+ * action or client-tool result.
679
+ */
680
+ get IsRunTainted() {
681
+ return this._taintedSources.length > 0;
682
+ }
683
+ /**
684
+ * Read-only view of all `'Untrusted'` and `'SemiTrusted'` sources ingested during the current run.
685
+ */
686
+ get TaintedSources() {
687
+ return this._taintedSources;
688
+ }
663
689
  /**
664
690
  * The identity of one action call's arguments, for the circuit breaker's identical-arguments
665
691
  * rule: two calls with the same normalized string are "the same call", whatever order the model
@@ -1041,6 +1067,9 @@ export class BaseAgent {
1041
1067
  if (POLICY_REFUSAL_RESULT_CODES.has(summary.resultCode)) {
1042
1068
  return 'policy';
1043
1069
  }
1070
+ if (NON_RETRYABLE_RESULT_CODES.has(summary.resultCode) || summary.errorRecovery?.Retryable === false) {
1071
+ return 'non-retryable';
1072
+ }
1044
1073
  if (record && record.identicalFailures >= IDENTICAL_FAILURE_THRESHOLD) {
1045
1074
  return 'identical-arguments';
1046
1075
  }
@@ -1075,6 +1104,15 @@ export class BaseAgent {
1075
1104
  switch (this.classifyActionFailure(summary)) {
1076
1105
  case 'policy':
1077
1106
  return this.formatPolicyRefusalDirective(summary);
1107
+ case 'non-retryable': {
1108
+ const suggestion = summary.errorRecovery?.RecoverySuggestion
1109
+ ? ` ${summary.errorRecovery.RecoverySuggestion}`
1110
+ : '';
1111
+ const nextActions = summary.errorRecovery?.SuggestedNextActions?.length
1112
+ ? ` Suggested alternative actions: ${summary.errorRecovery.SuggestedNextActions.map(a => `\`${a}\``).join(', ')}.`
1113
+ : '';
1114
+ return `[CRITICAL/NON_RETRYABLE_FAILURE] Action '${name}' failed with non-retryable error (${summary.resultCode}): "${summary.message}".${suggestion}${nextActions} DO NOT retry '${name}' against the same target or with the same parameters; pivot to an alternative tool, a different target, or inform the user.`;
1115
+ }
1078
1116
  case 'audience':
1079
1117
  return `[CRITICAL/NOT_AVAILABLE_IN_SHARED_CONVERSATION] Action '${name}' is not available in this shared conversation: what it ` +
1080
1118
  `returns could not be limited to what everyone in it may see ("${summary.message}"). It is not broken or misconfigured. ` +
@@ -1085,8 +1123,86 @@ export class BaseAgent {
1085
1123
  return `[CRITICAL/ATTEMPTS_EXHAUSTED] Action '${name}' has failed ${record?.totalConsecutiveFailures ?? ACTION_FAILURE_BUDGET} consecutive times: "${summary.message}". Retries for this action are exhausted. You MUST pivot to an alternative tool or continue with available data.`;
1086
1124
  case 'identical-arguments':
1087
1125
  return `[CRITICAL/REPEATED_IDENTICAL_CALL] Action '${name}' failed again with the EXACT SAME arguments: "${summary.message}". Calling '${name}' with these parameters will not work. You MUST either adjust your parameters or pivot to an alternative tool.`;
1088
- default:
1089
- return `[WARNING/ACTION_FAILURE] Action '${name}' failed: "${summary.message}". Review the error and adjust your input parameters (attempt ${record?.totalConsecutiveFailures ?? 1} of ${ACTION_FAILURE_BUDGET}). DO NOT retry calling '${name}' with identical arguments.`;
1126
+ default: {
1127
+ const suggestion = summary.errorRecovery?.RecoverySuggestion
1128
+ ? ` ${summary.errorRecovery.RecoverySuggestion}`
1129
+ : '';
1130
+ const suggestedValues = summary.errorRecovery?.SuggestedValues?.length
1131
+ ? ` Valid alternatives: ${summary.errorRecovery.SuggestedValues.join(', ')}.`
1132
+ : '';
1133
+ return `[WARNING/ACTION_FAILURE] Action '${name}' failed: "${summary.message}".${suggestion}${suggestedValues} Review the error and adjust your input parameters (attempt ${record?.totalConsecutiveFailures ?? 1} of ${ACTION_FAILURE_BUDGET}). DO NOT retry calling '${name}' with identical arguments.`;
1134
+ }
1135
+ }
1136
+ }
1137
+ /**
1138
+ * Resolves the output trust classification for an action from its `MJ: Actions` metadata
1139
+ * (`actionEntity.Config_Object?.outputTrustLevel`), with per-agent or per-run overrides via
1140
+ * `AgentTypePromptParams`.
1141
+ *
1142
+ * Precedence:
1143
+ * 1. An explicit per-action `actionTrustLevels` entry in `AgentTypePromptParams` — the operator's last word
1144
+ * 2. The `trustedActionNames` / `untrustedActionNames` lists in `AgentTypePromptParams`
1145
+ * 3. The action's metadata catalog setting (`Action.Config_Object?.outputTrustLevel`, looking up the
1146
+ * action by name in `ActionEngineBase.Instance.Actions` when `actionEntity` is omitted)
1147
+ * 4. `'Trusted'`
1148
+ * @protected
1149
+ */
1150
+ resolveActionTrustLevel(actionName, actionEntity, params) {
1151
+ const normalizedName = actionName.trim().toLowerCase();
1152
+ const entity = actionEntity ?? ActionEngineBase.Instance.Actions?.find(a => a.Name?.trim().toLowerCase() === normalizedName);
1153
+ const entityName = entity?.Name?.trim().toLowerCase();
1154
+ const namesAction = (candidate) => {
1155
+ const n = candidate.trim().toLowerCase();
1156
+ return n === normalizedName || (entityName !== undefined && n === entityName);
1157
+ };
1158
+ const isLevel = (v) => v === 'Trusted' || v === 'SemiTrusted' || v === 'Untrusted';
1159
+ const promptParams = (params?.data?.__agentTypePromptParams ?? this._agentTypePromptParams);
1160
+ // 1. Explicit per-action override
1161
+ if (promptParams?.actionTrustLevels && typeof promptParams.actionTrustLevels === 'object') {
1162
+ for (const [key, level] of Object.entries(promptParams.actionTrustLevels)) {
1163
+ if (namesAction(key) && isLevel(level)) {
1164
+ return level;
1165
+ }
1166
+ }
1167
+ }
1168
+ // 2. Per-agent / per-run name lists
1169
+ if (Array.isArray(promptParams?.trustedActionNames) && promptParams.trustedActionNames.some(namesAction)) {
1170
+ return 'Trusted';
1171
+ }
1172
+ if (Array.isArray(promptParams?.untrustedActionNames) && promptParams.untrustedActionNames.some(namesAction)) {
1173
+ return 'Untrusted';
1174
+ }
1175
+ // 3. Action metadata catalog setting (Action.Config_Object?.outputTrustLevel)
1176
+ const metadataLevel = entity?.Config_Object?.outputTrustLevel;
1177
+ if (isLevel(metadataLevel)) {
1178
+ return metadataLevel;
1179
+ }
1180
+ if (typeof entity?.Config_ === 'string' && entity.Config_.trim().length > 0) {
1181
+ const parsed = CleanAndParseJSON(entity.Config_, false);
1182
+ if (parsed && isLevel(parsed.outputTrustLevel)) {
1183
+ return parsed.outputTrustLevel;
1184
+ }
1185
+ }
1186
+ return 'Trusted';
1187
+ }
1188
+ /**
1189
+ * Records a tainted source ingested during the current agent run.
1190
+ * @protected
1191
+ */
1192
+ recordTaintedSource(stepNumber, sourceName, trustLevel) {
1193
+ if (!this._taintedSources.some(s => s.stepNumber === stepNumber && s.sourceName === sourceName && s.trustLevel === trustLevel)) {
1194
+ this._taintedSources.push({ stepNumber, sourceName, trustLevel });
1195
+ }
1196
+ }
1197
+ /**
1198
+ * Folds a finished sub-agent's tainted sources into this run's, attributed to the sub-agent step,
1199
+ * so delegating a web search taints the parent exactly as searching itself would. Runs whether or
1200
+ * not the child succeeded: a failed child may still have read external content.
1201
+ * @protected
1202
+ */
1203
+ absorbSubAgentTaint(subAgentName, subAgentResult, stepNumber) {
1204
+ for (const source of subAgentResult.taintedSources ?? []) {
1205
+ this.recordTaintedSource(stepNumber, `sub-agent:${subAgentName}/${source.sourceName}`, source.trustLevel);
1090
1206
  }
1091
1207
  }
1092
1208
  /**
@@ -1995,6 +2111,7 @@ export class BaseAgent {
1995
2111
  this._handoffResult = null;
1996
2112
  this._resolvedHandoffTarget = null;
1997
2113
  this._lastSubAgentArtifactDirective = undefined;
2114
+ this._taintedSources = [];
1998
2115
  this._messageLifecycleCallback = params.onMessageLifecycle;
1999
2116
  this._catalogNarrowing = undefined;
2000
2117
  this._openingRequest = OpeningRequestText(params.conversationMessages);
@@ -2048,14 +2165,19 @@ export class BaseAgent {
2048
2165
  // The user's new message, captured by identity before anything below adds to the list, so a
2049
2166
  // resumed stopped run can be spliced in ahead of it once the parallel phase settles.
2050
2167
  const continuationMessage = wrappedParams.conversationMessages[wrappedParams.conversationMessages.length - 1];
2168
+ // Stage Phase 2 system message injections in isolated arrays so their prefix order is
2169
+ // 100% deterministic regardless of Promise.all completion timing (Lesson 1 Vector 5).
2170
+ const memoryStagedMessages = [];
2171
+ const ragStagedMessages = [];
2172
+ const discoveryStagedMessages = [];
2051
2173
  // Positions matter: [0] is the config, [5] the stopped-run continuation, and [7] open sub-agent consults.
2052
2174
  const [config, , , , , stoppedRunContinuation, , openConsults] = await Promise.all([
2053
2175
  this.loadAgentConfiguration(params.agent),
2054
2176
  this.preloadAgentData(wrappedParams),
2055
- this.InjectContextMemory(typeof inputText === 'string' ? inputText : '', params.agent, userId, companyId, params.contextUser, wrappedParams.conversationMessages, runScope.EntityID, runScope.RecordID, runScope.Secondary, this.parseSecondaryScopeConfig(params.agent),
2177
+ this.InjectContextMemory(typeof inputText === 'string' ? inputText : '', params.agent, userId, companyId, params.contextUser, memoryStagedMessages, runScope.EntityID, runScope.RecordID, runScope.Secondary, this.parseSecondaryScopeConfig(params.agent),
2056
2178
  // Under an audience, one user's notes and examples are not shown to the room.
2057
2179
  this.runAudienceAddsReader(params)),
2058
- this.InjectPreExecutionRAG(typeof inputText === 'string' ? inputText : '', params.agent, params.contextUser, wrappedParams.conversationMessages, params.conversationMessages, runScope.EntityID, runScope.RecordID, runScope.Secondary, params.payload,
2180
+ this.InjectPreExecutionRAG(typeof inputText === 'string' ? inputText : '', params.agent, params.contextUser, ragStagedMessages, params.conversationMessages, runScope.EntityID, runScope.RecordID, runScope.Secondary, params.payload,
2059
2181
  // Phase 1 has already activated requested + persisted conversation skills.
2060
2182
  this.activeSkillIDsForRun(params),
2061
2183
  // Each reader must pass the scope gate; the search keeps what every one of them may read.
@@ -2069,11 +2191,14 @@ export class BaseAgent {
2069
2191
  this.loadStoppedRunContinuation(wrappedParams),
2070
2192
  // Decision discovery (plan Task 3.1), off unless the decisionsEnabled and decisionDiscovery prompt
2071
2193
  // params are true: may add a <suggested_agent> system message, within DECISION_DISCOVERY_TIMEOUT_MS.
2072
- this.InjectDecisionDiscovery(params.agent, params.contextUser, wrappedParams.conversationMessages, params.data),
2194
+ this.InjectDecisionDiscovery(params.agent, params.contextUser, discoveryStagedMessages, params.data),
2073
2195
  // If this run resumes a prior run that paused with FinalStep === 'Chat', reload any unanswered
2074
2196
  // sub-agent consults so the caller's answer can be relayed back to the waiting sub-agent.
2075
2197
  this.loadOpenConsults(wrappedParams)
2076
2198
  ]);
2199
+ if (memoryStagedMessages.length > 0 || ragStagedMessages.length > 0 || discoveryStagedMessages.length > 0) {
2200
+ wrappedParams.conversationMessages.unshift(...memoryStagedMessages, ...ragStagedMessages, ...discoveryStagedMessages);
2201
+ }
2077
2202
  // Resume (or summarize) a run the user stopped, now that nothing else is writing the list.
2078
2203
  this.applyStoppedRunContinuation(wrappedParams, stoppedRunContinuation, continuationMessage);
2079
2204
  // Inject scope-resolved prompt parts (role-faithful) for this agent's prompt, alongside
@@ -2486,9 +2611,8 @@ export class BaseAgent {
2486
2611
  const modelResolution = await this.resolveRealtimeModel(params);
2487
2612
  if (!modelResolution) {
2488
2613
  const message = `Agent '${params.agent.Name}' is session-driven (Realtime) but no usable Realtime model could be ` +
2489
- `resolved. Configure a model of AIModelType 'Realtime' with an active vendor DriverClass and a ` +
2490
- `valid API key (e.g. AI_VENDOR_API_KEY__<driver>). This is expected until the realtime drivers ` +
2491
- `and model metadata are provisioned.`;
2614
+ `resolved: no active vendor of an active model of AIModelType 'Realtime' has a usable key and ` +
2615
+ `driver. ${RealtimeKeyFixHint(params.CredentialScope)}`;
2492
2616
  this.logError(message, { agent: params.agent, category: 'RealtimeSession' });
2493
2617
  return await this.createFailureResult(message, params.contextUser);
2494
2618
  }
@@ -2610,9 +2734,9 @@ export class BaseAgent {
2610
2734
  HostFraming: ReadTrimmedString(params.data?.realtimeHostFraming, 'realtimeHostFraming'),
2611
2735
  PriorTranscript: ReadTrimmedString(params.data?.realtimePriorTranscript, 'realtimePriorTranscript'),
2612
2736
  ConversationID: ReadTrimmedString(params.data?.conversationId, 'conversationId'),
2613
- // The run's runtime API keys, so the bridged voice session mints on the caller's key when
2614
- // the run carries one for the realtime driver (the same run-key → platform order as
2615
- // GetAIAPIKey; realtime does not consult MJ Credentials). Absent ⇒ platform keys, as before.
2737
+ // The run's runtime API keys. The session service resolves each vendor's key in a prompt's
2738
+ // order: the platform's MJ Credential for the vendor, then these keys, then the environment
2739
+ // ('RuntimeOnly' scope: these keys alone). Absent ⇒ platform credentials, then the environment.
2616
2740
  // CreateBridgeRealtimeSession (the LiveKit / telephony factory) passes no apiKeys today.
2617
2741
  APIKeys: params.apiKeys,
2618
2742
  CredentialScope: params.CredentialScope,
@@ -2660,21 +2784,25 @@ export class BaseAgent {
2660
2784
  // would dead-end whenever the top model lacked a key — e.g. a power-11 model with no env key
2661
2785
  // (Inworld/AssemblyAI) outranking GPT Realtime — and surface "No usable Realtime model" even though
2662
2786
  // a usable model exists. This mirrors the same fix in RealtimeClientSessionService.
2663
- // The run's runtime API keys, in GetAIAPIKey's order: the run's key for a driver class, else
2664
- // the platform's. That is the legacy tier of prompt key resolution — a prompt consults MJ
2665
- // Credentials / AICredentialBindings first, and realtime does not consult them at all.
2787
+ // Keys resolve per vendor in the order a prompt's do: the platform's MJ Credential for the vendor
2788
+ // (AICredentialBindings on the model-vendor row, then the vendor, then the vendor's default
2789
+ // credential), then the run's key for the driver class, then the environment. A run whose
2790
+ // CredentialScope is 'RuntimeOnly' skips the platform credential and the environment.
2666
2791
  //
2667
2792
  // This also affects WHICH vendor runs the session, deliberately. Vendor selection walks
2668
- // candidates by priority and takes the first whose key resolves, so an organization that
2669
- // brings its own credential for a vendor we hold no platform key for now reaches that
2670
- // vendor — which is the point of bringing your own key, not a side effect of it.
2671
- const resolveAPIKey = MakeAIAPIKeyResolver(params.apiKeys, undefined, params.CredentialScope);
2793
+ // candidates by priority and takes the first whose key resolves, so a vendor reachable only
2794
+ // through a bound credential or the run's own key is still reached.
2795
+ const runThenEnvironment = MakeAIAPIKeyResolver(params.apiKeys, undefined, params.CredentialScope);
2672
2796
  // The vendor follows whether the run will show an avatar, by the co-agent session prep's rule: a vendor that
2673
2797
  // renders avatars (Vertex AI for Gemini 3.8 Live) only when it will, or when it is the only keyed vendor.
2674
2798
  const showsAvatar = this.realtimeRunShowsAvatar(params);
2675
2799
  const candidates = this.selectRealtimeModelCandidates(params.agent, overrideModelID);
2800
+ // Credential resolution is async and vendor selection is not, so every candidate's credentials
2801
+ // are resolved first; selection and the mint then read the same answer.
2802
+ const platform = await this.resolveRealtimePlatformCredentials(candidates.map(m => m.ID), params);
2676
2803
  for (const model of candidates) {
2677
- const vendor = SelectRealtimeVendorForModel(model.ID, resolveAPIKey);
2804
+ const resolveAPIKey = platform.ResolverFor(model.ID, runThenEnvironment);
2805
+ const vendor = SelectRealtimeVendorForModel(model.ID, resolveAPIKey, params.CredentialScope);
2678
2806
  const first = vendor ? this.instantiateRealtimeRunVendor(model.ID, vendor, resolveAPIKey) : null;
2679
2807
  if (!vendor || !first) {
2680
2808
  continue;
@@ -2703,6 +2831,17 @@ export class BaseAgent {
2703
2831
  PhoneCall: params.data?.realtimePhoneCall === true,
2704
2832
  });
2705
2833
  }
2834
+ /**
2835
+ * The platform MJ Credentials of the candidate realtime models' vendors, read as the run's user.
2836
+ * **Overridable seam** so tests can supply credentials without a credential store. Under a
2837
+ * `'RuntimeOnly'` scope it resolves none.
2838
+ *
2839
+ * @param modelIDs The candidate `MJ: AI Models` row ids.
2840
+ * @param params The execution parameters (context user and credential scope).
2841
+ */
2842
+ async resolveRealtimePlatformCredentials(modelIDs, params) {
2843
+ return ResolveRealtimePlatformCredentials(modelIDs, params.contextUser, params.CredentialScope);
2844
+ }
2706
2845
  /**
2707
2846
  * A vendor's realtime driver on its key, with the model and vendor identifiers a run resolves to; `null` when the
2708
2847
  * key or the driver is missing.
@@ -3517,7 +3656,11 @@ export class BaseAgent {
3517
3656
  // Prune and compact expired messages before executing the next step.
3518
3657
  // Uses _promptTurnCount (not stepCount) so expiration is measured in prompt
3519
3658
  // executions, not all steps (which include actions, loops, sub-agents, etc.)
3520
- await this.pruneAndCompactExpiredMessages(params, this._promptTurnCount);
3659
+ // Rewriting an earlier turn costs the cached prefix, so unless the caller asked for it
3660
+ // (messageExpirationOverride) it waits until the window reaches the compaction trigger.
3661
+ if (params.messageExpirationOverride || this.isMidLoopCompactionThresholdReached(params)) {
3662
+ await this.pruneAndCompactExpiredMessages(params, this._promptTurnCount);
3663
+ }
3521
3664
  // Execute the current step based on previous decision or initial prompt
3522
3665
  this.logStatus(`🔄 Executing step ${stepCount + 1} for agent '${params.agent.Name}'`, true, params);
3523
3666
  const nextStep = await this.executeNextStep(params, config, currentNextStep, stepCount);
@@ -5015,9 +5158,12 @@ export class BaseAgent {
5015
5158
  // Last gate before the history goes back to the model: no tool call may be left dangling.
5016
5159
  this.reconcileUnansweredToolCalls(params);
5017
5160
  if (this.GetNativeControlConfig(params).CompactToolArguments) {
5018
- const compacted = CompactAnsweredToolCallArguments(params.conversationMessages);
5019
- if (compacted > 0) {
5020
- this.logStatus(`[NativeTools] Compacted the large arguments of ${compacted} older tool call(s)`, true, params);
5161
+ const compactionBudget = this.resolveCompactionBudget(params, config);
5162
+ if (compactionBudget.BoundedBy === 'Default' || this.isMidLoopCompactionThresholdReached(params)) {
5163
+ const compacted = CompactAnsweredToolCallArguments(params.conversationMessages);
5164
+ if (compacted > 0) {
5165
+ this.logStatus(`[NativeTools] Compacted the large arguments of ${compacted} older tool call(s)`, true, params);
5166
+ }
5021
5167
  }
5022
5168
  }
5023
5169
  promptParams.conversationMessages = params.conversationMessages;
@@ -9412,6 +9558,8 @@ The context is now within limits. Please retry your request with the recovered c
9412
9558
  companyId: params.companyId,
9413
9559
  verbose: params.verbose,
9414
9560
  provider: this.ProviderToUse,
9561
+ isRunTainted: this.IsRunTainted,
9562
+ taintedSources: this._taintedSources,
9415
9563
  };
9416
9564
  }
9417
9565
  /**
@@ -12034,6 +12182,35 @@ The context is now within limits. Please retry your request with the recovered c
12034
12182
  return lines.join('\n');
12035
12183
  }).join('\n\n');
12036
12184
  }
12185
+ /**
12186
+ * The client tools in force for a run: the agent's static metadata tools under the session, app
12187
+ * and override tiers, merged by {@link ResolveClientTools} with its fixed precedence. The prompt
12188
+ * section and the client-tool step both resolve through here, so the tools the model is offered
12189
+ * and the metadata its results are classified against are one list.
12190
+ *
12191
+ * @param data - The run's data bag: `sessionID` selects the session tier, `appContext` the app
12192
+ * tier, `clientTools` the override tier.
12193
+ */
12194
+ resolveClientToolsForRun(agent, data) {
12195
+ // Static tier — agent's metadata tools from the AI Agent Client Tools junction.
12196
+ const staticTools = AIEngine.Instance.GetClientToolsForAgent(agent.ID).map(tool => ({
12197
+ Name: tool.Name,
12198
+ Description: tool.Description,
12199
+ InputSchema: tool.InputSchemaJSON ? JSON.parse(tool.InputSchemaJSON) : {},
12200
+ OutputSchema: tool.OutputSchemaJSON ? JSON.parse(tool.OutputSchemaJSON) : undefined,
12201
+ Category: tool.Category || undefined,
12202
+ DefaultTimeoutMs: tool.DefaultTimeoutMs || undefined
12203
+ }));
12204
+ // Dynamic (session) tier — client-SDK enriched tools for this session.
12205
+ const sessionID = data?.sessionID;
12206
+ const sessionTools = sessionID ? ClientToolRequestManager.Instance.GetSessionTools(sessionID) : [];
12207
+ // App tier — tools the active surface published in the app-context capability manifest.
12208
+ const appContext = data?.appContext;
12209
+ const appTools = appContext?.Capabilities?.Tools ?? [];
12210
+ // Override tier — tools passed directly in the run's data.
12211
+ const overrideTools = data?.clientTools ?? [];
12212
+ return ResolveClientTools({ agentId: agent.ID, staticTools, sessionTools, appTools, overrideTools });
12213
+ }
12037
12214
  /**
12038
12215
  * Build the client tool prompt section for system prompt injection.
12039
12216
  *
@@ -12053,25 +12230,7 @@ The context is now within limits. Please retry your request with the recovered c
12053
12230
  * static metadata tool of the same name. Collisions are rare in practice.
12054
12231
  */
12055
12232
  buildClientToolPromptSection(agent, extraData) {
12056
- // Static tier — agent's metadata tools from the AI Agent Client Tools junction.
12057
- const engine = AIEngine.Instance;
12058
- const staticTools = engine.GetClientToolsForAgent(agent.ID).map(tool => ({
12059
- Name: tool.Name,
12060
- Description: tool.Description,
12061
- InputSchema: tool.InputSchemaJSON ? JSON.parse(tool.InputSchemaJSON) : {},
12062
- OutputSchema: tool.OutputSchemaJSON ? JSON.parse(tool.OutputSchemaJSON) : undefined,
12063
- Category: tool.Category || undefined,
12064
- DefaultTimeoutMs: tool.DefaultTimeoutMs || undefined
12065
- }));
12066
- // Dynamic (session) tier — client-SDK enriched tools for this session.
12067
- const sessionID = extraData?.sessionID;
12068
- const sessionTools = sessionID ? ClientToolRequestManager.Instance.GetSessionTools(sessionID) : [];
12069
- // App tier — tools the active surface published in the app-context capability manifest.
12070
- const appContext = extraData?.appContext;
12071
- const appTools = appContext?.Capabilities?.Tools ?? [];
12072
- // Override tier — tools passed directly in the run's data.
12073
- const overrideTools = extraData?.clientTools ?? [];
12074
- const tools = ResolveClientTools({ agentId: agent.ID, staticTools, sessionTools, appTools, overrideTools });
12233
+ const tools = this.resolveClientToolsForRun(agent, extraData);
12075
12234
  if (tools.length === 0) {
12076
12235
  return ''; // No client tools available
12077
12236
  }
@@ -12240,7 +12399,7 @@ The context is now within limits. Please retry your request with the recovered c
12240
12399
  *
12241
12400
  * @param actionSummaries - The action summary objects built by executeActionStep
12242
12401
  * @returns Compact markdown string
12243
- * @private
12402
+ * @protected
12244
12403
  */
12245
12404
  formatActionResultsAsMarkdown(actionSummaries) {
12246
12405
  return actionSummaries.map(a => {
@@ -12248,6 +12407,30 @@ The context is now within limits. Please retry your request with the recovered c
12248
12407
  const lines = [];
12249
12408
  lines.push(`## ${a.actionName} ${marker}`);
12250
12409
  lines.push(`**Result:** ${a.resultCode} — ${a.message || '(no message)'}`);
12410
+ if (!a.success && a.errorRecovery) {
12411
+ const er = a.errorRecovery;
12412
+ if (er.Retryable !== undefined) {
12413
+ lines.push(`**Retryable:** ${er.Retryable ? 'Yes (adjust parameters before retrying)' : 'No (do not retry this action with the same goal)'}`);
12414
+ }
12415
+ if (er.RecoverySuggestion) {
12416
+ lines.push(`**How to Recover:** ${er.RecoverySuggestion}`);
12417
+ }
12418
+ if (er.SuggestedValues && er.SuggestedValues.length > 0) {
12419
+ lines.push(`**Did You Mean:** ${er.SuggestedValues.map(v => `\`${v}\``).join(', ')}`);
12420
+ }
12421
+ if (er.InvalidParams && er.InvalidParams.length > 0) {
12422
+ lines.push('**Invalid Parameters:**');
12423
+ for (const ip of er.InvalidParams) {
12424
+ lines.push(`• \`${ip.ParamName}\`: ${ip.Reason}`);
12425
+ }
12426
+ }
12427
+ if (er.ValidParameterExample) {
12428
+ lines.push(`**Valid Example:** \`${JSON.stringify(er.ValidParameterExample)}\``);
12429
+ }
12430
+ if (er.SuggestedNextActions && er.SuggestedNextActions.length > 0) {
12431
+ lines.push(`**Suggested Next Actions:** ${er.SuggestedNextActions.map(v => `\`${v}\``).join(', ')}`);
12432
+ }
12433
+ }
12251
12434
  // Format output params as bullet list. An exempt action's values go out verbatim.
12252
12435
  if (a.params && a.params.length > 0) {
12253
12436
  const crush = !this._actionResultCrush?.exemptActions?.has(a.actionName);
@@ -12256,7 +12439,11 @@ The context is now within limits. Please retry your request with the recovered c
12256
12439
  lines.push(`• \`${p.Name}\`: ${this.formatParamValueForResult(p.Value, 0, crush)}`);
12257
12440
  }
12258
12441
  }
12259
- return lines.join('\n');
12442
+ const formatted = lines.join('\n');
12443
+ if (a.trustLevel === 'Untrusted' || a.trustLevel === 'SemiTrusted') {
12444
+ return WrapUntrustedExternalData(formatted, `action:${a.actionName}`, a.trustLevel);
12445
+ }
12446
+ return formatted;
12260
12447
  }).join('\n\n');
12261
12448
  }
12262
12449
  /**
@@ -12668,6 +12855,7 @@ The context is now within limits. Please retry your request with the recovered c
12668
12855
  this._templateEngineConfiguredForRun = false;
12669
12856
  this._heldDecisions = undefined;
12670
12857
  this._awaitingWorkflowTaskID = null;
12858
+ this._taintedSources = [];
12671
12859
  // Resolve action-result compression config for this run (default on; opt out via
12672
12860
  // crushActionResults: false in the agent-type prompt params).
12673
12861
  this._actionResultCrush = this.resolveActionResultCrush(params);
@@ -14572,6 +14760,7 @@ The context is now within limits. Please retry your request with the recovered c
14572
14760
  // Child sub-agents don't use context messages (they inherit payload directly)
14573
14761
  const subAgentResult = await this.ExecuteSubAgent(params, subAgentRequest, subAgentEntity, stepEntity, scopedPayload, undefined, // No context message for child sub-agents
14574
14762
  stepCount);
14763
+ this.absorbSubAgentTaint(subAgentRequest.name, subAgentResult, stepEntity?.StepNumber ?? (stepCount + 1));
14575
14764
  let mergedPayload = previousDecision.newPayload; // Start with the original payload
14576
14765
  let currentStepPayloadChangeResult = undefined;
14577
14766
  if (subAgentResult.success) {
@@ -16146,6 +16335,10 @@ The context is now within limits. Please retry your request with the recovered c
16146
16335
  // Collect file outputs (PDF, Excel, Word, etc.) for post-run artifact processing
16147
16336
  const fileOutputs = this.detectFileOutputs(outputParams);
16148
16337
  this._fileOutputs.push(...fileOutputs);
16338
+ const trustLevel = this.resolveActionTrustLevel(result.action.name, result.actionEntity, params);
16339
+ if (trustLevel === 'Untrusted' || trustLevel === 'SemiTrusted') {
16340
+ this.recordTaintedSource(result.stepEntity?.StepNumber ?? (stepCount + 1), `action:${result.action.name}`, trustLevel);
16341
+ }
16149
16342
  return {
16150
16343
  actionName: result.action.name,
16151
16344
  success: isActionSuccess,
@@ -16156,8 +16349,11 @@ The context is now within limits. Please retry your request with the recovered c
16156
16349
  resultCode: actionResult?.Result?.ResultCode || actionResult?.ResultCode || (isActionSuccess ? 'SUCCESS' : 'ERROR'),
16157
16350
  message: actionResult?.Message || (isActionSuccess ? 'Action completed' : result.error || 'Unknown error'),
16158
16351
  // Kept on failure too: an action's recovery guidance is most useful when it failed.
16159
- aiDirectives: actionResult?.AIDirectives,
16160
- breakerReason: actionResult instanceof CircuitBreakerActionResult ? actionResult.Reason : undefined
16352
+ // Stripped on Untrusted actions (Primitive 2) so external payloads cannot inject high-priority AI directives.
16353
+ aiDirectives: trustLevel === 'Untrusted' ? undefined : actionResult?.AIDirectives,
16354
+ breakerReason: actionResult instanceof CircuitBreakerActionResult ? actionResult.Reason : undefined,
16355
+ trustLevel,
16356
+ errorRecovery: actionResult?.ErrorRecovery,
16161
16357
  };
16162
16358
  });
16163
16359
  // Check if any actions failed
@@ -16385,6 +16581,10 @@ The context is now within limits. Please retry your request with the recovered c
16385
16581
  const defaultTimeout = params.clientToolTimeoutMs ?? 30_000;
16386
16582
  const results = [];
16387
16583
  const agentRunID = this._agentRun?.ID ?? 'unknown';
16584
+ // Resolved once: the same tiers and precedence the prompt offered the model, keyed by name so each
16585
+ // result can read the tool's declared TrustLevel.
16586
+ const toolsByName = new Map(this.resolveClientToolsForRun(params.agent, { ...(params.data ?? {}), sessionID: params.sessionID })
16587
+ .map(t => [t.Name.trim().toLowerCase(), t]));
16388
16588
  // Execute tools sequentially (client may not support parallel UI operations)
16389
16589
  for (const tool of clientTools) {
16390
16590
  const stepEntity = await this.createStepEntity({
@@ -16401,12 +16601,21 @@ The context is now within limits. Please retry your request with the recovered c
16401
16601
  result: response.Result,
16402
16602
  media: response.Media?.map(m => ({ mimeType: m.MimeType, bytes: Math.floor((m.Base64.length * 3) / 4), width: m.Width, height: m.Height }))
16403
16603
  });
16604
+ const matchedClientToolMeta = toolsByName.get(tool.Name.trim().toLowerCase());
16605
+ const resolvedActionTrust = this.resolveActionTrustLevel(tool.Name, undefined, params);
16606
+ const clientToolTrustLevel = resolvedActionTrust !== 'Trusted'
16607
+ ? resolvedActionTrust
16608
+ : (matchedClientToolMeta?.TrustLevel ?? 'Trusted');
16609
+ if (clientToolTrustLevel === 'Untrusted' || clientToolTrustLevel === 'SemiTrusted') {
16610
+ this.recordTaintedSource(stepEntity?.StepNumber ?? (stepCount + 1), `client-tool:${tool.Name}`, clientToolTrustLevel);
16611
+ }
16404
16612
  results.push({
16405
16613
  ToolName: tool.Name,
16406
16614
  Success: response.Success,
16407
16615
  Result: response.Result,
16408
16616
  Media: response.Media,
16409
- ErrorMessage: response.ErrorMessage
16617
+ ErrorMessage: response.ErrorMessage,
16618
+ TrustLevel: clientToolTrustLevel,
16410
16619
  });
16411
16620
  }
16412
16621
  // Format results as conversation message
@@ -18461,6 +18670,7 @@ The context is now within limits. Please retry your request with the recovered c
18461
18670
  }
18462
18671
  return {
18463
18672
  success: false,
18673
+ taintedSources: this._taintedSources.length > 0 ? [...this._taintedSources] : undefined,
18464
18674
  agentRun: this._agentRun
18465
18675
  };
18466
18676
  }
@@ -18506,6 +18716,7 @@ The context is now within limits. Please retry your request with the recovered c
18506
18716
  }
18507
18717
  return {
18508
18718
  success: false,
18719
+ taintedSources: this._taintedSources.length > 0 ? [...this._taintedSources] : undefined,
18509
18720
  agentRun: this._agentRun
18510
18721
  };
18511
18722
  }
@@ -18693,6 +18904,7 @@ The context is now within limits. Please retry your request with the recovered c
18693
18904
  mediaOutputs: this._mediaOutputs.length > 0 ? this._mediaOutputs : undefined,
18694
18905
  fileOutputs: this._fileOutputs.length > 0 ? this._fileOutputs : undefined,
18695
18906
  feedbackRequestId: this._feedbackRequestId || undefined,
18907
+ taintedSources: this._taintedSources.length > 0 ? [...this._taintedSources] : undefined,
18696
18908
  handoff: this._handoffResult || undefined,
18697
18909
  resolvedStorageAccountId: this._resolvedStorageAccountId || undefined
18698
18910
  };
@@ -18833,6 +19045,40 @@ The context is now within limits. Please retry your request with the recovered c
18833
19045
  }
18834
19046
  return violations;
18835
19047
  }
19048
+ /**
19049
+ * Whether the window has reached the compaction trigger the operator configured — the same
19050
+ * `CompactionTriggerPercent` (agent, then agent type, then the default) that drives cross-turn
19051
+ * compaction, resolved by {@link resolveCompactionBudget} into `TriggerTokens`. Below it, the
19052
+ * mid-loop rewrites of earlier turns (shortening replayed tool-call arguments, expiring old action
19053
+ * results) are deferred, so routine tool loops keep the provider's byte-exact prompt-cache prefix.
19054
+ * One knob governs both kinds of compaction on purpose: a second number would be one more thing
19055
+ * to tune, and an in-run rewrite is only worth a cache miss once the window is actually filling up.
19056
+ * @protected
19057
+ */
19058
+ isMidLoopCompactionThresholdReached(params) {
19059
+ const messages = params?.conversationMessages;
19060
+ if (!Array.isArray(messages) || messages.length === 0) {
19061
+ return false;
19062
+ }
19063
+ const budget = this.resolveCompactionBudget(params, this._agentConfig);
19064
+ if (!budget.TriggerTokens || budget.TriggerTokens <= 0) {
19065
+ return false;
19066
+ }
19067
+ // estimateConversationTokens counts message content only. The arguments of replayed tool calls
19068
+ // travel on every turn too, so they are added here; nothing is counted twice.
19069
+ let estimatedTokens = this.estimateConversationTokens(messages);
19070
+ for (const msg of messages) {
19071
+ const toolCalls = msg.toolCalls;
19072
+ if (Array.isArray(toolCalls) && toolCalls.length > 0) {
19073
+ for (const call of toolCalls) {
19074
+ if (call?.arguments !== undefined) {
19075
+ estimatedTokens += this.estimateTokens(JSON.stringify(call.arguments));
19076
+ }
19077
+ }
19078
+ }
19079
+ }
19080
+ return estimatedTokens >= budget.TriggerTokens;
19081
+ }
18836
19082
  /**
18837
19083
  * Prunes and compacts expired messages in the conversation based on configured expiration rules.
18838
19084
  * Processes messages in three phases: identification, compaction, and removal.