@memberjunction/ai-agents 6.2.0-edge.4 → 6.2.0-edge.5

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 (104) hide show
  1. package/README.md +94 -7
  2. package/dist/AgentRunner.d.ts +6 -3
  3. package/dist/AgentRunner.d.ts.map +1 -1
  4. package/dist/AgentRunner.js +163 -38
  5. package/dist/AgentRunner.js.map +1 -1
  6. package/dist/ArtifactToolManager.d.ts +11 -3
  7. package/dist/ArtifactToolManager.d.ts.map +1 -1
  8. package/dist/ArtifactToolManager.js +72 -6
  9. package/dist/ArtifactToolManager.js.map +1 -1
  10. package/dist/ClientToolRequestManager.d.ts +11 -1
  11. package/dist/ClientToolRequestManager.d.ts.map +1 -1
  12. package/dist/ClientToolRequestManager.js +19 -6
  13. package/dist/ClientToolRequestManager.js.map +1 -1
  14. package/dist/PayloadChangeAnalyzer.d.ts.map +1 -1
  15. package/dist/PayloadChangeAnalyzer.js +53 -30
  16. package/dist/PayloadChangeAnalyzer.js.map +1 -1
  17. package/dist/PayloadManager.d.ts +35 -2
  18. package/dist/PayloadManager.d.ts.map +1 -1
  19. package/dist/PayloadManager.js +250 -149
  20. package/dist/PayloadManager.js.map +1 -1
  21. package/dist/ScratchpadManager.d.ts +18 -0
  22. package/dist/ScratchpadManager.d.ts.map +1 -1
  23. package/dist/ScratchpadManager.js +61 -0
  24. package/dist/ScratchpadManager.js.map +1 -1
  25. package/dist/agent-audience.d.ts +38 -0
  26. package/dist/agent-audience.d.ts.map +1 -0
  27. package/dist/agent-audience.js +99 -0
  28. package/dist/agent-audience.js.map +1 -0
  29. package/dist/agent-context-injector.d.ts +17 -2
  30. package/dist/agent-context-injector.d.ts.map +1 -1
  31. package/dist/agent-context-injector.js +23 -7
  32. package/dist/agent-context-injector.js.map +1 -1
  33. package/dist/agent-memory-context-builder.d.ts +7 -2
  34. package/dist/agent-memory-context-builder.d.ts.map +1 -1
  35. package/dist/agent-memory-context-builder.js +12 -3
  36. package/dist/agent-memory-context-builder.js.map +1 -1
  37. package/dist/agent-pre-execution-rag.d.ts +101 -9
  38. package/dist/agent-pre-execution-rag.d.ts.map +1 -1
  39. package/dist/agent-pre-execution-rag.js +224 -23
  40. package/dist/agent-pre-execution-rag.js.map +1 -1
  41. package/dist/agent-types/flow-agent-type.d.ts +8 -0
  42. package/dist/agent-types/flow-agent-type.d.ts.map +1 -1
  43. package/dist/agent-types/flow-agent-type.js +48 -6
  44. package/dist/agent-types/flow-agent-type.js.map +1 -1
  45. package/dist/agent-types/loop-agent-response-type.d.ts +8 -2
  46. package/dist/agent-types/loop-agent-response-type.d.ts.map +1 -1
  47. package/dist/agent-types/loop-agent-response-type.js.map +1 -1
  48. package/dist/agent-types/loop-agent-type.d.ts +9 -2
  49. package/dist/agent-types/loop-agent-type.d.ts.map +1 -1
  50. package/dist/agent-types/loop-agent-type.js +60 -16
  51. package/dist/agent-types/loop-agent-type.js.map +1 -1
  52. package/dist/base-agent.d.ts +568 -31
  53. package/dist/base-agent.d.ts.map +1 -1
  54. package/dist/base-agent.js +2294 -421
  55. package/dist/base-agent.js.map +1 -1
  56. package/dist/index.d.ts +4 -0
  57. package/dist/index.d.ts.map +1 -1
  58. package/dist/index.js +4 -0
  59. package/dist/index.js.map +1 -1
  60. package/dist/memory-manager-agent.d.ts.map +1 -1
  61. package/dist/memory-manager-agent.js +46 -34
  62. package/dist/memory-manager-agent.js.map +1 -1
  63. package/dist/native-tools/action-param-schema.d.ts +57 -0
  64. package/dist/native-tools/action-param-schema.d.ts.map +1 -0
  65. package/dist/native-tools/action-param-schema.js +238 -0
  66. package/dist/native-tools/action-param-schema.js.map +1 -0
  67. package/dist/native-tools/action-tool-builder.d.ts +5 -4
  68. package/dist/native-tools/action-tool-builder.d.ts.map +1 -1
  69. package/dist/native-tools/action-tool-builder.js +29 -71
  70. package/dist/native-tools/action-tool-builder.js.map +1 -1
  71. package/dist/native-tools/json-argument.d.ts +41 -0
  72. package/dist/native-tools/json-argument.d.ts.map +1 -0
  73. package/dist/native-tools/json-argument.js +79 -0
  74. package/dist/native-tools/json-argument.js.map +1 -0
  75. package/dist/query-builder-agent.d.ts +13 -4
  76. package/dist/query-builder-agent.d.ts.map +1 -1
  77. package/dist/query-builder-agent.js +102 -27
  78. package/dist/query-builder-agent.js.map +1 -1
  79. package/dist/realtime/realtime-client-session-service.d.ts +5 -4
  80. package/dist/realtime/realtime-client-session-service.d.ts.map +1 -1
  81. package/dist/realtime/realtime-client-session-service.js +42 -30
  82. package/dist/realtime/realtime-client-session-service.js.map +1 -1
  83. package/dist/realtime/realtime-coagent-config.d.ts +8 -1
  84. package/dist/realtime/realtime-coagent-config.d.ts.map +1 -1
  85. package/dist/realtime/realtime-coagent-config.js +17 -1
  86. package/dist/realtime/realtime-coagent-config.js.map +1 -1
  87. package/dist/realtime/realtime-recording-ledger.d.ts +130 -0
  88. package/dist/realtime/realtime-recording-ledger.d.ts.map +1 -0
  89. package/dist/realtime/realtime-recording-ledger.js +190 -0
  90. package/dist/realtime/realtime-recording-ledger.js.map +1 -0
  91. package/dist/realtime/realtime-recording-opus-assembly.d.ts +211 -0
  92. package/dist/realtime/realtime-recording-opus-assembly.d.ts.map +1 -0
  93. package/dist/realtime/realtime-recording-opus-assembly.js +706 -0
  94. package/dist/realtime/realtime-recording-opus-assembly.js.map +1 -0
  95. package/dist/realtime/realtime-recording-store.d.ts +38 -1
  96. package/dist/realtime/realtime-recording-store.d.ts.map +1 -1
  97. package/dist/realtime/realtime-recording-store.js +58 -30
  98. package/dist/realtime/realtime-recording-store.js.map +1 -1
  99. package/dist/realtime/realtime-turn-moderator.d.ts +2 -1
  100. package/dist/realtime/realtime-turn-moderator.d.ts.map +1 -1
  101. package/dist/realtime/realtime-turn-moderator.js +7 -1
  102. package/dist/realtime/realtime-turn-moderator.js.map +1 -1
  103. package/dist/volatile-child-prompt.js +3 -3
  104. package/package.json +21 -19
