Member Junction
    Preparing search index...

    Planning Designer Agent - Designs agent architectures by researching existing capabilities

    This agent creates TechnicalDesign or modificationPlan by researching available actions, agents, and database entities. It overrides validateSuccessNextStep to enforce that required research actions are called before finalizing designs.

    Key responsibilities:

    • Force discovery of existing agents before selecting actions
    • Force discovery of available actions before designing
    • Force database schema research for CRUD operations
    • Prevent hallucination of non-existent entities/actions
    • Ensure designs are research-backed, not assumption-based

    Hierarchy (View Summary)

    Index

    Constructors

    Properties

    Accessors

    Methods

    applyActionChanges applyResponseTypeAutoAlignment applySubAgentChanges attemptContextRecovery buildAgentBaseCatalog buildAgentTypePromptParams buildConversationSummaryHost buildHierarchicalStep buildPipelineRegistry buildPlanApprovalForm buildRealtimeSessionDeps buildSkillActivationMessage buildSkillInvocation capStandaloneToolResultText checkExecutionGuardrails checkMinimumExecutionRequirements checkPreTurnCompaction checkResearchRequirements cloneSubAgentPayload compactMessage contentToString convertUIMarkupInMessages createCompactionStep createStepEntity createSubAgentResultMessage determineNextStep doesChangeScopeApply emitMessageLifecycleEvent enableSkillCapabilities estimateConversationTokens estimateTokens Execute executeAgentInternal executeArtifactToolCallsAsSteps executeConversationToolCallsAsSteps executeExpandMessageStep executeMemoryWritesAsSteps executeNextStep executePipelineAsStep executePlanStep executePrompt executeRealtimeSession ExecuteSingleAction executeSkillStep ExecuteSubAgent extractSchemaDefaults filterActionChangesForSubAgent filterSubAgentChangesForSubAgent finalizeStepEntity formatHierarchicalMessage formatResearchViolations getActionExecutionCount getAgentPromptParameters getAgentPromptParametersJSON GetConfigurationPresets GetDefaultConfigurationPreset getDesignText getEffectiveActionsForValidation getEffectiveSubAgentsForValidation getExecutionCount getModelContextLimit getRequestedSubAgents getSkillAttributionForAction getSkillAttributionForSubAgent getStorageAccountID getSubAgentExecutionCount getSystemDefaultCompactPromptId getValueFromPath handleFinalPayloadValidationFailure handleStartingPayloadValidation hasExceededAgentRunGuardrails incrementExecutionCount initializeAgentType initializeEngines initializeStartingPayload injectArtifactToolResultsMessage InjectContextMemory injectConversationToolResultsMessage injectMemoryWriteResultsMessage injectPipelineResultMessage InjectPreExecutionRAG injectPriorTurnToolResults InjectScopedPromptParts isConfigurationError isFatalPromptError isSessionDrivenAgentType IsToolResultMessage IsVolatileResultMessage loadAgentConfiguration logError logStatus mapWithConcurrency mentionsDatabaseOperations notifyDroppedSkillRequests preActivateRequestedSkills preparePromptParams prepareSubAgentMessages processMemoryWritesForTurn processNextStep promoteMediaOutputs pruneAndCompactExpiredMessages queueStepSave recordSkillActivationStep recoveryStrategy_CompactAllToolResults recoveryStrategy_CompactOldToolResults recoveryStrategy_RemoveOldestToolResults recoveryStrategy_TrimLastUserMessage resolveCompactionBudget resolveInlineTemplateExpressions resolvePlanModeGate resolveRealtimeEffectiveConfig resolveRealtimeModel resolveSkillActivations resolveSubAgentByName resolveTemplates resolveValueFromContext runCrossTurnCompaction serializePayloadAtEnd serializePayloadAtStart smartTrimContent StartBridgeRealtimeSession startPostTurnCompaction tryGetModelMaxInputTokens updateCompactionStep validateActionInAgent validateActionsNextStep validateAgent validateChatNextStep validateFailedNextStep validateNextStep validatePlanNextStep validateRetryNextStep validateSkillNextStep validateSubAgentInAgent validateSubAgentNextStep validateSuccessNextStep BuildPriorTurnToolResultsMessage

    Constructors

    Properties

    CarryForwardToolFamilies: readonly string[]

    Tool families whose step results are eligible for prior-turn carry-forward — derived from CarryForwardToolFamily (the single source the stamp sites use). Read-tool families only: memory writes, pipelines, and client tools also record StepType='Tool' steps but must never be replayed as reusable results.

    SummarizeRangePromptName: "Summarize Conversation Range"

    Display name of the seeded system prompt behind summarizeRange's recursive sub-call (see metadata/prompts/.summarize-range-prompt.json). Resolved with a trimmed, case-insensitive compare — never an exact-case inline literal.

    Accessors

    • get AgentHierarchy(): readonly string[]
      Protected

      Agent name hierarchy from root to current (e.g. ['Sage', 'Skip', 'Researcher']).

      Returns readonly string[]

    • get AgentTypeInstance(): BaseAgentType

      Accessor for the agent's type instance

      Returns BaseAgentType

    • get AgentTypeState(): any

      Overridable accessor for the current agent instance's agent-type state

      Returns any

    • get DefaultAgentTimeoutMS(): number

      Engine-default wall-clock timeout applied to any agent run whose ExecuteAgentParams.maxExecutionTimeMs is not set. Sub-classes can override to globally change the default. Intentionally generous (2 hours) — tighten per-run for interactive scenarios.

      Returns number

    • get Depth(): number
      Protected

      Depth of this agent in the execution hierarchy (0 = root).

      Returns number

    • get FileOutputs(): FileOutputRef[]
      Protected

      Accumulated file outputs (PDF, Excel, Word, etc.) produced this run. Mirrors the existing MediaOutputs accessor pattern but is scoped to driver sub-classes since it's a more internal collection.

      Returns FileOutputRef[]

    • get maxStandaloneToolResultChars(): number
      Protected

      Character budget (~4 chars/token) for a SINGLE standalone artifact-tool result injected into the conversation. A get_full on a large artifact can otherwise dump the whole thing into context and overflow the model's window — the exact failure pipelines exist to avoid. Override in a subclass to tune. Pipelines are unaffected: their intermediate results never flow through here, and the executor already caps a pipeline's final output.

      Returns number

    • get MediaOutputs(): MediaOutput[]

      Gets the currently accumulated media outputs for this agent run.

      Returns MediaOutput[]

      Array of promoted media outputs

      3.1.0

    • get ParentStepCounts(): readonly number[]
      Protected

      Parent step counts used to build the 2.1.3 hierarchical step label.

      Returns readonly number[]

    • get ProviderToUse(): IMetadataProvider

      Returns the active metadata provider for this agent run. Subclasses MUST use this getter (rather than new Metadata() or Metadata.Provider) so that per-request provider isolation is preserved on the server.

      Returns IMetadataProvider

    • get ResolvedStorageAccountId(): string

      The resolved FileStorageAccount ID for this agent run. Set during Execute() via the hierarchical resolution chain (Runtime → Agent → Category → Type → fallback). Included in the ExecuteAgentResult so AgentRunner can route file artifact uploads.

      Subclasses can read this to customize storage behavior based on the resolved account.

      Returns string

    • get ValidationRetryCount(): number

      Gets the current validation retry count for the agent run. This count tracks how many times the agent has retried validation during the FinalPayloadValidation step.

      Returns number

    Methods

    • Protected

      Applies auto-alignment rules to includeResponseTypeDefinition based on other flags.

      When a documentation flag (e.g., includeForEachDocs) is explicitly set to false, the corresponding response type section (e.g., forEach) should also be excluded unless explicitly set otherwise.

      Auto-alignment mappings:

      • includePayloadInPrompt → includeResponseTypeDefinition.payload
      • includeResponseFormDocs → includeResponseTypeDefinition.responseForms
      • includeCommandDocs → includeResponseTypeDefinition.commands
      • includeForEachDocs → includeResponseTypeDefinition.forEach
      • includeWhileDocs → includeResponseTypeDefinition.while

      Parameters

      • params: Record<string, unknown>

        The merged params object to modify in place

      • OptionalexplicitResponseType: Record<string, unknown>

        The explicitly set response type config from agent/runtime (not schema defaults)

      Returns void

      2.132.0

    • Protected

      Attempts to recover from a context length exceeded error using multiple strategies. Uses escalating strategies: remove old results → compact old results → compact all → trim user message. This approach preserves the user's original request while removing stale tool results.

      Type Parameters

      • P

      Parameters

      • params: ExecuteAgentParams

        Agent execution parameters (conversationMessages will be modified)

      • payload: P

        Current payload to carry forward

      • errorMessage: string

        The original error message from the failed prompt

      • OptionalmodelSelectionInfo: AIModelSelectionInfo

        Model selection information containing the model and vendor used

      Returns Promise<BaseAgentNextStep<P>>

      A Retry step with reduced context or Failed if recovery unsuccessful

    • Protected

      Builds the agent-invariant AgentBaseCatalog — the resolved sub-agents + actions and their formatted markdown, plus the base agent-type prompt params. Computed once per agent and cached on AIEngine (see gatherPromptTemplateData); does NOT apply any runtime overrides.

      Parameters

      Returns AgentBaseCatalog

    • Protected

      Builds merged agent type prompt params from schema defaults, agent config, and runtime overrides.

      Merge precedence (lowest to highest):

      1. Schema defaults (from AgentType.PromptParamsSchema)
      2. Agent config (from AIAgent.AgentTypePromptParams)
      3. Runtime overrides (from ExecuteAgentParams.data.__agentTypePromptParams)

      Parameters

      • agentType: MJAIAgentTypeEntity

        The agent type entity with schema definition

      • agent: MJAIAgentEntityExtended

        The agent entity with configured values

      • OptionalruntimeOverrides: Record<string, unknown>

        Optional runtime overrides from ExecuteAgentParams.data

      Returns Record<string, unknown>

      Merged prompt params object

      2.131.0

    • Protected

      Builds hierarchical step string from parent and current step counts.

      Examples:

      • Root agent step 2: buildHierarchicalStep(2, []) => "2"
      • Sub-agent step 1 under root step 2: buildHierarchicalStep(1, [2]) => "2.1"
      • Nested sub-agent step 3: buildHierarchicalStep(3, [2, 1]) => "2.1.3"
      • Deep nesting: buildHierarchicalStep(5, [1, 2, 3, 4]) => "1.2.3.4.5"

      Exposed as protected so driver sub-classes can emit step labels that match the framework's 2.1.3 nesting convention.

      Parameters

      • currentStep: number

        Current agent's step number (1-based)

      • parentSteps: number[]

        Array of parent step counts from root to immediate parent

      Returns string

      Formatted hierarchical step string, or undefined if currentStep is undefined/null

    • Protected

      Builds a per-run PipelineToolRegistry that unifies the three pipeline-able substrates behind one namespace: built-in transforms, the agent's effective Actions, and the run's artifact tools. Transforms register first so their reserved names win; a source whose name collides with a transform is skipped for pipeline use (still callable normally) and logged, rather than aborting the whole pipeline.

      Parameters

      Returns PipelineToolRegistry

    • Protected

      Builds the editable plan-approval AgentResponseForm: the Markdown-rendered plan (with an Edit toggle so the human can amend it before approving), an optional feedback field that travels back to the agent with the decision (most useful on Reject — it steers the re-plan), and an Approve/Reject button group. Override to change the card's layout (e.g. split the plan into per-step checkboxes instead of one field).

      Approval is a HIGHER-ORDER signal, not just a form reply: conversation hosts detect decision === 'approve' on this form and switch the conversation out of Plan Mode (see ng-conversations' plan-decision handling), so the follow-up run executes the approved plan instead of planning again. Rejection keeps Plan Mode on — the agent re-plans with the feedback in context.

      Parameters

      • planText: string

      Returns AgentResponseForm

    • Protected

      Builds the message appended to conversationMessages when skill(s) activate — this is what actually puts each skill's Instructions into effect for the rest of the run. Override to change formatting (e.g. a more compact representation for a high skill-activation-count agent).

      Parameters

      Returns string

    • Protected

      Bound a standalone tool result to maxStandaloneToolResultChars: return a head slice plus a redirect that teaches the agent to page (get_rows) or reduce (pipeline) instead of reading a whole large artifact. Mirrors how read/search tools cap output at the tool boundary.

      Parameters

      • text: string

      Returns string

    • Checks if all minimum execution requirements are met for actions and sub-agents.

      NOTE: This method intentionally uses only database-configured AgentActions, not _effectiveActions. MinExecutionsPerRun is a database-only concept - dynamically added actions via actionChanges do not have minimum execution requirements. If minimum requirements for dynamic actions are needed in the future, consider adding a minActionLimits property to the ActionChange interface.

      Parameters

      Returns Promise<string[]>

      Array of violation messages (empty if all requirements are met)

    • Protected

      Pre-turn fallback: compacts synchronously when the assembled window is already over the trigger budget BEFORE the first prompt of this run, then splices the fresh summary into the live message array. Only runs with an EXPLICIT configured budget (agent or type ContextWindowMaxTokens) — before the first prompt the model is unknown, and compacting against the conservative default would over-trigger on large-context models. The post-turn hook (real model known) covers those.

      Parameters

      Returns Promise<void>

    • Protected

      Best-effort deep clone for sub-agent payloads. We need this so two parallel sub-agents can each receive their own working copy — without it, mutations by one in-flight sub-agent would race the others' reads.

      Uses structuredClone (Node 17+) where available; falls back to a JSON round-trip for environments without it. Returns the original value on non-cloneable inputs.

      JSON fallback caveats — the round-trip is not shape-preserving:

      • Date → ISO string
      • Map, Set, RegExp, typed arrays → {}
      • undefined values and function-valued properties → dropped
      • BigInt → throws (caught by the outer try/catch, returns original)
      • circular refs → throws (returns original) If payloads ever carry those shapes, behavior diverges between the structuredClone path (Node 17+) and the JSON path. Keep sub-agent payloads to plain JSON-safe shapes to avoid this skew.

      Exposed as protected so driver sub-classes performing their own parallel dispatch get the same payload-isolation guarantee.

      Type Parameters

      • T

      Parameters

      • payload: T

      Returns T

    • Protected

      Compacts a message using configured compaction mode.

      Parameters

      • message: AgentChatMessage

        The message to compact

      • metadata: {
            compactLength: number;
            compactMode: "AI Summary" | "First N Chars";
            compactPromptId: string;
            originalLength: number;
        }

        Compaction configuration

      • params: ExecuteAgentParams

        Agent execution parameters for context

      Returns Promise<string>

      Compacted content string

    • Protected

      Converts ChatMessageContent to a string representation. Handles both simple strings and content block arrays.

      Parameters

      Returns string

      String representation of the content

    • Converts UI markup (@{...} syntax) in user messages to plain text. This prevents agents from being confused by UI-specific JSON syntax and reduces token usage.

      Modifies the messages in-place, converting:

      • Mentions: @{_mode:"mention",...} → "@Agent Name" or "@User Name"
      • Form responses: @{_mode:"form",...} → "Field1: Value1, Field2: Value2"

      Parameters

      • messages: ChatMessage[]

        The conversation messages array to convert (modified in-place)

      Returns void

    • Protected

      Creates a step entity for tracking.

      Exposed as protected so driver sub-classes (e.g. Skip) can author custom AIAgentRunStep records with the same setup correctness — StepNumber, hierarchy breadcrumb, UUID validation, payload serialization, and the queueStepSave coupling that keeps INSERT-then-UPDATE ordering safe.

      Parameters

      • params: {
            completed?: {
                errorMessage?: string;
                outputData?: Record<string, unknown>;
                success: boolean;
            };
            contextUser: UserInfo;
            inputData?: any;
            parentId?: string;
            payloadAtEnd?: any;
            payloadAtStart?: any;
            skills?: AgentSkillInvocation[];
            stepName: string;
            stepType: | "Actions"
            | "Sub-Agent"
            | "ForEach"
            | "Prompt"
            | "While"
            | "Chat"
            | "Compaction"
            | "Decision"
            | "Plan"
            | "Skill"
            | "Tool"
            | "Validation";
            targetId?: string;
            targetLogId?: string;
        }

        Step creation parameters

        • Optionalcompleted?: {
              errorMessage?: string;
              outputData?: Record<string, unknown>;
              success: boolean;
          }

          For steps whose outcome is fully known BEFORE the row exists (e.g. recording an already-finished compaction pass): applies finalizeAgentRunStep in memory so the single queued INSERT carries the terminal state, and no follow-up finalizeStepEntity UPDATE is needed — one DB write instead of two. Do NOT use for steps with real work between start and finish; those stay two-phase so a crash mid-work leaves a visible Running row.

        • contextUser: UserInfo
        • OptionalinputData?: any
        • OptionalparentId?: string
        • OptionalpayloadAtEnd?: any
        • OptionalpayloadAtStart?: any
        • Optionalskills?: AgentSkillInvocation[]

          Skill-invocation records to persist on AIAgentRunStep.Skills for this step. When omitted, Prompt steps default to the full set of skills currently in effect (_skillInvocations) so prompt injection is always visible; all other step types default to no skill linkage. Pass explicitly for Skill steps (the activation performed) and Actions/Sub-Agent steps (the skill(s) that granted the tool).

        • stepName: string
        • stepType:
              | "Actions"
              | "Sub-Agent"
              | "ForEach"
              | "Prompt"
              | "While"
              | "Chat"
              | "Compaction"
              | "Decision"
              | "Plan"
              | "Skill"
              | "Tool"
              | "Validation"
        • OptionaltargetId?: string
        • OptionaltargetLogId?: string

      Returns Promise<MJAIAgentRunStepEntityExtended>

      • The created step entity
    • Protected

      Determines if an action change scope applies to the current agent.

      Parameters

      • scope: ActionChangeScope

        The scope of the action change

      • agentId: string

        The ID of the current agent

      • isRoot: boolean

        Whether this is the root agent

      • OptionalagentIds: string[]

        Array of specific agent IDs (for 'specific' scope)

      Returns boolean

      True if the change applies to this agent

      2.123.0

    • Protected

      Enables a skill's bundled Actions and sub-agents by pushing specific-scoped add entries (targeted at exactly the activating agent's ID) onto params.actionChanges / params.subAgentChanges. specific/[agent.ID] is the correct scope for "apply to THIS agent, at whatever depth it runs, and never leak to its sub-agents":

      • doesChangeScopeApply returns true only when the running agent's ID is in the list, so it applies to the activating agent regardless of depth (a sub-agent that activates a skill still gets its tools — which a root-scoped change would NOT do, since root means "the depth-0 agent," not "the current agent").
      • filterActionChangesForSubAgent / filterSubAgentChangesForSubAgent propagate specific as-is, and each downstream agent checks includes(itsOwnID) → false, so the grant never cascades to sub-agents the activating agent later delegates to. Because params is the same object reference used for the rest of this run, every subsequent turn's gatherPromptTemplateData() call picks up the change automatically — no extra plumbing.

      Override to change propagation scope (e.g. a subclass that wants skill-granted capabilities to cascade to sub-agents could push scope: 'all-subagents' instead).

      Parameters

      Returns void

    • Protected

      Estimates total token count across all conversation messages.

      Parameters

      Returns number

      Total estimated tokens

    • Protected

      Executes the agent's internal logic.

      This method contains the core execution logic that drives agent behavior. By default, it implements a sequential execution loop, but subclasses can override this to implement different execution patterns such as:

      • Parallel execution of multiple steps
      • Event-driven or reactive execution
      • State machine implementations
      • Custom termination conditions
      • Alternative flow control mechanisms

      Type Parameters

      • P = any

        The type of the return value from agent execution

      Parameters

      Returns Promise<{ finalStep: BaseAgentNextStep<P>; stepCount: number }>

      The execution result with typed final payload and step count

    • Protected

      Executes a batch of artifact tool calls, recording each as its own Tool AIAgentRunStep (a sibling of the Prompt step that requested them) with full inputs/outputs captured in InputData/OutputData. Returns the stored results so the caller can render them into a single recall-friendly message for the next prompt turn.

      Step naming convention: Artifact Tool: {toolName} for log/UI clarity.

      Parameters

      Returns Promise<StoredToolResult[]>

    • Protected

      Expands a previously compacted message to its original content.

      Parameters

      Returns string

      null when the expansion succeeded; otherwise a model-facing reason the expansion is impossible. Callers must surface a non-null reason into the next prompt's context — a silent no-op leaves the loop state identical and the model re-requests the same expansion indefinitely.

    • Protected

      Executes a batch of in-flight memory writes, recording each as its own Tool AIAgentRunStep (a sibling of the Prompt step that requested them) with full inputs/outcomes captured in InputData/OutputData.

      Writes run SEQUENTIALLY (not Promise.all like artifact tools) by design: each persisted note is embedded and synced into the in-memory vector service on Save, so write N must be visible to write N+1's near-duplicate check (this is also what makes same-run supersede-own work). The per-run cap bounds the cost of the serialization.

      Step naming convention: Memory Write for log/UI clarity.

      Parameters

      Returns Promise<MemoryWriteResult[]>

    • Protected

      Executes a 'Plan' next step (Plan Mode): records a Plan run-step, raises the standard MJ: AI Agent Requests HITL request with an editable plan-approval AgentResponseForm, and terminates this run awaiting the human's response — reusing the exact same pause/resume infrastructure executeChatStep uses (createFeedbackRequest + the existing MJAIAgentRequestEntityServer.Save() auto-resume-on-status-change hook). A rejected or edited-and-resubmitted plan resumes as a new linked run via the normal run-chain mechanism; resolvePlanModeGate re-checks approval on that new run so a rejection sends the agent back to present a revised plan rather than through to execution.

      Important: the RETURNED BaseAgentNextStep.step is 'Chat', not 'Plan' — 'Plan' is only ever an intermediate classification (used for the AIAgentRunStep.StepType audit record, which the UI reads to render a plan-approval card instead of a generic chat bubble). The step returned to the framework must stay within AIAgentRun.FinalStep's DB-CHECK- constrained, terminal-only vocabulary — 'Plan' is deliberately not part of it (see the BaseAgentNextStep.step doc comment) — so a plan-approval pause is represented as the same terminal shape executeChatStep already uses.

      Parameters

      Returns Promise<BaseAgentNextStep>

    • Protected

      Executes the configured prompt. Always uses the attemptJSONRepair option to try to fix LLM JSON syntax issues if they arise.

      Parameters

      Returns Promise<AIPromptRunResult<unknown>>

      The prompt execution result

    • Protected

      Executes a 'Skill' next step: activates one or more skills the LLM requested by name. Activating a skill (1) appends its full Instructions to the conversation so they take effect for the remainder of the run, and (2) enables its bundled Actions/sub-agents by pushing root-scoped add entries onto params.actionChanges/params.subAgentChanges — the same runtime tool-surface-extension mechanism ExecuteAgentParams already exposes to external callers. This is NOT a nested agent run; it never terminates the loop itself.

      Already-activated skills (tracked in _activatedSkillIDs) are skipped — re-requesting an active skill is a harmless no-op rather than re-appending duplicate instructions.

      Decomposed into resolveSkillActivations, buildSkillActivationMessage, enableSkillCapabilities, and recordSkillActivationStep — override any of those for fine-grained control (e.g. custom instruction formatting, additional side effects on activation) without re-implementing the whole step.

      Parameters

      Returns Promise<BaseAgentNextStep>

    • Protected

      Extracts default values from a JSON Schema definition.

      Parameters

      • schemaJson: string

        JSON string containing the schema

      Returns Record<string, unknown>

      Object with property names and their default values

      2.131.0

    • Protected

      Filters and transforms action changes for propagation to a sub-agent.

      This method applies the following propagation rules:

      • 'global': Propagated as-is to all sub-agents
      • 'root': Not propagated (only applies to root agent)
      • 'all-subagents': Propagated as 'global' (since sub-agent is now in scope)
      • 'specific': Propagated as-is (sub-agent checks if it's in agentIds)

      Parameters

      Returns ActionChange[]

      Filtered action changes for sub-agent, or undefined if empty

      2.123.0

    • Protected

      Finalizes a step entity with completion status. Pairs with createStepEntity — drivers that create custom steps should also finalize them through this method so Status/CompletedAt/Success/ErrorMessage/OutputData are populated consistently and the UPDATE is sequenced behind the INSERT via queueStepSave.

      Parameters

      Returns Promise<void>

    • Protected

      Formats a message with agent hierarchy for streaming/progress updates.

      Exposed as protected so driver sub-classes emit progress events whose breadcrumbs line up with the framework's own — keeps the Explorer tree view consistent across custom and built-in dispatch.

      Parameters

      • baseMessage: string

        The base message to format

      Returns string

      • The formatted message with hierarchy breadcrumb
    • Gets the count of how many times a specific action has been executed in this agent run.

      Parameters

      • agentRunId: string

        The agent run ID (not used anymore, kept for signature compatibility)

      • actionId: string

        The action ID to count

      Returns Promise<number>

      The number of times the action has been executed

    • Gets the available configuration presets for an agent. Returns semantic presets like "Fast", "Balanced", "High Quality" that users can choose from. These are actual presets stored in the database with specific AIConfiguration references.

      Parameters

      • agentId: string

        The ID of the agent to get presets for

      Returns MJAIAgentConfigurationEntity[]

      Array of configuration presets sorted by Priority, or empty array if none configured

      const agent = new ResearchAgent();
      const presets = agent.GetConfigurationPresets('agent-uuid-here');
      // Returns presets defined in database: [
      // { Name: 'Fast', DisplayName: 'Quick Draft', AIConfigurationID: 'fast-config-uuid', IsDefault: true },
      // { Name: 'HighQuality', DisplayName: 'Maximum Detail', AIConfigurationID: 'frontier-uuid', IsDefault: false }
      // ]
      // Note: If no presets configured, returns empty array - agent will use default behavior
    • Protected

      Gets the effective actions for validation, using runtime changes if available. Falls back to database-configured actions if _effectiveActions is empty.

      Parameters

      • agentId: string

        The ID of the agent to get actions for

      Returns MJActionEntityExtended[]

      Array of effective actions available to the agent

      2.123.0

    • Protected

      Gets the execution count for an item (action or sub-agent).

      Parameters

      • itemId: string

        The item ID to get count for

      Returns number

      The execution count (0 if never executed)

    • Protected

      Gets the context limit for the current model. Uses model selection info from the prompt result to determine the actual model's MaxInputTokens.

      Parameters

      • OptionalmodelSelectionInfo: AIModelSelectionInfo

        Model selection information from the prompt execution

      Returns number

      The maximum input tokens for the model

    • Returns the list of sub-agent requests on a next-step decision, normalizing the singular (subAgent) and plural (subAgents) forms. Plural takes precedence when both are present (parallel fan-out); otherwise the singular form is wrapped into a single-element array. Empty if neither is set.

      Use this anywhere code needs to enumerate the sub-agents an LLM requested — keeps validation and execution paths consistent and avoids the regression where one path read .subAgent?.name and missed parallel requests.

      Type Parameters

      • P
      • C

      Parameters

      Returns AgentSubAgentRequest<C>[]

    • Protected

      Resolves which activated skill(s), if any, granted the given action to this agent — the attribution recorded on the Actions step's Skills column. Returns undefined (no linkage) when the action is one of the agent's NATIVE grants (an Active MJ: AI Agent Actions row), even if an activated skill also bundles it: native authority takes precedence, and Skills = NULL is the contract for "the agent had this tool anyway".

      Parameters

      Returns AgentSkillInvocation[]

    • Resolves the file storage account ID for this agent's file artifacts.

      Resolution chain (first non-null wins):

      1. Runtime override (params.override?.storageAccountId)
      2. Agent-level (params.agent.DefaultStorageAccountID)
      3. Category hierarchy — walks up the agent's category tree via ParentID
      4. Agent Type-level (agentType.DefaultStorageAccountID)
      5. System fallback — single active storage account, if only one exists

      This method is protected so subclasses can override the resolution logic for custom storage routing (e.g., routing by file type or tenant).

      Parameters

      Returns Promise<string>

      The resolved FileStorageAccount ID, or null if none configured

    • Gets the count of how many times a specific sub-agent has been executed in this agent run.

      Parameters

      • agentRunId: string

        The agent run ID (not used anymore, kept for signature compatibility)

      • subAgentId: string

        The sub-agent ID to count

      Returns Promise<number>

      The number of times the sub-agent has been executed

    • Protected

      Returns the system default prompt ID for message compaction. Looks up the "Compact Agent Message" prompt by name.

      Returns string

    • Helper to get value from nested object path - extracts from LoopAgentType

      Parameters

      • obj: any
      • path: string

      Returns unknown

    • Protected

      Handles validation of the starting payload if configured.

      This method validates the input payload against the agent's StartingPayloadValidation schema before execution begins. It respects the agent's PayloadScope if configured.

      Type Parameters

      • P = any

      Parameters

      Returns Promise<ExecuteAgentResult>

      Error result if validation fails and mode is 'Fail', null otherwise

    • Protected

      Checks if any agent run guardrails have been exceeded. Override this method to implement custom guardrail logic.

      Parameters

      Returns Promise<
          {
              current?: number;
              exceeded: boolean;
              limit?: number;
              reason?: string;
              type?: "cost"
              | "tokens"
              | "iterations"
              | "time";
          },
      >

      Object indicating if guardrails exceeded and details

    • Protected

      Increments the execution count for an item (action or sub-agent).

      Exposed as protected so driver sub-classes performing custom dispatch bump the same per-item counter the framework checks against execution guardrails — without this, custom dispatch silently bypasses limits.

      Parameters

      • itemId: string

        The item ID to increment (action ID or sub-agent ID)

      Returns void

    • Protected

      Initializes the AI and Action engines. Subclasses can override this to add any additional engine/metadata loading initialization they want to do and this method will be called at the right time in the agent execution process.

      Parameters

      • OptionalcontextUser: UserInfo

        Optional user context

      Returns Promise<void>

    • Protected

      Pushes a single user-role message containing rendered artifact-tool results into the conversation. This mirrors the action-result "inject once, then expire" pattern — the LLM sees the results on its next turn, and older messages are pruned/compacted by pruneAndCompactExpiredMessages instead of being re-rendered into every system-prompt turn.

      Parameters

      Returns void

    • Inject notes and examples into agent context memory. Called automatically before agent execution if injection is enabled on the agent. Injects memory context directly into conversation messages array.

      Parameters

      • input: string

        The user input text for semantic search

      • agent: MJAIAgentEntityExtended

        The agent configuration entity

      • OptionaluserId: string

        Optional user ID for scoping

      • OptionalcompanyId: string

        Optional company ID for scoping

      • OptionalcontextUser: UserInfo

        User context

      • OptionalconversationMessages: ChatMessage[]

        The conversation messages array to inject into

      • OptionalprimaryScopeEntityId: string

        Optional primary scope entity ID for multi-tenant filtering

      • OptionalprimaryScopeRecordId: string

        Optional primary scope record ID for multi-tenant filtering

      • OptionalsecondaryScopes: Record<string, SecondaryScopeValue>

        Optional secondary scope dimensions for multi-tenant filtering

      • OptionalsecondaryScopeConfig: SecondaryScopeConfig

        Optional agent-level scope config for per-dimension inheritance

      Returns Promise<{ examples: MJAIAgentExampleEntity[]; notes: MJAIAgentNoteEntity[] }>

      Object containing injected notes and examples

    • Protected

      Pushes a single user-role message containing memory-write outcomes into the conversation, mirroring injectArtifactToolResultsMessage's inject-once-then-expire pattern. Closing the loop here is what stops the LLM from re-emitting the same memory on subsequent turns.

      Parameters

      Returns void

    • Inject pre-execution RAG context for this agent using scoped search.

      Runs in parallel with InjectContextMemory during Phase 2 of Execute(). Loads the agent's AIAgentSearchScope rows (Phase IN 'PreExecution'|'Both'), renders any per-scope query templates, calls SearchEngine.Search() per scope, cross-scope RRF fuses the results when multiple scopes contributed, and unshifts a <retrieved_context> system message onto conversationMessages.

      When the agent has no active pre-execution scopes (or all scopes returned zero results), this method is a no-op — no system message is injected and _injectedRAG stays null.

      See plans/search-scopes-rag-plus.md §4 (Agent Integration — Pre-Execution RAG).

      Parameters

      • lastUserMessage: string

        The most recent user message text.

      • agent: MJAIAgentEntityExtended

        The agent being executed.

      • contextUser: UserInfo

        Calling user (threaded to SearchEngine + Metadata).

      • conversationMessages: ChatMessage[]

        The mutated message array that flows to the LLM (system msg is unshifted here).

      • originalMessages: ChatMessage[]

        The unmodified messages array (for template recentMessages).

      • OptionalprimaryScopeEntityId: string

        Multi-tenant primary scope entity ID.

      • OptionalprimaryScopeRecordId: string

        Multi-tenant primary scope record ID.

      • OptionalsecondaryScopes: Record<string, SecondaryScopeValue>

        Multi-tenant secondary scope dimensions.

      • Optionalpayload: unknown

        The agent's current payload (for template rendering).

      Returns Promise<AgentPreExecutionRAGResult>

      The structured RAG result, or null if no scopes produced results.

    • Protected

      Carries the PREVIOUS turn's tool results forward into this run's context.

      Inline tool results (artifact + conversation tools) are injected into the run's in-memory messages only — the next turn rebuilds messages from the conversation window, so a result paged in on turn N is gone on turn N+1 and the agent must re-call the tool. The results already persist in each Tool step's OutputData; this re-injects the immediately previous completed run's successful results as one transient message. One-turn memory by construction: each run carries only its direct predecessor's results, so context never compounds.

      Gated on conversationId + root depth — programmatic runs and sub-agents skip it.

      Parameters

      Returns Promise<void>

    • Inject this agent's scoped prompt parts into the conversation, role-faithfully.

      Parallels InjectContextMemory: resolves MJ: Scoped Prompt Parts for the agent's primary prompt under the run's polymorphic scope (the SAME PrimaryScope/SecondaryScopes the runtime threads for memory), and unshifts the assembled role-tagged messages onto conversationMessages. In-memory + synchronous (parts are cached on AIEngine). No-op when the agent has no active prompt or no parts resolve for the scope.

      Parameters

      Returns void

    • Protected

      Determines if an error is a configuration error that cannot be resolved by retrying. Configuration errors indicate issues with agent setup that need manual intervention.

      This method provides detailed diagnostic information to help identify what configuration is missing or incorrect.

      Parameters

      • errorMessage: string

        The error message string

      • Optionalconfig: AgentConfiguration

        Optional agent configuration to check for missing pieces

      Returns { detailedMessage: string; isConfigError: boolean }

      Object with determination and detailed diagnostic message

    • Protected

      Determines if a prompt execution error is fatal and should stop agent execution. Fatal errors are those that won't be resolved by retrying, such as context length exceeded (when no larger model is available), authentication failures, or invalid request format.

      Parameters

      Returns boolean

      true if the error is fatal and agent should terminate, false otherwise

    • Type guard for whether the resolved agent-type instance is session-driven.

      Detects the Realtime agent type without importing it (and without instanceof, which is brittle under bundler class-duplication) by duck-typing the IsSessionDriven getter that RealtimeAgentType adds. BaseAgentType (and Loop/Flow) do not expose this member, so the guard returns false for them and the iterative loop runs unchanged.

      Parameters

      • agentType: BaseAgentType

        The resolved agent-type instance for this run.

      Returns agentType is BaseAgentType & { IsSessionDriven: true }

      true only when the type explicitly marks itself session-driven.

    • Returns true if the message is a tool result (action or client tool). Used by recovery strategies to identify compactable result messages.

      Parameters

      Returns boolean

    • Protected

      Returns true if the message is a turn-generated result (action, tool, client tool, sub-agent, or loop). These are the volatile, expirable messages that accumulate over turns. Everything else — system/RAG context, injected memory, the original user request — anchors the cache-stable prompt prefix and is protected from routine pruning.

      Parameters

      Returns boolean

    • Helper method for enhanced error logging with metadata

      Parameters

      • error: string | Error
      • Optionaloptions: {
            agent?: MJAIAgentEntityExtended;
            agentType?: MJAIAgentTypeEntity;
            category?: string;
            metadata?: Record<string, any>;
            severity?: "warning" | "error" | "critical";
        }

      Returns void

    • Helper method for status logging with verbose control

      Parameters

      • message: string

        The message to log

      • OptionalverboseOnly: boolean

        Whether this is a verbose-only message

      • Optionalparams: ExecuteAgentParams

        Optional agent execution parameters for custom verbose check

      Returns void

    • Protected

      Maps an array through an async worker with bounded concurrency. Preserves input order in the output. Used to cap parallel sub-agent and preload dispatches so a misbehaving LLM (or a runaway data source) can't exhaust the model API or DB pool.

      Exposed as protected so driver sub-classes performing custom parallel work get the same bounded-fan-out + ordered-results contract for free.

      Type Parameters

      • T
      • R

      Parameters

      • items: T[]
      • limit: number
      • worker: (item: T, index: number) => Promise<R>

      Returns Promise<R[]>

    • Protected

      Handles user-requested skill IDs that failed the activation guard (agent-accepted ∩ user-permitted). A silent drop leaves both the user AND the agent blind to the refusal — the agent then improvises around the missing capability instead of explaining it. This emits a server-side warning log and injects a system note into the conversation so the agent tells the user why the skill isn't available rather than working around it.

      Parameters

      Returns void

    • Protected

      Pre-activates skills the caller explicitly requested via ExecuteAgentParams.requestedSkillIDs (typically an end user's /skill-name composer mentions), at run start — so their Instructions and bundled Actions/sub-agents take effect from the first turn rather than waiting for the model to discover and activate them through the catalog.

      Root-agent only (skills never cascade to sub-agents), and each requested skill activates only if it survives the guard: it must be in the set AIEngine.GetSkillsForAgent allows for this agent (the AcceptsSkills gate) AND the acting user must have Run permission on it — both enforced by passing params.contextUser to GetSkillsForAgent. Requested IDs that fail either check are silently dropped, so a client can never force-activate a skill the user or agent isn't entitled to. Reuses the same recordSkillActivationStep / enableSkillCapabilities / buildSkillActivationMessage machinery as the model-initiated Skill step, so activation is recorded and takes effect identically. Plan Mode is unaffected — pre-activation widens the tool surface, but the plan-approval gate still blocks executing those tools until the plan is approved.

      Parameters

      Returns Promise<void>

    • Protected

      Prepares conversation messages for sub-agent execution based on database-configured message mode.

      Message passing is controlled by MessageMode and MaxMessages fields stored in either:

      • AIAgentRelationship table (for related sub-agents via AgentRelationships)
      • AIAgent table (for child sub-agents via ParentID)

      Message Modes:

      • 'None': Fresh start - only context message and task message (default)
      • 'All': Pass complete parent conversation history
      • 'Latest': Pass most recent N messages (where N = MaxMessages)
      • 'Bookend': Pass first 2 messages + indicator + most recent (N-2) messages

      Priority: AIAgentRelationship.MessageMode takes precedence over AIAgent.MessageMode to allow different parent agents to pass messages differently to the same sub-agent.

      Subclasses can override this method to implement custom message preparation logic specific to their domain (e.g., Skip agents adding special context).

      Parameters

      Returns ChatMessage[]

      Prepared message array for sub-agent execution

    • Protected

      Turn-loop entry point for in-flight memory writes, gated on the agent's AllowMemoryWrite flag. When disabled but the LLM emitted writes anyway (prompt drift / injection attempt), records ONE summary skip step — observable without per-write noise — and tells the agent the memories were NOT saved so it stops re-emitting. When enabled, executes the writes as run steps and injects the results message.

      Parameters

      Returns Promise<void>

    • Promotes media outputs to the agent's final outputs. Call this method to add generated images, audio, or video to the agent's outputs. These will be saved to AIAgentRunMedia and flow to ConversationDetailAttachment.

      Parameters

      • mediaOutputs: MediaOutput[]

        Array of media outputs to promote

      Returns void

      3.1.0

      // Promote images from action result
      this.promoteMediaOutputs([{
      modality: 'Image',
      mimeType: 'image/png',
      data: base64Data,
      label: 'Generated Product Image'
      }]);

      // Promote from prompt run media reference
      this.promoteMediaOutputs([{
      promptRunMediaId: 'prompt-run-media-uuid',
      modality: 'Image',
      mimeType: 'image/png',
      label: 'AI Generated Visualization'
      }]);
    • Protected

      Prunes and compacts expired messages in the conversation based on configured expiration rules. Processes messages in three phases: identification, compaction, and removal.

      Parameters

      • params: ExecuteAgentParams

        Agent execution parameters containing conversation messages

      • currentTurn: number

        Current turn number in the agent execution

      Returns Promise<void>

    • Protected

      Creates and immediately finalizes the AIAgentRunStep (StepType='Skill') that records this skill activation for observability/audit. The step's Skills column carries the single AgentSkillInvocation performed (activation type, provenance of authority, and the agent-stated reason when self-activated). Activation is not itself a failure mode today — it always finalizes as successful — but subclasses can override to add richer InputData/OutputData or to make activation conditionally fail (e.g. a licensing check).

      Parameters

      Returns Promise<void>

    • Protected

      Recovery Strategy 3: Aggressively compact ALL tool-result messages. Used when gentler strategies haven't freed enough space.

      Parameters

      • params: ExecuteAgentParams

        Agent execution parameters

      • tokensToSave: number

        Target number of tokens to free

      Returns Promise<{ strategyName: string; tokensSaved: number }>

      Result with tokens saved and strategy description

    • Protected

      Recovery Strategy 2: Compact old tool-result messages. Uses smart trimming to reduce size while preserving some content.

      Parameters

      • params: ExecuteAgentParams

        Agent execution parameters

      • tokensToSave: number

        Target number of tokens to free

      • currentStepCount: number

        Current turn/step number

      • OptionalminAge: number

        Minimum age in turns for compaction (default: 3)

      Returns Promise<{ strategyName: string; tokensSaved: number }>

      Result with tokens saved and strategy description

    • Protected

      Recovery Strategy 1: Remove oldest tool-result messages. Targets messages older than minAge turns for removal.

      Parameters

      • params: ExecuteAgentParams

        Agent execution parameters

      • tokensToSave: number

        Target number of tokens to free

      • currentStepCount: number

        Current turn/step number

      • OptionalminAge: number

        Minimum age in turns for removal (default: 5)

      Returns { strategyName: string; tokensSaved: number }

      Result with tokens saved and strategy description

    • Protected

      Recovery Strategy 4: Preserve beginning of last user message (fallback). Keeps the first 200-300 tokens of the user's request (which usually contains the core ask) and adds a clear marker that content was trimmed due to context limits.

      Parameters

      • params: ExecuteAgentParams

        Agent execution parameters

      • tokensToSave: number

        Target number of tokens to free

      Returns { strategyName: string; tokensSaved: number }

      Result with tokens saved and strategy description

    • Resolves multiple {{expression}} placeholders embedded within a literal string.

      Unlike the single-variable path (which can return objects/numbers), this always returns a string because the resolved values are interpolated back into surrounding text.

      Parameters

      • template: string
      • context: Record<string, any>
      • itemVariable: string

      Returns string

      // Given itemVariable="cityInfo", context.item={city:"Tokyo", country:"Japan"}
      resolveInlineTemplateExpressions(
      "largest company in {{cityInfo.city}} {{cityInfo.country}}",
      context, "cityInfo"
      )
      // → "largest company in Tokyo Japan"
    • Protected

      Resolves whether Plan Mode is active for this run, and whether its approval gate is already satisfied. Called once from initializeAgentRun, after _depth is set.

      • active: this is a root agent (_depth === 0) AND either agent.RequirePlanMode (mandatory HITL — forces plan mode on every root run regardless of the per-request flag; SupportsPlanMode is irrelevant when set) OR agent.SupportsPlanMode (capability, default ON/opt-out) AND params.planMode (per-request, default OFF). Sub-agents never gate on Plan Mode — only the top-level agent the user/caller invoked does.
      • approved: only meaningful when active. True when params.lastRunId points to a prior run whose Plan step's MJ: AI Agent Requests row resolved to Approved or Responded (a Rejected plan — or no matching request at all — leaves the gate unsatisfied, sending the agent back to present a revised plan).

      Override to change Plan Mode eligibility rules (e.g. gate on a specific agent category).

      Parameters

      Returns Promise<{ active: boolean; approved: boolean }>

    • Resolves the agent's EFFECTIVE realtime configuration — the agent TYPE's DefaultConfiguration (base layer) deep-merged with the agent's TypeConfiguration (per-agent layer; the server-bridged path has no runtime-override layer). Tolerant: malformed layers contribute nothing and an unloaded type cache yields no type defaults. See realtime/realtime-coagent-config.ts for the merge contract.

      Parameters

      Returns RealtimeCoAgentConfig

      The normalized effective configuration (possibly empty, never null).

    • Resolves the realtime model + vendor driver + API key for a session-driven run.

      Overridable seam. This is the single injection point that test subclasses override to return a mock BaseRealtimeModel, so executeRealtimeSession can be exercised without provider SDKs or DB metadata.

      Production resolution: pick the highest-power active model of AIModelType Realtime; then pick its highest-priority active vendor whose DriverClass has a resolvable API key; then instantiate the driver via the ClassFactory. Returns null (never throws) if any step can't be satisfied — the caller turns that into a clean FAILED result. (Per-agent realtime model preference can later be wired through the agent's prompt-model config, the same path loop agents use for ModelSelectionMode; the AI Agent entity has no direct model FK.)

      Parameters

      • params: ExecuteAgentParams

        The execution parameters (for the agent + context user).

      • OptionaloverrideModelID: string

      Returns Promise<
          {
              apiName: string;
              driverClass?: string;
              model: BaseRealtimeModel;
              modelID: string;
              vendorID: string;
          },
      >

      The resolved model instance plus its model/vendor identifiers, or null.

    • Protected

      Finds a sub-agent by name, checking child agents (ParentID) first, then related agents (AgentRelationships). Returns undefined when the name doesn't resolve to an active agent reachable from params.agent.

      Used by both the single and parallel sub-agent dispatch paths so name resolution is consistent and there's one place to fix lookup bugs.

      Exposed as protected so driver sub-classes with custom routing logic still resolve names through the same case-insensitive child-then-related lookup the framework uses internally.

      Parameters

      Returns {
          relationship?: MJAIAgentRelationshipEntity;
          subAgentEntity: MJAIAgentEntityExtended;
      }

    • Generic template resolver for loop iterations - extracts from LoopAgentType to make available to all agent types Resolves templates like {{item.field}}, {{index}}, etc. in action parameters and sub-agent payloads

      Parameters

      • obj: Record<string, unknown>
      • context: Record<string, any>
      • itemVariable: string

      Returns Record<string, unknown>

    • Resolves a value from context using variable references - extracts from LoopAgentType

      This method handles both scalar and complex object iterations in ForEach/While loops.

      Examples:

      Scalar array iteration: candidateEntities = ["Users", "Companies", "Invoices"] itemVariable = "entityName" Template: "{{entityName}}" → resolves to "Users", then "Companies", then "Invoices"

      Object array iteration: users = [{name: "Alice", age: 30}, {name: "Bob", age: 25}] itemVariable = "user" Template: "{{user.name}}" → resolves to "Alice", then "Bob" Template: "{{user}}" → resolves to entire object {name: "Alice", age: 30}

      Parameters

      • value: string
      • context: Record<string, any>
      • itemVariable: string

      Returns any

    • Protected

      Serializes payload for logging to PayloadAtEnd Override in subclasses to customize logging behavior (e.g., summarize large payloads)

      Parameters

      • payload: any

        The payload to serialize

      Returns string

      Serialized string or null to skip logging

    • Protected

      Serializes payload for logging to PayloadAtStart Override in subclasses to customize logging behavior (e.g., summarize large payloads)

      Parameters

      • payload: any

        The payload to serialize

      Returns string

      Serialized string or null to skip logging

    • Protected

      Smart trimming of message content based on detected format. Attempts to preserve structure while reducing size.

      Parameters

      • content: string

        The message content to trim (must be string)

      • OptionalmaxLength: number

        Maximum length for the trimmed content

      Returns { originalLength: number; strategy: string; trimmed: string }

      Object with trimmed content and strategy used

    • Opens a raw IRealtimeSession for this agent — the duplex model connection a Realtime Bridge hands to AIBridgeEngine.StartBridgeSession so the agent can talk + hear over a media transport (a LiveKit room, a Zoom/Teams meeting, a phone call). The bridge engine owns turn-taking and the transport seam, so this deliberately returns the session itself, NOT a RealtimeSessionRunner (which is the client-direct topology's own orchestration loop).

      It reuses the EXACT same resolution + assembly as executeRealtimeSession — model selection (resolveRealtimeModel), agent configuration (loadAgentConfiguration), effective-config persona/voice (resolveRealtimeEffectiveConfig), and the system-prompt + memory context (buildRealtimeSessionParams) — then opens the session via BaseRealtimeModel.StartSession. Tools are intentionally NOT pre-populated: the invoke-target-agent + interactive-surface tools are a runner concern; a bridge that needs them registers them on the returned session itself.

      Parameters

      • params: ExecuteAgentParams

        The execution parameters (agent + context user + the request-scoped provider). A fresh bridge session typically passes an empty conversationMessages array.

      Returns Promise<IRealtimeSession>

      The live realtime session.

      When the agent configuration fails to load or no usable Realtime model can be resolved.

    • Protected

      Post-turn hook (the primary path), called from finalizeAgentRun after the run row is saved. Fire-and-forget by design: the caller's completion event never waits on the summary LLM call. Fires for settled root runs with a conversation — settledRunStatuses: 'Completed' AND 'AwaitingFeedback', because a Chat final step (→ AwaitingFeedback) is the NORMAL ending of a conversational turn; gating on 'Completed' alone silently disabled post-turn compaction for exactly the long-chat scenario this feature targets.

      Returns void

    • Protected

      Extracts the vendor-specific MaxInputTokens from model selection info, returning null when it genuinely cannot be determined. Callers that need a hard number use getModelContextLimit (which falls back to a conservative default); callers for whom a guessed default would be WRONG — e.g. cross-turn compaction budget clamping, where a bogus 8000 would clamp a configured 200k budget — use this and handle null explicitly.

      Parameters

      Returns number

    • Parameters

      • actionName: string

      Returns string

    • Parameters

      • subAgentName: string

      Returns string

    • Renders prior-turn tool-result steps into the carried-forward message body. Pure and static for testability: keeps only steps whose OutputData satisfies the structured contract stamped by the tool executors — a carry-forward-eligible toolFamily (see CarryForwardToolFamilies) AND a non-empty tool name. Tolerant of missing/invalid OutputData JSON, keeps only successful results, caps each result and the total under maxChars (adding an explicit truncation note when results are dropped). Returns null when nothing usable remains.

      Parameters

      Returns string