@memberjunction/ai-agents 6.2.0-edge.1 → 6.2.0-edge.2

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 (99) hide show
  1. package/README.md +18 -0
  2. package/dist/AgentDecisionService.d.ts +83 -0
  3. package/dist/AgentDecisionService.d.ts.map +1 -0
  4. package/dist/AgentDecisionService.js +155 -0
  5. package/dist/AgentDecisionService.js.map +1 -0
  6. package/dist/AgentRunner.d.ts +7 -0
  7. package/dist/AgentRunner.d.ts.map +1 -1
  8. package/dist/AgentRunner.js +16 -5
  9. package/dist/AgentRunner.js.map +1 -1
  10. package/dist/KnowledgeAgent.d.ts.map +1 -1
  11. package/dist/KnowledgeAgent.js +6 -6
  12. package/dist/KnowledgeAgent.js.map +1 -1
  13. package/dist/PayloadFeedbackManager.d.ts +113 -14
  14. package/dist/PayloadFeedbackManager.d.ts.map +1 -1
  15. package/dist/PayloadFeedbackManager.js +228 -88
  16. package/dist/PayloadFeedbackManager.js.map +1 -1
  17. package/dist/agent-context-injector.d.ts +47 -3
  18. package/dist/agent-context-injector.d.ts.map +1 -1
  19. package/dist/agent-context-injector.js +77 -10
  20. package/dist/agent-context-injector.js.map +1 -1
  21. package/dist/agent-memory-context-builder.d.ts +13 -0
  22. package/dist/agent-memory-context-builder.d.ts.map +1 -1
  23. package/dist/agent-memory-context-builder.js +24 -5
  24. package/dist/agent-memory-context-builder.js.map +1 -1
  25. package/dist/agent-types/flow-agent-type.d.ts +97 -0
  26. package/dist/agent-types/flow-agent-type.d.ts.map +1 -1
  27. package/dist/agent-types/flow-agent-type.js +281 -24
  28. package/dist/agent-types/flow-agent-type.js.map +1 -1
  29. package/dist/agent-types/flow-graph-executor.d.ts +12 -1
  30. package/dist/agent-types/flow-graph-executor.d.ts.map +1 -1
  31. package/dist/agent-types/flow-graph-executor.js +25 -1
  32. package/dist/agent-types/flow-graph-executor.js.map +1 -1
  33. package/dist/agent-types/loop-agent-prompt-params.d.ts +239 -66
  34. package/dist/agent-types/loop-agent-prompt-params.d.ts.map +1 -1
  35. package/dist/agent-types/loop-agent-prompt-params.js +47 -2
  36. package/dist/agent-types/loop-agent-prompt-params.js.map +1 -1
  37. package/dist/agent-types/loop-agent-response-type.d.ts +12 -1
  38. package/dist/agent-types/loop-agent-response-type.d.ts.map +1 -1
  39. package/dist/agent-types/loop-agent-response-type.js.map +1 -1
  40. package/dist/agent-types/loop-agent-type.d.ts +6 -0
  41. package/dist/agent-types/loop-agent-type.d.ts.map +1 -1
  42. package/dist/agent-types/loop-agent-type.js +42 -3
  43. package/dist/agent-types/loop-agent-type.js.map +1 -1
  44. package/dist/base-agent.d.ts +492 -2
  45. package/dist/base-agent.d.ts.map +1 -1
  46. package/dist/base-agent.js +1686 -95
  47. package/dist/base-agent.js.map +1 -1
  48. package/dist/catalog-narrowing.d.ts +136 -0
  49. package/dist/catalog-narrowing.d.ts.map +1 -0
  50. package/dist/catalog-narrowing.js +212 -0
  51. package/dist/catalog-narrowing.js.map +1 -0
  52. package/dist/decision-discovery.d.ts +401 -0
  53. package/dist/decision-discovery.d.ts.map +1 -0
  54. package/dist/decision-discovery.js +511 -0
  55. package/dist/decision-discovery.js.map +1 -0
  56. package/dist/finish-if-mode-warnings.d.ts +39 -0
  57. package/dist/finish-if-mode-warnings.d.ts.map +1 -0
  58. package/dist/finish-if-mode-warnings.js +78 -0
  59. package/dist/finish-if-mode-warnings.js.map +1 -0
  60. package/dist/finish-if-state.d.ts +72 -0
  61. package/dist/finish-if-state.d.ts.map +1 -0
  62. package/dist/finish-if-state.js +109 -0
  63. package/dist/finish-if-state.js.map +1 -0
  64. package/dist/index.d.ts +6 -0
  65. package/dist/index.d.ts.map +1 -1
  66. package/dist/index.js +7 -0
  67. package/dist/index.js.map +1 -1
  68. package/dist/memory-manager-agent.d.ts +108 -2
  69. package/dist/memory-manager-agent.d.ts.map +1 -1
  70. package/dist/memory-manager-agent.js +172 -9
  71. package/dist/memory-manager-agent.js.map +1 -1
  72. package/dist/memory-note-gate.d.ts +208 -0
  73. package/dist/memory-note-gate.d.ts.map +1 -0
  74. package/dist/memory-note-gate.js +294 -0
  75. package/dist/memory-note-gate.js.map +1 -0
  76. package/dist/realtime/bridge-realtime-session-factory.d.ts +5 -2
  77. package/dist/realtime/bridge-realtime-session-factory.d.ts.map +1 -1
  78. package/dist/realtime/bridge-realtime-session-factory.js +7 -4
  79. package/dist/realtime/bridge-realtime-session-factory.js.map +1 -1
  80. package/dist/realtime/bridge-room-transcript-sink.d.ts.map +1 -1
  81. package/dist/realtime/bridge-room-transcript-sink.js +15 -9
  82. package/dist/realtime/bridge-room-transcript-sink.js.map +1 -1
  83. package/dist/realtime/realtime-client-session-service.d.ts +54 -12
  84. package/dist/realtime/realtime-client-session-service.d.ts.map +1 -1
  85. package/dist/realtime/realtime-client-session-service.js +76 -25
  86. package/dist/realtime/realtime-client-session-service.js.map +1 -1
  87. package/dist/realtime/realtime-vendor-resolution.d.ts +8 -3
  88. package/dist/realtime/realtime-vendor-resolution.d.ts.map +1 -1
  89. package/dist/realtime/realtime-vendor-resolution.js +3 -3
  90. package/dist/realtime/realtime-vendor-resolution.js.map +1 -1
  91. package/dist/rubric-evaluation-agent-runner.d.ts +2 -0
  92. package/dist/rubric-evaluation-agent-runner.d.ts.map +1 -0
  93. package/dist/rubric-evaluation-agent-runner.js +38 -0
  94. package/dist/rubric-evaluation-agent-runner.js.map +1 -0
  95. package/dist/self-check.d.ts +98 -0
  96. package/dist/self-check.d.ts.map +1 -0
  97. package/dist/self-check.js +74 -0
  98. package/dist/self-check.js.map +1 -0
  99. package/package.json +19 -18