package/README.md CHANGED
@@ -153,6 +153,23 @@ An agent can ask a fast decision model typed questions in six places on its own.
153
153
 
154
154
  Set it in an agent's `AgentTypePromptParams` (`{"decisionsEnabled": true, "finishIfMode": "shadow"}`) or for one run in `data.__agentTypePromptParams`. Uses someone placed explicitly do not read it: a Flow or task-graph Decision step, the Run Decision action, and other direct callers of `AgentDecisionService`. See the [Decision Models guide](./docs/loop-agent-decisions.md).
155
155
 
156
+ ##### Output Artifact Lifecycle (`artifactDirective`) & `_ARTIFACTS_ENABLED` Gating
157
+
158
+ When an artifact-producing Loop agent finishes a turn (`taskComplete: true`), it controls whether its final payload creates a new artifact, versions an existing artifact in the conversation, or suppresses artifact creation via `artifactDirective: { behavior: 'create-new' | 'version-source' | 'suppress', targetArtifactId?, name?, description? }`:
159
+
160
+ - **Default-on per-agent gating (`_ARTIFACTS_ENABLED`)**: `BaseAgent.isArtifactSupportEnabled(agent)` returns `true` unless `AIAgent.ArtifactCreationMode` is `'Never'` or `'System Only'`. The Loop Agent system prompt (`{% if _ARTIFACTS_ENABLED != false %}`) and `<mj-runtime-state>` automatically omit all `artifactDirective` instructions and the `_CONVERSATION_ARTIFACTS` catalog for non-artifact agents (such as `Sage` and `Knowledge Agent`), while enabling them by default for artifact-producing agents (`Query Builder`, `SkillSmith`, `Codesmith`, `Research Agent`, etc.).
161
+ - **Full-conversation artifact targeting (`targetArtifactId`)**: `AgentRunner` loads the conversation's prior output artifacts into `_CONVERSATION_ARTIFACTS` so the agent can version any earlier artifact by `targetArtifactId` (not just the immediately preceding turn's artifact).
162
+ - **Clean payload reset on `create-new`**: When `artifactDirective.behavior === 'create-new'` and the current payload is still the unmodified inherited payload from the prior conversation turn (`payload === params.payload`, even after read-only action steps) or `replaceElements` is used, `BaseAgent.executePromptStep` applies `payloadChangeRequest` against a fresh `{}` object so fields from a prior artifact never bleed into the new artifact.
163
+
164
+ See the [Artifact Tools & Output Lifecycle Guide](./docs/ARTIFACT_TOOLS_GUIDE.md#output-artifact-lifecycle-artifactdirective--_artifacts_enabled-prompt-gating).
165
+
166
+ ##### Single-Node Task Graph Folding (`foldSingleTaskStep`) vs. Multi-Step Durable Workflows
167
+
168
+ When a Loop agent (such as `Sage`) emits `nextStep.type: 'Tasks'`, `LoopAgentType.foldSingleTaskStep` inspects the `taskGraph`:
169
+
170
+ - **Single-node task graphs (1 task of kind `'Agent'` or `'Action'`)**: Automatically fold inline into a standard in-process `'Sub-Agents'` or `'Actions'` step — even when `taskGraph.continuation === 'reinvoke'` is specified (`terminateAfter: false` so the parent Loop agent gets another turn to synthesize the specialist's output). This avoids durable task-graph dispatch overhead for 1-step specialist delegations (e.g., `Query Builder`, `Visualization Agent`) and keeps live sub-agent streaming in the active chat turn.
171
+ - **Multi-node task graphs (2+ tasks with `dependsOn` / `payloadMapping` or non-trivial scheduling)**: Dispatch as durable `MJ: Tasks` rows through [`@memberjunction/task-graph`](../../TaskGraph/README.md), broadcasting real-time step transitions via `TaskGraphFrameBroadcaster` and delivering synthesized continuation replies and artifacts back to the conversation via `TaskGraphContinuationDeliverer`.
172
+
156
173
  #### FlowAgentType
157
174
 
158
175
  Step-based agent that follows a predefined flow graph — steps with explicit conditional paths between them. Best for deterministic workflows where the execution path is known in advance.
@@ -166,6 +183,7 @@ Consequences worth knowing before you debug one:
166
183
  - **The mode is on the run.** A completed `Decision` step named "Workflow runs in this run" or "Workflow runs on the task-graph dispatcher" records which engine ran it and why.
167
184
  - **A dispatched `Sub-Agent` node starts its own `AIAgentRun`**, linked from `Task.AgentRunID` and parented to the submitting run. If that sub-agent is itself a Flow agent, it runs in-process and returns its result to the task.
168
185
  - **A `Decision` step routes the same way in both modes.** Paths read its answers only through `decisions.<key>.<question>`; its `stepResult.result` is the payload, which carries no answers. A flow with a Decision step is compiled and validated before its first step in-run too, so an incomplete Choice fork, a decision read before it can answer, or one read through the payload is refused in both modes. An answer below its `minConfidence` stops an in-run flow (the dispatcher holds the fork, and `Retry` on the step asks again). A failed decision call is a failed step: the paths that read its answers are passed over, and a recovery path such as `stepResult.Success === false` is taken whatever its rank.
186
+ - **Multiple starting steps are supported.** A Flow agent with more than one active `StartingStep: true` step (for example, a workflow saved from a task graph with parallel wave-1 roots) compiles all active starting steps as root nodes (`dependsOn: []`) in dispatch mode, and walks all starting branches sequentially before entering any downstream join step in `inRun` mode.
169
187
  - **Answers live in the run, not the payload.** A run started with `startAtStep` past a Decision step has no answers from it, so every path that reads that decision stops the run with the reason. Start at or before the Decision step to route on it.
170
188
 
171
189
  See the **[Workflows and Task Graphs Guide](../../../guides/WORKFLOW_AND_TASK_GRAPH_GUIDE.md)** for the full model: node kinds, exclusive groups, payload mappings, loops, failure semantics, observability, and a worked configuration example.
@@ -255,7 +273,8 @@ The browser-side driver layer lives in [`@memberjunction/ai-realtime-client`](..
255
273
  Manages data flow through agent execution:
256
274
 
257
275
  - Stores key-value data accessible across all steps and sub-agents
258
- - Supports typed payload changes requested by the LLM
276
+ - Supports typed payload changes requested by the LLM (`newElements`, `updateElements`, `replaceElements`, `removeElements`)
277
+ - Auto-corrects LLM output shape errors (`autoCorrectStrayKeys`), moving stray sibling keys into `newElements`/`updateElements` and automatically unwrapping common LLM wrapper aliases (`setFields`, `setElements`, `createElements`, `addElements`, `modifyElements`, `patchElements`, `updates`, `fields`, `set`, `add`) when the wrapper key does not exist on the payload and is not in `allowedPaths`
259
278
  - Validates and applies changes through PayloadChangeAnalyzer
260
279
  - Provides feedback to the LLM about successful/failed changes via PayloadFeedbackManager
261
280
 
@@ -311,7 +330,7 @@ Handles persistent memory operations for agents:
311
330
  - Consolidation, decay, and protection-tier maintenance over the agent note pool (see below)
312
331
  - **Hardening pass** over agent-authored provisional notes — runs unconditionally at the start of every cycle (before the consolidation-gated phases): LLM-dedupes each `Status='Provisional'` note against hardened notes (duplicates archived with `ConsolidatedIntoNoteID` lineage), and hardens survivors to `Status='Active'` with `ExpiresAt=NULL` so they join importance scoring, consolidation, contradiction detection, and decay in the same cycle
313
332
 
314
- **Session tuning & resilience (v5.49)**: the effective config's `realtime.session` section (`effortLevel` — MJ-normalized, `parallelToolCalls`, `mcpTools`, `inputTranscriptionModel`) flows into the driver Config bag on both topologies via `GetSessionTuningSettings`. The session runner observes the chained cancellation signal (`AbortSignal` dep), performs bounded transport reconnects on fatal drops (`MaxTransportReconnects`, default 1), and accumulates per-modality usage detail (`RealtimeUsage.Input/OutputTokenDetails`) that the checkpoint persists for multi-channel cost attribution. See `guides/REALTIME_CO_AGENTS_GUIDE.md` § "Session tuning, cost attribution & resilience".
333
+ **Session tuning & resilience (v5.49)**: the effective config's `realtime.session` section (`effortLevel` — MJ-normalized, `parallelToolCalls`, `mcpTools`, `inputTranscriptionModel`, `transcriptionLanguages`) flows into the driver Config bag on both topologies via `GetSessionTuningSettings`. The session runner observes the chained cancellation signal (`AbortSignal` dep), performs bounded transport reconnects on fatal drops (`MaxTransportReconnects`, default 1), and accumulates per-modality usage detail (`RealtimeUsage.Input/OutputTokenDetails`) that the checkpoint persists for multi-channel cost attribution. See `guides/REALTIME_CO_AGENTS_GUIDE.md` § "Session tuning, cost attribution & resilience".
315
334
 
316
335
  #### Consolidation Pipeline
317
336
 
@@ -409,6 +428,21 @@ const result = await runner.ExecuteAgent({
409
428
 
410
429
  See [`docs/AGENT_MEMORY_SCOPING.md`](./docs/AGENT_MEMORY_SCOPING.md) for the full model — built-in scopes, primary/secondary semantics, inheritance modes, and how scope propagates through sub-agent invocations.
411
430
 
431
+ ### For an Audience (Shared Conversations)
432
+
433
+ When an agent answers in a conversation several people share, set `Audience` so the run shows only what the asker **and** every other participant may see. Set it from the host's own participant list, server-side; it is never read from `data`.
434
+
435
+ ```typescript
436
+ const result = await new AgentRunner().RunAgent({
437
+ agent,
438
+ conversationMessages: messages,
439
+ contextUser: asker,
440
+ Audience: { Mode: 'Intersection', UserIDs: otherParticipantIDs } // MJ: Users IDs
441
+ });
442
+ ```
443
+
444
+ The run fails before any prompt if the audience is malformed or names an ID no user has (the server's `UserCache` is refreshed once first). Under an audience that adds a reader besides the caller: pre-execution RAG checks every reader's scope permission and searches with `SearchParams.Audience`; only shared notes and examples are injected; data-source preloading and the previous turn's tool results are skipped; task graphs, client tools, the caller's app context, memory writes and realtime sessions are withheld or refused; no out-of-conversation request (`MJ: AI Agent Requests`) is raised, so the run is never resumed without the audience; and every action call carries `RunActionParams.Audience`, which the action engine refuses (`AUDIENCE_UNSUPPORTED`, locked out for the run under its own `'audience'` breaker reason) for any action that does not declare `SupportsAudience` — today only Search and Scoped Search do. Sub-agents inherit the audience. Limits (no persisted audience to resume with; per-reader scope expansion; no `Union` mode) and the full table are in [Searching for an audience](../../../guides/SEARCH_SCOPES_AND_RAG_GUIDE.md#searching-for-an-audience).
445
+
412
446
  ### With Message Lifecycle Management
413
447
 
414
448
  ```typescript
@@ -428,6 +462,28 @@ const result = await runner.ExecuteAgent({
428
462
  });
429
463
  ```
430
464
 
465
+ ### With Post-Run Compaction, Scratchpad Pruning & Memory Extraction (`compactAfterRun`)
466
+
467
+ Programmatic callers and multi-run workflows can opt into automatic post-run cleanup once an agent run settles via `ExecuteAgentParams.compactAfterRun`. When enabled (`true` or an `AgentPostRunCompactionConfig` object), `BaseAgent.finalizeAgentRun` executes a failure-isolated post-run compaction pass after pending step writes and the run record are saved:
468
+
469
+ 1. **Conversation Message Compaction** — When `params.conversationMessages.length >= messageCountThreshold` (default: `20`), older volatile result messages (`IsVolatileResultMessage`: `action-result`, `client-tool-result`, `tool-result`, `sub-agent-result`, `loop-result`) in `[1 .. length - preserveRecentCount - 1]` are compacted via `compactMessage()` while preserving the initial user goal (`index 0`), ordinary `user`/`assistant` conversational turns, turns carrying `toolCalls`, and the most recent turns.
470
+ 2. **Scratchpad Pruning** — When the loop scratchpad contains more notes or completed tasks than `maxScratchpadNotes` (default: `20`), `ScratchpadManager.PruneNotes()` and `ScratchpadManager.EnforceTaskLimit()` prune the oldest low-priority note lines first (preserving `[HIGH]` / `[IMPORTANT]` / `[PINNED]` / `❗` / `⚠️` notes) and trim excess completed tasks.
471
+ 3. **Background Memory Extraction** — When `extractMemories !== false` and `agentRun.Success` is `true`, triggers background memory extraction (`triggerPostRunMemoryExtraction`) to harvest durable learnings from the completed run without blocking the caller.
472
+
473
+ ```typescript
474
+ const result = await runner.ExecuteAgent({
475
+ agentId: 'my-agent-id',
476
+ conversationMessages: messages,
477
+ contextUser: currentUser,
478
+ compactAfterRun: {
479
+ enabled: true,
480
+ messageCountThreshold: 12,
481
+ extractMemories: true,
482
+ maxScratchpadNotes: 20
483
+ }
484
+ });
485
+ ```
486
+
431
487
  ## Latency Optimizations & Concurrent Sub-Agent Execution
432
488
 
433
489
  To drastically reduce execution latency, the framework includes the following optimizations:
@@ -446,10 +502,10 @@ In-memory caching is integrated into `AIEngine.EmbedText` to bypass redundant lo
446
502
  `AgentDataPreloader.PreloadAgentData` resolves agent data sources concurrently with a bounded concurrency cap (default 10 in-flight at once) so a long list of sources can't saturate the DB connection pool.
447
503
 
448
504
  ### 3. Non-blocking Observability DB Logging
449
- Observability writes (`AIAgentRunStep` records) are completely non-blocking:
450
- * Step creation and finalization `.Save()` operations are queued immediately into `_pendingSaves` promises.
451
- * Sequenced queueing via `_stepSavePromises` chains saves on the *same* step ID to prevent database write races (e.g. executing a step `UPDATE` before its initial `INSERT` completes).
452
- * All pending logging writes are drained with `Promise.allSettled` inside `finalizeAgentRun()` and the queues are cleared, so a reused agent instance doesn't leak settled promises. Save failures (rejected promises OR `Save()===false`) are logged via `LogError` and a summary is folded into `agentRun.ErrorMessage` for visibility.
505
+ Observability writes (`AIAgentRunStep` and `AIPromptRun` records) are non-blocking during step execution and settled at terminal boundaries:
506
+ * **Per-entity and cross-step save chaining (`AgentRunStepSaveQueue`)**: Step creation (`createStepEntity`, `createCompactionStep`) and finalization/updates (`finalizeStepEntity`, `updateCompactionStep`, `checkExecutionGuardrails`, `validateSuccessNextStep`, `handleFinalPayloadValidationFailure`) enqueue `INSERT` and `UPDATE` operations onto `_stepSaveQueue` without blocking the agent loop. Updates on a step are chained behind its initial `INSERT`, and `finalizeStepEntity` preserves pre-finalize step fields (such as `guardrailExceeded` in `OutputData` and `FinalPayloadValidationResult`/`FinalPayloadValidationMessages`) across post-INSERT reloads. Child steps (`ParentID`) are chained behind their parent step's `INSERT`.
507
+ * **In-flight `PayloadAtStartSourceStepID` FK ordering (`FK_AIAgentRunStep_PayloadAtStartSourceStep`)**: `findPayloadAtStartSource` matches the latest non-`Running` step with `PayloadAtEnd` even when that source step's initial `INSERT` is still in flight (`!sourceStep.IsSaved`), avoiding redundant multi-kilobyte `PayloadAtStart` clones on fast sequential steps. When the matched source step is not yet saved, `createStepEntity` chains the new step's `INSERT` after `[parentStepEntity, payloadAtStartSource]` and attaches a `beforeInsert` safety fallback that restores inline `PayloadAtStart` (and clears `PayloadAtStartSourceStepID = null`) if the source step's `INSERT` failed.
508
+ * **Complete terminal settlement**: `_stepSaveQueue.Flush()` and `_promptRunner.FlushPendingSaves()` are awaited across all terminal paths — normal completion (`finalizeAgentRun`), failure (`createFailureResult`), cancellation (`createCancelledResult`), and post-turn conversation compaction (`recordCompactionRunStep`) — before the final `agentRun.Save()` executes, ensuring no orphaned or `Running` steps/prompt runs remain in Flight when `ExecuteAgent()` resolves. Save failures are logged via `LogError` and folded into `agentRun.ErrorMessage` for visibility.
453
509
 
454
510
  ### 4. Concurrent Sub-Agent Execution
455
511
  Loop agents can request multiple sub-agents to run in parallel by returning a `subAgents` array in their `nextStep` decision:
@@ -518,6 +574,36 @@ Long conversations no longer grow the agent's context without bound. Two coopera
518
574
 
519
575
  A success clears both counters. A blocked call returns a `CircuitBreakerActionResult` (carrying `Reason`) in ~0 ms without reaching the action engine, and the model receives a `[CRITICAL/ACTION_UNAVAILABLE | REPEATED_IDENTICAL_CALL | ATTEMPTS_EXHAUSTED]` directive as a user message (a `[WARNING/ACTION_FAILURE]` with an "attempt N of 5" counter otherwise). Argument identity is `normalizeActionParams` (three protected layers: outer → per-entry → recursive value). The pipeline registry and the ForEach / While operators pass `{ skipCircuitBreaker: true }` and bypass every rule, leaving the history untouched. Evidence and thresholds: [Performance and Cost Briefing §4](./docs/PROMPT_CACHE_PERFORMANCE_BRIEFING.md).
520
576
 
577
+ ## Root-Tree Cumulative Budget Guards (`AgentTreeBudget`)
578
+
579
+ Per-agent entity guardrails (`MaxIterationsPerRun`, `MaxTokensPerRun`, `MaxCostPerRun`, `MaxTimePerRun`) bound each `AIAgentRun` in isolation, which cannot stop multiplicative fan-out when a parent agent delegates to sequential or parallel sub-agents (for example, a depth-3 tree where each agent stays under a 10-step limit can still execute hundreds of steps across the tree).
580
+
581
+ `BaseAgent` enforces **root-tree cumulative budget guards** via a single shared `AgentTreeBudget` instance initialized at the root run and passed by object reference (`params.treeBudget`) to every child, related, parallel, and realtime-delegated sub-agent run:
582
+
583
+ | Ceiling on `ExecuteAgentParams` / `AgentTreeBudget` | Shared Counter | Breach Message |
584
+ |---|---|---|
585
+ | `maxTreeSteps` | `totalSteps` (incremented on every `createStepEntity`) | `Agent tree step budget exceeded (${totalSteps}/${maxTreeSteps} total steps across tree)` |
586
+ | `maxTreeTokens` | `totalTokens` (accumulated after every prompt, decision, and compaction run) | `Agent tree token budget exceeded (${totalTokens}/${maxTreeTokens} total tokens across tree)` |
587
+ | `maxTreeCost` | `totalCost` (accumulated USD cost across all prompt runs in the tree) | `Agent tree cost budget exceeded ($${totalCost.toFixed(4)}/$${maxTreeCost.toFixed(4)} across tree)` |
588
+ | `maxTreeDurationMs` | `Date.now() - startedAtMs` (wall-clock elapsed time since root run started) | `Agent tree duration budget exceeded (${elapsedMs}ms/${maxTreeDurationMs}ms across tree)` |
589
+
590
+ When any ceiling is reached:
591
+ 1. `budget.breachedReason` is stamped on the shared `AgentTreeBudget` instance.
592
+ 2. `hasExceededAgentRunGuardrails()` and `executeNextStep()` immediately return a terminal `{ step: 'Failed', terminate: true }` decision with the breach reason.
593
+ 3. Any parent or parallel sibling sharing the `AgentTreeBudget` observes `breachedReason` as soon as its in-flight step settles and halts the tree cleanly.
594
+
595
+ ```typescript
596
+ const result = await runner.RunAgent({
597
+ agent: orchestratorAgent,
598
+ conversationMessages: messages,
599
+ contextUser: currentUser,
600
+ maxTreeSteps: 25,
601
+ maxTreeTokens: 100_000,
602
+ maxTreeCost: 1.50,
603
+ maxTreeDurationMs: 120_000
604
+ });
605
+ ```
606
+
521
607
  ## Documentation
522
608
 
523
609
  Detailed guides are available in the [`docs/`](./docs/) directory:
@@ -525,6 +611,7 @@ Detailed guides are available in the [`docs/`](./docs/) directory:
525
611
  | Guide | Description |
526
612
  |---|---|
527
613
  | [Actions Guide](./docs/actions-guide.md) | Action discovery, execution, result lifecycle, expiration/compaction, context recovery |
614
+ | [Artifact Tools & Output Lifecycle Guide](./docs/ARTIFACT_TOOLS_GUIDE.md) | Inbound artifact routing (`Inline` vs `ToolsOnly`), tool libraries, output `artifactDirective` lifecycle (`create-new`, `version-source`, `suppress`), `_ARTIFACTS_ENABLED` prompt gating, full-conversation artifact targeting, and `ArtifactType.ExtractRules` |
528
615
  | [Decision Models](./docs/loop-agent-decisions.md) | The `decisionsEnabled` master switch, then each automatic use: inline decisions, finishIf gates, discovery, the payload change check, catalog narrowing, the Memory Manager note gate |
529
616
  | [Prompt-Cache Performance and Cost Briefing](./docs/PROMPT_CACHE_PERFORMANCE_BRIEFING.md) | Before/after cached share and cost per model and topology for the trailing runtime-state layout; the action circuit breaker's before/after; what to re-measure |
530
617
  | [Agent Prompt Caching Guide](../../../guides/AGENT_PROMPT_CACHING_GUIDE.md) | Repo-level guide: the trailing-state layout, the `PrefixPromptCache` flag from the model catalog, the Anthropic breakpoint seam, specialization placement, the circuit breaker |
@@ -533,7 +620,7 @@ Detailed guides are available in the [`docs/`](./docs/) directory:
533
620
  | [Human-in-the-Loop](./docs/HUMAN_IN_THE_LOOP.md) | Feedback requests, assignment strategies, request lifecycle |
534
621
  | [Agent Memory Scoping](./docs/AGENT_MEMORY_SCOPING.md) | Multi-tenant memory (notes/examples) with UserScope support |
535
622
  | [Iterative Operations](./docs/guide-to-iterative-operations-in-agents.md) | ForEach and While loop patterns, parallel execution |
536
- | [State Management](./docs/state-management.md) | Payload management, agent type state |
623
+ | [State Management](./docs/state-management.md) | Payload management, agent type state, stray-key & wrapper-alias recovery |
537
624
  | [Expression Context (PRD)](./docs/prd-expression-context-phase1.md) | Expression evaluation in agent contexts |
538
625
  | [Agent Profiles (Proposal)](./docs/agent-profiles-proposal.md) | Proposed agent profile system |
539
626
  | [Code Refactoring Notes](./docs/code-refactoring.md) | Internal refactoring notes |
@@ -72,6 +72,8 @@ export declare class AgentRunner {
72
72
  private static saveFailureReason;
73
73
  /** Fallback artifact type for agent payloads when the agent declares no DefaultArtifactTypeID. */
74
74
  private static readonly JSON_ARTIFACT_TYPE_ID;
75
+ /** Artifact type for structured research report payloads containing `{ report: { html } }`. */
76
+ private static readonly RESEARCH_CONTENT_ARTIFACT_TYPE_ID;
75
77
  /**
76
78
  * Max length of `MJ: Artifacts.Name` (`nvarchar(255)`).
77
79
  *
@@ -660,13 +662,14 @@ export declare class AgentRunner {
660
662
  private inferArtifactTypeName;
661
663
  /**
662
664
  * Downloads binary content for a file-backed artifact from MJStorage.
663
- * Uses FileStorageEngine to resolve the storage account and driver,
664
- * then fetches the file by its ProviderKey.
665
+ * Reads the `MJ: Files` row as the user, then resolves it through
666
+ * `FileStorageEngine.ResolveFileObject`, which applies the storage-account gate and the
667
+ * tracked-file rule before any driver call — the same path every other file-ID route uses.
665
668
  *
666
669
  * @param fileId - The MJ: Files entity ID referenced by ArtifactVersion.FileID
667
670
  * @param contextUser - User context for storage driver authentication
668
671
  * @returns Buffer of file content, or null if download fails
669
672
  */
670
- private downloadArtifactFileContent;
673
+ protected DownloadArtifactFileContent(fileId: string, contextUser: UserInfo): Promise<Buffer | null>;
671
674
  }
672
675
  //# sourceMappingURL=AgentRunner.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"AgentRunner.d.ts","sourceRoot":"","sources":["../src/AgentRunner.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAGH,OAAO,EAAsG,QAAQ,EA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AoB;IAkB5B;;;;;;;;;;;;;;;;;;OAkBG;YACW,gCAAgC;IA4C9C;;;;;;;;;;;;;;;;;OAiBG;YACW,4BAA4B;IAY1C;;;OAGG;YACW,qBAAqB;IAYnC;;;;;;;;;OASG;YACW,2BAA2B;IA2IzC;;;;;;;;;;;;;;;;OAgBG;YACW,uBAAuB;IAgDrC;;;OAGG;IACH,OAAO,CAAC,qBAAqB;IAS7B;;;;;;;;;OASG;cACa,2BAA2B,CAAC,MAAM,EAAE,MAAM,EAAE,WAAW,EAAE,QAAQ,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC;CA0C7G"}
@@ -11,9 +11,9 @@
11
11
  */
12
12
  import { createHash } from 'crypto';
13
13
  import { LogError, LogStatusEx, IsVerboseLoggingEnabled, LogStatus, Metadata, RunView, RunQuery, ProviderType } from '@memberjunction/core';
14
- import { MJGlobal, UUIDsEqual, IsValidUUID, EscapeSQLString } from '@memberjunction/global';
14
+ import { MJGlobal, UUIDsEqual, IsValidUUID, EscapeSQLString, IndexByUUID } from '@memberjunction/global';
15
15
  import { AIEngine } from '@memberjunction/aiengine';
16
- import { ResolvePromptRunUserID } from '@memberjunction/ai-core-plus';
16
+ import { ResolvePromptRunUserID, WithAgentRunDataTrustApplied } from '@memberjunction/ai-core-plus';
17
17
  import { PlanArtifactTarget, IsKnownArtifactBehavior } from './artifact-target-plan.js';
18
18
  import { BaseAgent } from './base-agent.js';
19
19
  import { MJEnvironmentEntityExtended, ArtifactMetadataEngine, ConversationEngine, ExtractBase64FromDataUrl, DecideInlineStorage } from '@memberjunction/core-entities';
@@ -86,6 +86,8 @@ export class AgentRunner {
86
86
  }
87
87
  /** Fallback artifact type for agent payloads when the agent declares no DefaultArtifactTypeID. */
88
88
  static { this.JSON_ARTIFACT_TYPE_ID = 'ae674c7e-ea0d-49ea-89e4-0649f5eb20d4'; }
89
+ /** Artifact type for structured research report payloads containing `{ report: { html } }`. */
90
+ static { this.RESEARCH_CONTENT_ARTIFACT_TYPE_ID = 'a7b8c9d0-e1f2-3a4b-5c6d-7e8f9a0b1c2d'; }
89
91
  /**
90
92
  * Max length of `MJ: Artifacts.Name` (`nvarchar(255)`).
91
93
  *
@@ -138,12 +140,34 @@ export class AgentRunner {
138
140
  if (!agentInstance) {
139
141
  throw new Error(`Failed to create agent instance for driver class: ${driverClass}`);
140
142
  }
143
+ // Ensure caller params carries the shared AgentTreeBudget reference before any shallow
144
+ // clone occurs in hydrateConversationArtifacts or Execute.
145
+ if (!params.treeBudget) {
146
+ params.treeBudget = {
147
+ maxTreeSteps: params.maxTreeSteps,
148
+ maxTreeTokens: params.maxTreeTokens,
149
+ maxTreeCost: params.maxTreeCost,
150
+ maxTreeDurationMs: params.maxTreeDurationMs,
151
+ totalSteps: 0,
152
+ totalTokens: 0,
153
+ totalCost: 0,
154
+ startedAtMs: Date.now()
155
+ };
156
+ }
141
157
  // A conversation-linked run must see the conversation's artifacts no matter which
142
158
  // entry point the caller used. See hydrateConversationArtifacts for why.
143
159
  const runParams = await this.hydrateConversationArtifacts(params);
160
+ runParams.treeBudget = params.treeBudget;
144
161
  // Execute the agent and return the result directly, threading the isolated provider.
145
162
  // Favor provider already in params (caller-supplied) over the instance-level provider.
146
- return await agentInstance.Execute({ ...runParams, provider: runParams.provider || this._provider });
163
+ try {
164
+ return await agentInstance.Execute({ ...runParams, provider: runParams.provider || this._provider });
165
+ }
166
+ finally {
167
+ if (agentInstance.TreeBudget) {
168
+ params.treeBudget = agentInstance.TreeBudget;
169
+ }
170
+ }
147
171
  }
148
172
  catch (error) {
149
173
  const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
@@ -314,6 +338,13 @@ export class AgentRunner {
314
338
  // Flag to prevent late progress callbacks from overwriting final status
315
339
  // Progress callbacks fire async and may complete AFTER agent returns
316
340
  let agentExecutionCompleted = false;
341
+ // Progress saves run one at a time on this chain, and the final update awaits it.
342
+ // EnsureSaveComplete() alone is not enough: it resolves on the entity's 'save' event,
343
+ // which BaseEntity raises before the save finishes committing, so a progress save
344
+ // can still be in flight when the final update calls Save(). BaseEntity.Save() hands
345
+ // a concurrent caller the in-flight save's promise, so the final status was dropped
346
+ // and the detail stayed 'In-Progress' with the last progress message.
347
+ let progressSaves = Promise.resolve();
317
348
  // Wrap progress callback to update agent response detail
318
349
  const originalOnProgress = params.onProgress;
319
350
  const wrappedOnProgress = agentResponseDetail
@@ -329,11 +360,21 @@ export class AgentRunner {
329
360
  }
330
361
  // Update the agent response detail with progress message
331
362
  if (agentResponseDetail && progress.message) {
332
- agentResponseDetail.Message = progress.message;
333
- const saved = await agentResponseDetail.Save();
334
- if (!saved) {
335
- LogError(`Failed to save agent response detail progress update: ${AgentRunner.saveFailureReason(agentResponseDetail)}`);
336
- }
363
+ const detail = agentResponseDetail;
364
+ const message = progress.message;
365
+ progressSaves = progressSaves.then(async () => {
366
+ try {
367
+ detail.Message = message;
368
+ if (!(await detail.Save())) {
369
+ LogError(`Failed to save agent response detail progress update: ${AgentRunner.saveFailureReason(detail)}`);
370
+ }
371
+ }
372
+ catch (error) {
373
+ // A failed progress save must not break the chain the final update awaits
374
+ LogError(`Failed to save agent response detail progress update: ${error}`, undefined, error);
375
+ }
376
+ });
377
+ await progressSaves;
337
378
  }
338
379
  // Call original callback if provided
339
380
  if (originalOnProgress) {
@@ -397,8 +438,9 @@ export class AgentRunner {
397
438
  // Step 5: Update agent response detail with final result.
398
439
  const updateDetail = async () => {
399
440
  if (agentResponseDetail && agentResponseDetailId) {
400
- // Wait for any in-flight progress save to complete
401
- // EnsureSaveComplete() resolves immediately if no save in progress
441
+ // Wait for every queued progress save (none can be added: the flag is set),
442
+ // then for any other save still in flight on this entity
443
+ await progressSaves;
402
444
  await agentResponseDetail.EnsureSaveComplete();
403
445
  LogStatus('Updating agent response detail with final result');
404
446
  // Reload to get any updates from agent execution
@@ -806,8 +848,34 @@ export class AgentRunner {
806
848
  }
807
849
  // Check agent's ArtifactCreationMode
808
850
  await AIEngine.Instance.Config(false, contextUser);
809
- const agent = AIEngine.Instance.Agents.find(a => UUIDsEqual(a.ID, agentRun.AgentID));
810
- const creationMode = agent?.ArtifactCreationMode;
851
+ const agentsById = IndexByUUID(AIEngine.Instance.Agents);
852
+ let agent = agentsById.Get(agentRun.AgentID);
853
+ let creationMode = agent?.ArtifactCreationMode;
854
+ // When an orchestrator with ArtifactCreationMode='Never' or 'System Only' (or no
855
+ // DefaultArtifactTypeID, such as Sage) delegates a folded single-node task graph (or
856
+ // sub-agent step) to a specialist agent (such as Query Builder or Research Agent) that
857
+ // DOES produce user-visible artifacts, resolve the artifact creation mode and
858
+ // DefaultArtifactTypeID from the last completed Sub-Agent step's specialist agent so
859
+ // the specialist's deliverable artifact is persisted with the specialist's
860
+ // DefaultArtifactTypeID and visibility.
861
+ if ((creationMode === 'Never' || creationMode === 'System Only' || !agent?.DefaultArtifactTypeID) && agentRun?.Steps?.length) {
862
+ for (let i = agentRun.Steps.length - 1; i >= 0; i--) {
863
+ const step = agentRun.Steps[i];
864
+ if (step.StepType === 'Sub-Agent' && step.Success) {
865
+ const subAgentId = step.TargetID || step.SubAgentRun?.AgentID;
866
+ const delegatedAgent = subAgentId
867
+ ? agentsById.Get(subAgentId)
868
+ : undefined;
869
+ if (delegatedAgent &&
870
+ delegatedAgent.ArtifactCreationMode !== 'Never' &&
871
+ (delegatedAgent.DefaultArtifactTypeID != null || delegatedAgent.ArtifactCreationMode === 'Always')) {
872
+ agent = delegatedAgent;
873
+ creationMode = delegatedAgent.ArtifactCreationMode;
874
+ break;
875
+ }
876
+ }
877
+ }
878
+ }
811
879
  if (creationMode === 'Never') {
812
880
  LogStatus(`Skipping artifact creation - agent "${agent?.Name}" has ArtifactCreationMode='Never'`);
813
881
  return undefined;
@@ -886,7 +954,7 @@ export class AgentRunner {
886
954
  LogStatus(`Creating version ${newVersionNumber} of existing artifact ${artifactId}`);
887
955
  }
888
956
  else {
889
- const artifact = await this.createArtifactHeader(md, contextUser, agent, creationMode, directive);
957
+ const artifact = await this.createArtifactHeader(md, contextUser, agent, creationMode, directive, payload);
890
958
  artifactId = artifact.ID;
891
959
  newVersionNumber = 1;
892
960
  isNewArtifact = true;
@@ -914,19 +982,54 @@ export class AgentRunner {
914
982
  version.VersionNumber = newVersionNumber;
915
983
  version.Content = serializedContent;
916
984
  version.UserID = contextUser.ID;
985
+ const directiveName = AgentRunner.safeDirectiveText(directive?.name, AgentRunner.ARTIFACT_NAME_MAX_LENGTH);
986
+ const directiveDescription = AgentRunner.safeDirectiveText(directive?.description);
987
+ const payloadRecord = (typeof payload === 'object' && payload !== null && !Array.isArray(payload))
988
+ ? payload
989
+ : undefined;
990
+ const reportRecord = (typeof payloadRecord?.report === 'object' && payloadRecord.report !== null && !Array.isArray(payloadRecord.report))
991
+ ? payloadRecord.report
992
+ : undefined;
993
+ const synthesisRecord = (typeof payloadRecord?.synthesis === 'object' && payloadRecord.synthesis !== null && !Array.isArray(payloadRecord.synthesis))
994
+ ? payloadRecord.synthesis
995
+ : undefined;
996
+ const payloadName = AgentRunner.safeDirectiveText(payloadRecord?.title ?? payloadRecord?.name ?? payloadRecord?.savedQueryName ?? reportRecord?.name, AgentRunner.ARTIFACT_NAME_MAX_LENGTH);
997
+ const payloadDescription = AgentRunner.safeDirectiveText(payloadRecord?.description ?? payloadRecord?.interpretation ?? reportRecord?.description ?? synthesisRecord?.executiveSummary);
998
+ if (directiveName || payloadName) {
999
+ version.Name = directiveName || payloadName || null;
1000
+ }
1001
+ if (directiveDescription || payloadDescription) {
1002
+ version.Description = directiveDescription || payloadDescription || null;
1003
+ }
917
1004
  if (!(await version.Save())) {
918
1005
  throw new Error('Failed to save artifact version');
919
1006
  }
920
1007
  LogStatus(`Created artifact version ${newVersionNumber} (${version.ID})`);
921
- // First version of a new artifact: adopt the extracted Name attribute unless the agent named it
922
- if (isNewArtifact && newVersionNumber === 1 && !AgentRunner.safeDirectiveText(directive?.name, AgentRunner.ARTIFACT_NAME_MAX_LENGTH)) {
923
- const nameAttr = version.Attributes?.find((attr) => attr.StandardProperty === 'name' || attr.Name?.toLowerCase() === 'name');
924
- let extractedName = nameAttr?.Value?.trim();
925
- if (extractedName && extractedName.toLowerCase() !== 'null') {
926
- extractedName = extractedName.replace(/^["']|["']$/g, '');
1008
+ // First version of a new artifact: adopt the extracted Name/Description attribute (or payload title/description)
1009
+ // unless the agent explicitly named/described it via artifactDirective.
1010
+ if (isNewArtifact && newVersionNumber === 1 && (!directiveName || !directiveDescription)) {
1011
+ const attrs = version.Attributes;
1012
+ const nameAttr = attrs?.find((attr) => attr.StandardProperty === 'name' || attr.Name?.toLowerCase() === 'name');
1013
+ const descAttr = attrs?.find((attr) => attr.StandardProperty === 'description' || attr.Name?.toLowerCase() === 'description');
1014
+ const cleanAttr = (val, maxLen) => {
1015
+ const trimmed = val?.trim();
1016
+ if (!trimmed || trimmed.toLowerCase() === 'null') {
1017
+ return undefined;
1018
+ }
1019
+ const unquoted = trimmed.replace(/^["']|["']$/g, '').trim();
1020
+ return AgentRunner.safeDirectiveText(unquoted, maxLen);
1021
+ };
1022
+ const resolvedName = !directiveName ? (cleanAttr(nameAttr?.Value, AgentRunner.ARTIFACT_NAME_MAX_LENGTH) || payloadName) : undefined;
1023
+ const resolvedDescription = !directiveDescription ? (cleanAttr(descAttr?.Value) || payloadDescription) : undefined;
1024
+ if (resolvedName || resolvedDescription) {
927
1025
  const artifact = await md.GetEntityObject('MJ: Artifacts', contextUser);
928
1026
  if (await artifact.Load(artifactId)) {
929
- artifact.Name = extractedName;
1027
+ if (resolvedName) {
1028
+ artifact.Name = resolvedName;
1029
+ }
1030
+ if (resolvedDescription) {
1031
+ artifact.Description = resolvedDescription;
1032
+ }
930
1033
  if (await artifact.Save()) {
931
1034
  LogStatus(`Updated artifact name to: ${artifact.Name}`);
932
1035
  }
@@ -1140,7 +1243,7 @@ export class AgentRunner {
1140
1243
  * Creates the artifact header row. Name and description come from the agent's directive when
1141
1244
  * it supplied them (e.g. Skip's artifactRequest); otherwise the historical placeholder.
1142
1245
  */
1143
- async createArtifactHeader(md, contextUser, agent, creationMode, directive) {
1246
+ async createArtifactHeader(md, contextUser, agent, creationMode, directive, payload) {
1144
1247
  const artifact = await md.GetEntityObject('MJ: Artifacts', contextUser);
1145
1248
  const agentName = agent?.Name || 'Agent';
1146
1249
  // Both fields are model output: coerced, trimmed, and (for Name) clamped to its column so a
@@ -1150,8 +1253,17 @@ export class AgentRunner {
1150
1253
  // Description is nvarchar(MAX), so there is no length to clamp to — only the type to check.
1151
1254
  artifact.Description = AgentRunner.safeDirectiveText(directive?.description)
1152
1255
  || `Payload returned by ${agentName}`;
1153
- // Use agent's DefaultArtifactTypeID if available
1154
- artifact.TypeID = agent?.DefaultArtifactTypeID || AgentRunner.JSON_ARTIFACT_TYPE_ID;
1256
+ // Use agent's DefaultArtifactTypeID if available; otherwise infer Research Content when
1257
+ // the payload carries a non-empty report.html string (e.g., Research Report Writer).
1258
+ const payloadObj = (typeof payload === 'object' && payload !== null && !Array.isArray(payload))
1259
+ ? payload
1260
+ : undefined;
1261
+ const reportObj = (typeof payloadObj?.report === 'object' && payloadObj.report !== null && !Array.isArray(payloadObj.report))
1262
+ ? payloadObj.report
1263
+ : undefined;
1264
+ const hasReportHtml = typeof reportObj?.html === 'string' && reportObj.html.trim().length > 0;
1265
+ artifact.TypeID = agent?.DefaultArtifactTypeID
1266
+ || (hasReportHtml ? AgentRunner.RESEARCH_CONTENT_ARTIFACT_TYPE_ID : AgentRunner.JSON_ARTIFACT_TYPE_ID);
1155
1267
  artifact.UserID = contextUser.ID;
1156
1268
  artifact.EnvironmentID = contextUser.EnvironmentID || MJEnvironmentEntityExtended.DefaultEnvironmentID;
1157
1269
  // Set visibility based on agent's ArtifactCreationMode
@@ -1698,8 +1810,10 @@ export class AgentRunner {
1698
1810
  if (!contextUser?.ReturningVisitorContext) {
1699
1811
  return;
1700
1812
  }
1701
- // Gate 2: need a conversation to read from, and an explicit caller scope always wins.
1702
- if (!conversationId || params.PrimaryScopeRecordID || params.data?.PrimaryScopeRecordID) {
1813
+ // Gate 2: need a conversation to read from, and an explicit caller scope always wins — a data scope only when
1814
+ // the run will honour it (TrustReservedRunData; BaseAgent.Execute drops it otherwise).
1815
+ const runData = WithAgentRunDataTrustApplied(params).Params.data;
1816
+ if (!conversationId || params.PrimaryScopeRecordID || runData?.PrimaryScopeRecordID) {
1703
1817
  return;
1704
1818
  }
1705
1819
  const convo = await md.GetEntityObject('MJ: Conversations', contextUser);
@@ -1839,7 +1953,7 @@ export class AgentRunner {
1839
1953
  const typeName = row.TypeName || 'Text';
1840
1954
  let content = '';
1841
1955
  if (row.ContentMode === 'File' && row.FileID) {
1842
- const downloaded = await this.downloadArtifactFileContent(row.FileID, contextUser);
1956
+ const downloaded = await this.DownloadArtifactFileContent(row.FileID, contextUser);
1843
1957
  if (downloaded) {
1844
1958
  content = downloaded;
1845
1959
  }
@@ -1865,10 +1979,18 @@ export class AgentRunner {
1865
1979
  content = await this.hydrateSqlBackedContent(content, contextUser);
1866
1980
  }
1867
1981
  if (content) {
1982
+ const rawDescription = row.VersionDescription || row.ArtifactDescription;
1983
+ const cleanDescription = rawDescription && !rawDescription.startsWith('Payload returned by ')
1984
+ ? rawDescription
1985
+ : undefined;
1868
1986
  inputArtifacts.push({
1869
1987
  name: artifactName,
1870
1988
  typeName,
1871
1989
  content,
1990
+ ...(row.ArtifactID ? { artifactId: row.ArtifactID } : {}),
1991
+ ...(row.VersionID ? { versionId: row.VersionID } : {}),
1992
+ ...(row.VersionNumber != null ? { versionNumber: row.VersionNumber } : {}),
1993
+ ...(cleanDescription ? { description: cleanDescription } : {}),
1872
1994
  mimeType: row.MimeType ?? undefined,
1873
1995
  ...(row.ToolLibraryClass ? { toolLibraryClass: row.ToolLibraryClass } : {}),
1874
1996
  deliveryMode: row.DefaultDeliveryMode ?? 'ToolsOnly',
@@ -1973,20 +2095,25 @@ export class AgentRunner {
1973
2095
  }
1974
2096
  /**
1975
2097
  * Downloads binary content for a file-backed artifact from MJStorage.
1976
- * Uses FileStorageEngine to resolve the storage account and driver,
1977
- * then fetches the file by its ProviderKey.
2098
+ * Reads the `MJ: Files` row as the user, then resolves it through
2099
+ * `FileStorageEngine.ResolveFileObject`, which applies the storage-account gate and the
2100
+ * tracked-file rule before any driver call — the same path every other file-ID route uses.
1978
2101
  *
1979
2102
  * @param fileId - The MJ: Files entity ID referenced by ArtifactVersion.FileID
1980
2103
  * @param contextUser - User context for storage driver authentication
1981
2104
  * @returns Buffer of file content, or null if download fails
1982
2105
  */
1983
- async downloadArtifactFileContent(fileId, contextUser) {
2106
+ async DownloadArtifactFileContent(fileId, contextUser) {
2107
+ if (!IsValidUUID(fileId)) {
2108
+ LogError(`[AgentRunner] Refusing to read artifact file content: '${fileId}' is not a file ID`);
2109
+ return null;
2110
+ }
1984
2111
  try {
1985
2112
  await FileStorageEngine.Instance.Config(false, contextUser);
1986
- const rv = new RunView();
2113
+ const rv = RunView.FromMetadataProvider(this._provider);
1987
2114
  const fileResult = await rv.RunView({
1988
2115
  EntityName: 'MJ: Files',
1989
- ExtraFilter: `ID = '${fileId}'`,
2116
+ ExtraFilter: `ID = '${EscapeSQLString(fileId.trim())}'`,
1990
2117
  Fields: ['ID', 'Name', 'ContentType', 'ProviderID', 'ProviderKey'],
1991
2118
  ResultType: 'simple',
1992
2119
  }, contextUser);
@@ -1994,15 +2121,13 @@ export class AgentRunner {
1994
2121
  LogError(`[AgentRunner] File not found in MJ: Files for FileID: ${fileId}`);
1995
2122
  return null;
1996
2123
  }
1997
- const file = fileResult.Results[0];
1998
- const accounts = FileStorageEngine.Instance.GetAccountsByProviderID(file.ProviderID);
1999
- if (accounts.length === 0) {
2000
- LogError(`[AgentRunner] No FileStorageAccount found for ProviderID: ${file.ProviderID}`);
2124
+ // Account gate and tracked-file rule first; a refusal throws and is logged below.
2125
+ const resolved = await FileStorageEngine.Instance.ResolveFileObject(fileResult.Results[0], contextUser, 'Read', this._provider);
2126
+ if (!resolved) {
2127
+ LogError(`[AgentRunner] No FileStorageAccount found for ProviderID: ${fileResult.Results[0].ProviderID}`);
2001
2128
  return null;
2002
2129
  }
2003
- const driver = await FileStorageEngine.Instance.GetDriver(accounts[0].ID, contextUser);
2004
- const objectName = file.ProviderKey ?? file.Name;
2005
- const content = await driver.GetObject({ fullPath: objectName });
2130
+ const content = await resolved.Driver.GetObject({ fullPath: resolved.ObjectKey });
2006
2131
  // GetObject returns string or Buffer depending on provider
2007
2132
  if (Buffer.isBuffer(content)) {
2008
2133
  return content;