@memberjunction/ai-agents 6.3.0-edge.0 → 6.3.0-edge.1
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.
- package/README.md +8 -5
- package/dist/AgentDataPreloader.d.ts +9 -2
- package/dist/AgentDataPreloader.d.ts.map +1 -1
- package/dist/AgentDataPreloader.js +134 -15
- package/dist/AgentDataPreloader.js.map +1 -1
- package/dist/AgentDecisionService.d.ts +10 -1
- package/dist/AgentDecisionService.d.ts.map +1 -1
- package/dist/AgentDecisionService.js +28 -13
- package/dist/AgentDecisionService.js.map +1 -1
- package/dist/AgentRunner.d.ts +57 -15
- package/dist/AgentRunner.d.ts.map +1 -1
- package/dist/AgentRunner.js +692 -101
- package/dist/AgentRunner.js.map +1 -1
- package/dist/ArtifactToolManager.d.ts +134 -39
- package/dist/ArtifactToolManager.d.ts.map +1 -1
- package/dist/ArtifactToolManager.js +2761 -321
- package/dist/ArtifactToolManager.js.map +1 -1
- package/dist/GovernedArtifactService.d.ts +367 -0
- package/dist/GovernedArtifactService.d.ts.map +1 -0
- package/dist/GovernedArtifactService.js +2569 -0
- package/dist/GovernedArtifactService.js.map +1 -0
- package/dist/PayloadManager.d.ts +46 -0
- package/dist/PayloadManager.d.ts.map +1 -1
- package/dist/PayloadManager.js +284 -66
- package/dist/PayloadManager.js.map +1 -1
- package/dist/SkillMarkdownConverter.d.ts.map +1 -1
- package/dist/SkillMarkdownConverter.js +4 -2
- package/dist/SkillMarkdownConverter.js.map +1 -1
- package/dist/agent-context-injector.d.ts +2 -25
- package/dist/agent-context-injector.d.ts.map +1 -1
- package/dist/agent-context-injector.js +38 -153
- package/dist/agent-context-injector.js.map +1 -1
- package/dist/agent-instance.d.ts +28 -0
- package/dist/agent-instance.d.ts.map +1 -0
- package/dist/agent-instance.js +39 -0
- package/dist/agent-instance.js.map +1 -0
- package/dist/agent-memory-context-builder.d.ts.map +1 -1
- package/dist/agent-memory-context-builder.js +46 -42
- package/dist/agent-memory-context-builder.js.map +1 -1
- package/dist/agent-pre-execution-rag.d.ts.map +1 -1
- package/dist/agent-pre-execution-rag.js +5 -0
- package/dist/agent-pre-execution-rag.js.map +1 -1
- package/dist/agent-run-watchdog.d.ts +38 -6
- package/dist/agent-run-watchdog.d.ts.map +1 -1
- package/dist/agent-run-watchdog.js +75 -13
- package/dist/agent-run-watchdog.js.map +1 -1
- package/dist/agent-types/flow-agent-type.d.ts +6 -1
- package/dist/agent-types/flow-agent-type.d.ts.map +1 -1
- package/dist/agent-types/flow-agent-type.js +30 -7
- package/dist/agent-types/flow-agent-type.js.map +1 -1
- package/dist/agent-types/loop-agent-type.d.ts +4 -0
- package/dist/agent-types/loop-agent-type.d.ts.map +1 -1
- package/dist/agent-types/loop-agent-type.js +29 -0
- package/dist/agent-types/loop-agent-type.js.map +1 -1
- package/dist/artifact-presence-locator.d.ts +132 -0
- package/dist/artifact-presence-locator.d.ts.map +1 -0
- package/dist/artifact-presence-locator.js +472 -0
- package/dist/artifact-presence-locator.js.map +1 -0
- package/dist/artifact-tools/CSVToolLibrary.d.ts +2 -2
- package/dist/artifact-tools/CSVToolLibrary.d.ts.map +1 -1
- package/dist/artifact-tools/CSVToolLibrary.js +41 -14
- package/dist/artifact-tools/CSVToolLibrary.js.map +1 -1
- package/dist/artifact-tools/DataSnapshotToolLibrary.d.ts +2 -2
- package/dist/artifact-tools/DataSnapshotToolLibrary.d.ts.map +1 -1
- package/dist/artifact-tools/DataSnapshotToolLibrary.js +53 -21
- package/dist/artifact-tools/DataSnapshotToolLibrary.js.map +1 -1
- package/dist/artifact-tools/DocumentToolLibrary.d.ts +101 -0
- package/dist/artifact-tools/DocumentToolLibrary.d.ts.map +1 -0
- package/dist/artifact-tools/DocumentToolLibrary.js +1846 -0
- package/dist/artifact-tools/DocumentToolLibrary.js.map +1 -0
- package/dist/artifact-tools/DocxToolLibrary.d.ts +2 -4
- package/dist/artifact-tools/DocxToolLibrary.d.ts.map +1 -1
- package/dist/artifact-tools/DocxToolLibrary.js +42 -30
- package/dist/artifact-tools/DocxToolLibrary.js.map +1 -1
- package/dist/artifact-tools/ExcelToolLibrary.d.ts +2 -3
- package/dist/artifact-tools/ExcelToolLibrary.d.ts.map +1 -1
- package/dist/artifact-tools/ExcelToolLibrary.js +105 -49
- package/dist/artifact-tools/ExcelToolLibrary.js.map +1 -1
- package/dist/artifact-tools/GenericBinaryToolLibrary.d.ts +2 -2
- package/dist/artifact-tools/GenericBinaryToolLibrary.d.ts.map +1 -1
- package/dist/artifact-tools/GenericBinaryToolLibrary.js +3 -2
- package/dist/artifact-tools/GenericBinaryToolLibrary.js.map +1 -1
- package/dist/artifact-tools/JSONToolLibrary.d.ts +4 -4
- package/dist/artifact-tools/JSONToolLibrary.d.ts.map +1 -1
- package/dist/artifact-tools/JSONToolLibrary.js +32 -11
- package/dist/artifact-tools/JSONToolLibrary.js.map +1 -1
- package/dist/artifact-tools/PDFToolLibrary.d.ts +27 -3
- package/dist/artifact-tools/PDFToolLibrary.d.ts.map +1 -1
- package/dist/artifact-tools/PDFToolLibrary.js +36 -21
- package/dist/artifact-tools/PDFToolLibrary.js.map +1 -1
- package/dist/artifact-tools/SearchResultSetToolLibrary.d.ts +2 -2
- package/dist/artifact-tools/SearchResultSetToolLibrary.d.ts.map +1 -1
- package/dist/artifact-tools/SearchResultSetToolLibrary.js +83 -24
- package/dist/artifact-tools/SearchResultSetToolLibrary.js.map +1 -1
- package/dist/artifact-tools/SlideDeckToolLibrary.d.ts +50 -0
- package/dist/artifact-tools/SlideDeckToolLibrary.d.ts.map +1 -0
- package/dist/artifact-tools/SlideDeckToolLibrary.js +1617 -0
- package/dist/artifact-tools/SlideDeckToolLibrary.js.map +1 -0
- package/dist/artifact-tools/SpreadsheetToolLibrary.d.ts +87 -0
- package/dist/artifact-tools/SpreadsheetToolLibrary.d.ts.map +1 -0
- package/dist/artifact-tools/SpreadsheetToolLibrary.js +3351 -0
- package/dist/artifact-tools/SpreadsheetToolLibrary.js.map +1 -0
- package/dist/artifact-tools/TextToolLibrary.d.ts +3 -3
- package/dist/artifact-tools/TextToolLibrary.d.ts.map +1 -1
- package/dist/artifact-tools/TextToolLibrary.js +34 -24
- package/dist/artifact-tools/TextToolLibrary.js.map +1 -1
- package/dist/artifact-tools/WhiteboardToolLibrary.d.ts +69 -0
- package/dist/artifact-tools/WhiteboardToolLibrary.d.ts.map +1 -0
- package/dist/artifact-tools/WhiteboardToolLibrary.js +555 -0
- package/dist/artifact-tools/WhiteboardToolLibrary.js.map +1 -0
- package/dist/artifact-tools/artifact-comment-suggestion-helper.d.ts +98 -0
- package/dist/artifact-tools/artifact-comment-suggestion-helper.d.ts.map +1 -0
- package/dist/artifact-tools/artifact-comment-suggestion-helper.js +851 -0
- package/dist/artifact-tools/artifact-comment-suggestion-helper.js.map +1 -0
- package/dist/artifact-tools/artifact-tool-helpers.d.ts +21 -0
- package/dist/artifact-tools/artifact-tool-helpers.d.ts.map +1 -0
- package/dist/artifact-tools/artifact-tool-helpers.js +74 -0
- package/dist/artifact-tools/artifact-tool-helpers.js.map +1 -0
- package/dist/artifact-tools/grepHelper.d.ts +27 -0
- package/dist/artifact-tools/grepHelper.d.ts.map +1 -0
- package/dist/artifact-tools/grepHelper.js +229 -0
- package/dist/artifact-tools/grepHelper.js.map +1 -0
- package/dist/artifact-tools/node-vm-safe-regex.d.ts +10 -0
- package/dist/artifact-tools/node-vm-safe-regex.d.ts.map +1 -0
- package/dist/artifact-tools/node-vm-safe-regex.js +148 -0
- package/dist/artifact-tools/node-vm-safe-regex.js.map +1 -0
- package/dist/base-agent.d.ts +119 -14
- package/dist/base-agent.d.ts.map +1 -1
- package/dist/base-agent.js +529 -112
- package/dist/base-agent.js.map +1 -1
- package/dist/decision-discovery.d.ts +42 -15
- package/dist/decision-discovery.d.ts.map +1 -1
- package/dist/decision-discovery.js +90 -20
- package/dist/decision-discovery.js.map +1 -1
- package/dist/index.d.ts +12 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +12 -2
- package/dist/index.js.map +1 -1
- package/dist/memory-decision-uses.d.ts +206 -0
- package/dist/memory-decision-uses.d.ts.map +1 -0
- package/dist/memory-decision-uses.js +259 -0
- package/dist/memory-decision-uses.js.map +1 -0
- package/dist/memory-manager-agent.d.ts +66 -6
- package/dist/memory-manager-agent.d.ts.map +1 -1
- package/dist/memory-manager-agent.js +184 -31
- package/dist/memory-manager-agent.js.map +1 -1
- package/dist/memory-note-gate.d.ts +12 -9
- package/dist/memory-note-gate.d.ts.map +1 -1
- package/dist/memory-note-gate.js +16 -11
- package/dist/memory-note-gate.js.map +1 -1
- package/dist/native-tools/agent-tool-circuit-breaker.d.ts +44 -0
- package/dist/native-tools/agent-tool-circuit-breaker.d.ts.map +1 -0
- package/dist/native-tools/agent-tool-circuit-breaker.js +71 -0
- package/dist/native-tools/agent-tool-circuit-breaker.js.map +1 -0
- package/dist/native-tools/agent-tools.d.ts +7 -0
- package/dist/native-tools/agent-tools.d.ts.map +1 -1
- package/dist/native-tools/agent-tools.js.map +1 -1
- package/dist/native-tools/control-tools.d.ts +8 -1
- package/dist/native-tools/control-tools.d.ts.map +1 -1
- package/dist/native-tools/control-tools.js +38 -5
- package/dist/native-tools/control-tools.js.map +1 -1
- package/dist/native-tools/framework-tools.d.ts +3 -3
- package/dist/native-tools/framework-tools.d.ts.map +1 -1
- package/dist/native-tools/framework-tools.js +20 -8
- package/dist/native-tools/framework-tools.js.map +1 -1
- package/dist/payload-path-keys.d.ts +54 -0
- package/dist/payload-path-keys.d.ts.map +1 -0
- package/dist/payload-path-keys.js +126 -0
- package/dist/payload-path-keys.js.map +1 -0
- package/dist/pipeline/template.d.ts +9 -4
- package/dist/pipeline/template.d.ts.map +1 -1
- package/dist/pipeline/template.js +29 -30
- package/dist/pipeline/template.js.map +1 -1
- package/dist/realtime/artifact-workspace-channel-server.d.ts +27 -0
- package/dist/realtime/artifact-workspace-channel-server.d.ts.map +1 -0
- package/dist/realtime/artifact-workspace-channel-server.js +43 -0
- package/dist/realtime/artifact-workspace-channel-server.js.map +1 -0
- package/dist/realtime/bridge-realtime-session-factory.d.ts +2 -2
- package/dist/realtime/bridge-realtime-session-factory.d.ts.map +1 -1
- package/dist/realtime/bridge-realtime-session-factory.js +7 -56
- package/dist/realtime/bridge-realtime-session-factory.js.map +1 -1
- package/dist/realtime/realtime-artifact-helpers.d.ts +37 -0
- package/dist/realtime/realtime-artifact-helpers.d.ts.map +1 -0
- package/dist/realtime/realtime-artifact-helpers.js +150 -0
- package/dist/realtime/realtime-artifact-helpers.js.map +1 -0
- package/dist/realtime/realtime-client-session-service.d.ts +87 -17
- package/dist/realtime/realtime-client-session-service.d.ts.map +1 -1
- package/dist/realtime/realtime-client-session-service.js +259 -39
- package/dist/realtime/realtime-client-session-service.js.map +1 -1
- package/dist/realtime/realtime-coagent-config.d.ts +22 -7
- package/dist/realtime/realtime-coagent-config.d.ts.map +1 -1
- package/dist/realtime/realtime-coagent-config.js +20 -22
- package/dist/realtime/realtime-coagent-config.js.map +1 -1
- package/dist/realtime/realtime-moderator-decision.d.ts +86 -0
- package/dist/realtime/realtime-moderator-decision.d.ts.map +1 -0
- package/dist/realtime/realtime-moderator-decision.js +131 -0
- package/dist/realtime/realtime-moderator-decision.js.map +1 -0
- package/dist/realtime/realtime-tool-broker.d.ts +6 -0
- package/dist/realtime/realtime-tool-broker.d.ts.map +1 -1
- package/dist/realtime/realtime-tool-broker.js +4 -2
- package/dist/realtime/realtime-tool-broker.js.map +1 -1
- package/dist/realtime/realtime-turn-moderator.d.ts +20 -0
- package/dist/realtime/realtime-turn-moderator.d.ts.map +1 -1
- package/dist/realtime/realtime-turn-moderator.js +63 -8
- package/dist/realtime/realtime-turn-moderator.js.map +1 -1
- package/dist/repeated-failing-step.d.ts +50 -0
- package/dist/repeated-failing-step.d.ts.map +1 -0
- package/dist/repeated-failing-step.js +130 -0
- package/dist/repeated-failing-step.js.map +1 -0
- package/dist/tsconfig.tsbuildinfo +1 -0
- package/package.json +20 -20
package/dist/AgentRunner.js
CHANGED
|
@@ -2,25 +2,27 @@
|
|
|
2
2
|
* @fileoverview AgentRunner provides a thin wrapper for executing AI agents
|
|
3
3
|
* using the MemberJunction AI Agent framework.
|
|
4
4
|
*
|
|
5
|
-
* This module handles agent instantiation
|
|
6
|
-
* the
|
|
5
|
+
* This module handles agent instantiation through {@link CreateAgentInstance}, so the
|
|
6
|
+
* subclass named by the agent's own DriverClass runs (or the plain BaseAgent when it names none).
|
|
7
7
|
*
|
|
8
8
|
* @module @memberjunction/ai-agents
|
|
9
9
|
* @author MemberJunction.com
|
|
10
10
|
* @since 2.49.0
|
|
11
11
|
*/
|
|
12
12
|
import { createHash } from 'crypto';
|
|
13
|
-
import { LogError, LogStatusEx, IsVerboseLoggingEnabled, LogStatus, Metadata, RunView, RunQuery, ProviderType } from '@memberjunction/core';
|
|
14
|
-
import {
|
|
13
|
+
import { LogError, LogStatusEx, IsVerboseLoggingEnabled, LogStatus, Metadata, RunView, RunQuery, DatabaseProviderBase, ProviderType } from '@memberjunction/core';
|
|
14
|
+
import { UUIDsEqual, NormalizeUUID, IsValidUUID, EscapeSQLString, IndexByUUID } from '@memberjunction/global';
|
|
15
15
|
import { AIEngine } from '@memberjunction/aiengine';
|
|
16
16
|
import { ResolvePromptRunUserID, WithAgentRunDataTrustApplied, MJAIAgentRunEntityExtended } from '@memberjunction/ai-core-plus';
|
|
17
17
|
import { ResolveConversationAgentPreset } from '@memberjunction/ai-engine-base';
|
|
18
18
|
import { PlanArtifactTarget, IsKnownArtifactBehavior } from './artifact-target-plan.js';
|
|
19
|
-
import {
|
|
19
|
+
import { GetArtifactLiveContentReaderHook } from './artifact-presence-locator.js';
|
|
20
|
+
import { CreateAgentInstance } from './agent-instance.js';
|
|
20
21
|
import { HostAllowedAgentIDs } from './decision-discovery.js';
|
|
21
22
|
import { ResolveHandoffTarget, HandoffRefusalReasonText } from './handoff-target.js';
|
|
22
|
-
import { MJEnvironmentEntityExtended, ArtifactMetadataEngine, ConversationEngine, ExtractBase64FromDataUrl, DecideInlineStorage } from '@memberjunction/core-entities';
|
|
23
|
+
import { MJEnvironmentEntityExtended, ArtifactMetadataEngine, ArtifactPermissionEngine, ConversationEngine, ExtractBase64FromDataUrl, DecideInlineStorage } from '@memberjunction/core-entities';
|
|
23
24
|
import { ActionEngineServer } from '@memberjunction/actions';
|
|
25
|
+
import { UserCache } from '@memberjunction/generic-database-provider';
|
|
24
26
|
import { FileStorageEngine } from '@memberjunction/storage';
|
|
25
27
|
/**
|
|
26
28
|
* Choose the artifact a run should be represented by.
|
|
@@ -56,8 +58,8 @@ export function HandoffBriefMessage(sourceName, brief, reason) {
|
|
|
56
58
|
* AgentRunner provides a thin wrapper for executing AI agents.
|
|
57
59
|
*
|
|
58
60
|
* This class handles:
|
|
59
|
-
* -
|
|
60
|
-
* - Instantiating the
|
|
61
|
+
* - Checking the agent's type exists
|
|
62
|
+
* - Instantiating the agent's own class (CreateAgentInstance)
|
|
61
63
|
* - Passing through to the agent's Execute method
|
|
62
64
|
*
|
|
63
65
|
* @class AgentRunner
|
|
@@ -125,8 +127,8 @@ export class AgentRunner {
|
|
|
125
127
|
* Runs an AI agent with the specified parameters.
|
|
126
128
|
*
|
|
127
129
|
* This method acts as a thin pass-through that:
|
|
128
|
-
* 1.
|
|
129
|
-
* 2.
|
|
130
|
+
* 1. Checks the agent's type exists
|
|
131
|
+
* 2. Instantiates the agent's own class via CreateAgentInstance
|
|
130
132
|
* 3. Calls Execute on the agent instance and returns the result
|
|
131
133
|
*
|
|
132
134
|
* @param {ExecuteAgentParams} params - Parameters for agent execution (same as BaseAgent.Execute)
|
|
@@ -145,22 +147,19 @@ export class AgentRunner {
|
|
|
145
147
|
});
|
|
146
148
|
// Ensure AIEngine is configured
|
|
147
149
|
await AIEngine.Instance.Config(false, params.contextUser);
|
|
148
|
-
//
|
|
150
|
+
// The agent must have a known type
|
|
149
151
|
const agentType = AIEngine.Instance.AgentTypes.find(at => UUIDsEqual(at.ID, params.agent.TypeID));
|
|
150
152
|
if (!agentType) {
|
|
151
153
|
throw new Error(`Agent type not found for ID: ${params.agent.TypeID}`);
|
|
152
154
|
}
|
|
153
|
-
//
|
|
154
|
-
|
|
155
|
+
// The agent's own DriverClass, or the plain BaseAgent when it declares none. Never the
|
|
156
|
+
// agent type's DriverClass (a BaseAgentType key), and an unregistered key throws (#4112).
|
|
155
157
|
LogStatusEx({
|
|
156
|
-
message: `AgentRunner: Using driver class: ${
|
|
158
|
+
message: `AgentRunner: Using driver class: ${params.agent.DriverClass?.trim() || 'BaseAgent'}`,
|
|
157
159
|
verboseOnly: true,
|
|
158
160
|
isVerboseEnabled: () => params.verbose === true || IsVerboseLoggingEnabled()
|
|
159
161
|
});
|
|
160
|
-
const agentInstance =
|
|
161
|
-
if (!agentInstance) {
|
|
162
|
-
throw new Error(`Failed to create agent instance for driver class: ${driverClass}`);
|
|
163
|
-
}
|
|
162
|
+
const agentInstance = await CreateAgentInstance(params.agent);
|
|
164
163
|
// Ensure caller params carries the shared AgentTreeBudget reference before any shallow
|
|
165
164
|
// clone occurs in hydrateConversationArtifacts or Execute.
|
|
166
165
|
if (!params.treeBudget) {
|
|
@@ -424,6 +423,9 @@ export class AgentRunner {
|
|
|
424
423
|
const detail = agentResponseDetail;
|
|
425
424
|
const message = progress.message;
|
|
426
425
|
progressSaves = progressSaves.then(async () => {
|
|
426
|
+
if (agentExecutionCompleted) {
|
|
427
|
+
return;
|
|
428
|
+
}
|
|
427
429
|
try {
|
|
428
430
|
detail.Message = message;
|
|
429
431
|
if (!(await detail.Save())) {
|
|
@@ -435,12 +437,13 @@ export class AgentRunner {
|
|
|
435
437
|
LogError(`Failed to save agent response detail progress update: ${error}`, undefined, error);
|
|
436
438
|
}
|
|
437
439
|
});
|
|
438
|
-
await progressSaves;
|
|
439
440
|
}
|
|
440
|
-
// Call original callback if provided
|
|
441
|
+
// Call original callback immediately if provided so WebSocket progress is emitted without waiting on DB save
|
|
441
442
|
if (originalOnProgress) {
|
|
442
443
|
await originalOnProgress(progress);
|
|
443
444
|
}
|
|
445
|
+
// Wait for in-flight progress saves to settle so callers that await onProgress still wait for the save
|
|
446
|
+
await progressSaves;
|
|
444
447
|
}
|
|
445
448
|
: originalOnProgress;
|
|
446
449
|
// The run reads the branch the caller named, else the branch its reply row carries. Undefined is Main.
|
|
@@ -453,7 +456,7 @@ export class AgentRunner {
|
|
|
453
456
|
// Brand-new conversations created right above have zero prior artifacts, so skip the 3 DB queries.
|
|
454
457
|
const inputArtifacts = isNewConversation
|
|
455
458
|
? []
|
|
456
|
-
: await this.gatherConversationArtifacts(conversationId, contextUser, params.ConversationHistoryFrom, runBranchId);
|
|
459
|
+
: await this.gatherConversationArtifacts(conversationId, contextUser, params.ConversationHistoryFrom, runBranchId, params.provider);
|
|
457
460
|
const modifiedParams = {
|
|
458
461
|
...params,
|
|
459
462
|
// First-class conversationId gates the cross-turn context features
|
|
@@ -568,6 +571,63 @@ export class AgentRunner {
|
|
|
568
571
|
}
|
|
569
572
|
return [];
|
|
570
573
|
};
|
|
574
|
+
// Step 6c: Link any governed collaborative artifacts touched/created mid-run
|
|
575
|
+
// (Docs, Sheets, Slides created via workspace tools or CoreActions) so the
|
|
576
|
+
// conversation message shows artifact cards even when `payload` is empty.
|
|
577
|
+
const processTouchedArtifacts = async () => {
|
|
578
|
+
if (suppressArtifacts || !agentResult.success || !agentResponseDetailId || !agentResult.touchedArtifacts?.length) {
|
|
579
|
+
return [];
|
|
580
|
+
}
|
|
581
|
+
const rv = RunView.FromMetadataProvider(md);
|
|
582
|
+
const existingLinksRes = await rv.RunView({
|
|
583
|
+
EntityName: 'MJ: Conversation Detail Artifacts',
|
|
584
|
+
ExtraFilter: `ConversationDetailID='${EscapeSQLString(agentResponseDetailId)}'`,
|
|
585
|
+
Fields: ['ArtifactVersionID'],
|
|
586
|
+
MaxRows: 100,
|
|
587
|
+
SkipTotalRowCount: true,
|
|
588
|
+
ResultType: 'simple'
|
|
589
|
+
}, contextUser);
|
|
590
|
+
const linkedVersionIds = new Set((existingLinksRes.Success && existingLinksRes.Results ? existingLinksRes.Results : [])
|
|
591
|
+
.map(r => (r.ArtifactVersionID ?? '').trim().toLowerCase())
|
|
592
|
+
.filter(Boolean));
|
|
593
|
+
const linked = [];
|
|
594
|
+
for (const touched of agentResult.touchedArtifacts) {
|
|
595
|
+
let versionId = (touched.ArtifactVersionID ?? '').trim();
|
|
596
|
+
let versionNumber = touched.VersionNumber ?? 1;
|
|
597
|
+
if (!versionId) {
|
|
598
|
+
const latestVer = await rv.RunView({
|
|
599
|
+
EntityName: 'MJ: Artifact Versions',
|
|
600
|
+
ExtraFilter: `ArtifactID='${EscapeSQLString(touched.ArtifactID)}'`,
|
|
601
|
+
OrderBy: 'VersionNumber DESC',
|
|
602
|
+
Fields: ['ID', 'VersionNumber'],
|
|
603
|
+
MaxRows: 1,
|
|
604
|
+
SkipTotalRowCount: true,
|
|
605
|
+
ResultType: 'simple'
|
|
606
|
+
}, contextUser);
|
|
607
|
+
if (latestVer.Success && latestVer.Results?.length) {
|
|
608
|
+
versionId = latestVer.Results[0].ID;
|
|
609
|
+
versionNumber = latestVer.Results[0].VersionNumber ?? versionNumber;
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
if (!versionId)
|
|
613
|
+
continue;
|
|
614
|
+
if (!linkedVersionIds.has(versionId.toLowerCase())) {
|
|
615
|
+
const junction = await md.GetEntityObject('MJ: Conversation Detail Artifacts', contextUser);
|
|
616
|
+
junction.ConversationDetailID = agentResponseDetailId;
|
|
617
|
+
junction.ArtifactVersionID = versionId;
|
|
618
|
+
junction.Direction = 'Output';
|
|
619
|
+
if (await junction.Save()) {
|
|
620
|
+
linkedVersionIds.add(versionId.toLowerCase());
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
linked.push({
|
|
624
|
+
artifactId: touched.ArtifactID,
|
|
625
|
+
versionId,
|
|
626
|
+
versionNumber
|
|
627
|
+
});
|
|
628
|
+
}
|
|
629
|
+
return linked;
|
|
630
|
+
};
|
|
571
631
|
// Step 7: Save media outputs to AIAgentRunMedia (audit) and create artifacts (display)
|
|
572
632
|
const saveMedia = async () => {
|
|
573
633
|
if (agentResult.mediaOutputs && agentResult.mediaOutputs.length > 0) {
|
|
@@ -650,18 +710,17 @@ export class AgentRunner {
|
|
|
650
710
|
else {
|
|
651
711
|
await runDespiteFailedReply('Step 6 (payload artifacts)', processArtifacts);
|
|
652
712
|
await runDespiteFailedReply('Step 6b (file artifacts)', processFileArtifacts);
|
|
713
|
+
await runDespiteFailedReply('Step 6c (touched workspace artifacts)', processTouchedArtifacts);
|
|
653
714
|
await runDespiteFailedReply('Step 7 (media)', saveMedia);
|
|
654
715
|
}
|
|
655
716
|
throw replySaveError;
|
|
656
717
|
}
|
|
657
718
|
const payloadArtifact = await processArtifacts();
|
|
658
719
|
const fileArtifacts = await processFileArtifacts();
|
|
720
|
+
const touchedArtifacts = await processTouchedArtifacts();
|
|
659
721
|
await saveMedia();
|
|
660
|
-
// A file
|
|
661
|
-
|
|
662
|
-
// (a report agent) and misleading when it is not — a document run reported the
|
|
663
|
-
// payload, so "open the artifact" opened raw JSON instead of the document.
|
|
664
|
-
const artifactInfo = SelectPrimaryArtifact(fileArtifacts, payloadArtifact);
|
|
722
|
+
// A file or workspace-touched collaborative artifact wins over raw JSON payload state.
|
|
723
|
+
const artifactInfo = SelectPrimaryArtifact([...fileArtifacts, ...touchedArtifacts], payloadArtifact);
|
|
665
724
|
return {
|
|
666
725
|
agentResult,
|
|
667
726
|
conversationId,
|
|
@@ -1241,7 +1300,16 @@ export class AgentRunner {
|
|
|
1241
1300
|
const junction = result.Results[0];
|
|
1242
1301
|
const md = provider || this._provider;
|
|
1243
1302
|
const version = await md.GetEntityObject('MJ: Artifact Versions', contextUser);
|
|
1244
|
-
|
|
1303
|
+
let loaded = false;
|
|
1304
|
+
try {
|
|
1305
|
+
loaded = await version.Load(junction.ArtifactVersionID);
|
|
1306
|
+
}
|
|
1307
|
+
catch (loadError) {
|
|
1308
|
+
LogStatus(`Previous artifact version ${junction.ArtifactVersionID} is not accessible to user ${contextUser.ID} (${loadError?.message ?? 'access denied'}) — falling back to create-new`);
|
|
1309
|
+
return null;
|
|
1310
|
+
}
|
|
1311
|
+
if (!loaded) {
|
|
1312
|
+
LogStatus(`Previous artifact version ${junction.ArtifactVersionID} could not be loaded for user ${contextUser.ID} — falling back to create-new`);
|
|
1245
1313
|
return null;
|
|
1246
1314
|
}
|
|
1247
1315
|
return {
|
|
@@ -1382,6 +1450,19 @@ export class AgentRunner {
|
|
|
1382
1450
|
LogStatus(`Skipping artifact creation - agent "${agent?.Name}" suppressed artifacts for this step`);
|
|
1383
1451
|
return undefined;
|
|
1384
1452
|
}
|
|
1453
|
+
// Governed collaborative artifacts created/mutated mid-run via ArtifactToolManager or
|
|
1454
|
+
// GovernedArtifactService already persisted their authoritative MJ: Artifact Versions row.
|
|
1455
|
+
// Never overwrite those artifacts with JSON.stringify(agentResult.payload), and do not emit
|
|
1456
|
+
// a legacy payload artifact when the run's deliverable was produced via artifact tools without
|
|
1457
|
+
// an explicit create-new directive.
|
|
1458
|
+
const touchedArtifactIds = new Set((agentResult.touchedArtifacts ?? [])
|
|
1459
|
+
.map((item) => (item.ArtifactID ?? '').trim().toLowerCase())
|
|
1460
|
+
.filter(Boolean));
|
|
1461
|
+
if (plan.kind === 'legacy' && touchedArtifactIds.size > 0) {
|
|
1462
|
+
LogStatus(`Skipping legacy payload artifact creation for agent "${agent?.Name}" - ` +
|
|
1463
|
+
`${touchedArtifactIds.size} governed artifact(s) already persisted via artifact tools`);
|
|
1464
|
+
return undefined;
|
|
1465
|
+
}
|
|
1385
1466
|
// Vet whatever artifact we are about to version, then walk DOWN the fallback ladder on
|
|
1386
1467
|
// failure: a directive-named target degrades to the caller's sourceArtifactId, and a bad
|
|
1387
1468
|
// sourceArtifactId degrades to the historical chain. Each rung is re-vetted, so a value
|
|
@@ -1389,19 +1470,40 @@ export class AgentRunner {
|
|
|
1389
1470
|
// source id back as its target used to do exactly that: rejected as model output, then
|
|
1390
1471
|
// versioned anyway as a caller id, logged as both "not readable" and "creating version N").
|
|
1391
1472
|
const rejectedIds = new Set();
|
|
1473
|
+
const rejectedCandidateIds = [];
|
|
1392
1474
|
while (plan.kind === 'version') {
|
|
1475
|
+
const candidateId = typeof plan.artifactId === 'string' && IsValidUUID(plan.artifactId)
|
|
1476
|
+
? plan.artifactId.trim()
|
|
1477
|
+
: undefined;
|
|
1478
|
+
if (candidateId && touchedArtifactIds.has(candidateId.toLowerCase())) {
|
|
1479
|
+
LogStatus(`Skipping payload artifact version for ${candidateId} - ` +
|
|
1480
|
+
`artifact was already persisted via governed artifact tools in this run`);
|
|
1481
|
+
return undefined;
|
|
1482
|
+
}
|
|
1393
1483
|
const vetted = await this.VetArtifactVersionTarget(plan, contextUser, md, agent?.Name, rejectedIds);
|
|
1394
1484
|
if (vetted) {
|
|
1395
1485
|
plan = vetted;
|
|
1396
1486
|
break;
|
|
1397
1487
|
}
|
|
1488
|
+
if (candidateId) {
|
|
1489
|
+
rejectedCandidateIds.push(candidateId);
|
|
1490
|
+
}
|
|
1398
1491
|
plan = plan.source === 'directive'
|
|
1399
1492
|
? PlanArtifactTarget(undefined, sourceArtifactId) // drop the directive, keep the caller's id
|
|
1400
1493
|
: { kind: 'legacy' }; // the caller's own id failed; nothing left to try
|
|
1401
1494
|
}
|
|
1495
|
+
if (plan.kind === 'legacy' && touchedArtifactIds.size > 0) {
|
|
1496
|
+
LogStatus(`Skipping legacy payload artifact creation for agent "${agent?.Name}" - ` +
|
|
1497
|
+
`${touchedArtifactIds.size} governed artifact(s) already persisted via artifact tools`);
|
|
1498
|
+
return undefined;
|
|
1499
|
+
}
|
|
1402
1500
|
let artifactId;
|
|
1403
1501
|
let newVersionNumber;
|
|
1404
1502
|
let isNewArtifact = false;
|
|
1503
|
+
let forkedSourceArtifactId;
|
|
1504
|
+
let forkCommentNote;
|
|
1505
|
+
// Known for a new header; looked up for an existing artifact when the version is built.
|
|
1506
|
+
let artifactTypeId = null;
|
|
1405
1507
|
if (plan.kind === 'version') {
|
|
1406
1508
|
const maxVersion = await this.GetMaxVersionForArtifact(plan.artifactId, contextUser, provider);
|
|
1407
1509
|
artifactId = plan.artifactId;
|
|
@@ -1410,20 +1512,75 @@ export class AgentRunner {
|
|
|
1410
1512
|
}
|
|
1411
1513
|
else {
|
|
1412
1514
|
// Legacy: look behind this message (only inside a conversation). 'create-new' skips the lookup.
|
|
1413
|
-
|
|
1515
|
+
let previousArtifact = (plan.kind === 'legacy' && conversationDetailId)
|
|
1414
1516
|
? await this.FindPreviousArtifactForMessage(conversationDetailId, contextUser, md)
|
|
1415
1517
|
: null;
|
|
1416
1518
|
if (previousArtifact) {
|
|
1519
|
+
const prevCandidateId = IsValidUUID(previousArtifact.artifactId)
|
|
1520
|
+
? previousArtifact.artifactId.trim()
|
|
1521
|
+
: undefined;
|
|
1522
|
+
const vettedPrevious = await this.VetArtifactVersionTarget({ kind: 'version', artifactId: previousArtifact.artifactId, source: 'caller' }, contextUser, md, agent?.Name, rejectedIds, 'legacy previousArtifact');
|
|
1523
|
+
if (!vettedPrevious) {
|
|
1524
|
+
if (prevCandidateId) {
|
|
1525
|
+
rejectedCandidateIds.push(prevCandidateId);
|
|
1526
|
+
}
|
|
1527
|
+
LogStatus(`Previous artifact ${previousArtifact.artifactId} is not editable by user ${contextUser.ID} — falling back to create-new`);
|
|
1528
|
+
previousArtifact = null;
|
|
1529
|
+
}
|
|
1530
|
+
else {
|
|
1531
|
+
previousArtifact = {
|
|
1532
|
+
artifactId: vettedPrevious.artifactId,
|
|
1533
|
+
versionNumber: previousArtifact.versionNumber
|
|
1534
|
+
};
|
|
1535
|
+
}
|
|
1536
|
+
}
|
|
1537
|
+
if (previousArtifact) {
|
|
1538
|
+
if (touchedArtifactIds.has(previousArtifact.artifactId.trim().toLowerCase())) {
|
|
1539
|
+
LogStatus(`Skipping payload artifact version for ${previousArtifact.artifactId} - ` +
|
|
1540
|
+
`artifact was already persisted via governed artifact tools in this run`);
|
|
1541
|
+
return undefined;
|
|
1542
|
+
}
|
|
1417
1543
|
artifactId = previousArtifact.artifactId;
|
|
1418
1544
|
newVersionNumber = previousArtifact.versionNumber + 1;
|
|
1419
1545
|
LogStatus(`Creating version ${newVersionNumber} of existing artifact ${artifactId}`);
|
|
1420
1546
|
}
|
|
1421
1547
|
else {
|
|
1422
|
-
|
|
1548
|
+
if (plan.kind !== 'create-new') {
|
|
1549
|
+
const normalizedCallerSource = typeof sourceArtifactId === 'string' && IsValidUUID(sourceArtifactId)
|
|
1550
|
+
? sourceArtifactId.trim()
|
|
1551
|
+
: undefined;
|
|
1552
|
+
forkedSourceArtifactId =
|
|
1553
|
+
normalizedCallerSource && rejectedIds.has(normalizedCallerSource.toLowerCase())
|
|
1554
|
+
? normalizedCallerSource
|
|
1555
|
+
: rejectedCandidateIds[0];
|
|
1556
|
+
if (forkedSourceArtifactId) {
|
|
1557
|
+
const callerDisplayName = contextUser.Name?.trim() || contextUser.Email?.trim() || 'current user';
|
|
1558
|
+
forkCommentNote =
|
|
1559
|
+
`Forked new artifact from ${forkedSourceArtifactId} because edit access was not granted on the source artifact for user ${callerDisplayName}.`;
|
|
1560
|
+
}
|
|
1561
|
+
}
|
|
1562
|
+
const artifact = await this.createArtifactHeader(md, contextUser, agent, creationMode, directive, payload, forkCommentNote);
|
|
1423
1563
|
artifactId = artifact.ID;
|
|
1564
|
+
artifactTypeId = artifact.TypeID;
|
|
1424
1565
|
newVersionNumber = 1;
|
|
1425
1566
|
isNewArtifact = true;
|
|
1426
1567
|
LogStatus(`Created new artifact: ${artifact.Name} (${artifactId})${plan.kind === 'create-new' ? ' per agent directive' : ''}`);
|
|
1568
|
+
if (forkedSourceArtifactId) {
|
|
1569
|
+
const failedGrantRecipients = await this.grantForkedArtifactReadPermissions(md, artifactId, forkedSourceArtifactId, conversationDetailId, contextUser);
|
|
1570
|
+
if (failedGrantRecipients.length > 0) {
|
|
1571
|
+
const warningNote = `Warning: read access could not be automatically granted to conversation participant(s): ${failedGrantRecipients.join(', ')}.`;
|
|
1572
|
+
forkCommentNote = forkCommentNote
|
|
1573
|
+
? `${forkCommentNote} ${warningNote}`
|
|
1574
|
+
: warningNote;
|
|
1575
|
+
artifact.Comments = forkCommentNote;
|
|
1576
|
+
const savedWarning = await artifact.Save();
|
|
1577
|
+
if (!savedWarning) {
|
|
1578
|
+
LogError(`Failed to save fork permission warning comment on artifact ${artifact.ID}: ${artifact.LatestResult?.CompleteMessage ||
|
|
1579
|
+
artifact.LatestResult?.Message ||
|
|
1580
|
+
'Save() returned false'}`);
|
|
1581
|
+
}
|
|
1582
|
+
}
|
|
1583
|
+
}
|
|
1427
1584
|
}
|
|
1428
1585
|
}
|
|
1429
1586
|
// Serialize the payload once — used for both dedup check and version creation
|
|
@@ -1447,6 +1604,9 @@ export class AgentRunner {
|
|
|
1447
1604
|
version.VersionNumber = newVersionNumber;
|
|
1448
1605
|
version.Content = serializedContent;
|
|
1449
1606
|
version.UserID = contextUser.ID;
|
|
1607
|
+
// Preview plugins match on the version's MIME type; without it their contentType arm never
|
|
1608
|
+
// fires for payload artifacts (#4597).
|
|
1609
|
+
version.MimeType = await this.ResolvePayloadVersionMimeType(artifactTypeId ?? await this.GetArtifactTypeIDForArtifact(artifactId, contextUser, provider), contextUser);
|
|
1450
1610
|
const directiveName = AgentRunner.safeDirectiveText(directive?.name, AgentRunner.ARTIFACT_NAME_MAX_LENGTH);
|
|
1451
1611
|
const directiveDescription = AgentRunner.safeDirectiveText(directive?.description);
|
|
1452
1612
|
const payloadRecord = (typeof payload === 'object' && payload !== null && !Array.isArray(payload))
|
|
@@ -1466,6 +1626,9 @@ export class AgentRunner {
|
|
|
1466
1626
|
if (directiveDescription || payloadDescription) {
|
|
1467
1627
|
version.Description = directiveDescription || payloadDescription || null;
|
|
1468
1628
|
}
|
|
1629
|
+
if (forkCommentNote) {
|
|
1630
|
+
version.Comments = forkCommentNote;
|
|
1631
|
+
}
|
|
1469
1632
|
if (!(await version.Save())) {
|
|
1470
1633
|
throw new Error('Failed to save artifact version');
|
|
1471
1634
|
}
|
|
@@ -1649,8 +1812,9 @@ export class AgentRunner {
|
|
|
1649
1812
|
* the same id cannot be re-admitted further down the ladder.
|
|
1650
1813
|
* @returns The vetted plan with a trimmed id, or `null` to fall back.
|
|
1651
1814
|
*/
|
|
1652
|
-
async VetArtifactVersionTarget(plan, contextUser, md, agentName, rejectedIds) {
|
|
1653
|
-
const origin =
|
|
1815
|
+
async VetArtifactVersionTarget(plan, contextUser, md, agentName, rejectedIds, originLabel) {
|
|
1816
|
+
const origin = originLabel
|
|
1817
|
+
?? (plan.source === 'directive' ? `artifact directive from agent "${agentName}"` : 'sourceArtifactId');
|
|
1654
1818
|
if (typeof plan.artifactId !== 'string' || !IsValidUUID(plan.artifactId)) {
|
|
1655
1819
|
LogError(`Ignoring ${origin}: "${AgentRunner.describeUntrustedValue(plan.artifactId)}" is not a valid artifact ID`);
|
|
1656
1820
|
return null;
|
|
@@ -1660,57 +1824,245 @@ export class AgentRunner {
|
|
|
1660
1824
|
LogError(`Ignoring ${origin}: artifact ${artifactId} was already rejected for this run`);
|
|
1661
1825
|
return null;
|
|
1662
1826
|
}
|
|
1663
|
-
if (plan.source !== 'directive') {
|
|
1664
|
-
return { ...plan, artifactId };
|
|
1665
|
-
}
|
|
1666
1827
|
const reject = (reason) => {
|
|
1667
1828
|
rejectedIds.add(artifactId.toLowerCase());
|
|
1668
|
-
LogError(`Ignoring ${origin}: target artifact ${artifactId} ${reason}`);
|
|
1829
|
+
LogError(`Ignoring ${origin}: target artifact ${artifactId} ${reason} — falling back to create-new`);
|
|
1669
1830
|
return null;
|
|
1670
1831
|
};
|
|
1832
|
+
try {
|
|
1833
|
+
const perms = await ArtifactPermissionEngine.Instance.ResolvePermissions(md, artifactId, contextUser);
|
|
1834
|
+
if (perms.CanEdit) {
|
|
1835
|
+
return { ...plan, artifactId };
|
|
1836
|
+
}
|
|
1837
|
+
const reasonDetail = perms.Reason
|
|
1838
|
+
? `user holds no CanEdit grant on it (${perms.Reason})`
|
|
1839
|
+
: 'user holds no CanEdit grant on it';
|
|
1840
|
+
return reject(reasonDetail);
|
|
1841
|
+
}
|
|
1842
|
+
catch (error) {
|
|
1843
|
+
// Fail closed: an unavailable lookup must not become an unchecked write.
|
|
1844
|
+
return reject(`could not be verified (${error?.message ?? 'unknown error'})`);
|
|
1845
|
+
}
|
|
1846
|
+
}
|
|
1847
|
+
/**
|
|
1848
|
+
* Grants explicit `CanRead = true` on a newly forked artifact to the original source
|
|
1849
|
+
* artifact's owner, the conversation's owner, and every distinct conversation participant (`D3`).
|
|
1850
|
+
* Returns human-readable display names for any recipients whose grant could not be persisted
|
|
1851
|
+
* (never raw user GUIDs).
|
|
1852
|
+
*/
|
|
1853
|
+
async grantForkedArtifactReadPermissions(md, newArtifactId, sourceArtifactId, conversationDetailId, contextUser) {
|
|
1854
|
+
const failedRecipients = [];
|
|
1855
|
+
const recipientByNormId = new Map();
|
|
1856
|
+
const displayNameByNormId = new Map();
|
|
1671
1857
|
try {
|
|
1672
1858
|
const rv = RunView.FromMetadataProvider(md);
|
|
1673
|
-
|
|
1674
|
-
|
|
1675
|
-
{
|
|
1676
|
-
|
|
1677
|
-
|
|
1678
|
-
|
|
1679
|
-
|
|
1680
|
-
|
|
1681
|
-
|
|
1682
|
-
|
|
1683
|
-
{
|
|
1684
|
-
|
|
1685
|
-
|
|
1686
|
-
|
|
1859
|
+
const addRecipient = (candidateUserId, candidateDisplayName) => {
|
|
1860
|
+
const trimmed = (candidateUserId ?? '').trim();
|
|
1861
|
+
if (!trimmed || UUIDsEqual(trimmed, contextUser.ID)) {
|
|
1862
|
+
return;
|
|
1863
|
+
}
|
|
1864
|
+
const norm = NormalizeUUID(trimmed);
|
|
1865
|
+
if (!recipientByNormId.has(norm)) {
|
|
1866
|
+
recipientByNormId.set(norm, trimmed);
|
|
1867
|
+
}
|
|
1868
|
+
const cleanDisplay = (candidateDisplayName ?? '').trim();
|
|
1869
|
+
if (cleanDisplay && !displayNameByNormId.has(norm)) {
|
|
1870
|
+
displayNameByNormId.set(norm, cleanDisplay);
|
|
1871
|
+
}
|
|
1872
|
+
};
|
|
1873
|
+
const sourceArtRes = await rv.RunView({
|
|
1874
|
+
EntityName: 'MJ: Artifacts',
|
|
1875
|
+
ExtraFilter: `ID='${EscapeSQLString(sourceArtifactId)}'`,
|
|
1876
|
+
Fields: ['ID', 'UserID', 'User'],
|
|
1877
|
+
MaxRows: 1,
|
|
1878
|
+
SkipTotalRowCount: true,
|
|
1879
|
+
ResultType: 'simple'
|
|
1880
|
+
}, contextUser);
|
|
1881
|
+
if (sourceArtRes.Success && sourceArtRes.Results?.length) {
|
|
1882
|
+
addRecipient(sourceArtRes.Results[0].UserID, sourceArtRes.Results[0].User);
|
|
1883
|
+
}
|
|
1884
|
+
if (conversationDetailId && IsValidUUID(conversationDetailId)) {
|
|
1885
|
+
const detailRes = await rv.RunView({
|
|
1886
|
+
EntityName: 'MJ: Conversation Details',
|
|
1887
|
+
ExtraFilter: `ID='${EscapeSQLString(conversationDetailId.trim())}'`,
|
|
1888
|
+
Fields: ['ID', 'ConversationID'],
|
|
1687
1889
|
MaxRows: 1,
|
|
1688
1890
|
SkipTotalRowCount: true,
|
|
1689
|
-
ResultType: 'simple'
|
|
1690
|
-
},
|
|
1691
|
-
|
|
1692
|
-
|
|
1693
|
-
|
|
1694
|
-
|
|
1891
|
+
ResultType: 'simple'
|
|
1892
|
+
}, contextUser);
|
|
1893
|
+
const convId = detailRes.Success ? detailRes.Results?.[0]?.ConversationID?.trim() : undefined;
|
|
1894
|
+
if (convId && IsValidUUID(convId)) {
|
|
1895
|
+
const safeConvId = EscapeSQLString(convId);
|
|
1896
|
+
const participantPageSize = 500;
|
|
1897
|
+
const maxParticipantPages = 100;
|
|
1898
|
+
const fetchAllParticipantRows = async () => {
|
|
1899
|
+
const collected = [];
|
|
1900
|
+
let startRow = 0;
|
|
1901
|
+
for (let page = 0; page < maxParticipantPages; page++) {
|
|
1902
|
+
const pageRes = await rv.RunView({
|
|
1903
|
+
EntityName: 'MJ: Conversation Details',
|
|
1904
|
+
ExtraFilter: `ConversationID='${safeConvId}' AND UserID IS NOT NULL`,
|
|
1905
|
+
Fields: ['UserID', 'User'],
|
|
1906
|
+
OrderBy: '__mj_CreatedAt ASC, ID ASC',
|
|
1907
|
+
MaxRows: participantPageSize,
|
|
1908
|
+
StartRow: startRow,
|
|
1909
|
+
SkipTotalRowCount: true,
|
|
1910
|
+
ResultType: 'simple'
|
|
1911
|
+
}, contextUser);
|
|
1912
|
+
if (!pageRes.Success) {
|
|
1913
|
+
LogError(`Failed to query conversation participants for forked artifact ${newArtifactId} (conversation ${convId}): ${pageRes.ErrorMessage || 'RunView returned Success=false'}`);
|
|
1914
|
+
break;
|
|
1915
|
+
}
|
|
1916
|
+
const rows = Array.isArray(pageRes.Results) ? pageRes.Results : [];
|
|
1917
|
+
collected.push(...rows);
|
|
1918
|
+
if (rows.length < participantPageSize) {
|
|
1919
|
+
break;
|
|
1920
|
+
}
|
|
1921
|
+
if (page === maxParticipantPages - 1 && rows.length === participantPageSize) {
|
|
1922
|
+
LogError(`Participant paging reached the ${maxParticipantPages}-page (${maxParticipantPages * participantPageSize}-row) safety cap for conversation ${convId} while sharing forked artifact ${newArtifactId}.`);
|
|
1923
|
+
}
|
|
1924
|
+
startRow += rows.length;
|
|
1925
|
+
}
|
|
1926
|
+
return collected;
|
|
1927
|
+
};
|
|
1928
|
+
const [convRes, participantRows] = await Promise.all([
|
|
1929
|
+
rv.RunView({
|
|
1930
|
+
EntityName: 'MJ: Conversations',
|
|
1931
|
+
ExtraFilter: `ID='${safeConvId}'`,
|
|
1932
|
+
Fields: ['ID', 'UserID', 'User'],
|
|
1933
|
+
MaxRows: 1,
|
|
1934
|
+
SkipTotalRowCount: true,
|
|
1935
|
+
ResultType: 'simple'
|
|
1936
|
+
}, contextUser),
|
|
1937
|
+
fetchAllParticipantRows()
|
|
1938
|
+
]);
|
|
1939
|
+
if (convRes.Success && convRes.Results?.length) {
|
|
1940
|
+
addRecipient(convRes.Results[0].UserID, convRes.Results[0].User);
|
|
1941
|
+
}
|
|
1942
|
+
for (const row of participantRows) {
|
|
1943
|
+
addRecipient(row.UserID, row.User);
|
|
1944
|
+
}
|
|
1945
|
+
}
|
|
1695
1946
|
}
|
|
1696
|
-
|
|
1697
|
-
|
|
1947
|
+
const userByNormId = new Map();
|
|
1948
|
+
const cachedUsers = UserCache.Instance.Users;
|
|
1949
|
+
if (Array.isArray(cachedUsers)) {
|
|
1950
|
+
for (const u of cachedUsers) {
|
|
1951
|
+
if (u?.ID) {
|
|
1952
|
+
userByNormId.set(NormalizeUUID(u.ID), u);
|
|
1953
|
+
}
|
|
1954
|
+
}
|
|
1698
1955
|
}
|
|
1699
|
-
|
|
1700
|
-
|
|
1956
|
+
const formatRecipientLabel = (normId) => {
|
|
1957
|
+
const u = userByNormId.get(normId);
|
|
1958
|
+
const fromUser = u?.Name?.trim() || u?.Email?.trim();
|
|
1959
|
+
if (fromUser) {
|
|
1960
|
+
return fromUser;
|
|
1961
|
+
}
|
|
1962
|
+
const fromRow = displayNameByNormId.get(normId);
|
|
1963
|
+
if (fromRow) {
|
|
1964
|
+
return fromRow;
|
|
1965
|
+
}
|
|
1966
|
+
return 'participant';
|
|
1967
|
+
};
|
|
1968
|
+
for (const [normId, recipientUserId] of recipientByNormId.entries()) {
|
|
1969
|
+
try {
|
|
1970
|
+
const perm = await md.GetEntityObject('MJ: Artifact Permissions', contextUser);
|
|
1971
|
+
perm.NewRecord();
|
|
1972
|
+
perm.ArtifactID = newArtifactId;
|
|
1973
|
+
perm.UserID = recipientUserId;
|
|
1974
|
+
perm.CanRead = true;
|
|
1975
|
+
perm.CanEdit = false;
|
|
1976
|
+
perm.CanDelete = false;
|
|
1977
|
+
perm.CanShare = false;
|
|
1978
|
+
perm.SharedByUserID = contextUser.ID;
|
|
1979
|
+
if (!(await perm.Save())) {
|
|
1980
|
+
failedRecipients.push(formatRecipientLabel(normId));
|
|
1981
|
+
LogError(`Failed to grant CanRead on forked artifact ${newArtifactId} to user ${recipientUserId}: ${perm.LatestResult?.CompleteMessage ||
|
|
1982
|
+
perm.LatestResult?.Message ||
|
|
1983
|
+
'Save() returned false'}`);
|
|
1984
|
+
}
|
|
1985
|
+
}
|
|
1986
|
+
catch (saveErr) {
|
|
1987
|
+
failedRecipients.push(formatRecipientLabel(normId));
|
|
1988
|
+
LogError(`Failed to grant CanRead on forked artifact ${newArtifactId} to user ${recipientUserId}: ${saveErr instanceof Error ? saveErr.message : String(saveErr)}`);
|
|
1989
|
+
}
|
|
1701
1990
|
}
|
|
1702
|
-
|
|
1991
|
+
}
|
|
1992
|
+
catch (err) {
|
|
1993
|
+
LogError(`Failed to grant read visibility on forked artifact ${newArtifactId}: ${err instanceof Error ? err.message : String(err)}`);
|
|
1994
|
+
}
|
|
1995
|
+
return failedRecipients;
|
|
1996
|
+
}
|
|
1997
|
+
/**
|
|
1998
|
+
* MIME type stamped on an agent payload version: its artifact type's `ContentType` when that is
|
|
1999
|
+
* concrete, `null` when it is empty or a wildcard (`image/*`, `text/*`), since a wildcard is not
|
|
2000
|
+
* a real MIME type.
|
|
2001
|
+
*
|
|
2002
|
+
* @param contentType - The artifact type's `ContentType`.
|
|
2003
|
+
* @returns The MIME type to store, or `null`.
|
|
2004
|
+
*/
|
|
2005
|
+
static PayloadVersionMimeType(contentType) {
|
|
2006
|
+
const trimmed = contentType?.trim();
|
|
2007
|
+
if (!trimmed || trimmed.includes('*')) {
|
|
2008
|
+
return null;
|
|
2009
|
+
}
|
|
2010
|
+
return trimmed;
|
|
2011
|
+
}
|
|
2012
|
+
/**
|
|
2013
|
+
* Resolves the MIME type for a payload version from its artifact type (see
|
|
2014
|
+
* {@link PayloadVersionMimeType}). Never throws: a lookup failure leaves the MIME type empty
|
|
2015
|
+
* rather than failing the artifact.
|
|
2016
|
+
*
|
|
2017
|
+
* @param artifactTypeId - The artifact's `TypeID`, or `null` when unknown.
|
|
2018
|
+
* @param contextUser - User the run executes as.
|
|
2019
|
+
* @returns The MIME type to store, or `null`.
|
|
2020
|
+
*/
|
|
2021
|
+
async ResolvePayloadVersionMimeType(artifactTypeId, contextUser) {
|
|
2022
|
+
if (!artifactTypeId) {
|
|
2023
|
+
return null;
|
|
2024
|
+
}
|
|
2025
|
+
try {
|
|
2026
|
+
await ArtifactMetadataEngine.Instance.Config(false, contextUser);
|
|
2027
|
+
const artifactType = ArtifactMetadataEngine.Instance.ArtifactTypes.find(t => UUIDsEqual(t.ID, artifactTypeId));
|
|
2028
|
+
return AgentRunner.PayloadVersionMimeType(artifactType?.ContentType);
|
|
1703
2029
|
}
|
|
1704
2030
|
catch (error) {
|
|
1705
|
-
|
|
1706
|
-
return
|
|
2031
|
+
LogError(`Could not resolve artifact type ${artifactTypeId} for payload version MIME type: ${error?.message ?? 'unknown error'}`);
|
|
2032
|
+
return null;
|
|
2033
|
+
}
|
|
2034
|
+
}
|
|
2035
|
+
/**
|
|
2036
|
+
* Reads an existing artifact's `TypeID`. Never throws.
|
|
2037
|
+
*
|
|
2038
|
+
* @param artifactId - The artifact being versioned.
|
|
2039
|
+
* @param contextUser - User the run executes as.
|
|
2040
|
+
* @param provider - Optional provider for the lookup.
|
|
2041
|
+
* @returns The type id, or `null` when the artifact cannot be read.
|
|
2042
|
+
*/
|
|
2043
|
+
async GetArtifactTypeIDForArtifact(artifactId, contextUser, provider) {
|
|
2044
|
+
try {
|
|
2045
|
+
const rv = RunView.FromMetadataProvider(provider || this._provider);
|
|
2046
|
+
const result = await rv.RunView({
|
|
2047
|
+
EntityName: 'MJ: Artifacts',
|
|
2048
|
+
ExtraFilter: `ID='${AgentRunner.filterId(artifactId, 'GetArtifactTypeIDForArtifact artifactId')}'`,
|
|
2049
|
+
Fields: ['TypeID'],
|
|
2050
|
+
MaxRows: 1,
|
|
2051
|
+
SkipTotalRowCount: true,
|
|
2052
|
+
ResultType: 'simple'
|
|
2053
|
+
}, contextUser);
|
|
2054
|
+
return result.Success ? (result.Results?.[0]?.TypeID ?? null) : null;
|
|
2055
|
+
}
|
|
2056
|
+
catch (error) {
|
|
2057
|
+
LogError(`Error reading artifact type for ${artifactId}: ${error?.message ?? 'unknown error'}`);
|
|
2058
|
+
return null;
|
|
1707
2059
|
}
|
|
1708
2060
|
}
|
|
1709
2061
|
/**
|
|
1710
2062
|
* Creates the artifact header row. Name and description come from the agent's directive when
|
|
1711
2063
|
* it supplied them (e.g. Skip's artifactRequest); otherwise the historical placeholder.
|
|
1712
2064
|
*/
|
|
1713
|
-
async createArtifactHeader(md, contextUser, agent, creationMode, directive, payload) {
|
|
2065
|
+
async createArtifactHeader(md, contextUser, agent, creationMode, directive, payload, comments) {
|
|
1714
2066
|
const artifact = await md.GetEntityObject('MJ: Artifacts', contextUser);
|
|
1715
2067
|
const agentName = agent?.Name || 'Agent';
|
|
1716
2068
|
// Both fields are model output: coerced, trimmed, and (for Name) clamped to its column so a
|
|
@@ -1741,6 +2093,9 @@ export class AgentRunner {
|
|
|
1741
2093
|
else {
|
|
1742
2094
|
artifact.Visibility = 'Always';
|
|
1743
2095
|
}
|
|
2096
|
+
if (comments) {
|
|
2097
|
+
artifact.Comments = comments;
|
|
2098
|
+
}
|
|
1744
2099
|
if (!(await artifact.Save())) {
|
|
1745
2100
|
// Surface WHY. A bare message here sent every cause — a validation failure on a
|
|
1746
2101
|
// model-supplied name, a permission denial, a transient DB fault — to the same
|
|
@@ -1841,7 +2196,7 @@ export class AgentRunner {
|
|
|
1841
2196
|
const md = provider || this._provider;
|
|
1842
2197
|
try {
|
|
1843
2198
|
try {
|
|
1844
|
-
await FileStorageEngine.Instance.Config(false, contextUser);
|
|
2199
|
+
await FileStorageEngine.Instance.Config(false, contextUser, md);
|
|
1845
2200
|
}
|
|
1846
2201
|
catch (configError) {
|
|
1847
2202
|
LogError(`SaveAgentRunMedia: failed to configure FileStorageEngine, falling back to inline: ${configError.message}`);
|
|
@@ -2003,11 +2358,11 @@ export class AgentRunner {
|
|
|
2003
2358
|
// until it has loaded, so checking HasStorageAccounts without configuring it first reads
|
|
2004
2359
|
// an empty cache and silently routes every media artifact inline — indistinguishable from
|
|
2005
2360
|
// a deployment that genuinely has no storage.
|
|
2361
|
+
const md = provider || this._provider;
|
|
2006
2362
|
await Promise.all([
|
|
2007
2363
|
ArtifactMetadataEngine.Instance.Config(false, contextUser),
|
|
2008
|
-
FileStorageEngine.Instance.Config(false, contextUser),
|
|
2364
|
+
FileStorageEngine.Instance.Config(false, contextUser, md),
|
|
2009
2365
|
]);
|
|
2010
|
-
const md = provider || this._provider;
|
|
2011
2366
|
let successCount = 0;
|
|
2012
2367
|
for (let i = 0; i < mediaOutputs.length; i++) {
|
|
2013
2368
|
const media = mediaOutputs[i];
|
|
@@ -2102,7 +2457,7 @@ export class AgentRunner {
|
|
|
2102
2457
|
// Hoist engine configs before parallel processing
|
|
2103
2458
|
await Promise.all([
|
|
2104
2459
|
ArtifactMetadataEngine.Instance.Config(false, contextUser),
|
|
2105
|
-
FileStorageEngine.Instance.Config(false, contextUser),
|
|
2460
|
+
FileStorageEngine.Instance.Config(false, contextUser, md),
|
|
2106
2461
|
]);
|
|
2107
2462
|
const created = await Promise.all(fileOutputs.map(fo => this.processFileOutput(fo, conversationDetailId, contextUser, resolvedStorageAccountId, md, acceptUnregistered)));
|
|
2108
2463
|
// Entries are undefined only for outputs whose creation failed (logged above), so the
|
|
@@ -2177,9 +2532,9 @@ export class AgentRunner {
|
|
|
2177
2532
|
// TransactionGroup. This ensures saves execute immediately within the SQL transaction,
|
|
2178
2533
|
// so server-side entity hooks (e.g. ArtifactVersion.ExtractAndSaveAttributes) can
|
|
2179
2534
|
// Load() parent records that were saved earlier in the same transaction.
|
|
2180
|
-
const dbProvider = provider;
|
|
2181
|
-
const useTransaction = dbProvider.ProviderType === ProviderType.Database;
|
|
2182
|
-
if (useTransaction) {
|
|
2535
|
+
const dbProvider = provider instanceof DatabaseProviderBase ? provider : undefined;
|
|
2536
|
+
const useTransaction = dbProvider != null && dbProvider.ProviderType === ProviderType.Database;
|
|
2537
|
+
if (useTransaction && dbProvider) {
|
|
2183
2538
|
await dbProvider.BeginTransaction();
|
|
2184
2539
|
}
|
|
2185
2540
|
try {
|
|
@@ -2364,7 +2719,7 @@ export class AgentRunner {
|
|
|
2364
2719
|
if (!conversationId) {
|
|
2365
2720
|
return params;
|
|
2366
2721
|
}
|
|
2367
|
-
const inputArtifacts = await this.gatherConversationArtifacts(conversationId, params.contextUser, params.ConversationHistoryFrom, params.ConversationBranchID);
|
|
2722
|
+
const inputArtifacts = await this.gatherConversationArtifacts(conversationId, params.contextUser, params.ConversationHistoryFrom, params.ConversationBranchID, params.provider);
|
|
2368
2723
|
return inputArtifacts.length > 0 ? { ...params, inputArtifacts } : params;
|
|
2369
2724
|
}
|
|
2370
2725
|
/**
|
|
@@ -2392,10 +2747,11 @@ export class AgentRunner {
|
|
|
2392
2747
|
* @param branchId The run's branch; only artifacts of messages on its path that no rerun
|
|
2393
2748
|
* replaced are gathered.
|
|
2394
2749
|
*/
|
|
2395
|
-
async gatherConversationArtifacts(conversationId, contextUser, historyFrom, branchId) {
|
|
2750
|
+
async gatherConversationArtifacts(conversationId, contextUser, historyFrom, branchId, provider) {
|
|
2396
2751
|
try {
|
|
2397
|
-
const
|
|
2398
|
-
const
|
|
2752
|
+
const effectiveProvider = provider ?? this._provider;
|
|
2753
|
+
const rv = RunView.FromMetadataProvider(effectiveProvider);
|
|
2754
|
+
const pathFilter = await ConversationEngine.BranchPathFilterFresh(conversationId, branchId, contextUser, effectiveProvider);
|
|
2399
2755
|
// Get the IDs of the live conversation details on the run's branch path (from its floor, if the run has one)
|
|
2400
2756
|
const details = await rv.RunView({
|
|
2401
2757
|
EntityName: 'MJ: Conversation Details',
|
|
@@ -2408,7 +2764,7 @@ export class AgentRunner {
|
|
|
2408
2764
|
if (!details.Success || details.Results.length === 0) {
|
|
2409
2765
|
return [];
|
|
2410
2766
|
}
|
|
2411
|
-
const detailIds = details.Results.map((d) => d.ID);
|
|
2767
|
+
const detailIds = details.Results.map((d) => EscapeSQLString(d.ID));
|
|
2412
2768
|
// Get all artifact junctions for these conversation details
|
|
2413
2769
|
const junctions = await rv.RunView({
|
|
2414
2770
|
EntityName: 'MJ: Conversation Detail Artifacts',
|
|
@@ -2432,32 +2788,262 @@ export class AgentRunner {
|
|
|
2432
2788
|
const inputArtifacts = [];
|
|
2433
2789
|
if (uniqueJunctions.length > 0) {
|
|
2434
2790
|
const versionIds = uniqueJunctions.map((j) => j.ArtifactVersionID);
|
|
2435
|
-
const rq = new RunQuery();
|
|
2791
|
+
const rq = effectiveProvider instanceof DatabaseProviderBase ? new RunQuery(effectiveProvider) : new RunQuery();
|
|
2436
2792
|
const versionResult = await rq.RunQuery({
|
|
2437
2793
|
QueryName: 'GetArtifactVersionsByID',
|
|
2438
2794
|
CategoryPath: '/MJ/AI/Agents/',
|
|
2439
2795
|
Parameters: { versionIds },
|
|
2440
2796
|
}, contextUser);
|
|
2797
|
+
const rawRows = versionResult.Success && Array.isArray(versionResult.Results)
|
|
2798
|
+
? [...versionResult.Results]
|
|
2799
|
+
: [];
|
|
2441
2800
|
if (!versionResult.Success) {
|
|
2442
2801
|
LogError(`[AgentRunner] GetArtifactVersionsByID failed: ${versionResult.ErrorMessage}`);
|
|
2443
2802
|
}
|
|
2444
|
-
|
|
2445
|
-
|
|
2803
|
+
// S12 / R2 companion: if GetArtifactVersionsByID failed OR excluded delegate-authorized
|
|
2804
|
+
// artifacts, fall back to RunView('MJ: Artifact Versions', contextUser) so delegate ACLs run cleanly.
|
|
2805
|
+
const hydrateArtifactVersionsViaRunView = async (targetVersionIds) => {
|
|
2806
|
+
const hydrated = [];
|
|
2807
|
+
if (!effectiveProvider || targetVersionIds.length === 0) {
|
|
2808
|
+
return hydrated;
|
|
2809
|
+
}
|
|
2810
|
+
const rvMissing = RunView.FromMetadataProvider(effectiveProvider);
|
|
2811
|
+
const inMissing = targetVersionIds.map((id) => `'${EscapeSQLString(id)}'`).join(',');
|
|
2812
|
+
const missingRes = await rvMissing.RunView({
|
|
2813
|
+
EntityName: 'MJ: Artifact Versions',
|
|
2814
|
+
ExtraFilter: `ID IN (${inMissing})`,
|
|
2815
|
+
Fields: ['ID', 'ArtifactID', 'VersionNumber', 'Name', 'Description', 'ContentMode', 'FileID', 'Content', 'MimeType', 'ForceToolsOnly'],
|
|
2816
|
+
MaxRows: targetVersionIds.length,
|
|
2817
|
+
SkipTotalRowCount: true,
|
|
2818
|
+
ResultType: 'simple',
|
|
2819
|
+
}, contextUser);
|
|
2820
|
+
if (missingRes.Success && missingRes.Results?.length) {
|
|
2821
|
+
const missingArtIds = Array.from(new Set(missingRes.Results.map((v) => v.ArtifactID).filter(Boolean)));
|
|
2822
|
+
const artMap = new Map();
|
|
2823
|
+
if (missingArtIds.length > 0) {
|
|
2824
|
+
const artRes = await rvMissing.RunView({
|
|
2825
|
+
EntityName: 'MJ: Artifacts',
|
|
2826
|
+
ExtraFilter: `ID IN (${missingArtIds.map((id) => `'${EscapeSQLString(id)}'`).join(',')})`,
|
|
2827
|
+
Fields: ['ID', 'Name', 'Description', 'TypeID'],
|
|
2828
|
+
MaxRows: missingArtIds.length,
|
|
2829
|
+
SkipTotalRowCount: true,
|
|
2830
|
+
ResultType: 'simple',
|
|
2831
|
+
}, contextUser);
|
|
2832
|
+
if (artRes.Success && artRes.Results) {
|
|
2833
|
+
for (const a of artRes.Results) {
|
|
2834
|
+
artMap.set(NormalizeUUID(a.ID), a);
|
|
2835
|
+
}
|
|
2836
|
+
}
|
|
2837
|
+
}
|
|
2838
|
+
await ArtifactMetadataEngine.Instance.Config(false, contextUser, effectiveProvider);
|
|
2839
|
+
const artifactTypesById = IndexByUUID(ArtifactMetadataEngine.Instance.ArtifactTypes, (t) => t.ID);
|
|
2840
|
+
for (const vr of missingRes.Results) {
|
|
2841
|
+
const art = artMap.get(NormalizeUUID(vr.ArtifactID));
|
|
2842
|
+
const artType = art?.TypeID
|
|
2843
|
+
? artifactTypesById.Get(art.TypeID)
|
|
2844
|
+
: undefined;
|
|
2845
|
+
hydrated.push({
|
|
2846
|
+
VersionID: vr.ID,
|
|
2847
|
+
ArtifactID: vr.ArtifactID,
|
|
2848
|
+
VersionNumber: vr.VersionNumber,
|
|
2849
|
+
VersionName: vr.Name,
|
|
2850
|
+
VersionDescription: vr.Description,
|
|
2851
|
+
ContentMode: vr.ContentMode === 'File' ? 'File' : 'Text',
|
|
2852
|
+
FileID: vr.FileID,
|
|
2853
|
+
Content: vr.Content,
|
|
2854
|
+
MimeType: vr.MimeType,
|
|
2855
|
+
ForceToolsOnly: vr.ForceToolsOnly,
|
|
2856
|
+
ArtifactName: art?.Name ?? 'Artifact',
|
|
2857
|
+
ArtifactDescription: art?.Description ?? null,
|
|
2858
|
+
TypeName: artType?.Name ?? '',
|
|
2859
|
+
ToolLibraryClass: artType?.ToolLibraryClass ?? null,
|
|
2860
|
+
DefaultDeliveryMode: artType?.DefaultDeliveryMode === 'ToolsOnly' ? 'ToolsOnly' : artType?.DefaultDeliveryMode === 'Inline' ? 'Inline' : null,
|
|
2861
|
+
});
|
|
2862
|
+
}
|
|
2863
|
+
}
|
|
2864
|
+
else if (!missingRes.Success) {
|
|
2865
|
+
LogError(`[AgentRunner] Fallback RunView('MJ: Artifact Versions') failed: ${missingRes.ErrorMessage}`);
|
|
2866
|
+
}
|
|
2867
|
+
return hydrated;
|
|
2868
|
+
};
|
|
2869
|
+
if (effectiveProvider) {
|
|
2870
|
+
const returnedIds = new Set(rawRows.map((r) => NormalizeUUID(r.VersionID)));
|
|
2871
|
+
const missingIds = versionIds.filter((id) => !returnedIds.has(NormalizeUUID(id)));
|
|
2872
|
+
if (missingIds.length > 0) {
|
|
2873
|
+
try {
|
|
2874
|
+
const fallbackRows = await hydrateArtifactVersionsViaRunView(missingIds);
|
|
2875
|
+
rawRows.push(...fallbackRows);
|
|
2876
|
+
}
|
|
2877
|
+
catch (fallbackErr) {
|
|
2878
|
+
LogError(`[AgentRunner] Fallback artifact version hydration failed: ${fallbackErr instanceof Error ? fallbackErr.message : String(fallbackErr)}`);
|
|
2879
|
+
}
|
|
2880
|
+
}
|
|
2881
|
+
}
|
|
2882
|
+
if (rawRows.length > 0) {
|
|
2883
|
+
// Deduplicate by normalized ArtifactID keeping the highest VersionNumber so multiple
|
|
2884
|
+
// conversation messages referencing earlier and newer versions collapse onto the latest one.
|
|
2885
|
+
const latestByArtifactId = new Map();
|
|
2886
|
+
for (const row of rawRows) {
|
|
2887
|
+
const artId = (row.ArtifactID ?? '').trim();
|
|
2888
|
+
if (!artId) {
|
|
2889
|
+
continue;
|
|
2890
|
+
}
|
|
2891
|
+
const normArtId = NormalizeUUID(artId);
|
|
2892
|
+
const existing = latestByArtifactId.get(normArtId);
|
|
2893
|
+
if (!existing || (row.VersionNumber ?? 0) >= (existing.VersionNumber ?? 0)) {
|
|
2894
|
+
latestByArtifactId.set(normArtId, row);
|
|
2895
|
+
}
|
|
2896
|
+
}
|
|
2897
|
+
const rows = Array.from(latestByArtifactId.values());
|
|
2898
|
+
const canReadByArtifactId = new Map();
|
|
2899
|
+
const permissionProvider = effectiveProvider;
|
|
2900
|
+
for (const row of rows) {
|
|
2901
|
+
const artId = (row.ArtifactID ?? '').trim();
|
|
2902
|
+
if (!artId) {
|
|
2903
|
+
continue;
|
|
2904
|
+
}
|
|
2905
|
+
const normArtId = NormalizeUUID(artId);
|
|
2906
|
+
if (!canReadByArtifactId.has(normArtId)) {
|
|
2907
|
+
if (!permissionProvider) {
|
|
2908
|
+
canReadByArtifactId.set(normArtId, false);
|
|
2909
|
+
continue;
|
|
2910
|
+
}
|
|
2911
|
+
const perms = await ArtifactPermissionEngine.Instance.ResolvePermissions(permissionProvider, artId, contextUser);
|
|
2912
|
+
canReadByArtifactId.set(normArtId, perms.CanRead === true);
|
|
2913
|
+
}
|
|
2914
|
+
}
|
|
2915
|
+
// P0-17: Resolve the latest MJ: Artifact Versions row per readable ArtifactID
|
|
2916
|
+
// so agents always hydrate from the current head version rather than a stale
|
|
2917
|
+
// version pinned when an earlier conversation message was written.
|
|
2918
|
+
if (effectiveProvider) {
|
|
2919
|
+
const readableRows = rows.filter((r) => {
|
|
2920
|
+
const aid = (r.ArtifactID ?? '').trim();
|
|
2921
|
+
return aid && canReadByArtifactId.get(NormalizeUUID(aid)) === true;
|
|
2922
|
+
});
|
|
2923
|
+
if (readableRows.length > 0) {
|
|
2924
|
+
try {
|
|
2925
|
+
const rv = RunView.FromMetadataProvider(effectiveProvider);
|
|
2926
|
+
const inList = Array.from(new Set(readableRows.map((r) => r.ArtifactID.trim())))
|
|
2927
|
+
.map((id) => `'${EscapeSQLString(id)}'`)
|
|
2928
|
+
.join(',');
|
|
2929
|
+
const latestVerRes = await rv.RunView({
|
|
2930
|
+
EntityName: 'MJ: Artifact Versions',
|
|
2931
|
+
ExtraFilter: `ArtifactID IN (${inList})`,
|
|
2932
|
+
OrderBy: 'VersionNumber DESC',
|
|
2933
|
+
Fields: ['ID', 'ArtifactID', 'VersionNumber'],
|
|
2934
|
+
MaxRows: readableRows.length * 10,
|
|
2935
|
+
SkipTotalRowCount: true,
|
|
2936
|
+
ResultType: 'simple',
|
|
2937
|
+
}, contextUser);
|
|
2938
|
+
if (latestVerRes.Success && latestVerRes.Results?.length) {
|
|
2939
|
+
const newerVersionIds = [];
|
|
2940
|
+
const seenLatestByArt = new Map();
|
|
2941
|
+
for (const vr of latestVerRes.Results) {
|
|
2942
|
+
const vrArtId = (vr.ArtifactID ?? '').trim();
|
|
2943
|
+
const vrVerId = (vr.ID ?? '').trim();
|
|
2944
|
+
if (!vrArtId || !vrVerId)
|
|
2945
|
+
continue;
|
|
2946
|
+
const normArt = NormalizeUUID(vrArtId);
|
|
2947
|
+
const vNum = vr.VersionNumber ?? 0;
|
|
2948
|
+
const prev = seenLatestByArt.get(normArt);
|
|
2949
|
+
if (!prev || vNum > prev.VersionNumber) {
|
|
2950
|
+
seenLatestByArt.set(normArt, { ID: vrVerId, VersionNumber: vNum });
|
|
2951
|
+
}
|
|
2952
|
+
}
|
|
2953
|
+
for (const [normArt, latestDb] of seenLatestByArt.entries()) {
|
|
2954
|
+
const currentRow = latestByArtifactId.get(normArt);
|
|
2955
|
+
if (currentRow &&
|
|
2956
|
+
latestDb.VersionNumber > (currentRow.VersionNumber ?? 0) &&
|
|
2957
|
+
!UUIDsEqual(latestDb.ID, currentRow.VersionID)) {
|
|
2958
|
+
newerVersionIds.push(latestDb.ID);
|
|
2959
|
+
}
|
|
2960
|
+
}
|
|
2961
|
+
if (newerVersionIds.length > 0) {
|
|
2962
|
+
const refreshedRes = await rq.RunQuery({
|
|
2963
|
+
QueryName: 'GetArtifactVersionsByID',
|
|
2964
|
+
CategoryPath: '/MJ/AI/Agents/',
|
|
2965
|
+
Parameters: { versionIds: newerVersionIds },
|
|
2966
|
+
}, contextUser);
|
|
2967
|
+
const refreshedRows = refreshedRes.Success && Array.isArray(refreshedRes.Results)
|
|
2968
|
+
? [...refreshedRes.Results]
|
|
2969
|
+
: [];
|
|
2970
|
+
if (!refreshedRes.Success) {
|
|
2971
|
+
LogError(`[AgentRunner] Refresh GetArtifactVersionsByID failed: ${refreshedRes.ErrorMessage}`);
|
|
2972
|
+
}
|
|
2973
|
+
const refreshedIds = new Set(refreshedRows.map((r) => NormalizeUUID(r.VersionID)));
|
|
2974
|
+
const missingRefreshedIds = newerVersionIds.filter((id) => !refreshedIds.has(NormalizeUUID(id)));
|
|
2975
|
+
if (missingRefreshedIds.length > 0) {
|
|
2976
|
+
try {
|
|
2977
|
+
const fallbackLatestRows = await hydrateArtifactVersionsViaRunView(missingRefreshedIds);
|
|
2978
|
+
refreshedRows.push(...fallbackLatestRows);
|
|
2979
|
+
}
|
|
2980
|
+
catch (fallbackLatestErr) {
|
|
2981
|
+
LogError(`[AgentRunner] Fallback latest artifact version hydration failed: ${fallbackLatestErr instanceof Error ? fallbackLatestErr.message : String(fallbackLatestErr)}`);
|
|
2982
|
+
}
|
|
2983
|
+
}
|
|
2984
|
+
for (const freshRow of refreshedRows) {
|
|
2985
|
+
const freshArtId = (freshRow.ArtifactID ?? '').trim();
|
|
2986
|
+
if (!freshArtId)
|
|
2987
|
+
continue;
|
|
2988
|
+
const normFresh = NormalizeUUID(freshArtId);
|
|
2989
|
+
const prior = latestByArtifactId.get(normFresh);
|
|
2990
|
+
if (!prior || (freshRow.VersionNumber ?? 0) > (prior.VersionNumber ?? 0)) {
|
|
2991
|
+
latestByArtifactId.set(normFresh, freshRow);
|
|
2992
|
+
}
|
|
2993
|
+
}
|
|
2994
|
+
}
|
|
2995
|
+
}
|
|
2996
|
+
}
|
|
2997
|
+
catch (latestErr) {
|
|
2998
|
+
LogError(`[AgentRunner] Failed resolving latest artifact versions: ${latestErr instanceof Error ? latestErr.message : String(latestErr)}`);
|
|
2999
|
+
}
|
|
3000
|
+
}
|
|
3001
|
+
}
|
|
3002
|
+
const effectiveRows = Array.from(latestByArtifactId.values());
|
|
3003
|
+
const liveReader = GetArtifactLiveContentReaderHook();
|
|
3004
|
+
for (const row of effectiveRows) {
|
|
3005
|
+
const rowArtifactId = (row.ArtifactID ?? '').trim();
|
|
3006
|
+
if (!rowArtifactId || canReadByArtifactId.get(NormalizeUUID(rowArtifactId)) !== true) {
|
|
3007
|
+
continue;
|
|
3008
|
+
}
|
|
2446
3009
|
const artifactName = row.VersionName || row.ArtifactName || 'Untitled';
|
|
2447
3010
|
const typeName = row.TypeName || 'Text';
|
|
3011
|
+
let effectiveVersionId = row.VersionID;
|
|
3012
|
+
let effectiveVersionNumber = row.VersionNumber;
|
|
2448
3013
|
let content = '';
|
|
2449
|
-
|
|
2450
|
-
|
|
2451
|
-
|
|
2452
|
-
|
|
3014
|
+
let liveHydrated = false;
|
|
3015
|
+
if (liveReader) {
|
|
3016
|
+
try {
|
|
3017
|
+
const liveSnap = await liveReader(rowArtifactId, contextUser);
|
|
3018
|
+
if (liveSnap && typeof liveSnap.Content === 'string') {
|
|
3019
|
+
content = liveSnap.Content;
|
|
3020
|
+
liveHydrated = true;
|
|
3021
|
+
if (typeof liveSnap.VersionNumber === 'number') {
|
|
3022
|
+
effectiveVersionNumber = liveSnap.VersionNumber;
|
|
3023
|
+
}
|
|
3024
|
+
if (liveSnap.VersionID) {
|
|
3025
|
+
effectiveVersionId = liveSnap.VersionID;
|
|
3026
|
+
}
|
|
3027
|
+
}
|
|
2453
3028
|
}
|
|
2454
|
-
|
|
2455
|
-
LogError(`[AgentRunner]
|
|
2456
|
-
continue;
|
|
3029
|
+
catch (liveErr) {
|
|
3030
|
+
LogError(`[AgentRunner] Live content reader failed for artifact ${rowArtifactId}: ${liveErr instanceof Error ? liveErr.message : String(liveErr)}`);
|
|
2457
3031
|
}
|
|
2458
3032
|
}
|
|
2459
|
-
|
|
2460
|
-
|
|
3033
|
+
if (!liveHydrated) {
|
|
3034
|
+
if (row.ContentMode === 'File' && row.FileID) {
|
|
3035
|
+
const downloaded = await this.DownloadArtifactFileContent(row.FileID, contextUser, effectiveProvider);
|
|
3036
|
+
if (downloaded) {
|
|
3037
|
+
content = downloaded;
|
|
3038
|
+
}
|
|
3039
|
+
else {
|
|
3040
|
+
LogError(`[AgentRunner] Failed to download file content for artifact "${artifactName}" (FileID: ${row.FileID})`);
|
|
3041
|
+
continue;
|
|
3042
|
+
}
|
|
3043
|
+
}
|
|
3044
|
+
else {
|
|
3045
|
+
content = row.Content ?? '';
|
|
3046
|
+
}
|
|
2461
3047
|
}
|
|
2462
3048
|
// Binary artifacts stored as a base64 data URL by the
|
|
2463
3049
|
// server hook (xlsx, docx, pdf, image when inline) need
|
|
@@ -2472,7 +3058,7 @@ export class AgentRunner {
|
|
|
2472
3058
|
if (typeof content === 'string' && content) {
|
|
2473
3059
|
content = await this.hydrateSqlBackedContent(content, contextUser);
|
|
2474
3060
|
}
|
|
2475
|
-
if (content) {
|
|
3061
|
+
if (typeof content === 'string' || content.length > 0) {
|
|
2476
3062
|
const rawDescription = row.VersionDescription || row.ArtifactDescription;
|
|
2477
3063
|
const cleanDescription = rawDescription && !rawDescription.startsWith('Payload returned by ')
|
|
2478
3064
|
? rawDescription
|
|
@@ -2482,8 +3068,8 @@ export class AgentRunner {
|
|
|
2482
3068
|
typeName,
|
|
2483
3069
|
content,
|
|
2484
3070
|
...(row.ArtifactID ? { artifactId: row.ArtifactID } : {}),
|
|
2485
|
-
...(
|
|
2486
|
-
...(
|
|
3071
|
+
...(effectiveVersionId ? { versionId: effectiveVersionId } : {}),
|
|
3072
|
+
...(effectiveVersionNumber != null ? { versionNumber: effectiveVersionNumber } : {}),
|
|
2487
3073
|
...(cleanDescription ? { description: cleanDescription } : {}),
|
|
2488
3074
|
mimeType: row.MimeType ?? undefined,
|
|
2489
3075
|
...(row.ToolLibraryClass ? { toolLibraryClass: row.ToolLibraryClass } : {}),
|
|
@@ -2528,7 +3114,11 @@ export class AgentRunner {
|
|
|
2528
3114
|
async hydrateSqlBackedContent(content, contextUser) {
|
|
2529
3115
|
let parsed;
|
|
2530
3116
|
try {
|
|
2531
|
-
|
|
3117
|
+
const raw = JSON.parse(content);
|
|
3118
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
|
|
3119
|
+
return content;
|
|
3120
|
+
}
|
|
3121
|
+
parsed = raw;
|
|
2532
3122
|
}
|
|
2533
3123
|
catch {
|
|
2534
3124
|
return content;
|
|
@@ -2538,8 +3128,8 @@ export class AgentRunner {
|
|
|
2538
3128
|
}
|
|
2539
3129
|
let changed = false;
|
|
2540
3130
|
const rq = await this.adhocSqlRunner();
|
|
2541
|
-
const rootMeta = parsed
|
|
2542
|
-
const rootRows = parsed
|
|
3131
|
+
const rootMeta = parsed.metadata;
|
|
3132
|
+
const rootRows = parsed.rows;
|
|
2543
3133
|
if (rootMeta?.sql && (!rootRows || rootRows.length === 0)) {
|
|
2544
3134
|
const result = await rq.RunQuery({ SQL: rootMeta.sql }, contextUser);
|
|
2545
3135
|
if (result.Success) {
|
|
@@ -2555,7 +3145,7 @@ export class AgentRunner {
|
|
|
2555
3145
|
LogError(`[AgentRunner] hydrateSqlBackedContent root SQL failed: ${result.ErrorMessage}`);
|
|
2556
3146
|
}
|
|
2557
3147
|
}
|
|
2558
|
-
const tables = parsed
|
|
3148
|
+
const tables = parsed.tables;
|
|
2559
3149
|
if (Array.isArray(tables)) {
|
|
2560
3150
|
for (const table of tables) {
|
|
2561
3151
|
if (table?.metadata?.sql && (!table.rows || table.rows.length === 0)) {
|
|
@@ -2576,12 +3166,12 @@ export class AgentRunner {
|
|
|
2576
3166
|
}
|
|
2577
3167
|
/** True when the parsed artifact carries stored SQL whose rows are missing. */
|
|
2578
3168
|
hasUnhydratedSql(parsed) {
|
|
2579
|
-
const rootMeta = parsed
|
|
2580
|
-
const rootRows = parsed
|
|
3169
|
+
const rootMeta = parsed.metadata;
|
|
3170
|
+
const rootRows = parsed.rows;
|
|
2581
3171
|
if (rootMeta?.sql && (!rootRows || rootRows.length === 0)) {
|
|
2582
3172
|
return true;
|
|
2583
3173
|
}
|
|
2584
|
-
const tables = parsed
|
|
3174
|
+
const tables = parsed.tables;
|
|
2585
3175
|
return Array.isArray(tables) && tables.some(t => !!t?.metadata?.sql && (!t.rows || t.rows.length === 0));
|
|
2586
3176
|
}
|
|
2587
3177
|
/**
|
|
@@ -2627,14 +3217,15 @@ export class AgentRunner {
|
|
|
2627
3217
|
* @param contextUser - User context for storage driver authentication
|
|
2628
3218
|
* @returns Buffer of file content, or null if download fails
|
|
2629
3219
|
*/
|
|
2630
|
-
async DownloadArtifactFileContent(fileId, contextUser) {
|
|
3220
|
+
async DownloadArtifactFileContent(fileId, contextUser, provider) {
|
|
2631
3221
|
if (!IsValidUUID(fileId)) {
|
|
2632
3222
|
LogError(`[AgentRunner] Refusing to read artifact file content: '${fileId}' is not a file ID`);
|
|
2633
3223
|
return null;
|
|
2634
3224
|
}
|
|
2635
3225
|
try {
|
|
2636
|
-
|
|
2637
|
-
|
|
3226
|
+
const md = provider ?? this._provider;
|
|
3227
|
+
await FileStorageEngine.Instance.Config(false, contextUser, md);
|
|
3228
|
+
const rv = RunView.FromMetadataProvider(md);
|
|
2638
3229
|
const fileResult = await rv.RunView({
|
|
2639
3230
|
EntityName: 'MJ: Files',
|
|
2640
3231
|
ExtraFilter: `ID = '${EscapeSQLString(fileId.trim())}'`,
|
|
@@ -2646,7 +3237,7 @@ export class AgentRunner {
|
|
|
2646
3237
|
return null;
|
|
2647
3238
|
}
|
|
2648
3239
|
// Account gate and tracked-file rule first; a refusal throws and is logged below.
|
|
2649
|
-
const resolved = await FileStorageEngine.Instance.ResolveFileObject(fileResult.Results[0], contextUser, 'Read',
|
|
3240
|
+
const resolved = await FileStorageEngine.Instance.ResolveFileObject(fileResult.Results[0], contextUser, 'Read', md);
|
|
2650
3241
|
if (!resolved) {
|
|
2651
3242
|
LogError(`[AgentRunner] No FileStorageAccount found for ProviderID: ${fileResult.Results[0].ProviderID}`);
|
|
2652
3243
|
return null;
|