@@ -14,21 +14,24 @@ import { MJAIAgentTypeEntity, MJTemplateParamEntity, MJAIAgentRelationshipEntity
14
14
  import { type NativeToolBinding } from './native-tools/control-tools.js';
15
15
  import { MJAIAgentRunEntityExtended, MJAIAgentRunStepEntityExtended, MJAIPromptEntityExtended, MJAIAgentEntityExtended, MJAIModelEntityExtended, MJAIPromptRunEntityExtended } from "@memberjunction/ai-core-plus";
16
16
  import { UserInfo, IMetadataProvider } from '@memberjunction/core';
17
- import { ChatMessage, ChatMessageContent, BaseRealtimeModel, IRealtimeSession, ChatToolChoice } from '@memberjunction/ai';
17
+ import { AIDecisionRunResult } from '@memberjunction/ai-prompts';
18
+ import { ChatMessage, ChatMessageContent, BaseRealtimeModel, IRealtimeSession, ChatToolChoice, DecisionAnswer } from '@memberjunction/ai';
18
19
  import { BaseAgentType } from './agent-types/base-agent-type.js';
19
20
  import { type CodeLang } from '@memberjunction/context-crush/code';
20
21
  import { RealtimeSessionRunnerDeps } from './realtime/realtime-session-runner.js';
21
22
  import { RealtimeCoAgentConfig } from './realtime/realtime-coagent-config.js';
22
23
  import { AIEngine } from '@memberjunction/aiengine';
24
+ import { AgentMemoryObservability } from './agent-memory-context-builder.js';
23
25
  import { CompactionOutcome, EffectiveContextBudget } from './ConversationCompactionManager.js';
24
26
  import { ConversationToolCall, ConversationToolExecutionResult, ConversationToolSummaryHost } from './ConversationToolManager.js';
25
27
  import { CarryForwardStepRecord } from './tool-result-format.js';
26
28
  import { AgentPreExecutionRAGResult } from './agent-pre-execution-rag.js';
27
- import { AIPromptParams, AIPromptRunResult, ExecuteAgentParams, AgentConfiguration, ExecuteAgentResult, AgentAction, AgentSubAgentRequest, BaseAgentNextStep, MessageLifecycleEvent, AgentChatMessage, AgentChatMessageMetadata, AIModelSelectionInfo, ActionChange, ActionChangeScope, SubAgentChange, MediaOutput, FileOutputRef, SecondaryScopeConfig, SecondaryScopeValue, AgentResponseForm, AgentPipelineRequest, AgentSkillActivationRequest, AgentSkillInvocation, SkillAvailabilityPurpose } from '@memberjunction/ai-core-plus';
29
+ import { AIPromptParams, AIPromptRunResult, ExecuteAgentParams, AgentConfiguration, ExecuteAgentResult, AgentAction, AgentSubAgentRequest, BaseAgentNextStep, MessageLifecycleEvent, AgentChatMessage, AgentChatMessageMetadata, AIModelSelectionInfo, ActionChange, ActionChangeScope, SubAgentChange, MediaOutput, FileOutputRef, SecondaryScopeConfig, SecondaryScopeValue, AgentResponseForm, AgentPipelineRequest, AgentSkillActivationRequest, AgentSkillInvocation, SkillAvailabilityPurpose, AgentDecisionRequest, AgentDecisionResult, AgentDecisionAnswerSummary } from '@memberjunction/ai-core-plus';
28
30
  import { MJActionEntityExtended, ActionResult, ActionParam, AIDirective } from '@memberjunction/actions-base';
29
31
  import { RuntimeStateDateTime, RuntimeStateScratchpad } from './runtime-state-fragment.js';
30
32
  import { ArtifactToolCall, StoredToolResult } from './ArtifactToolManager.js';
31
33
  import { MemoryWriteRequest, MemoryWriteResult } from './MemoryWriteManager.js';
34
+ import { AgentDecisionService } from './AgentDecisionService.js';
32
35
  import { PipelineToolRegistry, PipelineExecutionResult } from './pipeline/index.js';
33
36
  /**
34
37
  * Compact representation of a single action's execution result, used for
@@ -123,6 +126,12 @@ interface AgentBaseCatalog {
123
126
  /** Agent-type prompt params merged from schema defaults + agent config (NO runtime overrides). */
124
127
  baseAgentTypePromptParams: Record<string, unknown>;
125
128
  }
129
+ /**
130
+ * Turns one decision call's typed answers into what its reader gets. A loop turn's model reads
131
+ * `AgentDecisionService.SummarizeAnswers`; an agent type that routes on the answers reads
132
+ * `SummarizeDecisionAnswers`, which keeps each distribution.
133
+ */
134
+ type DecisionAnswerSummarizer = (answers: Record<string, DecisionAnswer>) => Record<string, AgentDecisionAnswerSummary>;
126
135
  export declare class BaseAgent {
127
136
  /**
128
137
  * Maximum allowed validation retries before forcing failure.
@@ -649,6 +658,10 @@ export declare class BaseAgent {
649
658
  * Allows agents to explore input artifacts on demand.
650
659
  */
651
660
  private _artifactToolManager;
661
+ /**
662
+ * Service for evaluating agent decisions inline via fast decision models.
663
+ */
664
+ protected _agentDecisionService: AgentDecisionService;
652
665
  /**
653
666
  * Reverse map from sanitized tool name back to Action, for the turn currently being prepared.
654
667
  *
@@ -685,6 +698,41 @@ export declare class BaseAgent {
685
698
  * @private
686
699
  */
687
700
  private _effectiveSubAgents;
701
+ /**
702
+ * The merged agent-type prompt params of the current step. Populated during
703
+ * gatherPromptTemplateData() and read by the finishIf gate, which runs in executeActionsStep()
704
+ * and executeNextStep() after the prompt that requested the step.
705
+ * @private
706
+ */
707
+ private _agentTypePromptParams;
708
+ /**
709
+ * The run's catalog narrowing (plan Task 3.7): what the prompt hides from its action, sub-agent
710
+ * and skill lists. Computed once, on the run's first prompt, and reused by every later step, so
711
+ * the catalog the model sees never changes mid-run. `undefined` until then; hides nothing when
712
+ * narrowing is off or failed open.
713
+ * @private
714
+ */
715
+ private _catalogNarrowing;
716
+ /**
717
+ * The request that opened the run: the last user message when it started, before the framework
718
+ * added anything. Catalog narrowing judges the catalog against it.
719
+ * @private
720
+ */
721
+ private _openingRequest;
722
+ /**
723
+ * Whether the run answers its conversation's opening request ({@link IsOpeningTurn}), read from
724
+ * the messages it started with. Decision discovery asks about no other turn.
725
+ * @private
726
+ */
727
+ private _isOpeningTurn;
728
+ /** The longest the catalog narrowing decision may take before the run shows the full catalog. */
729
+ private static readonly CATALOG_NARROWING_TIMEOUT_MS;
730
+ /**
731
+ * Decision requests held back by the prompt that made them, because the step that carried them
732
+ * can end the run. They run before the next prompt, or are skipped when the run ends first.
733
+ * @private
734
+ */
735
+ private _heldDecisions;
688
736
  /**
689
737
  * IDs of skills already activated during this run. Prevents re-activation from re-appending
690
738
  * the same instructions to context / re-pushing duplicate actionChanges/subAgentChanges entries
@@ -1321,6 +1369,16 @@ export declare class BaseAgent {
1321
1369
  * @returns A human-readable scope label
1322
1370
  */
1323
1371
  private determineNoteScope;
1372
+ /**
1373
+ * The observability context memory injection runs under for an agent run: the run's ID, the next
1374
+ * step number, and a callback that adds each rerank step to the run's steps. A rerank step carries
1375
+ * the rerank's prompt run, whose cost and token rollups include a prompt-backed reranker's own
1376
+ * prompt runs, so the run's totals and its `MaxCostPerRun` / `MaxTokensPerRun` guardrails count
1377
+ * them. Undefined when there is no run.
1378
+ *
1379
+ * @param run - The current agent run, or null before one exists
1380
+ */
1381
+ protected MemoryObservability(run: MJAIAgentRunEntityExtended | null): AgentMemoryObservability | undefined;
1324
1382
  /**
1325
1383
  * Inject notes and examples into agent context memory.
1326
1384
  * Called automatically before agent execution if injection is enabled on the agent.
@@ -1378,6 +1436,98 @@ export declare class BaseAgent {
1378
1436
  * @returns The structured RAG result, or `null` if no scopes produced results.
1379
1437
  */
1380
1438
  protected InjectPreExecutionRAG(lastUserMessage: string, agent: MJAIAgentEntityExtended, contextUser: UserInfo | undefined, conversationMessages: ChatMessage[] | undefined, originalMessages: ChatMessage[] | undefined, primaryScopeEntityId?: string, primaryScopeRecordId?: string, secondaryScopes?: Record<string, SecondaryScopeValue>, payload?: unknown): Promise<AgentPreExecutionRAGResult | null>;
1439
+ /**
1440
+ * Decision discovery (plan Task 3.1): suggests the agent to delegate to before the first prompt.
1441
+ *
1442
+ * Runs in parallel with the rest of Phase 2 of `Execute()`, and only when the merged agent-type
1443
+ * prompt params set `decisionsEnabled: true` (the master switch, {@link DecisionsEnabled}) and
1444
+ * `decisionDiscovery: true`, the run answers its conversation's opening request
1445
+ * ({@link IsOpeningTurn}), and that request @mentions no agent. A follow-up turn is never asked
1446
+ * about: it may be continuing work with an agent already engaged, and a suggestion must not pull
1447
+ * the agent away from it. One decision asks which of the agents the user may run (and the host
1448
+ * allows) should handle the request, and whether a specialist should. When both answers are
1449
+ * confident, a `<suggested_agent>` system message is unshifted onto `conversationMessages`, the
1450
+ * way pre-execution RAG adds `<retrieved_context>`. Each discovery is recorded as one
1451
+ * `Agent discovery` Decision step.
1452
+ *
1453
+ * Fails safe: an error, a timeout, a cancelled run, an unusable answer or an unsure one adds
1454
+ * nothing, so the agent behaves as it would without discovery. So do fewer than
1455
+ * {@link DECISION_DISCOVERY_MIN_OPTIONS} options. Never delays the first prompt by more than
1456
+ * {@link DECISION_DISCOVERY_TIMEOUT_MS}, and never throws.
1457
+ *
1458
+ * The any-applies question does not name the options, so the decision cannot say that none of
1459
+ * them fits: see {@link DECISION_DISCOVERY_APPLIES_INSTRUCTIONS} for why it stays that way for now.
1460
+ *
1461
+ * @param agent - The agent being executed.
1462
+ * @param contextUser - The user whose run permission decides the options.
1463
+ * @param conversationMessages - The mutated message array that flows to the LLM (the suggestion is unshifted here).
1464
+ * @param data - The run's `ExecuteAgentParams.data`. Its `__agentTypePromptParams` overrides the agent's prompt
1465
+ * params, and its `ALL_AVAILABLE_AGENTS`, when an array, is the host's allow-list: no other agent is suggested.
1466
+ */
1467
+ protected InjectDecisionDiscovery(agent: MJAIAgentEntityExtended, contextUser: UserInfo | undefined, conversationMessages: ChatMessage[] | undefined, data: Record<string, unknown> | undefined): Promise<void>;
1468
+ /**
1469
+ * Whether discovery is on for this run: the master switch ({@link DecisionsEnabled}) and
1470
+ * `decisionDiscovery` are both on. Read without rebuilding the merged prompt params, since it is
1471
+ * asked on every run of every agent: each setting from the per-run override when it sets one,
1472
+ * otherwise from the agent's base params, cached on AIEngine with its base catalog. Only a cold
1473
+ * cache builds them.
1474
+ */
1475
+ private isDecisionDiscoveryOnFor;
1476
+ /**
1477
+ * The run's merged agent-type prompt params (schema defaults < agent < per-run overrides), once
1478
+ * discovery is on: the cached base params when there is no override, otherwise built.
1479
+ */
1480
+ private decisionDiscoveryPromptParams;
1481
+ /** The agent's base prompt params (no per-run overrides), from the base catalog AIEngine caches, when it holds one. */
1482
+ private cachedBasePromptParams;
1483
+ /** Builds the merged prompt params, as `gatherPromptTemplateData` does. */
1484
+ private buildDecisionDiscoveryPromptParams;
1485
+ /**
1486
+ * Records one `Agent discovery` step around a bounded discovery, and returns what it found. A
1487
+ * failed discovery is logged as a warning; an unsure one only in verbose logs, except that an
1488
+ * answer from a model with no discovery calibration is warned about once per model, because
1489
+ * then discovery can never suggest anything.
1490
+ */
1491
+ private runDecisionDiscovery;
1492
+ /** The answering models already warned about as having no discovery calibration, so each is warned about once per process. */
1493
+ private static readonly _uncalibratedDiscoveryModelsWarned;
1494
+ /**
1495
+ * Warns, once per model, that discovery answered by a model with no discovery calibration
1496
+ * suggests nothing. That happens when a decision model is added or renamed, when a vendor model
1497
+ * moves to another version (Jev's `APIName`), or when LLM Decision answers through a chat model
1498
+ * other than the one its calibration was fitted on; without the warning the only trace is each
1499
+ * `Agent discovery` step's reason.
1500
+ */
1501
+ private static warnUncalibratedDiscoveryModel;
1502
+ /**
1503
+ * Runs `discover` until it finishes, {@link DECISION_DISCOVERY_TIMEOUT_MS} passes, or the run is
1504
+ * cancelled. A timeout or a cancellation aborts the signal `discover` was given, which aborts the
1505
+ * decision call, and returns a failed discovery at once. What `discover` returns after that
1506
+ * suggests nothing, but the prompt run of its decision call is still linked to `step` once it
1507
+ * settles ({@link linkLateDecisionPromptRun}), so the run counts the call's cost.
1508
+ */
1509
+ private boundDecisionDiscovery;
1510
+ /**
1511
+ * The discovery itself: the options, rebuilt from the permitted catalog, then one decision about
1512
+ * the opening request, and what its answer means. Never throws.
1513
+ */
1514
+ private discoverAgent;
1515
+ /**
1516
+ * The Choice's options, rebuilt on every call and never cached ({@link BuildDecisionDiscoveryOptionSet}):
1517
+ * from AIEngine's current catalog, the agents the user may run, the decision prompt's option cap,
1518
+ * and the semantic search over the opening request when the provider can run it.
1519
+ */
1520
+ private decisionDiscoveryOptionSet;
1521
+ /** Opens the `Agent discovery` Decision step. Without a run there is no step. */
1522
+ private startDecisionDiscoveryStep;
1523
+ /**
1524
+ * Finalizes the `Agent discovery` step: the answer, whether it was injected, the host allow-list,
1525
+ * the agents left out for having no description (at most {@link DECISION_DISCOVERY_MAX_RECORDED_IDS}
1526
+ * IDs), any narrowing, and the call's usage.
1527
+ */
1528
+ private finishDecisionDiscoveryStep;
1529
+ /** Logs that decision discovery failed, so nothing was suggested. */
1530
+ private warnDecisionDiscovery;
1381
1531
  /**
1382
1532
  * Converts UI markup (@{...} syntax) in user messages to plain text.
1383
1533
  * This prevents agents from being confused by UI-specific JSON syntax and reduces token usage.
@@ -1861,6 +2011,11 @@ export declare class BaseAgent {
1861
2011
  * @returns Modified next step if guardrails exceeded, or original next step
1862
2012
  * @protected
1863
2013
  */
2014
+ private _selfCheckAttemptsByRun;
2015
+ private _selfCheckLinkByAgent;
2016
+ private applySelfCheck;
2017
+ /** Runs the self-check when a success exit did not pass through the guardrail hook. */
2018
+ private selfCheckSuccess;
1864
2019
  protected checkExecutionGuardrails<P>(params: ExecuteAgentParams, nextStep: BaseAgentNextStep<P>, currentPayload: P, agentRun: MJAIAgentRunEntityExtended, currentStep: MJAIAgentRunStepEntityExtended): Promise<BaseAgentNextStep<P>>;
1865
2020
  /**
1866
2021
  * Checks if any agent run guardrails have been exceeded.
@@ -2303,6 +2458,171 @@ export declare class BaseAgent {
2303
2458
  * @protected
2304
2459
  */
2305
2460
  protected injectPipelineResultMessage(params: ExecuteAgentParams, result: PipelineExecutionResult): void;
2461
+ /** At most this many decision calls run at once for one agent turn. */
2462
+ private static readonly DECISION_CONCURRENCY;
2463
+ /**
2464
+ * Runs `fn` over `items` with at most `limit` calls in flight, keeping results in input order.
2465
+ * One call's failure never rejects the others: a call that throws is settled with `onError`'s
2466
+ * result in its place.
2467
+ */
2468
+ private runWithConcurrencyLimit;
2469
+ /**
2470
+ * Answers the decision requests from one agent turn, each logged as an `AIAgentRunStep`
2471
+ * (StepType 'Decision'), with bounded concurrency. A failed request never fails the run: it
2472
+ * becomes that request's `success: false`, which the agent reads on its next turn.
2473
+ *
2474
+ * Two limits bound the turn. At most `decisionsMaxRequests` requests run (default
2475
+ * {@link MAX_DECISION_REQUESTS_PER_TURN}); each request over that cap is not run and records no
2476
+ * step, and its result says why. And the requests make at most `decisionsMaxCallsPerTurn`
2477
+ * decision calls in total, counting every `forEachItemIn` item (default
2478
+ * {@link MAX_DECISION_CALLS_PER_TURN}). That budget is handed out in request order before any
2479
+ * call is made, so which calls run never depends on timing. A `forEachItemIn` request it cuts
2480
+ * short asks its first items and reports the rest in `skippedCount`. A request it leaves no calls
2481
+ * for is not run, records no step, and its result says why.
2482
+ *
2483
+ * @since 2.132.0
2484
+ */
2485
+ protected executeDecisionRequestsAsSteps(requests: AgentDecisionRequest[], finalPayload: unknown, agentTypePromptParams: Record<string, unknown> | undefined, params: ExecuteAgentParams): Promise<AgentDecisionResult[]>;
2486
+ /** The most decision requests one turn may run: `decisionsMaxRequests`, or {@link MAX_DECISION_REQUESTS_PER_TURN}. */
2487
+ private decisionRequestCap;
2488
+ /**
2489
+ * The most decision calls one turn's requests make in total, `forEachItemIn` items included:
2490
+ * `decisionsMaxCallsPerTurn`, or {@link MAX_DECISION_CALLS_PER_TURN}.
2491
+ */
2492
+ private decisionCallBudget;
2493
+ /** The most items one `forEachItemIn` request asks about: `decisionsMaxItems`, or its default. */
2494
+ private decisionMaxItems;
2495
+ /** A decision limit from the prompt params when it is a non-negative integer, or `fallback` when it is absent or anything else. */
2496
+ private decisionLimit;
2497
+ /**
2498
+ * Hands out the turn's decision-call budget to its requests in order, before any of them runs.
2499
+ * Each request gets the calls it wants while the budget lasts. The first one the budget cannot
2500
+ * cover gets what is left, and the ones after it get none.
2501
+ */
2502
+ private allotDecisionCalls;
2503
+ /**
2504
+ * The decision calls a request makes with no budget: one, or one per `forEachItemIn` item up to
2505
+ * `decisionsMaxItems`. A request that cannot make any, because it is not an object or its
2506
+ * `forEachItemIn` is not an array, wants none. A request that fails before it asks, such as one
2507
+ * with no valid question, still holds what its shape wants: the budget can then go unused, but
2508
+ * it is never exceeded.
2509
+ */
2510
+ private decisionCallsWanted;
2511
+ /**
2512
+ * The result of a request the turn's decision-call budget left no calls for. It was not run.
2513
+ * A budget of 0 turns decision calls off for the agent, so then asking again on a later turn
2514
+ * cannot help, and the result does not invite it.
2515
+ */
2516
+ private overBudgetDecisionResult;
2517
+ /** A request's id for its result, or its position when the model sent no usable id. */
2518
+ private decisionRequestId;
2519
+ /**
2520
+ * Runs a `'Decision'` next step: an agent type's decision requests, answered with no LLM turn.
2521
+ *
2522
+ * Each request goes through the same path a loop turn's decisions take
2523
+ * ({@link executeSingleDecisionRequestAsStep}), so it gets the same prompt default, state
2524
+ * resolution and error handling, and is logged as a `Decision` run step. Where a loop turn's
2525
+ * results go into the conversation, these come back to the agent type on the returned `'Retry'`
2526
+ * (`decisionResults`), because it routes on them. So each answer keeps its whole distribution
2527
+ * (`SummarizeDecisionAnswers`), which a path condition may read. A failed request is a result
2528
+ * with `success: false`, never a failed run: what a failure means is the agent type's call.
2529
+ *
2530
+ * @since 6.2.0
2531
+ */
2532
+ protected executeDecisionStep<P>(params: ExecuteAgentParams, decision: BaseAgentNextStep<P>): Promise<BaseAgentNextStep<P>>;
2533
+ /**
2534
+ * Answers one decision request, either once against its `state` or once per item of its
2535
+ * `forEachItemIn` array, and records it as a Decision step. The request is unchecked model
2536
+ * output, so any error finishes the step as failed rather than escaping: this never throws
2537
+ * once the step exists.
2538
+ *
2539
+ * @param callAllowance The most decision calls the request may make, from the turn's
2540
+ * `decisionsMaxCallsPerTurn` budget. It caps a `forEachItemIn` request's items below
2541
+ * `decisionsMaxItems`. A single-state request makes one call, and
2542
+ * {@link executeDecisionRequestsAsSteps} never starts one the budget left without it.
2543
+ * Unbounded by default.
2544
+ * @param summarize how the typed answers are summarised for whoever reads them next; defaults
2545
+ * to the loop turn's model-facing summary
2546
+ * @since 2.132.0
2547
+ */
2548
+ protected executeSingleDecisionRequestAsStep(request: AgentDecisionRequest, finalPayload: unknown, agentTypePromptParams: Record<string, unknown> | undefined, params: ExecuteAgentParams, callAllowance?: number, summarize?: DecisionAnswerSummarizer): Promise<AgentDecisionResult>;
2549
+ /** Asks the request's questions about one state, with the configured decision prompt. */
2550
+ private decisionAsker;
2551
+ /** Asks the questions once, against the request's state. */
2552
+ private askOnce;
2553
+ /**
2554
+ * Asks the same questions of each item of a payload array, up to `decisionsMaxItems` and the
2555
+ * request's share of the turn's call budget. Each item's call is its own child Decision step of
2556
+ * the request's step, carrying that call's prompt run, as each iteration of a ForEach is a child
2557
+ * step of its loop step.
2558
+ */
2559
+ private askForEachItem;
2560
+ /** Asks about one item of a `forEachItemIn` request, recorded as a child step of the request's step. */
2561
+ private askItemAsStep;
2562
+ /**
2563
+ * Links a decision call's prompt run to its step, as the Prompt step links its own, so the run's
2564
+ * cost and token totals and its `MaxCostPerRun` / `MaxTokensPerRun` checks count the call.
2565
+ */
2566
+ protected attachDecisionPromptRun(step: MJAIAgentRunStepEntityExtended, result: AIDecisionRunResult): void;
2567
+ /**
2568
+ * Links the prompt run of a decision call the run stopped waiting for (a timeout or a cancellation)
2569
+ * to its step, once the call settles. `AIDecisionRunner` writes the prompt run before it calls the
2570
+ * model, so a stopped call still has one. The link keeps that row on the run's trace, and counts its
2571
+ * usage in the run's cost and token totals when it settles before the run ends, as
2572
+ * {@link attachDecisionPromptRun} does on time. The step may already be finalized, so the link is
2573
+ * saved on its own. Never throws, and a call that never settles links nothing.
2574
+ */
2575
+ private linkLateDecisionPromptRun;
2576
+ /**
2577
+ * A literal state, or a value read from the payload: the whole payload for `payload`, one value
2578
+ * for a `payload.` path.
2579
+ */
2580
+ private resolveDecisionState;
2581
+ /** Reads a `payload.`-prefixed dotted path (or `payload` itself) from the payload. */
2582
+ private resolvePayloadPath;
2583
+ /** Strings pass through; anything else becomes indented JSON. */
2584
+ private decisionStateText;
2585
+ /** Finalizes the Decision step and builds the result the agent reads next turn. */
2586
+ private finishDecisionStep;
2587
+ /**
2588
+ * Answers the decision requests a prompt returned, or holds them when the step that carries
2589
+ * them can end the run, because then no turn would read their answers. Held requests run before
2590
+ * the next prompt ({@link runHeldDecisions}), or are skipped if the run ends first
2591
+ * ({@link skipHeldDecisions}). Skips them all, unasked, while the master switch is off
2592
+ * ({@link DecisionsEnabled}) or the agent's `decisions` response field is.
2593
+ */
2594
+ private processTurnDecisions;
2595
+ /**
2596
+ * Why the decisions sent with this step would be paid for and never read, or `undefined` when
2597
+ * the next turn reads them. Three ways a step's own outcome ends the run: a passing finishIf gate
2598
+ * (only an Actions step or a single sub-agent is gated), a sub-agent's `terminateAfter`, and
2599
+ * client tools sent with `taskComplete`, which end the run once the tools return. Every other
2600
+ * step, including client tools without `taskComplete`, goes on to a prompt that reads them.
2601
+ */
2602
+ private decisionsHoldReason;
2603
+ /**
2604
+ * Runs the decision requests a prompt held back, now that the step that carried them has run
2605
+ * without ending the run, so the prompt about to run reads their answers.
2606
+ */
2607
+ private runHeldDecisions;
2608
+ /**
2609
+ * Skips the decision requests a prompt held back, because the run ended before they could be
2610
+ * asked: the step that carried them ended it, or it was cancelled, or an error was thrown out of
2611
+ * the step loop. Called from the loop's terminate branch and from `Execute()`'s `finally`, so
2612
+ * every way out logs them. The held state is cleared before the log line, so the second call on
2613
+ * the terminate path logs nothing and each held request is logged exactly once.
2614
+ *
2615
+ * @param runEnd How the run ended, as a clause for the log line.
2616
+ */
2617
+ private skipHeldDecisions;
2618
+ /** How the run ended, as a clause for held decision requests that a cancellation or an error left unasked. */
2619
+ private runEndForHeldDecisions;
2620
+ /**
2621
+ * Injects decision results into the conversation as one tool-result message for the next turn.
2622
+ *
2623
+ * @since 2.132.0
2624
+ */
2625
+ protected injectDecisionResultsMessage(params: ExecuteAgentParams, results: AgentDecisionResult[]): void;
2306
2626
  /**
2307
2627
  * Creates a chat message containing sub-agent execution results.
2308
2628
  *
@@ -2332,6 +2652,52 @@ export declare class BaseAgent {
2332
2652
  * @private
2333
2653
  */
2334
2654
  private gatherPromptTemplateData;
2655
+ /**
2656
+ * Narrows the catalog once per run, on its first prompt (plan Task 3.7), and caches the result for
2657
+ * every later step. With narrowing off, or the master switch ({@link DecisionsEnabled}) off, it
2658
+ * asks nothing and records nothing, so the prompt describes the whole catalog. Never throws: any
2659
+ * failure leaves the full catalog in place. It narrows the prose catalog only:
2660
+ * {@link applyNativeTools} still declares every action and sub-agent.
2661
+ */
2662
+ private ensureCatalogNarrowing;
2663
+ /**
2664
+ * The run's limits, with actions left whole when the agent lacks Find Candidate Actions: a hidden
2665
+ * action would then be unreachable. That case is logged as a warning when it keeps a long action
2666
+ * list whole, since the agent asked for narrowing and did not get it.
2667
+ */
2668
+ private reachableCatalogNarrowingLimits;
2669
+ /**
2670
+ * Every item of the three lists as a narrowing candidate. An action or sub-agent with
2671
+ * `MinExecutionsPerRun` set, and the Find Candidate tools, are pinned: always shown.
2672
+ */
2673
+ private catalogNarrowingCandidates;
2674
+ /**
2675
+ * Asks the one decision, records it as the `Catalog narrowing` step, and returns what to hide.
2676
+ * Any failure is logged as a warning and hides nothing, so the prompt shows the full catalog.
2677
+ */
2678
+ private narrowCatalog;
2679
+ /**
2680
+ * The one decision call, against the opening request. Never throws, and never waits longer than
2681
+ * {@link CATALOG_NARROWING_TIMEOUT_MS} or past the run's cancellation: a throw, a timeout and a
2682
+ * cancelled run each come back as a failed result. Stopping also aborts the call, and links the
2683
+ * prompt run it still returns to `step` once it does ({@link linkLateDecisionPromptRun}).
2684
+ */
2685
+ private askCatalogNarrowing;
2686
+ /** Opens the `Catalog narrowing` Decision step with the decision's inputs. Without a run there is no step. */
2687
+ private startCatalogNarrowingStep;
2688
+ /** Finalizes the `Catalog narrowing` step: each narrowed list's counts, kept names and probabilities, or why it failed open. */
2689
+ private finishCatalogNarrowingStep;
2690
+ /** Logs that catalog narrowing failed open. */
2691
+ private warnCatalogNarrowing;
2692
+ /** The items of one list the prompt shows. Returns `items` itself when the run's narrowing hides none of them. */
2693
+ private hideNarrowedOut;
2694
+ /**
2695
+ * One catalog section as the prompt shows it: `full` when the run's narrowing hides none of
2696
+ * `items`, otherwise a {@link CatalogNarrowingNote} saying how many are hidden and how to reach
2697
+ * them, then the items still shown. A hidden item can still be called. Fails OPEN, unlike the
2698
+ * skill policy: an error shows `full` and logs a warning.
2699
+ */
2700
+ private narrowedCatalogSection;
2335
2701
  /**
2336
2702
  * Builds the agent-invariant {@link AgentBaseCatalog} — the resolved sub-agents + actions and
2337
2703
  * their formatted markdown, plus the base agent-type prompt params. Computed once per agent and
@@ -2372,6 +2738,40 @@ export declare class BaseAgent {
2372
2738
  * @since 2.131.0
2373
2739
  */
2374
2740
  protected buildAgentTypePromptParams(agentType: MJAIAgentTypeEntity | undefined, agent: MJAIAgentEntityExtended, runtimeOverrides?: Record<string, unknown>): Record<string, unknown>;
2741
+ /**
2742
+ * The agent and value pairs {@link warnOnceOnUnknownFinishIfMode} has already reported. It is
2743
+ * process-wide because the prompt params are merged again for every run of an agent, and on every
2744
+ * turn that carries runtime overrides. One warning per agent and value is enough. A run request
2745
+ * can set the value, so what this keeps is bounded: see {@link FinishIfModeWarnings}.
2746
+ */
2747
+ private static readonly finishIfModeWarnings;
2748
+ /**
2749
+ * Warns, once per agent and value, when the merged `finishIfMode` is set but is not a
2750
+ * {@link FinishIfMode}. {@link ResolveFinishIfMode} treats such a value as `'off'`, so without
2751
+ * this a typo such as `"On"` or `"true"` would turn the agent's gates off without a word. An
2752
+ * absent value is the default, so it is not reported.
2753
+ */
2754
+ private warnOnceOnUnknownFinishIfMode;
2755
+ /**
2756
+ * The master switch for decision-model use by this agent: `decisionsEnabled` in its merged
2757
+ * agent-type prompt params (type default < agent < the run's `data.__agentTypePromptParams`).
2758
+ * Anything but `true` is off, the default.
2759
+ *
2760
+ * While it is off the agent never asks a decision model on its own. Each automatic use checks it
2761
+ * before it asks, whatever its own setting says: inline `decisions` ({@link processTurnDecisions}),
2762
+ * `finishIf` gates ({@link finishIfSettings}), decision discovery ({@link isDecisionDiscoveryOnFor}),
2763
+ * the payload change check ({@link isPayloadFeedbackCheckOn}), catalog narrowing
2764
+ * ({@link ensureCatalogNarrowing}) and the Memory Manager's note gate. And
2765
+ * {@link applyResponseTypeAutoAlignment} keeps the `decisions` and `finishIf` docs and response
2766
+ * fields out of the prompt. While it is on, each use keeps its own setting, and each is off by default.
2767
+ *
2768
+ * Explicit uses never read it: a Flow agent's Decision step ({@link executeDecisionStep}) runs because
2769
+ * someone placed it, and the task-graph Decision step and the Run Decision action call
2770
+ * {@link AgentDecisionService} directly. That is why the check sits at each automatic use, not in the service.
2771
+ *
2772
+ * @param promptParams - The merged agent-type prompt params.
2773
+ */
2774
+ protected DecisionsEnabled(promptParams: Record<string, unknown> | undefined): boolean;
2375
2775
  /**
2376
2776
  * Applies auto-alignment rules to includeResponseTypeDefinition based on other flags.
2377
2777
  *
@@ -2385,6 +2785,10 @@ export declare class BaseAgent {
2385
2785
  * - includeCommandDocs → includeResponseTypeDefinition.commands
2386
2786
  * - includeForEachDocs → includeResponseTypeDefinition.forEach
2387
2787
  * - includeWhileDocs → includeResponseTypeDefinition.while
2788
+ * - includeDecisionsDocs → includeResponseTypeDefinition.decisions
2789
+ *
2790
+ * While the master switch is off ({@link DecisionsEnabled}), the decisions and finishIf docs and
2791
+ * response fields are off, even when set explicitly.
2388
2792
  *
2389
2793
  * @param params - The merged params object to modify in place
2390
2794
  * @param explicitResponseType - The explicitly set response type config from agent/runtime (not schema defaults)
@@ -2402,6 +2806,90 @@ export declare class BaseAgent {
2402
2806
  * @since 2.131.0
2403
2807
  */
2404
2808
  protected extractSchemaDefaults(schemaJson: string | null | undefined): Record<string, unknown>;
2809
+ /**
2810
+ * The finishIf settings of the current step, from its merged agent-type prompt params. A gate is
2811
+ * evaluated when the master switch is on ({@link DecisionsEnabled}), `finishIfMode` is `shadow` or
2812
+ * `on`, and `includeResponseTypeDefinition.finishIf` is not `false`; it ends the run only in `on`.
2813
+ */
2814
+ private finishIfSettings;
2815
+ /** Whether a passing finishIf gate ends the run: only in `on` mode. */
2816
+ private finishIfActs;
2817
+ /**
2818
+ * Whether an evaluated gate ends the run. In shadow mode a passing gate is only logged: the
2819
+ * outcome is already recorded on its `Finish check` step, and the model takes its next turn.
2820
+ */
2821
+ private gateEndsRun;
2822
+ /**
2823
+ * Runs the finishIf gate after an Actions step, and returns the Success step when it passes.
2824
+ * ForEach and While call executeActionsStep without a conversation message, and are never gated.
2825
+ */
2826
+ private finishAfterActions;
2827
+ /**
2828
+ * Runs the finishIf gate after a Sub-Agent step that succeeded without terminating, and returns
2829
+ * the step with `terminate: true` when it passes, as `terminateAfter` would.
2830
+ */
2831
+ private finishAfterSubAgent;
2832
+ /**
2833
+ * Asks the finishIf questions about the step's results, then checks that the normal Success
2834
+ * validation would allow the run to end. Records the check as a `Finish check` Decision step.
2835
+ * Never throws: any error means the gate did not pass, and the run continues as it would have.
2836
+ */
2837
+ private evaluateFinishIf;
2838
+ /**
2839
+ * Asks each finishIf question as a Likelihood. Every one must reach the threshold. The call's
2840
+ * prompt run is linked to the `Finish check` step, so the run's cost and tokens count it.
2841
+ */
2842
+ private askFinishIf;
2843
+ /**
2844
+ * Returns why the normal Success validation would refuse to end the run, or `undefined` when it
2845
+ * allows it. The check must not count as a validation retry, so the counters are restored:
2846
+ * otherwise a gate that keeps not passing could exhaust the retries and fail the run.
2847
+ */
2848
+ private finishIfValidationRefusal;
2849
+ /** The Success step a passing gate returns after actions, in the shape of the client-tools `terminateAfterExecution` branch. */
2850
+ private finishIfSuccessStep;
2851
+ /** Finalizes the `Finish check` step with the outcome. A failure to save it never affects the run. */
2852
+ private finalizeFinishCheckStep;
2853
+ /**
2854
+ * Whether the merged agent-type prompt params turn the payload change check on. It is off unless
2855
+ * the master switch ({@link DecisionsEnabled}) and `payloadFeedbackCheck` are both `true`.
2856
+ */
2857
+ private isPayloadFeedbackCheckOn;
2858
+ /**
2859
+ * Runs the payload change check ({@link checkPayloadChanges}) on a step's applied payload changes
2860
+ * when it applies: the analyzer flagged a change for feedback, the check is on
2861
+ * ({@link isPayloadFeedbackCheckOn}), and a turn will read the result. A step that ends the run
2862
+ * skips it: no call to pay for, and no message left in the conversation. Never throws.
2863
+ */
2864
+ private checkPayloadChangesWhenOn;
2865
+ /**
2866
+ * Whether the step ends the run, so no turn would read the payload change check's message: it
2867
+ * terminates, or it is a `Success` or `Chat` step, which hand the run back to the caller.
2868
+ */
2869
+ private stepEndsRun;
2870
+ /**
2871
+ * The payload change check. Asks whether each change the analyzer flagged was intended, as one
2872
+ * Likelihood per change in one decision call, and records it as a `Payload change check`
2873
+ * Decision step. The changes judged unintended are listed in a message for the agent's next
2874
+ * turn, which asks it to confirm or restore them.
2875
+ *
2876
+ * It never reverts or blocks a change: the agent decides. When the decision cannot answer,
2877
+ * every change is accepted, as it is with the check off. Never throws.
2878
+ */
2879
+ private checkPayloadChanges;
2880
+ /**
2881
+ * What the payload change check's decision reads: the agent's own reasoning for the step (from its
2882
+ * response, else from the step), its message, and the reasoning it gave with the change. The check
2883
+ * never runs on a `Chat` or `Success` step, so the message comes from the response alone.
2884
+ */
2885
+ private payloadFeedbackContext;
2886
+ /**
2887
+ * Finalizes the `Payload change check` step with each change's probability and outcome. The step
2888
+ * fails when no decision answered, and its error says why. A failure to save it never affects the run.
2889
+ */
2890
+ private finalizePayloadCheckStep;
2891
+ /** Adds the payload change check's message to the conversation, for the agent's next turn. */
2892
+ private injectPayloadCheckMessage;
2405
2893
  /**
2406
2894
  * Whether THIS action may use the run's runtime API key for THIS driver class. The default is
2407
2895
  * yes: the run was started on those keys, and an action that calls a vendor on the user's behalf
@@ -3282,6 +3770,8 @@ export declare class BaseAgent {
3282
3770
  * them calls this after MJ's gates
3283
3771
  * (AcceptsSkills, Status, agent grant, user Run permission, the ActivationMode double gate) and
3284
3772
  * before anything activates. The default is the identity: MJ's gates are the whole policy.
3773
+ * Catalog narrowing (plan Task 3.7) is not part of this policy: it runs after it, at the catalog
3774
+ * site, and only hides skills from the prompt. An override never needs to call `super` for it.
3285
3775
  *
3286
3776
  * Override it to layer a policy MJ has no table for — a tenant licensing model, a per-organization
3287
3777
  * entitlement, a feature flag — and it applies everywhere at once. Without this seam a subclass