@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
|
@@ -1,62 +1,19 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
class CompositeArtifactToolLibrary extends BaseArtifactToolLibrary {
|
|
18
|
-
constructor(chain) {
|
|
19
|
-
super();
|
|
20
|
-
this.chain = chain;
|
|
21
|
-
}
|
|
22
|
-
// Composite wraps a chain of real libraries and fully overrides the public
|
|
23
|
-
// dispatchers — the abstract Subclass methods below are required to make the
|
|
24
|
-
// class concrete but are never reached.
|
|
25
|
-
GetToolList() {
|
|
26
|
-
const seen = new Set();
|
|
27
|
-
const merged = [];
|
|
28
|
-
for (const lib of this.chain) {
|
|
29
|
-
for (const tool of lib.GetToolList()) {
|
|
30
|
-
if (seen.has(tool.name))
|
|
31
|
-
continue;
|
|
32
|
-
seen.add(tool.name);
|
|
33
|
-
merged.push(tool);
|
|
34
|
-
}
|
|
35
|
-
}
|
|
36
|
-
return merged;
|
|
37
|
-
}
|
|
38
|
-
async InvokeTool(toolName, input, artifactContent) {
|
|
39
|
-
// Dispatch to the first library (leaf-first) that declares this tool.
|
|
40
|
-
for (const lib of this.chain) {
|
|
41
|
-
if (lib.GetToolList().some((t) => t.name === toolName)) {
|
|
42
|
-
return lib.InvokeTool(toolName, input, artifactContent);
|
|
43
|
-
}
|
|
44
|
-
}
|
|
45
|
-
return {
|
|
46
|
-
success: false,
|
|
47
|
-
data: null,
|
|
48
|
-
errorMessage: `Tool "${toolName}" is not defined by any library in this artifact type's chain.`,
|
|
49
|
-
};
|
|
50
|
-
}
|
|
51
|
-
// Required by the abstract base but never invoked — GetToolList / InvokeTool
|
|
52
|
-
// are fully overridden above.
|
|
53
|
-
getSubclassToolList() {
|
|
54
|
-
return [];
|
|
55
|
-
}
|
|
56
|
-
async invokeSubclassTool() {
|
|
57
|
-
return { success: false, data: null, errorMessage: 'CompositeArtifactToolLibrary does not dispatch via invokeSubclassTool.' };
|
|
58
|
-
}
|
|
59
|
-
}
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { CleanAndParseJSON, EscapeSQLString, GetGlobalObjectStore, IndexByUUID, IsValidUUID, MJEventType, MJGlobal, NormalizeUUID, UUIDsEqual } from '@memberjunction/global';
|
|
3
|
+
import { CompositeKey, LogError, RunView } from '@memberjunction/core';
|
|
4
|
+
import { ArtifactMetadataEngine, ArtifactPermissionEngine, ArtifactSynthesisEngine, BuildArtifactVersionConfigurationWithPreview, SpreadsheetEngine, XlsxOpenXmlAdapter, } from '@memberjunction/core-entities';
|
|
5
|
+
import { FileStorageEngine } from '@memberjunction/storage';
|
|
6
|
+
import { UserCache } from '@memberjunction/generic-database-provider';
|
|
7
|
+
import { AIEngine } from '@memberjunction/aiengine';
|
|
8
|
+
import { AIRerankerRunner } from '@memberjunction/ai-reranker';
|
|
9
|
+
import { ARTIFACT_LIVE_MUTATION_EVENT_CODE, ExtractAgentTargetLocation, FormatAgentActionSummary, GetArtifactLiveMutationHook, MUTATING_ARTIFACT_TOOL_NAMES, ResolvePresenceDomain, SetArtifactLiveMutationHook, } from './artifact-presence-locator.js';
|
|
10
|
+
import { DecodeBinaryArtifactContent } from './artifact-tools/artifact-tool-helpers.js';
|
|
11
|
+
import { GetPdfJsModule } from './artifact-tools/PDFToolLibrary.js';
|
|
12
|
+
import { BuildMergedFileVersionConfiguration, FormatFileModeStructuralToolError, GovernedArtifactService, MergeTouchedArtifactSummary, STRUCTURAL_SPREADSHEET_TOOLS, } from './GovernedArtifactService.js';
|
|
13
|
+
export { SetArtifactLiveMutationHook, GetArtifactLiveMutationHook };
|
|
14
|
+
const XLSX_MIME_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
|
|
15
|
+
const GLOBAL_KEY_TRUSTED_AGENT_DRAFT = '__MJ_TRUSTED_AGENT_DRAFT_VERSION_ENTITIES__';
|
|
16
|
+
const MAX_INITIAL_OPERATIONS = 100;
|
|
60
17
|
/**
|
|
61
18
|
* Manages artifact tools for a single agent run.
|
|
62
19
|
*
|
|
@@ -72,86 +29,232 @@ export class ArtifactToolManager {
|
|
|
72
29
|
this.artifacts = new Map();
|
|
73
30
|
this.toolResults = [];
|
|
74
31
|
this.nextAlphaIndex = 0;
|
|
32
|
+
this.workspaceEnabled = false;
|
|
33
|
+
this.allowFreezeFromUserConfirmation = false;
|
|
34
|
+
this.touchedArtifacts = new Map();
|
|
35
|
+
this.enteredPresenceArtifactIds = new Set();
|
|
75
36
|
}
|
|
37
|
+
static { this.MUTATING_TOOL_NAMES = MUTATING_ARTIFACT_TOOL_NAMES; }
|
|
38
|
+
static { this.STRUCTURAL_SPREADSHEET_TOOLS = STRUCTURAL_SPREADSHEET_TOOLS; }
|
|
76
39
|
// ─── LIFECYCLE ───
|
|
77
|
-
/**
|
|
78
|
-
|
|
40
|
+
/** Sets or updates the agent run attribution context (`D5`). */
|
|
41
|
+
SetAgentRunContext(agentRunId, agentName) {
|
|
42
|
+
this.agentRunId = agentRunId;
|
|
43
|
+
if (agentName !== undefined) {
|
|
44
|
+
this.agentName = agentName;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/** Initialize with input artifacts, assigning alpha IDs and optional persistence context (`A4`) */
|
|
48
|
+
Initialize(inputArtifacts, options) {
|
|
79
49
|
this.Clear();
|
|
50
|
+
this.contextUser = options?.contextUser;
|
|
51
|
+
this.provider = options?.provider;
|
|
52
|
+
this.getAgentRun = options?.getAgentRun;
|
|
53
|
+
this.agentRunId = options?.agentRunId;
|
|
54
|
+
this.agentName = options?.agentName;
|
|
55
|
+
this.workspaceEnabled = options?.workspaceEnabled ?? Boolean(options?.contextUser || inputArtifacts.length > 0);
|
|
56
|
+
this.allowFreezeFromUserConfirmation = options?.allowFreezeFromUserConfirmation === true;
|
|
80
57
|
for (const artifact of inputArtifacts) {
|
|
81
|
-
|
|
82
|
-
this.artifacts.set(alphaId, {
|
|
83
|
-
alphaId,
|
|
84
|
-
name: artifact.name,
|
|
85
|
-
typeName: artifact.typeName,
|
|
86
|
-
artifactId: artifact.artifactId,
|
|
87
|
-
versionId: artifact.versionId,
|
|
88
|
-
versionNumber: artifact.versionNumber,
|
|
89
|
-
description: artifact.description,
|
|
90
|
-
mimeType: artifact.mimeType,
|
|
91
|
-
content: artifact.content,
|
|
92
|
-
library: this.resolveLibrary(artifact.typeName, artifact.toolLibraryClass),
|
|
93
|
-
annotation: artifact.annotation,
|
|
94
|
-
deliveryMode: artifact.deliveryMode,
|
|
95
|
-
forceToolsOnly: artifact.forceToolsOnly,
|
|
96
|
-
});
|
|
58
|
+
this.RegisterArtifact(artifact);
|
|
97
59
|
}
|
|
98
60
|
}
|
|
99
61
|
/** Register a mid-run artifact and return its alpha ID */
|
|
100
62
|
RegisterArtifact(artifact) {
|
|
101
63
|
const alphaId = this.nextAlphaId();
|
|
64
|
+
const isXlsxBinary = Buffer.isBuffer(artifact.content) &&
|
|
65
|
+
artifact.content.length > 4 &&
|
|
66
|
+
artifact.content[0] === 0x50 &&
|
|
67
|
+
artifact.content[1] === 0x4b;
|
|
68
|
+
const typeEntity = ArtifactMetadataEngine.Instance.FindArtifactType(artifact.typeName);
|
|
102
69
|
this.artifacts.set(alphaId, {
|
|
103
70
|
alphaId,
|
|
104
71
|
name: artifact.name,
|
|
105
72
|
typeName: artifact.typeName,
|
|
73
|
+
driverClass: typeEntity?.DriverClass ?? undefined,
|
|
74
|
+
toolLibraryClass: artifact.toolLibraryClass ?? typeEntity?.ToolLibraryClass ?? undefined,
|
|
106
75
|
artifactId: artifact.artifactId,
|
|
107
76
|
versionId: artifact.versionId,
|
|
108
77
|
versionNumber: artifact.versionNumber,
|
|
78
|
+
baseVersionNumber: artifact.versionNumber,
|
|
79
|
+
currentVersionNumber: artifact.versionNumber,
|
|
80
|
+
contentMode: isXlsxBinary ? 'File' : undefined,
|
|
81
|
+
originalXlsxBytes: isXlsxBinary ? new Uint8Array(artifact.content) : undefined,
|
|
109
82
|
description: artifact.description,
|
|
110
83
|
mimeType: artifact.mimeType,
|
|
111
84
|
content: artifact.content,
|
|
112
85
|
library: this.resolveLibrary(artifact.typeName, artifact.toolLibraryClass),
|
|
86
|
+
annotation: artifact.annotation,
|
|
87
|
+
deliveryMode: artifact.deliveryMode,
|
|
88
|
+
forceToolsOnly: artifact.forceToolsOnly,
|
|
113
89
|
});
|
|
114
90
|
return alphaId;
|
|
115
91
|
}
|
|
92
|
+
parseIdentifierRef(idOrAlpha) {
|
|
93
|
+
if (typeof idOrAlpha !== 'string')
|
|
94
|
+
return undefined;
|
|
95
|
+
const trimmed = idOrAlpha.trim();
|
|
96
|
+
if (!trimmed)
|
|
97
|
+
return undefined;
|
|
98
|
+
const normalizedAlpha = trimmed.replace(/^artifact\s+/i, '').trim().toUpperCase();
|
|
99
|
+
return {
|
|
100
|
+
trimmed,
|
|
101
|
+
byAlpha: this.artifacts.get(normalizedAlpha),
|
|
102
|
+
isUuid: /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(trimmed),
|
|
103
|
+
};
|
|
104
|
+
}
|
|
116
105
|
/**
|
|
117
106
|
* Resolves a manifest alpha ID (e.g. `"A"`, `"B"`), an artifact UUID, or a version UUID
|
|
118
107
|
* to the underlying `MJ: Artifacts` record UUID (`artifactId`).
|
|
119
108
|
* Allows agents to reference either `"A"` or the full UUID in `artifactDirective.targetArtifactId`.
|
|
120
109
|
*/
|
|
121
110
|
ResolveArtifactUuid(idOrAlpha) {
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
const trimmed = idOrAlpha.trim();
|
|
125
|
-
if (!trimmed)
|
|
111
|
+
const parsed = this.parseIdentifierRef(idOrAlpha);
|
|
112
|
+
if (!parsed)
|
|
126
113
|
return undefined;
|
|
127
114
|
// 1. Direct alpha ID lookup (case-insensitive, e.g. 'A', 'B', 'AA', or 'Artifact B')
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
if (byAlpha?.artifactId) {
|
|
131
|
-
return byAlpha.artifactId;
|
|
115
|
+
if (parsed.byAlpha?.artifactId) {
|
|
116
|
+
return parsed.byAlpha.artifactId;
|
|
132
117
|
}
|
|
133
118
|
// 2. Match by artifactId or versionId UUID
|
|
134
119
|
for (const entry of this.artifacts.values()) {
|
|
135
|
-
if (entry.artifactId && (UUIDsEqual(entry.artifactId, trimmed) || (entry.versionId && UUIDsEqual(entry.versionId, trimmed)))) {
|
|
120
|
+
if (entry.artifactId && (UUIDsEqual(entry.artifactId, parsed.trimmed) || (entry.versionId && UUIDsEqual(entry.versionId, parsed.trimmed)))) {
|
|
136
121
|
return entry.artifactId;
|
|
137
122
|
}
|
|
138
123
|
}
|
|
139
124
|
// 3. Pass through well-formed UUIDs so callers can pass an explicit artifact UUID directly
|
|
140
|
-
|
|
141
|
-
|
|
125
|
+
return parsed.isUuid ? parsed.trimmed : undefined;
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Resolves a manifest alpha ID (e.g. `"E"`, `"Artifact E"`) or version UUID
|
|
129
|
+
* to the underlying `MJ: Artifact Versions` record UUID (`versionId`).
|
|
130
|
+
*/
|
|
131
|
+
ResolveArtifactVersionUuid(idOrAlpha) {
|
|
132
|
+
const parsed = this.parseIdentifierRef(idOrAlpha);
|
|
133
|
+
if (!parsed)
|
|
134
|
+
return undefined;
|
|
135
|
+
// 1. Direct alpha ID lookup: map session short ID to its tracked ArtifactVersion UUID
|
|
136
|
+
if (parsed.byAlpha) {
|
|
137
|
+
return parsed.byAlpha.versionId ?? undefined;
|
|
142
138
|
}
|
|
143
|
-
|
|
139
|
+
// 2. Match by tracked versionId UUID
|
|
140
|
+
for (const entry of this.artifacts.values()) {
|
|
141
|
+
if (entry.versionId && UUIDsEqual(entry.versionId, parsed.trimmed)) {
|
|
142
|
+
return entry.versionId;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
// 3. Pass through well-formed UUIDs so callers can pass an explicit version UUID directly
|
|
146
|
+
return parsed.isUuid ? parsed.trimmed : undefined;
|
|
144
147
|
}
|
|
145
148
|
/** Reset all state */
|
|
146
149
|
Clear() {
|
|
147
150
|
this.artifacts.clear();
|
|
148
151
|
this.toolResults = [];
|
|
149
152
|
this.nextAlphaIndex = 0;
|
|
153
|
+
this.contextUser = undefined;
|
|
154
|
+
this.provider = undefined;
|
|
155
|
+
this.getAgentRun = undefined;
|
|
156
|
+
this.agentRunId = undefined;
|
|
157
|
+
this.agentName = undefined;
|
|
158
|
+
this.workspaceEnabled = false;
|
|
159
|
+
this.touchedArtifacts.clear();
|
|
160
|
+
this.enteredPresenceArtifactIds.clear();
|
|
150
161
|
}
|
|
151
|
-
/** Whether any artifacts are
|
|
162
|
+
/** Whether any artifacts are attached/registered in the session */
|
|
152
163
|
HasArtifacts() {
|
|
153
164
|
return this.artifacts.size > 0;
|
|
154
165
|
}
|
|
166
|
+
/** Whether artifact workspace tools (including `create_artifact`, `open_artifact`, etc.) are available */
|
|
167
|
+
IsWorkspaceEnabled() {
|
|
168
|
+
return this.artifacts.size > 0 || this.workspaceEnabled;
|
|
169
|
+
}
|
|
170
|
+
/** Returns deduplicated summaries of all governed artifacts created or mutated during this run. */
|
|
171
|
+
GetTouchedArtifacts() {
|
|
172
|
+
const merged = new Map();
|
|
173
|
+
for (const [key, item] of this.touchedArtifacts.entries()) {
|
|
174
|
+
merged.set(key, { ...item });
|
|
175
|
+
}
|
|
176
|
+
const runId = this.agentRunId ?? this.getAgentRun?.()?.ID;
|
|
177
|
+
for (const item of GovernedArtifactService.Instance.PeekTouchedArtifacts(runId)) {
|
|
178
|
+
const key = item.ArtifactID.trim().toLowerCase();
|
|
179
|
+
merged.set(key, MergeTouchedArtifactSummary(merged.get(key), item));
|
|
180
|
+
}
|
|
181
|
+
return Array.from(merged.values());
|
|
182
|
+
}
|
|
183
|
+
/** Records a sub-agent or service touched artifact into this manager's run summary set. */
|
|
184
|
+
AbsorbTouchedArtifacts(items) {
|
|
185
|
+
if (!items?.length)
|
|
186
|
+
return;
|
|
187
|
+
for (const item of items) {
|
|
188
|
+
if (!item.ArtifactID)
|
|
189
|
+
continue;
|
|
190
|
+
this.recordTouchedArtifactSummary(item);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
/** Exports current artifacts merged with any caller seeds so sub-agents see artifacts created earlier in the run. */
|
|
194
|
+
ExportInputArtifacts(seed) {
|
|
195
|
+
const out = [];
|
|
196
|
+
const seen = new Set();
|
|
197
|
+
for (const entry of this.artifacts.values()) {
|
|
198
|
+
const key = (entry.artifactId ?? entry.alphaId).toLowerCase();
|
|
199
|
+
seen.add(key);
|
|
200
|
+
out.push({
|
|
201
|
+
name: entry.name,
|
|
202
|
+
typeName: entry.typeName,
|
|
203
|
+
content: entry.content,
|
|
204
|
+
mimeType: entry.mimeType,
|
|
205
|
+
description: entry.description,
|
|
206
|
+
artifactId: entry.artifactId,
|
|
207
|
+
versionId: entry.versionId,
|
|
208
|
+
versionNumber: entry.currentVersionNumber ?? entry.versionNumber,
|
|
209
|
+
toolLibraryClass: entry.toolLibraryClass,
|
|
210
|
+
annotation: entry.annotation,
|
|
211
|
+
deliveryMode: entry.deliveryMode,
|
|
212
|
+
forceToolsOnly: entry.forceToolsOnly,
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
if (seed?.length) {
|
|
216
|
+
for (const s of seed) {
|
|
217
|
+
const key = (s.artifactId ?? s.name).toLowerCase();
|
|
218
|
+
if (!seen.has(key)) {
|
|
219
|
+
seen.add(key);
|
|
220
|
+
out.push(s);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
return out.length > 0 ? out : undefined;
|
|
225
|
+
}
|
|
226
|
+
/** Emits `'exit'` awareness on every artifact this run entered so remote viewers clear active badges cleanly. */
|
|
227
|
+
async NotifyRunCompleted() {
|
|
228
|
+
if (!this.contextUser) {
|
|
229
|
+
this.enteredPresenceArtifactIds.clear();
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
const activeRunId = this.agentRunId ?? this.getAgentRun?.()?.ID;
|
|
233
|
+
const activeAgentName = this.agentName ?? this.getAgentRun?.()?.Agent ?? undefined;
|
|
234
|
+
const allIds = new Set(this.enteredPresenceArtifactIds);
|
|
235
|
+
for (const touched of GovernedArtifactService.Instance.PeekTouchedArtifacts(activeRunId)) {
|
|
236
|
+
if (touched.ArtifactID) {
|
|
237
|
+
allIds.add(touched.ArtifactID);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
this.enteredPresenceArtifactIds.clear();
|
|
241
|
+
if (allIds.size === 0)
|
|
242
|
+
return;
|
|
243
|
+
await Promise.all(Array.from(allIds).map((artifactId) => GovernedArtifactService.Instance.EmitAgentPresence({
|
|
244
|
+
artifactId,
|
|
245
|
+
phase: 'exit',
|
|
246
|
+
contextUser: this.contextUser,
|
|
247
|
+
agentRunId: activeRunId,
|
|
248
|
+
agentName: activeAgentName,
|
|
249
|
+
})));
|
|
250
|
+
}
|
|
251
|
+
recordTouchedArtifactSummary(summary) {
|
|
252
|
+
if (!summary.ArtifactID)
|
|
253
|
+
return;
|
|
254
|
+
const key = summary.ArtifactID.trim().toLowerCase();
|
|
255
|
+
const prev = this.touchedArtifacts.get(key);
|
|
256
|
+
this.touchedArtifacts.set(key, MergeTouchedArtifactSummary(prev, summary));
|
|
257
|
+
}
|
|
155
258
|
/**
|
|
156
259
|
* Returns artifact content formatted as NativeFileInput candidates for the
|
|
157
260
|
* AIPromptRunner. Only artifacts with a known MIME type and string/Buffer
|
|
@@ -211,17 +314,17 @@ export class ArtifactToolManager {
|
|
|
211
314
|
// (would need mammoth for docx, xlsx-parse for xlsx, etc.)
|
|
212
315
|
return null;
|
|
213
316
|
}
|
|
214
|
-
/** Extract all text from a PDF buffer using pdfjs-dist. Returns null on failure. */
|
|
317
|
+
/** Extract all text from a PDF buffer using memoized pdfjs-dist. Returns null on failure. */
|
|
215
318
|
async extractPdfText(buffer) {
|
|
216
319
|
try {
|
|
217
|
-
const pdfjsLib = await
|
|
320
|
+
const pdfjsLib = await GetPdfJsModule();
|
|
218
321
|
const pdfDoc = await pdfjsLib.getDocument({ data: new Uint8Array(buffer) }).promise;
|
|
219
322
|
try {
|
|
220
323
|
const pages = [];
|
|
221
324
|
for (let i = 1; i <= pdfDoc.numPages; i++) {
|
|
222
325
|
const page = await pdfDoc.getPage(i);
|
|
223
326
|
const tc = await page.getTextContent();
|
|
224
|
-
pages.push(tc.items.map((item) => item.str).join(' '));
|
|
327
|
+
pages.push(tc.items.map((item) => item.str ?? '').join(' '));
|
|
225
328
|
}
|
|
226
329
|
return pages.join('\n\n');
|
|
227
330
|
}
|
|
@@ -248,63 +351,63 @@ export class ArtifactToolManager {
|
|
|
248
351
|
* Pass `undefined` to disable the check (legacy callers).
|
|
249
352
|
*/
|
|
250
353
|
ToManifestString(opts) {
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
354
|
+
const lines = [];
|
|
355
|
+
if (this.artifacts.size === 0) {
|
|
356
|
+
if (!this.workspaceEnabled)
|
|
357
|
+
return '';
|
|
358
|
+
lines.push('## Available Artifacts\n');
|
|
359
|
+
lines.push('No artifacts are currently attached to this conversation turn. Use `create_artifact` to create a new governed Spreadsheet, Markdown Document, or Presentation, `list_workspace_artifacts` to discover existing workspace artifacts, or `open_artifact` to load an artifact by UUID into this session.\n');
|
|
360
|
+
}
|
|
361
|
+
else {
|
|
362
|
+
lines.push('## Available Artifacts\n');
|
|
363
|
+
const supportedMimes = opts?.supportedMimeTypes ?? null;
|
|
364
|
+
for (const entry of this.artifacts.values()) {
|
|
365
|
+
const sizeSuffix = Buffer.isBuffer(entry.content)
|
|
259
366
|
? ` (${(entry.content.length / 1024).toFixed(0)} KB)`
|
|
260
|
-
: ''
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
lines.push('artifact tools below (e.g. `get_full`), or use one as a pipeline source (e.g. `get_full`');
|
|
293
|
-
lines.push('then `where`/`select`/`distinct`). NEVER ask the user to paste, provide, upload, or "send"');
|
|
294
|
-
lines.push('an artifact\'s content, and do NOT request a data snapshot to obtain it — you already have it.');
|
|
367
|
+
: typeof entry.content === 'string' && entry.content.length > 0
|
|
368
|
+
? ` (${(entry.content.length / 1024).toFixed(0)} KB)`
|
|
369
|
+
: '';
|
|
370
|
+
const versionNote = entry.versionNumber != null ? ` (v${entry.versionNumber})` : '';
|
|
371
|
+
const idNote = entry.artifactId ? ` [artifactId: ${entry.artifactId}]` : '';
|
|
372
|
+
const mimeNote = entry.mimeType ? ` [${entry.mimeType}]` : '';
|
|
373
|
+
lines.push(`**${entry.alphaId}** — ${entry.typeName}: "${entry.name}"${versionNote}${idNote}${mimeNote}${sizeSuffix}`);
|
|
374
|
+
if (entry.description) {
|
|
375
|
+
const desc = entry.description.length > 240 ? entry.description.slice(0, 240) + '…' : entry.description;
|
|
376
|
+
lines.push(` > Description: ${desc}`);
|
|
377
|
+
}
|
|
378
|
+
const shape = this.describeContentShape(entry.content);
|
|
379
|
+
if (shape) {
|
|
380
|
+
lines.push(` > Shape: ${shape}`);
|
|
381
|
+
}
|
|
382
|
+
const mismatch = this.modalityMismatchMessage(entry.mimeType, supportedMimes);
|
|
383
|
+
if (mismatch) {
|
|
384
|
+
lines.push(` > ⚠ ${mismatch}`);
|
|
385
|
+
}
|
|
386
|
+
if (entry.annotation) {
|
|
387
|
+
const annotation = entry.annotation.length > ArtifactToolManager.MAX_MANIFEST_PREVIEW_CHARS_PER_ARTIFACT
|
|
388
|
+
? entry.annotation.slice(0, ArtifactToolManager.MAX_MANIFEST_PREVIEW_CHARS_PER_ARTIFACT) + '...[truncated]'
|
|
389
|
+
: entry.annotation;
|
|
390
|
+
lines.push(` > Note: ${annotation}`);
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
lines.push('');
|
|
394
|
+
lines.push('These artifacts are ALREADY available to you server-side. Read them directly with the');
|
|
395
|
+
lines.push('artifact tools below (e.g. `get_full`), or use one as a pipeline source (e.g. `get_full`');
|
|
396
|
+
lines.push('then `where`/`select`/`distinct`). NEVER ask the user to paste, provide, upload, or "send"');
|
|
397
|
+
lines.push('an artifact\'s content, and do NOT request a data snapshot to obtain it — you already have it.');
|
|
398
|
+
}
|
|
295
399
|
if (opts?.nativeTools) {
|
|
296
|
-
|
|
297
|
-
lines.push('IMPORTANT: Always use the single-letter artifact ID (A, B, C, etc.) as the `artifactId` argument of `artifact_tool` — NOT the artifact name.');
|
|
400
|
+
lines.push('IMPORTANT: For per-artifact tools, pass the single-letter artifact ID (A, B, C, etc.) as `artifactId` on `artifact_tool` (for workspace-wide tools such as `create_artifact`, `open_artifact`, or `list_workspace_artifacts`, `artifactId` may be omitted).');
|
|
298
401
|
return lines.join('\n');
|
|
299
402
|
}
|
|
300
|
-
lines.push('IMPORTANT:
|
|
301
|
-
|
|
403
|
+
lines.push('IMPORTANT: For per-artifact tools, pass the single-letter artifact ID (A, B, C, etc.) as `artifactId` in `artifactToolCalls` (for workspace-wide tools such as `create_artifact`, `open_artifact`, or `list_workspace_artifacts`, pass `artifactId: "workspace"`).');
|
|
404
|
+
if (this.artifacts.size > 0) {
|
|
405
|
+
lines.push('Artifact tools persist and version your edits directly — do NOT write artifact contents or tool state into `payload`/`payloadChangeRequest`, and do NOT emit `artifactDirective` (`version-source`) for artifacts you edited via artifact tools. Reserve `artifactDirective.targetArtifactId` (UUID or single-letter ID) only when persisting a standalone JSON `payload` deliverable.');
|
|
406
|
+
}
|
|
302
407
|
return lines.join('\n');
|
|
303
408
|
}
|
|
304
409
|
/**
|
|
305
|
-
* Distinct artifact tool names available across all input artifacts
|
|
306
|
-
* artifact tools into a pipeline's tool registry (one invocable per name; the target
|
|
307
|
-
* artifact is selected at call time via an `artifactId` param).
|
|
410
|
+
* Distinct artifact tool names available across all input artifacts and workspace tools.
|
|
308
411
|
*/
|
|
309
412
|
GetAvailableToolNames() {
|
|
310
413
|
const names = new Set();
|
|
@@ -313,6 +416,16 @@ export class ArtifactToolManager {
|
|
|
313
416
|
names.add(tool.name);
|
|
314
417
|
}
|
|
315
418
|
}
|
|
419
|
+
if (this.IsWorkspaceEnabled()) {
|
|
420
|
+
names.add('create_artifact');
|
|
421
|
+
names.add('open_artifact');
|
|
422
|
+
names.add('list_workspace_artifacts');
|
|
423
|
+
names.add('create_synthesized_artifact');
|
|
424
|
+
names.add('refresh_and_snapshot_artifact');
|
|
425
|
+
}
|
|
426
|
+
if (this.artifacts.size > 0) {
|
|
427
|
+
names.add('reload_artifact');
|
|
428
|
+
}
|
|
316
429
|
return [...names];
|
|
317
430
|
}
|
|
318
431
|
/**
|
|
@@ -347,13 +460,15 @@ export class ArtifactToolManager {
|
|
|
347
460
|
extras.push(`Title: "${obj.title.trim().slice(0, 120)}".`);
|
|
348
461
|
}
|
|
349
462
|
if (Array.isArray(obj.tables) && obj.tables.length > 0) {
|
|
350
|
-
const tableSummaries = obj.tables.slice(0, 8).map((
|
|
463
|
+
const tableSummaries = obj.tables.slice(0, 8).map((item) => {
|
|
464
|
+
const t = item !== null && typeof item === 'object' && !Array.isArray(item) ? item : undefined;
|
|
351
465
|
const tName = typeof t?.name === 'string' ? t.name : (typeof t?.id === 'string' ? t.id : 'table');
|
|
466
|
+
const meta = t?.metadata !== null && typeof t?.metadata === 'object' && !Array.isArray(t?.metadata)
|
|
467
|
+
? t.metadata
|
|
468
|
+
: undefined;
|
|
352
469
|
const tRows = Array.isArray(t?.rows)
|
|
353
470
|
? t.rows.length
|
|
354
|
-
: (typeof
|
|
355
|
-
? t.metadata.rowCount
|
|
356
|
-
: 0);
|
|
471
|
+
: (typeof meta?.rowCount === 'number' ? meta.rowCount : 0);
|
|
357
472
|
return `"${tName}" (${tRows} rows)`;
|
|
358
473
|
});
|
|
359
474
|
extras.push(`Tables (${obj.tables.length}): ${tableSummaries.join(', ')}.`);
|
|
@@ -373,9 +488,9 @@ export class ArtifactToolManager {
|
|
|
373
488
|
const preview = s.replace(/\s+/g, ' ').slice(0, 120);
|
|
374
489
|
return `text, ${s.split('\n').length} line(s); starts: "${preview}${s.length > 120 ? '…' : ''}"`;
|
|
375
490
|
}
|
|
376
|
-
/** Markdown tool documentation grouped by artifact type */
|
|
491
|
+
/** Markdown tool documentation grouped by artifact type and workspace capabilities */
|
|
377
492
|
GetToolDocumentation() {
|
|
378
|
-
if (this.
|
|
493
|
+
if (!this.IsWorkspaceEnabled())
|
|
379
494
|
return '';
|
|
380
495
|
// Collect unique type → library pairs
|
|
381
496
|
const typeLibraries = new Map();
|
|
@@ -391,11 +506,23 @@ export class ArtifactToolManager {
|
|
|
391
506
|
continue;
|
|
392
507
|
sections.push(`## ${typeName} Artifact Tools`);
|
|
393
508
|
for (const tool of tools) {
|
|
394
|
-
const
|
|
509
|
+
const schemaProps = tool.inputSchema.properties;
|
|
510
|
+
const propObj = schemaProps !== null && typeof schemaProps === 'object' && !Array.isArray(schemaProps)
|
|
511
|
+
? schemaProps
|
|
512
|
+
: {};
|
|
513
|
+
const params = Object.keys(propObj).join(', ');
|
|
395
514
|
sections.push(`- **${tool.name}**(artifactId${params ? ', ' + params : ''}) — ${tool.description}`);
|
|
396
515
|
}
|
|
516
|
+
sections.push(`- **reload_artifact**(artifactId) — Reloads the latest persisted version of the artifact from the database to recover after a concurrent modification conflict.`);
|
|
397
517
|
sections.push('');
|
|
398
518
|
}
|
|
519
|
+
sections.push('## Workspace & Cross-Artifact Tools');
|
|
520
|
+
sections.push('- **create_artifact**(title, artifactType, description?, content?, sheetNames?, initialOperations?, collectionId?) — Creates and persists a new governed artifact (`"Excel Spreadsheet"`, `"Markdown Document"`, or `"Presentation"`), optionally applying an array of initial `{ tool, input }` domain operations atomically before saving v1 (or registers it in this session with its alpha ID `A`, `B`, ... so you can call domain tools like `upsert_live_table`, `write_cells`, `insert_block_after`, `add_slide`), and streams live edits to connected viewers.');
|
|
521
|
+
sections.push('- **open_artifact**(artifactId) — Opens an existing governed artifact by UUID (checking Read permission and hydrating from any active live collaboration room), registers it in this session, and returns its alpha ID plus available domain tools.');
|
|
522
|
+
sections.push('- **list_workspace_artifacts**(collectionId?, typeFilter?, search?) — Lists readable artifacts in the current workspace (and optionally inside a Collection) along with summaries and Spreadsheet ChartID/range references.');
|
|
523
|
+
sections.push('- **create_synthesized_artifact**(title, targetKind, goal?, sourceArtifactIds?, content?, description?, collectionId?, linkChartsAndRanges?) — Creates and persists a new synthesized governed artifact (`targetKind`: `"presentation"` | `"document"` | `"spreadsheet"`) from multiple source artifacts while enforcing permissions and stripping unauthorized references.');
|
|
524
|
+
sections.push('- **refresh_and_snapshot_artifact**(targetArtifactId, mode?, versionComment?, skipIfUnchanged?, forceRefreshFrozen?) — Refreshes live blocks and `=MJ.*` formulas under Edit permissions (`mode`: `"live_refresh"`; block freezing is disabled for agents and requires a direct human action in the UI), reconciles live collaboration state, preserves `.xlsx` File-mode binaries, and persists a new version when changed.');
|
|
525
|
+
sections.push('');
|
|
399
526
|
return sections.join('\n');
|
|
400
527
|
}
|
|
401
528
|
/**
|
|
@@ -451,6 +578,82 @@ export class ArtifactToolManager {
|
|
|
451
578
|
.join(', ')})`;
|
|
452
579
|
}
|
|
453
580
|
// ─── TOOL EXECUTION ───
|
|
581
|
+
/**
|
|
582
|
+
* Serializes async operations per artifact through the process-wide `GovernedArtifactService` lock
|
|
583
|
+
* backed by `GetGlobalObjectStore()` so parallel calls, sub-agents, and CoreActions never race.
|
|
584
|
+
*/
|
|
585
|
+
async withArtifactLock(lockKey, fn) {
|
|
586
|
+
return GovernedArtifactService.Instance.WithArtifactLock(lockKey, fn);
|
|
587
|
+
}
|
|
588
|
+
resolveExistingArtifactEntry(rawArtifactId) {
|
|
589
|
+
const trimmed = (rawArtifactId ?? '').trim();
|
|
590
|
+
if (!trimmed || trimmed.toLowerCase() === 'default' || trimmed === '*') {
|
|
591
|
+
return this.artifacts.size === 1 ? this.artifacts.values().next().value : undefined;
|
|
592
|
+
}
|
|
593
|
+
const direct = this.artifacts.get(trimmed);
|
|
594
|
+
if (direct)
|
|
595
|
+
return direct;
|
|
596
|
+
const lower = trimmed.toLowerCase();
|
|
597
|
+
const isUuid = IsValidUUID(trimmed);
|
|
598
|
+
for (const e of this.artifacts.values()) {
|
|
599
|
+
if (e.alphaId.toLowerCase() === lower || `artifact ${e.alphaId.toLowerCase()}` === lower) {
|
|
600
|
+
return e;
|
|
601
|
+
}
|
|
602
|
+
if (isUuid && e.artifactId && UUIDsEqual(e.artifactId, trimmed)) {
|
|
603
|
+
return e;
|
|
604
|
+
}
|
|
605
|
+
if (e.name.toLowerCase() === lower || e.name.toLowerCase().replace(/\s+/g, '_') === lower) {
|
|
606
|
+
return e;
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
return undefined;
|
|
610
|
+
}
|
|
611
|
+
sanitizeToolInput(input) {
|
|
612
|
+
if (!input)
|
|
613
|
+
return {};
|
|
614
|
+
const sanitized = {};
|
|
615
|
+
for (const [k, v] of Object.entries(input)) {
|
|
616
|
+
if (k === '_actorUserId' || k === '_ownerUserId' || k === '_isEditor')
|
|
617
|
+
continue;
|
|
618
|
+
sanitized[k] = v;
|
|
619
|
+
}
|
|
620
|
+
return sanitized;
|
|
621
|
+
}
|
|
622
|
+
async resolveEntryOwnerUserId(entry) {
|
|
623
|
+
if (entry.ownerUserId !== undefined) {
|
|
624
|
+
return entry.ownerUserId;
|
|
625
|
+
}
|
|
626
|
+
if (!entry.artifactId || !this.provider || !this.contextUser || !IsValidUUID(entry.artifactId)) {
|
|
627
|
+
return undefined;
|
|
628
|
+
}
|
|
629
|
+
try {
|
|
630
|
+
const rv = RunView.FromMetadataProvider(this.provider);
|
|
631
|
+
const artRes = await rv.RunView({
|
|
632
|
+
EntityName: 'MJ: Artifacts',
|
|
633
|
+
ExtraFilter: `ID='${EscapeSQLString(entry.artifactId)}'`,
|
|
634
|
+
Fields: ['ID', 'UserID'],
|
|
635
|
+
MaxRows: 1,
|
|
636
|
+
SkipTotalRowCount: true,
|
|
637
|
+
ResultType: 'simple',
|
|
638
|
+
}, this.contextUser);
|
|
639
|
+
if (artRes.Success && artRes.Results?.length) {
|
|
640
|
+
const owner = (artRes.Results[0].UserID ?? '').trim();
|
|
641
|
+
if (owner) {
|
|
642
|
+
entry.ownerUserId = owner;
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
catch {
|
|
647
|
+
// Best-effort owner resolution; leave undefined if mock/provider omits UserID
|
|
648
|
+
}
|
|
649
|
+
return entry.ownerUserId;
|
|
650
|
+
}
|
|
651
|
+
/**
|
|
652
|
+
* Alias for {@link ExecuteSingleToolCall} supporting single-call dispatch.
|
|
653
|
+
*/
|
|
654
|
+
async ExecuteToolCall(call) {
|
|
655
|
+
return this.ExecuteSingleToolCall(call);
|
|
656
|
+
}
|
|
454
657
|
/**
|
|
455
658
|
* Execute a single tool call and return its stored result. The result is
|
|
456
659
|
* also retained in the manager's internal store, so {@link ToJSON} reflects
|
|
@@ -462,21 +665,22 @@ export class ArtifactToolManager {
|
|
|
462
665
|
*/
|
|
463
666
|
async ExecuteSingleToolCall(call) {
|
|
464
667
|
const startedAt = Date.now();
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
if (e.name.toLowerCase() === call.artifactId.toLowerCase() || e.name.toLowerCase().replace(/\s+/g, '_') === call.artifactId.toLowerCase()) {
|
|
471
|
-
entry = e;
|
|
472
|
-
break;
|
|
473
|
-
}
|
|
474
|
-
}
|
|
668
|
+
if (call.tool === 'create_artifact') {
|
|
669
|
+
return this.handleCreateArtifactTool(call, startedAt);
|
|
670
|
+
}
|
|
671
|
+
if (call.tool === 'open_artifact') {
|
|
672
|
+
return this.handleOpenArtifactTool(call, startedAt);
|
|
475
673
|
}
|
|
476
|
-
if (
|
|
477
|
-
|
|
478
|
-
entry = this.artifacts.values().next().value;
|
|
674
|
+
if (call.tool === 'list_workspace_artifacts') {
|
|
675
|
+
return this.handleListWorkspaceArtifactsTool(call, startedAt);
|
|
479
676
|
}
|
|
677
|
+
if (call.tool === 'create_synthesized_artifact') {
|
|
678
|
+
return this.handleCreateSynthesizedArtifactTool(call, startedAt);
|
|
679
|
+
}
|
|
680
|
+
if (call.tool === 'refresh_and_snapshot_artifact') {
|
|
681
|
+
return this.handleRefreshAndSnapshotArtifactTool(call, startedAt);
|
|
682
|
+
}
|
|
683
|
+
const entry = this.resolveExistingArtifactEntry(call.artifactId);
|
|
480
684
|
if (!entry) {
|
|
481
685
|
const stored = {
|
|
482
686
|
artifactId: call.artifactId,
|
|
@@ -485,7 +689,7 @@ export class ArtifactToolManager {
|
|
|
485
689
|
result: {
|
|
486
690
|
success: false,
|
|
487
691
|
data: null,
|
|
488
|
-
errorMessage: `Unknown artifact ID: ${call.artifactId}. Use
|
|
692
|
+
errorMessage: `Unknown artifact ID: ${call.artifactId}. Use open_artifact or pass an alpha ID (A, B, C, etc.) from the manifest.`,
|
|
489
693
|
},
|
|
490
694
|
timestamp: new Date(),
|
|
491
695
|
durationMs: Date.now() - startedAt,
|
|
@@ -493,103 +697,2423 @@ export class ArtifactToolManager {
|
|
|
493
697
|
this.toolResults.push(stored);
|
|
494
698
|
return stored;
|
|
495
699
|
}
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
700
|
+
const targetEntry = entry;
|
|
701
|
+
const lockKey = targetEntry.artifactId ?? targetEntry.alphaId;
|
|
702
|
+
return this.withArtifactLock(lockKey, async () => {
|
|
703
|
+
const isMutatingTool = ArtifactToolManager.MUTATING_TOOL_NAMES.has(call.tool);
|
|
704
|
+
const sanitizedInput = this.sanitizeToolInput(call.input);
|
|
705
|
+
let resolvedPerms;
|
|
706
|
+
// 1. Permission check before any tool execution (Blocker 2, Lower #4 fail-closed on missing context)
|
|
707
|
+
if (targetEntry.artifactId) {
|
|
708
|
+
if (!this.contextUser || !this.provider) {
|
|
709
|
+
const missingCtxStored = {
|
|
710
|
+
artifactId: call.artifactId,
|
|
711
|
+
tool: call.tool,
|
|
712
|
+
input: sanitizedInput,
|
|
713
|
+
result: {
|
|
714
|
+
success: false,
|
|
715
|
+
data: null,
|
|
716
|
+
errorMessage: 'Permission denied: authenticated contextUser and provider are required to access a persisted artifact.',
|
|
717
|
+
},
|
|
718
|
+
timestamp: new Date(),
|
|
719
|
+
durationMs: Date.now() - startedAt,
|
|
720
|
+
};
|
|
721
|
+
this.toolResults.push(missingCtxStored);
|
|
722
|
+
return missingCtxStored;
|
|
723
|
+
}
|
|
724
|
+
resolvedPerms = await ArtifactPermissionEngine.Instance.ResolvePermissions(this.provider, targetEntry.artifactId, this.contextUser);
|
|
725
|
+
if (isMutatingTool && !resolvedPerms.CanEdit) {
|
|
726
|
+
const deniedStored = {
|
|
727
|
+
artifactId: call.artifactId,
|
|
728
|
+
tool: call.tool,
|
|
729
|
+
input: sanitizedInput,
|
|
730
|
+
result: {
|
|
731
|
+
success: false,
|
|
732
|
+
data: null,
|
|
733
|
+
errorMessage: 'Permission denied: user does not have edit access to this artifact',
|
|
734
|
+
},
|
|
735
|
+
timestamp: new Date(),
|
|
736
|
+
durationMs: Date.now() - startedAt,
|
|
737
|
+
};
|
|
738
|
+
this.toolResults.push(deniedStored);
|
|
739
|
+
return deniedStored;
|
|
740
|
+
}
|
|
741
|
+
if (!isMutatingTool && !resolvedPerms.CanRead) {
|
|
742
|
+
const deniedStored = {
|
|
743
|
+
artifactId: call.artifactId,
|
|
744
|
+
tool: call.tool,
|
|
745
|
+
input: sanitizedInput,
|
|
746
|
+
result: {
|
|
747
|
+
success: false,
|
|
748
|
+
data: null,
|
|
749
|
+
errorMessage: 'Permission denied: user does not have read access to this artifact',
|
|
750
|
+
},
|
|
751
|
+
timestamp: new Date(),
|
|
752
|
+
durationMs: Date.now() - startedAt,
|
|
753
|
+
};
|
|
754
|
+
this.toolResults.push(deniedStored);
|
|
755
|
+
return deniedStored;
|
|
756
|
+
}
|
|
757
|
+
}
|
|
758
|
+
// 1b. Handle universal reload_artifact recovery tool (Round 3 Item 9)
|
|
759
|
+
if (call.tool === 'reload_artifact') {
|
|
760
|
+
const reloadResult = await this.reloadArtifactFromDatabase(targetEntry);
|
|
761
|
+
const reloadStored = {
|
|
762
|
+
artifactId: call.artifactId,
|
|
763
|
+
tool: call.tool,
|
|
764
|
+
input: call.input,
|
|
765
|
+
result: reloadResult,
|
|
766
|
+
timestamp: new Date(),
|
|
767
|
+
durationMs: Date.now() - startedAt,
|
|
768
|
+
};
|
|
769
|
+
this.toolResults.push(reloadStored);
|
|
770
|
+
return reloadStored;
|
|
771
|
+
}
|
|
772
|
+
// 2. Real DB concurrency pre-check before mutating in-memory session state
|
|
773
|
+
if (isMutatingTool && targetEntry.artifactId && this.contextUser && this.provider) {
|
|
774
|
+
const conflictError = await this.checkConcurrentDatabaseModification(targetEntry);
|
|
775
|
+
if (conflictError) {
|
|
776
|
+
const conflictStored = {
|
|
777
|
+
artifactId: call.artifactId,
|
|
778
|
+
tool: call.tool,
|
|
779
|
+
input: call.input,
|
|
780
|
+
result: {
|
|
781
|
+
success: false,
|
|
782
|
+
data: null,
|
|
783
|
+
errorMessage: conflictError,
|
|
784
|
+
},
|
|
785
|
+
timestamp: new Date(),
|
|
786
|
+
durationMs: Date.now() - startedAt,
|
|
787
|
+
};
|
|
788
|
+
this.toolResults.push(conflictStored);
|
|
789
|
+
return conflictStored;
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
// 2b. Refuse structural mutations on File-mode .xlsx workbooks to preserve OpenXML fidelity (Round 3 Item 12)
|
|
793
|
+
if ((targetEntry.contentMode === 'File' || Boolean(targetEntry.originalXlsxBytes)) &&
|
|
794
|
+
ArtifactToolManager.STRUCTURAL_SPREADSHEET_TOOLS.has(call.tool)) {
|
|
795
|
+
const refusedStored = {
|
|
796
|
+
artifactId: call.artifactId,
|
|
797
|
+
tool: call.tool,
|
|
798
|
+
input: call.input,
|
|
799
|
+
result: {
|
|
800
|
+
success: false,
|
|
801
|
+
data: null,
|
|
802
|
+
errorMessage: FormatFileModeStructuralToolError(call.tool),
|
|
803
|
+
},
|
|
804
|
+
timestamp: new Date(),
|
|
805
|
+
durationMs: Date.now() - startedAt,
|
|
806
|
+
};
|
|
807
|
+
this.toolResults.push(refusedStored);
|
|
808
|
+
return refusedStored;
|
|
809
|
+
}
|
|
810
|
+
const presenceArtifactId = targetEntry.artifactId;
|
|
811
|
+
const activeRunIdForCall = this.agentRunId ?? this.getAgentRun?.()?.ID;
|
|
812
|
+
const activeAgentNameForCall = this.agentName ?? this.getAgentRun?.()?.Agent ?? undefined;
|
|
813
|
+
const preLocation = ExtractAgentTargetLocation(call.tool, sanitizedInput, targetEntry.content, targetEntry.typeName);
|
|
814
|
+
let presenceEmittedWorking = false;
|
|
815
|
+
let settledContent = targetEntry.content;
|
|
816
|
+
let settledData;
|
|
817
|
+
if (presenceArtifactId && this.contextUser) {
|
|
818
|
+
this.enteredPresenceArtifactIds.add(presenceArtifactId);
|
|
819
|
+
presenceEmittedWorking = true;
|
|
820
|
+
await GovernedArtifactService.Instance.EmitAgentPresence({
|
|
821
|
+
artifactId: presenceArtifactId,
|
|
822
|
+
phase: 'working',
|
|
823
|
+
contextUser: this.contextUser,
|
|
824
|
+
agentRunId: activeRunIdForCall,
|
|
825
|
+
agentName: activeAgentNameForCall,
|
|
826
|
+
toolName: call.tool,
|
|
827
|
+
actionSummary: FormatAgentActionSummary(call.tool, sanitizedInput, preLocation),
|
|
828
|
+
location: preLocation ?? { Domain: ResolvePresenceDomain(targetEntry.typeName) },
|
|
829
|
+
});
|
|
830
|
+
}
|
|
831
|
+
try {
|
|
832
|
+
const ownerUserId = await this.resolveEntryOwnerUserId(targetEntry);
|
|
833
|
+
// Wrap InvokeTool so any exception inside a handler becomes a structured
|
|
834
|
+
// error result instead of propagating up to the agent loop.
|
|
835
|
+
const toolContext = {
|
|
836
|
+
contextUser: this.contextUser,
|
|
837
|
+
actorUserId: this.contextUser?.ID,
|
|
838
|
+
ownerUserId,
|
|
839
|
+
isEditor: resolvedPerms?.CanEdit,
|
|
840
|
+
provider: this.provider,
|
|
841
|
+
artifactId: targetEntry.artifactId,
|
|
842
|
+
agentRunId: activeRunIdForCall,
|
|
843
|
+
agentName: activeAgentNameForCall,
|
|
844
|
+
resolveArtifactId: (idOrAlpha) => this.ResolveArtifactUuid(idOrAlpha),
|
|
845
|
+
resolveVersionId: (idOrAlpha) => this.ResolveArtifactVersionUuid(idOrAlpha),
|
|
846
|
+
};
|
|
847
|
+
let result;
|
|
848
|
+
try {
|
|
849
|
+
result = await targetEntry.library.InvokeTool(call.tool, sanitizedInput, targetEntry.content, toolContext);
|
|
850
|
+
}
|
|
851
|
+
catch (err) {
|
|
852
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
853
|
+
result = {
|
|
854
|
+
success: false,
|
|
855
|
+
data: null,
|
|
856
|
+
errorMessage: `Tool "${call.tool}" on artifact ${targetEntry.alphaId} threw: ${msg}. The artifact content may be malformed for this tool — try a different tool or a different artifact.`,
|
|
857
|
+
};
|
|
858
|
+
}
|
|
859
|
+
let storedResult = result;
|
|
860
|
+
const resultObj = result.success && result.data !== null && typeof result.data === 'object' && !Array.isArray(result.data)
|
|
861
|
+
? result.data
|
|
862
|
+
: undefined;
|
|
863
|
+
const rawConfigurationPatch = resultObj &&
|
|
864
|
+
resultObj.configurationPatch !== null &&
|
|
865
|
+
typeof resultObj.configurationPatch === 'object' &&
|
|
866
|
+
!Array.isArray(resultObj.configurationPatch)
|
|
867
|
+
? resultObj.configurationPatch
|
|
868
|
+
: undefined;
|
|
869
|
+
const hasContentMutation = Boolean(resultObj && resultObj.updatedContent !== undefined);
|
|
870
|
+
const hasConfigPatchMutation = Boolean(rawConfigurationPatch);
|
|
871
|
+
if (resultObj && (hasContentMutation || hasConfigPatchMutation)) {
|
|
872
|
+
if (resolvedPerms && !resolvedPerms.CanEdit) {
|
|
873
|
+
const deniedMutation = {
|
|
874
|
+
artifactId: call.artifactId,
|
|
875
|
+
tool: call.tool,
|
|
876
|
+
input: sanitizedInput,
|
|
877
|
+
result: {
|
|
878
|
+
success: false,
|
|
879
|
+
data: null,
|
|
880
|
+
errorMessage: 'Permission denied: user does not have edit access to this artifact',
|
|
881
|
+
},
|
|
882
|
+
timestamp: new Date(),
|
|
883
|
+
durationMs: Date.now() - startedAt,
|
|
884
|
+
};
|
|
885
|
+
this.toolResults.push(deniedMutation);
|
|
886
|
+
return deniedMutation;
|
|
887
|
+
}
|
|
888
|
+
if (!isMutatingTool && targetEntry.artifactId && this.contextUser && this.provider) {
|
|
889
|
+
const lateConflict = await this.checkConcurrentDatabaseModification(targetEntry);
|
|
890
|
+
if (lateConflict) {
|
|
891
|
+
const conflictStored = {
|
|
892
|
+
artifactId: call.artifactId,
|
|
893
|
+
tool: call.tool,
|
|
894
|
+
input: sanitizedInput,
|
|
895
|
+
result: {
|
|
896
|
+
success: false,
|
|
897
|
+
data: null,
|
|
898
|
+
errorMessage: lateConflict,
|
|
899
|
+
},
|
|
900
|
+
timestamp: new Date(),
|
|
901
|
+
durationMs: Date.now() - startedAt,
|
|
902
|
+
};
|
|
903
|
+
this.toolResults.push(conflictStored);
|
|
904
|
+
return conflictStored;
|
|
905
|
+
}
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
if (resultObj && (typeof resultObj.updatedContent === 'string' || hasConfigPatchMutation)) {
|
|
909
|
+
const rawData = resultObj;
|
|
910
|
+
const rawUpdatedContent = typeof rawData.updatedContent === 'string' ? rawData.updatedContent : undefined;
|
|
911
|
+
const hasUpdatedContentString = rawUpdatedContent !== undefined;
|
|
912
|
+
const fallbackExistingStr = typeof targetEntry.content === 'string'
|
|
913
|
+
? targetEntry.content
|
|
914
|
+
: typeof targetEntry.configuration === 'string'
|
|
915
|
+
? targetEntry.configuration
|
|
916
|
+
: '';
|
|
917
|
+
const updatedContent = rawUpdatedContent ?? fallbackExistingStr;
|
|
918
|
+
let xlsxBase64 = typeof rawData.xlsxBase64 === 'string' ? rawData.xlsxBase64 : undefined;
|
|
919
|
+
const previousContent = targetEntry.content;
|
|
920
|
+
const previousContentStr = typeof previousContent === 'string' ? previousContent : undefined;
|
|
921
|
+
const previousOriginalXlsxBytes = targetEntry.originalXlsxBytes;
|
|
922
|
+
// If the spreadsheet started from an uploaded .xlsx binary, patch the original ZIP bytes in-place (fail closed on error)
|
|
923
|
+
if (targetEntry.originalXlsxBytes) {
|
|
924
|
+
if (!hasUpdatedContentString && !xlsxBase64) {
|
|
925
|
+
// Config-patch-only mutation (e.g. suggestion/comment): preserve existing .xlsx binary bytes intact.
|
|
926
|
+
xlsxBase64 = Buffer.from(targetEntry.originalXlsxBytes).toString('base64');
|
|
927
|
+
}
|
|
928
|
+
else if (hasUpdatedContentString) {
|
|
929
|
+
try {
|
|
930
|
+
const parsedWorkbook = await SpreadsheetEngine.Instance.ParseWorkbookIsolated(updatedContent, undefined, {
|
|
931
|
+
SkipEvaluate: true,
|
|
932
|
+
});
|
|
933
|
+
const patchedBytes = await XlsxOpenXmlAdapter.Instance.PatchXlsxBytesIsolated(targetEntry.originalXlsxBytes, parsedWorkbook);
|
|
934
|
+
targetEntry.originalXlsxBytes = patchedBytes;
|
|
935
|
+
xlsxBase64 = Buffer.from(patchedBytes).toString('base64');
|
|
936
|
+
}
|
|
937
|
+
catch (patchErr) {
|
|
938
|
+
const failedPatch = {
|
|
939
|
+
artifactId: call.artifactId,
|
|
940
|
+
tool: call.tool,
|
|
941
|
+
input: call.input,
|
|
942
|
+
result: {
|
|
943
|
+
success: false,
|
|
944
|
+
data: null,
|
|
945
|
+
errorMessage: `Failed to patch File-mode .xlsx binary in-place: ${patchErr instanceof Error ? patchErr.message : String(patchErr)}`,
|
|
946
|
+
},
|
|
947
|
+
timestamp: new Date(),
|
|
948
|
+
durationMs: Date.now() - startedAt,
|
|
949
|
+
};
|
|
950
|
+
this.toolResults.push(failedPatch);
|
|
951
|
+
return failedPatch;
|
|
952
|
+
}
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
// 1. Reconcile against live Yjs collaboration room via registered hook BEFORE persisting Version
|
|
956
|
+
// so persisted MJ: Artifact Versions and targetEntry.content never diverge from the live room (`R8-2d`).
|
|
957
|
+
const hook = GetArtifactLiveMutationHook();
|
|
958
|
+
const activeAgentRunId = this.agentRunId ?? this.getAgentRun?.()?.ID;
|
|
959
|
+
const activeAgentName = this.agentName ?? this.getAgentRun?.()?.Agent ?? undefined;
|
|
960
|
+
let hookResult = undefined;
|
|
961
|
+
let hookInvokedBeforePersist = false;
|
|
962
|
+
const willPersist = Boolean(targetEntry.artifactId && this.contextUser && this.provider);
|
|
963
|
+
const prospectiveVersionNumber = willPersist
|
|
964
|
+
? targetEntry.agentRunVersionEntity && targetEntry.agentRunVersionId
|
|
965
|
+
? (targetEntry.currentVersionNumber ?? targetEntry.versionNumber ?? 1)
|
|
966
|
+
: (targetEntry.currentVersionNumber ?? targetEntry.versionNumber ?? 0) + 1
|
|
967
|
+
: targetEntry.versionNumber;
|
|
968
|
+
if (hook && targetEntry.artifactId) {
|
|
969
|
+
hookInvokedBeforePersist = true;
|
|
970
|
+
try {
|
|
971
|
+
hookResult = await hook({
|
|
972
|
+
artifactId: targetEntry.artifactId,
|
|
973
|
+
alphaId: targetEntry.alphaId,
|
|
974
|
+
versionId: targetEntry.agentRunVersionId ?? targetEntry.versionId,
|
|
975
|
+
versionNumber: prospectiveVersionNumber,
|
|
976
|
+
previousContent: previousContentStr,
|
|
977
|
+
updatedContent,
|
|
978
|
+
xlsxBase64,
|
|
979
|
+
configurationPatch: rawConfigurationPatch,
|
|
980
|
+
tool: call.tool,
|
|
981
|
+
contextUser: this.contextUser,
|
|
982
|
+
agentRunId: activeAgentRunId,
|
|
983
|
+
agentName: activeAgentName,
|
|
984
|
+
deferCommit: willPersist,
|
|
985
|
+
});
|
|
986
|
+
}
|
|
987
|
+
catch (hookErr) {
|
|
988
|
+
const hookMsg = hookErr instanceof Error ? hookErr.message : String(hookErr);
|
|
989
|
+
LogError(`ArtifactToolManager: live mutation hook failed for artifact '${targetEntry.artifactId}': ${hookMsg}`);
|
|
990
|
+
if (willPersist) {
|
|
991
|
+
targetEntry.originalXlsxBytes = previousOriginalXlsxBytes;
|
|
992
|
+
const failedHookStored = {
|
|
993
|
+
artifactId: call.artifactId,
|
|
994
|
+
tool: call.tool,
|
|
995
|
+
input: call.input,
|
|
996
|
+
result: {
|
|
997
|
+
success: false,
|
|
998
|
+
data: null,
|
|
999
|
+
errorMessage: `Live collaboration room hook failed before save: ${hookMsg}`,
|
|
1000
|
+
},
|
|
1001
|
+
timestamp: new Date(),
|
|
1002
|
+
durationMs: Date.now() - startedAt,
|
|
1003
|
+
};
|
|
1004
|
+
this.toolResults.push(failedHookStored);
|
|
1005
|
+
return failedHookStored;
|
|
1006
|
+
}
|
|
1007
|
+
}
|
|
1008
|
+
}
|
|
1009
|
+
let effectiveContent = hookResult && typeof hookResult === 'object' && typeof hookResult.mergedContent === 'string'
|
|
1010
|
+
? hookResult.mergedContent
|
|
1011
|
+
: updatedContent;
|
|
1012
|
+
if (effectiveContent !== updatedContent && previousOriginalXlsxBytes) {
|
|
1013
|
+
try {
|
|
1014
|
+
const mergedWorkbook = await SpreadsheetEngine.Instance.ParseWorkbookIsolated(effectiveContent, undefined, {
|
|
1015
|
+
SkipEvaluate: true,
|
|
1016
|
+
});
|
|
1017
|
+
const mergedBytes = await XlsxOpenXmlAdapter.Instance.PatchXlsxBytesIsolated(previousOriginalXlsxBytes, mergedWorkbook);
|
|
1018
|
+
targetEntry.originalXlsxBytes = mergedBytes;
|
|
1019
|
+
xlsxBase64 = Buffer.from(mergedBytes).toString('base64');
|
|
1020
|
+
}
|
|
1021
|
+
catch (repatchErr) {
|
|
1022
|
+
LogError(`ArtifactToolManager: failed re-patching xlsx bytes after live merge for artifact '${targetEntry.artifactId}': ${repatchErr instanceof Error ? repatchErr.message : String(repatchErr)}`);
|
|
1023
|
+
}
|
|
1024
|
+
}
|
|
1025
|
+
// 2. Update in-memory entry.content so sequential tool calls see the reconciled content & revisionHash
|
|
1026
|
+
if (hasUpdatedContentString || !Buffer.isBuffer(previousContent)) {
|
|
1027
|
+
targetEntry.content = effectiveContent;
|
|
1028
|
+
}
|
|
1029
|
+
if (hasConfigPatchMutation && (!targetEntry.artifactId || !this.contextUser || !this.provider)) {
|
|
1030
|
+
targetEntry.configuration = BuildMergedFileVersionConfiguration({
|
|
1031
|
+
existingConfiguration: targetEntry.configuration,
|
|
1032
|
+
contentConfigurationJson: hasUpdatedContentString ? effectiveContent : undefined,
|
|
1033
|
+
configurationPatch: rawConfigurationPatch,
|
|
1034
|
+
});
|
|
1035
|
+
}
|
|
1036
|
+
// 3. Persist a single MJ: Artifact Versions record per agent run when artifactId, contextUser, and provider are available
|
|
1037
|
+
let persisted = false;
|
|
1038
|
+
let commitWarning = null;
|
|
1039
|
+
if (targetEntry.artifactId && this.contextUser && this.provider) {
|
|
1040
|
+
const persistOutcome = await this.persistArtifactVersionMutation(targetEntry, effectiveContent, xlsxBase64, call.tool, previousContentStr, rawConfigurationPatch);
|
|
1041
|
+
if (!persistOutcome.persisted) {
|
|
1042
|
+
targetEntry.content = previousContent;
|
|
1043
|
+
targetEntry.originalXlsxBytes = previousOriginalXlsxBytes;
|
|
1044
|
+
const failedStored = {
|
|
1045
|
+
artifactId: call.artifactId,
|
|
1046
|
+
tool: call.tool,
|
|
1047
|
+
input: call.input,
|
|
1048
|
+
result: {
|
|
1049
|
+
success: false,
|
|
1050
|
+
data: null,
|
|
1051
|
+
errorMessage: persistOutcome.errorMessage ?? 'Failed to persist artifact version mutation',
|
|
1052
|
+
},
|
|
1053
|
+
timestamp: new Date(),
|
|
1054
|
+
durationMs: Date.now() - startedAt,
|
|
1055
|
+
};
|
|
1056
|
+
this.toolResults.push(failedStored);
|
|
1057
|
+
return failedStored;
|
|
1058
|
+
}
|
|
1059
|
+
persisted = true;
|
|
1060
|
+
if (hookResult && typeof hookResult === 'object') {
|
|
1061
|
+
try {
|
|
1062
|
+
const commitOutcome = await hookResult.commit?.({
|
|
1063
|
+
versionId: targetEntry.versionId,
|
|
1064
|
+
versionNumber: targetEntry.versionNumber,
|
|
1065
|
+
});
|
|
1066
|
+
if (commitOutcome && typeof commitOutcome === 'object') {
|
|
1067
|
+
const preCommitRollback = hookResult.rollback;
|
|
1068
|
+
hookResult = commitOutcome;
|
|
1069
|
+
if (commitOutcome.applied === false) {
|
|
1070
|
+
const warnMsg = `Deferred mutation was not applied to active room for artifact '${targetEntry.artifactId}'`;
|
|
1071
|
+
LogError(`ArtifactToolManager: ${warnMsg}`);
|
|
1072
|
+
commitWarning = warnMsg;
|
|
1073
|
+
const rolledBackVersionId = persistOutcome.versionEntity?.ID ?? undefined;
|
|
1074
|
+
let shouldRollbackRoom = true;
|
|
1075
|
+
if (persistOutcome.versionEntity && persistOutcome.rollbackSnapshot) {
|
|
1076
|
+
shouldRollbackRoom = await this.rollbackPersistedArtifactVersionMutation(targetEntry, persistOutcome.versionEntity, persistOutcome.rollbackSnapshot, { previousContentStr });
|
|
1077
|
+
}
|
|
1078
|
+
if (persistOutcome.uploadedFileId) {
|
|
1079
|
+
await this.deleteUnreferencedArtifactFile(persistOutcome.uploadedFileId);
|
|
1080
|
+
}
|
|
1081
|
+
const rollbackToRun = commitOutcome.rollback ?? preCommitRollback;
|
|
1082
|
+
if (shouldRollbackRoom && rollbackToRun) {
|
|
1083
|
+
try {
|
|
1084
|
+
await rollbackToRun(rolledBackVersionId);
|
|
1085
|
+
}
|
|
1086
|
+
catch (rbErr) {
|
|
1087
|
+
LogError(`ArtifactToolManager: exception in hookResult.rollback for artifact '${targetEntry.artifactId}': ${rbErr instanceof Error ? rbErr.message : String(rbErr)}`);
|
|
1088
|
+
}
|
|
1089
|
+
}
|
|
1090
|
+
targetEntry.content = previousContent;
|
|
1091
|
+
if (previousOriginalXlsxBytes) {
|
|
1092
|
+
targetEntry.originalXlsxBytes = previousOriginalXlsxBytes;
|
|
1093
|
+
}
|
|
1094
|
+
const failedStored = {
|
|
1095
|
+
artifactId: call.artifactId,
|
|
1096
|
+
tool: call.tool,
|
|
1097
|
+
input: call.input,
|
|
1098
|
+
result: {
|
|
1099
|
+
success: false,
|
|
1100
|
+
data: null,
|
|
1101
|
+
errorMessage: warnMsg,
|
|
1102
|
+
},
|
|
1103
|
+
timestamp: new Date(),
|
|
1104
|
+
durationMs: Date.now() - startedAt,
|
|
1105
|
+
};
|
|
1106
|
+
this.toolResults.push(failedStored);
|
|
1107
|
+
return failedStored;
|
|
1108
|
+
}
|
|
1109
|
+
if (typeof commitOutcome.mergedContent === 'string' && commitOutcome.mergedContent !== effectiveContent) {
|
|
1110
|
+
effectiveContent = commitOutcome.mergedContent;
|
|
1111
|
+
targetEntry.content = effectiveContent;
|
|
1112
|
+
if (previousOriginalXlsxBytes) {
|
|
1113
|
+
try {
|
|
1114
|
+
const mergedWorkbook = await SpreadsheetEngine.Instance.ParseWorkbookIsolated(effectiveContent, undefined, {
|
|
1115
|
+
SkipEvaluate: true,
|
|
1116
|
+
});
|
|
1117
|
+
const mergedBytes = await XlsxOpenXmlAdapter.Instance.PatchXlsxBytesIsolated(previousOriginalXlsxBytes, mergedWorkbook);
|
|
1118
|
+
targetEntry.originalXlsxBytes = mergedBytes;
|
|
1119
|
+
xlsxBase64 = Buffer.from(mergedBytes).toString('base64');
|
|
1120
|
+
}
|
|
1121
|
+
catch (repatchErr) {
|
|
1122
|
+
LogError(`ArtifactToolManager: failed re-patching xlsx bytes after live merge for artifact '${targetEntry.artifactId}': ${repatchErr instanceof Error ? repatchErr.message : String(repatchErr)}`);
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
1125
|
+
const rePersistOutcome = await this.persistArtifactVersionMutation(targetEntry, effectiveContent, xlsxBase64, call.tool, previousContentStr, rawConfigurationPatch);
|
|
1126
|
+
if (!rePersistOutcome.persisted) {
|
|
1127
|
+
const failMsg = rePersistOutcome.errorMessage ?? 'Failed to persist merged artifact version after concurrent edit reconciliation';
|
|
1128
|
+
LogError(`ArtifactToolManager: ${failMsg}`);
|
|
1129
|
+
const rolledBackVersionId = persistOutcome.versionEntity?.ID ?? undefined;
|
|
1130
|
+
let shouldRollbackRoom = true;
|
|
1131
|
+
if (persistOutcome.versionEntity && persistOutcome.rollbackSnapshot) {
|
|
1132
|
+
shouldRollbackRoom = await this.rollbackPersistedArtifactVersionMutation(targetEntry, persistOutcome.versionEntity, persistOutcome.rollbackSnapshot, { previousContentStr });
|
|
1133
|
+
}
|
|
1134
|
+
if (rePersistOutcome.uploadedFileId) {
|
|
1135
|
+
await this.deleteUnreferencedArtifactFile(rePersistOutcome.uploadedFileId);
|
|
1136
|
+
}
|
|
1137
|
+
if (persistOutcome.uploadedFileId) {
|
|
1138
|
+
await this.deleteUnreferencedArtifactFile(persistOutcome.uploadedFileId);
|
|
1139
|
+
}
|
|
1140
|
+
const rollbackToRun = commitOutcome.rollback ?? preCommitRollback;
|
|
1141
|
+
if (shouldRollbackRoom && rollbackToRun) {
|
|
1142
|
+
try {
|
|
1143
|
+
await rollbackToRun(rolledBackVersionId);
|
|
1144
|
+
}
|
|
1145
|
+
catch (rbErr) {
|
|
1146
|
+
LogError(`ArtifactToolManager: exception in hookResult.rollback for artifact '${targetEntry.artifactId}': ${rbErr instanceof Error ? rbErr.message : String(rbErr)}`);
|
|
1147
|
+
}
|
|
1148
|
+
}
|
|
1149
|
+
targetEntry.content = previousContent;
|
|
1150
|
+
targetEntry.originalXlsxBytes = previousOriginalXlsxBytes;
|
|
1151
|
+
const failedStored = {
|
|
1152
|
+
artifactId: call.artifactId,
|
|
1153
|
+
tool: call.tool,
|
|
1154
|
+
input: call.input,
|
|
1155
|
+
result: {
|
|
1156
|
+
success: false,
|
|
1157
|
+
data: null,
|
|
1158
|
+
errorMessage: failMsg,
|
|
1159
|
+
},
|
|
1160
|
+
timestamp: new Date(),
|
|
1161
|
+
durationMs: Date.now() - startedAt,
|
|
1162
|
+
};
|
|
1163
|
+
this.toolResults.push(failedStored);
|
|
1164
|
+
return failedStored;
|
|
1165
|
+
}
|
|
1166
|
+
if (rePersistOutcome.supersededFileId) {
|
|
1167
|
+
await this.deleteUnreferencedArtifactFile(rePersistOutcome.supersededFileId);
|
|
1168
|
+
}
|
|
1169
|
+
}
|
|
1170
|
+
}
|
|
1171
|
+
}
|
|
1172
|
+
catch (commitErr) {
|
|
1173
|
+
const errMsg = `ArtifactToolManager: commit hook failed for artifact '${targetEntry.artifactId}': ${commitErr instanceof Error ? commitErr.message : String(commitErr)}`;
|
|
1174
|
+
LogError(errMsg);
|
|
1175
|
+
const rolledBackVersionId = persistOutcome.versionEntity?.ID ?? undefined;
|
|
1176
|
+
let shouldRollbackRoom = true;
|
|
1177
|
+
if (persistOutcome.versionEntity && persistOutcome.rollbackSnapshot) {
|
|
1178
|
+
shouldRollbackRoom = await this.rollbackPersistedArtifactVersionMutation(targetEntry, persistOutcome.versionEntity, persistOutcome.rollbackSnapshot, { previousContentStr });
|
|
1179
|
+
}
|
|
1180
|
+
if (persistOutcome.uploadedFileId) {
|
|
1181
|
+
await this.deleteUnreferencedArtifactFile(persistOutcome.uploadedFileId);
|
|
1182
|
+
}
|
|
1183
|
+
if (shouldRollbackRoom && hookResult && typeof hookResult === 'object' && hookResult.rollback) {
|
|
1184
|
+
try {
|
|
1185
|
+
await hookResult.rollback(rolledBackVersionId);
|
|
1186
|
+
}
|
|
1187
|
+
catch (rbErr) {
|
|
1188
|
+
LogError(`ArtifactToolManager: exception in hookResult.rollback for artifact '${targetEntry.artifactId}': ${rbErr instanceof Error ? rbErr.message : String(rbErr)}`);
|
|
1189
|
+
}
|
|
1190
|
+
}
|
|
1191
|
+
targetEntry.content = previousContent;
|
|
1192
|
+
if (previousOriginalXlsxBytes) {
|
|
1193
|
+
targetEntry.originalXlsxBytes = previousOriginalXlsxBytes;
|
|
1194
|
+
}
|
|
1195
|
+
const failedStored = {
|
|
1196
|
+
artifactId: call.artifactId,
|
|
1197
|
+
tool: call.tool,
|
|
1198
|
+
input: call.input,
|
|
1199
|
+
result: {
|
|
1200
|
+
success: false,
|
|
1201
|
+
data: null,
|
|
1202
|
+
errorMessage: errMsg,
|
|
1203
|
+
},
|
|
1204
|
+
timestamp: new Date(),
|
|
1205
|
+
durationMs: Date.now() - startedAt,
|
|
1206
|
+
};
|
|
1207
|
+
this.toolResults.push(failedStored);
|
|
1208
|
+
return failedStored;
|
|
1209
|
+
}
|
|
1210
|
+
}
|
|
1211
|
+
if (persistOutcome.supersededFileId) {
|
|
1212
|
+
await this.deleteUnreferencedArtifactFile(persistOutcome.supersededFileId);
|
|
1213
|
+
}
|
|
1214
|
+
}
|
|
1215
|
+
// 3b. For File-mode artifacts (where storage upload succeeded first), invoke hook after persist and reconcile if needed
|
|
1216
|
+
if (hook && targetEntry.artifactId && !hookInvokedBeforePersist) {
|
|
1217
|
+
try {
|
|
1218
|
+
hookResult = await hook({
|
|
1219
|
+
artifactId: targetEntry.artifactId,
|
|
1220
|
+
alphaId: targetEntry.alphaId,
|
|
1221
|
+
versionId: targetEntry.versionId,
|
|
1222
|
+
versionNumber: targetEntry.versionNumber,
|
|
1223
|
+
previousContent: previousContentStr,
|
|
1224
|
+
updatedContent: effectiveContent,
|
|
1225
|
+
xlsxBase64,
|
|
1226
|
+
tool: call.tool,
|
|
1227
|
+
contextUser: this.contextUser,
|
|
1228
|
+
agentRunId: activeAgentRunId,
|
|
1229
|
+
agentName: activeAgentName,
|
|
1230
|
+
});
|
|
1231
|
+
if (hookResult &&
|
|
1232
|
+
typeof hookResult === 'object' &&
|
|
1233
|
+
typeof hookResult.mergedContent === 'string' &&
|
|
1234
|
+
hookResult.mergedContent !== effectiveContent) {
|
|
1235
|
+
effectiveContent = hookResult.mergedContent;
|
|
1236
|
+
targetEntry.content = effectiveContent;
|
|
1237
|
+
if (this.contextUser && this.provider) {
|
|
1238
|
+
const rePersistOutcome = await this.persistArtifactVersionMutation(targetEntry, effectiveContent, xlsxBase64, call.tool, previousContentStr, rawConfigurationPatch);
|
|
1239
|
+
if (!rePersistOutcome.persisted) {
|
|
1240
|
+
const failMsg = rePersistOutcome.errorMessage ?? 'Failed to persist merged artifact version after concurrent edit reconciliation';
|
|
1241
|
+
LogError(`ArtifactToolManager: ${failMsg}`);
|
|
1242
|
+
if (rePersistOutcome.uploadedFileId) {
|
|
1243
|
+
await this.deleteUnreferencedArtifactFile(rePersistOutcome.uploadedFileId);
|
|
1244
|
+
}
|
|
1245
|
+
if (hookResult.rollback) {
|
|
1246
|
+
try {
|
|
1247
|
+
await hookResult.rollback(targetEntry.versionId);
|
|
1248
|
+
}
|
|
1249
|
+
catch {
|
|
1250
|
+
// Non-fatal
|
|
1251
|
+
}
|
|
1252
|
+
}
|
|
1253
|
+
targetEntry.content = previousContent;
|
|
1254
|
+
targetEntry.originalXlsxBytes = previousOriginalXlsxBytes;
|
|
1255
|
+
const failedStored = {
|
|
1256
|
+
artifactId: call.artifactId,
|
|
1257
|
+
tool: call.tool,
|
|
1258
|
+
input: call.input,
|
|
1259
|
+
result: {
|
|
1260
|
+
success: false,
|
|
1261
|
+
data: null,
|
|
1262
|
+
errorMessage: failMsg,
|
|
1263
|
+
},
|
|
1264
|
+
timestamp: new Date(),
|
|
1265
|
+
durationMs: Date.now() - startedAt,
|
|
1266
|
+
};
|
|
1267
|
+
this.toolResults.push(failedStored);
|
|
1268
|
+
return failedStored;
|
|
1269
|
+
}
|
|
1270
|
+
if (rePersistOutcome.supersededFileId) {
|
|
1271
|
+
await this.deleteUnreferencedArtifactFile(rePersistOutcome.supersededFileId);
|
|
1272
|
+
}
|
|
1273
|
+
}
|
|
1274
|
+
}
|
|
1275
|
+
}
|
|
1276
|
+
catch (hookErr) {
|
|
1277
|
+
LogError(`ArtifactToolManager: live mutation hook failed for artifact '${targetEntry.artifactId}': ${hookErr instanceof Error ? hookErr.message : String(hookErr)}`);
|
|
1278
|
+
}
|
|
1279
|
+
}
|
|
1280
|
+
const alreadyAppliedToRoom = Boolean(hookResult && typeof hookResult === 'object');
|
|
1281
|
+
if (targetEntry.artifactId && this.contextUser) {
|
|
1282
|
+
try {
|
|
1283
|
+
MJGlobal.Instance.RaiseEvent({
|
|
1284
|
+
component: this,
|
|
1285
|
+
event: MJEventType.ComponentEvent,
|
|
1286
|
+
eventCode: ARTIFACT_LIVE_MUTATION_EVENT_CODE,
|
|
1287
|
+
args: {
|
|
1288
|
+
ArtifactID: targetEntry.artifactId,
|
|
1289
|
+
NewContent: effectiveContent,
|
|
1290
|
+
PreviousContent: previousContent,
|
|
1291
|
+
ToolName: call.tool,
|
|
1292
|
+
User: this.contextUser,
|
|
1293
|
+
SaveVersion: false,
|
|
1294
|
+
...(alreadyAppliedToRoom ? { AlreadyAppliedToRoom: true } : {}),
|
|
1295
|
+
},
|
|
1296
|
+
});
|
|
1297
|
+
}
|
|
1298
|
+
catch {
|
|
1299
|
+
// Never fail tool execution if event subscribers throw
|
|
1300
|
+
}
|
|
1301
|
+
}
|
|
1302
|
+
// 4. Sanitize the LLM-facing copy of result.data without mutating rawData returned by library.InvokeTool
|
|
1303
|
+
const sanitizedData = {};
|
|
1304
|
+
for (const [k, v] of Object.entries(rawData)) {
|
|
1305
|
+
if (k === 'updatedContent' || k === 'xlsxBase64')
|
|
1306
|
+
continue;
|
|
1307
|
+
sanitizedData[k] = v;
|
|
1308
|
+
}
|
|
1309
|
+
if (commitWarning) {
|
|
1310
|
+
const existingWarnings = Array.isArray(sanitizedData.warnings)
|
|
1311
|
+
? sanitizedData.warnings.filter((w) => typeof w === 'string')
|
|
1312
|
+
: [];
|
|
1313
|
+
sanitizedData.warnings = [...existingWarnings, commitWarning];
|
|
1314
|
+
}
|
|
1315
|
+
if (effectiveContent !== updatedContent &&
|
|
1316
|
+
'revisionHash' in sanitizedData) {
|
|
1317
|
+
const recomputed = targetEntry.library.ComputeRevisionHash?.(effectiveContent);
|
|
1318
|
+
if (typeof recomputed === 'string') {
|
|
1319
|
+
sanitizedData.revisionHash = recomputed;
|
|
1320
|
+
}
|
|
1321
|
+
}
|
|
1322
|
+
const rejectedCount = hookResult && typeof hookResult === 'object'
|
|
1323
|
+
? (hookResult.rejectedHunksCount ?? hookResult.rejectedAgentHunks?.length ?? 0)
|
|
1324
|
+
: 0;
|
|
1325
|
+
if (rejectedCount > 0) {
|
|
1326
|
+
const rejectedLinesPreview = [];
|
|
1327
|
+
if (hookResult && typeof hookResult === 'object' && Array.isArray(hookResult.rejectedAgentHunks)) {
|
|
1328
|
+
for (const hunk of hookResult.rejectedAgentHunks) {
|
|
1329
|
+
if (Array.isArray(hunk.RejectedAgentLines)) {
|
|
1330
|
+
for (const line of hunk.RejectedAgentLines) {
|
|
1331
|
+
const trimmed = line.trim();
|
|
1332
|
+
if (trimmed.length > 0 && rejectedLinesPreview.length < 3) {
|
|
1333
|
+
rejectedLinesPreview.push(trimmed);
|
|
1334
|
+
}
|
|
1335
|
+
}
|
|
1336
|
+
}
|
|
1337
|
+
if (rejectedLinesPreview.length >= 3) {
|
|
1338
|
+
break;
|
|
1339
|
+
}
|
|
1340
|
+
}
|
|
1341
|
+
}
|
|
1342
|
+
const previewSuffix = rejectedLinesPreview.length > 0
|
|
1343
|
+
? ` (rejected: ${rejectedLinesPreview.map((l) => `"${l}"`).join(', ')})`
|
|
1344
|
+
: '';
|
|
1345
|
+
const conflictWarning = `${rejectedCount} edit${rejectedCount === 1 ? '' : 's'} not applied because of concurrent edits${previewSuffix}`;
|
|
1346
|
+
sanitizedData.rejectedEditsCount = rejectedCount;
|
|
1347
|
+
sanitizedData.conflictWarning = conflictWarning;
|
|
1348
|
+
if (rejectedLinesPreview.length > 0) {
|
|
1349
|
+
sanitizedData.rejectedLinesPreview = rejectedLinesPreview;
|
|
1350
|
+
}
|
|
1351
|
+
const existingWarnings = Array.isArray(sanitizedData.warnings)
|
|
1352
|
+
? sanitizedData.warnings.filter((w) => typeof w === 'string')
|
|
1353
|
+
: [];
|
|
1354
|
+
sanitizedData.warnings = [...existingWarnings, conflictWarning];
|
|
1355
|
+
}
|
|
1356
|
+
sanitizedData.persisted = persisted;
|
|
1357
|
+
if (targetEntry.versionNumber !== undefined) {
|
|
1358
|
+
sanitizedData.versionNumber = targetEntry.versionNumber;
|
|
1359
|
+
}
|
|
1360
|
+
storedResult = {
|
|
1361
|
+
...result,
|
|
1362
|
+
data: sanitizedData,
|
|
1363
|
+
};
|
|
1364
|
+
if (targetEntry.artifactId) {
|
|
1365
|
+
const touchedSummary = {
|
|
1366
|
+
ArtifactID: targetEntry.artifactId,
|
|
1367
|
+
ArtifactVersionID: targetEntry.versionId ?? '',
|
|
1368
|
+
VersionNumber: targetEntry.versionNumber ?? 1,
|
|
1369
|
+
Name: targetEntry.name,
|
|
1370
|
+
ArtifactTypeName: targetEntry.typeName,
|
|
1371
|
+
DriverClass: targetEntry.driverClass,
|
|
1372
|
+
Operation: 'mutated',
|
|
1373
|
+
};
|
|
1374
|
+
this.recordTouchedArtifactSummary(touchedSummary);
|
|
1375
|
+
GovernedArtifactService.Instance.RecordTouchedArtifact(activeRunIdForCall, touchedSummary);
|
|
1376
|
+
}
|
|
1377
|
+
settledContent = effectiveContent;
|
|
1378
|
+
settledData = rawData;
|
|
1379
|
+
}
|
|
1380
|
+
else if (result.success) {
|
|
1381
|
+
if (resultObj && resultObj['rlsCheckRequired'] === true) {
|
|
1382
|
+
storedResult = await this.handleFollowSourceLinkRuntime(resultObj, activeRunIdForCall);
|
|
1383
|
+
}
|
|
1384
|
+
else if (resultObj && resultObj['requested'] === 'rerank') {
|
|
1385
|
+
storedResult = await this.handleRerankRuntime(targetEntry, resultObj, activeRunIdForCall);
|
|
1386
|
+
}
|
|
1387
|
+
settledContent = targetEntry.content;
|
|
1388
|
+
settledData =
|
|
1389
|
+
storedResult.data !== null && typeof storedResult.data === 'object' && !Array.isArray(storedResult.data)
|
|
1390
|
+
? storedResult.data
|
|
1391
|
+
: undefined;
|
|
1392
|
+
}
|
|
1393
|
+
const stored = {
|
|
1394
|
+
artifactId: call.artifactId,
|
|
1395
|
+
tool: call.tool,
|
|
1396
|
+
input: sanitizedInput,
|
|
1397
|
+
result: storedResult,
|
|
1398
|
+
timestamp: new Date(),
|
|
1399
|
+
durationMs: Date.now() - startedAt,
|
|
1400
|
+
};
|
|
1401
|
+
this.toolResults.push(stored);
|
|
1402
|
+
return stored;
|
|
1403
|
+
}
|
|
1404
|
+
finally {
|
|
1405
|
+
if (presenceEmittedWorking && presenceArtifactId && this.contextUser) {
|
|
1406
|
+
const postLocation = ExtractAgentTargetLocation(call.tool, sanitizedInput, settledContent, targetEntry.typeName, settledData) ??
|
|
1407
|
+
preLocation;
|
|
1408
|
+
await GovernedArtifactService.Instance.EmitAgentPresence({
|
|
1409
|
+
artifactId: presenceArtifactId,
|
|
1410
|
+
phase: 'settled',
|
|
1411
|
+
contextUser: this.contextUser,
|
|
1412
|
+
agentRunId: activeRunIdForCall,
|
|
1413
|
+
agentName: activeAgentNameForCall,
|
|
1414
|
+
toolName: call.tool,
|
|
1415
|
+
actionSummary: FormatAgentActionSummary(call.tool, sanitizedInput, postLocation),
|
|
1416
|
+
location: postLocation ?? { Domain: ResolvePresenceDomain(targetEntry.typeName) },
|
|
1417
|
+
}).catch(() => undefined);
|
|
1418
|
+
}
|
|
1419
|
+
}
|
|
1420
|
+
});
|
|
1421
|
+
}
|
|
1422
|
+
/**
|
|
1423
|
+
* Queries `MJ: Artifact Versions` to verify no human/external writer saved a newer version
|
|
1424
|
+
* (`VersionNumber > entry.currentVersionNumber` with `ID !== entry.agentRunVersionId`).
|
|
1425
|
+
*/
|
|
1426
|
+
async checkConcurrentDatabaseModification(entry) {
|
|
1427
|
+
if (!entry.artifactId || !this.contextUser || !this.provider) {
|
|
1428
|
+
return null;
|
|
1429
|
+
}
|
|
501
1430
|
try {
|
|
502
|
-
|
|
1431
|
+
const rv = RunView.FromMetadataProvider(this.provider);
|
|
1432
|
+
const latestRes = await rv.RunView({
|
|
1433
|
+
EntityName: 'MJ: Artifact Versions',
|
|
1434
|
+
ExtraFilter: `ArtifactID='${EscapeSQLString(entry.artifactId)}'`,
|
|
1435
|
+
OrderBy: 'VersionNumber DESC',
|
|
1436
|
+
Fields: ['ID', 'VersionNumber', 'ContentMode', 'FileID', 'Configuration'],
|
|
1437
|
+
MaxRows: 1,
|
|
1438
|
+
SkipTotalRowCount: true,
|
|
1439
|
+
ResultType: 'simple',
|
|
1440
|
+
}, this.contextUser);
|
|
1441
|
+
if (!latestRes.Success) {
|
|
1442
|
+
return `Failed to verify artifact concurrency before mutation: ${latestRes.ErrorMessage || 'RunView failed'}`;
|
|
1443
|
+
}
|
|
1444
|
+
if (!latestRes.Results?.length) {
|
|
1445
|
+
return null;
|
|
1446
|
+
}
|
|
1447
|
+
const latestRow = latestRes.Results[0];
|
|
1448
|
+
if (!entry.contentMode && (latestRow.ContentMode === 'File' || latestRow.ContentMode === 'Text')) {
|
|
1449
|
+
entry.contentMode = latestRow.ContentMode;
|
|
1450
|
+
}
|
|
1451
|
+
if (!entry.configuration && typeof latestRow.Configuration === 'string') {
|
|
1452
|
+
entry.configuration = latestRow.Configuration;
|
|
1453
|
+
}
|
|
1454
|
+
const expectedVersion = entry.currentVersionNumber ?? entry.versionNumber ?? 0;
|
|
1455
|
+
if (latestRow.VersionNumber > expectedVersion &&
|
|
1456
|
+
(!entry.agentRunVersionId || !UUIDsEqual(latestRow.ID, entry.agentRunVersionId))) {
|
|
1457
|
+
return `Artifact was modified concurrently (v${latestRow.VersionNumber} > v${expectedVersion}); call reload_artifact before mutating`;
|
|
1458
|
+
}
|
|
503
1459
|
}
|
|
504
1460
|
catch (err) {
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
}
|
|
1461
|
+
if (this.provider) {
|
|
1462
|
+
const runViewProvider = this.provider;
|
|
1463
|
+
if (runViewProvider.RunView) {
|
|
1464
|
+
return `Failed to verify artifact concurrency before mutation: ${err instanceof Error ? err.message : String(err)}`;
|
|
1465
|
+
}
|
|
1466
|
+
}
|
|
511
1467
|
}
|
|
512
|
-
|
|
513
|
-
artifactId: call.artifactId,
|
|
514
|
-
tool: call.tool,
|
|
515
|
-
input: call.input,
|
|
516
|
-
result,
|
|
517
|
-
timestamp: new Date(),
|
|
518
|
-
durationMs: Date.now() - startedAt,
|
|
519
|
-
};
|
|
520
|
-
this.toolResults.push(stored);
|
|
521
|
-
return stored;
|
|
1468
|
+
return null;
|
|
522
1469
|
}
|
|
523
1470
|
/**
|
|
524
|
-
*
|
|
525
|
-
*
|
|
526
|
-
* invocation in its own AIAgentRunStep. Returns void to preserve the
|
|
527
|
-
* original contract.
|
|
1471
|
+
* Downloads binary content for a file-backed artifact version (`FileID`) from `FileStorageEngine`
|
|
1472
|
+
* using the same `MJ: Files` -> `ResolveFileObject` -> `Driver.GetObject` pipeline as `AgentRunner.DownloadArtifactFileContent`.
|
|
528
1473
|
*/
|
|
529
|
-
async
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
1474
|
+
async downloadArtifactFileContent(fileId) {
|
|
1475
|
+
if (!this.contextUser || !this.provider) {
|
|
1476
|
+
return null;
|
|
1477
|
+
}
|
|
1478
|
+
const trimmedFileId = (fileId ?? '').trim();
|
|
1479
|
+
if (!IsValidUUID(trimmedFileId)) {
|
|
1480
|
+
LogError(`ArtifactToolManager: refusing to read artifact file content — '${fileId}' is not a valid UUID`);
|
|
1481
|
+
return null;
|
|
1482
|
+
}
|
|
1483
|
+
try {
|
|
1484
|
+
await FileStorageEngine.Instance.Config(false, this.contextUser, this.provider);
|
|
1485
|
+
const rv = RunView.FromMetadataProvider(this.provider);
|
|
1486
|
+
const fileResult = await rv.RunView({
|
|
1487
|
+
EntityName: 'MJ: Files',
|
|
1488
|
+
ExtraFilter: `ID = '${EscapeSQLString(trimmedFileId)}'`,
|
|
1489
|
+
Fields: ['ID', 'Name', 'ContentType', 'ProviderID', 'ProviderKey'],
|
|
1490
|
+
ResultType: 'simple',
|
|
1491
|
+
}, this.contextUser);
|
|
1492
|
+
if (!fileResult.Success || !fileResult.Results?.length) {
|
|
1493
|
+
LogError(`ArtifactToolManager: file not found in MJ: Files for FileID '${trimmedFileId}'`);
|
|
1494
|
+
return null;
|
|
1495
|
+
}
|
|
1496
|
+
const resolved = await FileStorageEngine.Instance.ResolveFileObject(fileResult.Results[0], this.contextUser, 'Read', this.provider);
|
|
1497
|
+
if (!resolved) {
|
|
1498
|
+
LogError(`ArtifactToolManager: no FileStorageAccount resolved for ProviderID '${fileResult.Results[0].ProviderID}'`);
|
|
1499
|
+
return null;
|
|
1500
|
+
}
|
|
1501
|
+
const rawContent = await resolved.Driver.GetObject({ fullPath: resolved.ObjectKey });
|
|
1502
|
+
if (Buffer.isBuffer(rawContent)) {
|
|
1503
|
+
return rawContent;
|
|
1504
|
+
}
|
|
1505
|
+
if (rawContent instanceof Uint8Array) {
|
|
1506
|
+
return Buffer.from(rawContent);
|
|
1507
|
+
}
|
|
1508
|
+
if (typeof rawContent === 'string') {
|
|
1509
|
+
return Buffer.from(rawContent);
|
|
1510
|
+
}
|
|
1511
|
+
return null;
|
|
1512
|
+
}
|
|
1513
|
+
catch (err) {
|
|
1514
|
+
LogError(`ArtifactToolManager: failed to download file content for FileID '${trimmedFileId}': ${err instanceof Error ? err.message : String(err)}`);
|
|
1515
|
+
return null;
|
|
1516
|
+
}
|
|
543
1517
|
}
|
|
544
|
-
// ─── STATIC HELPERS ───
|
|
545
1518
|
/**
|
|
546
|
-
*
|
|
547
|
-
*
|
|
1519
|
+
* Reloads the latest persisted `MJ: Artifact Versions` record from the database into the in-memory
|
|
1520
|
+
* session entry so an agent run can recover after a concurrent modification conflict (`Round 3 Item 9`, `E9`).
|
|
1521
|
+
* Re-downloads `FileID` binary bytes when set and fails closed without advancing baseline version numbers on error.
|
|
548
1522
|
*/
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
1523
|
+
async reloadArtifactFromDatabase(entry) {
|
|
1524
|
+
if (!entry.artifactId || !this.contextUser || !this.provider) {
|
|
1525
|
+
return {
|
|
1526
|
+
success: false,
|
|
1527
|
+
data: null,
|
|
1528
|
+
errorMessage: 'Cannot reload artifact without artifactId, contextUser, and provider.',
|
|
1529
|
+
};
|
|
1530
|
+
}
|
|
1531
|
+
try {
|
|
1532
|
+
const loaded = await GovernedArtifactService.Instance.LoadReadableArtifactState(this.provider, this.contextUser, entry.artifactId, {
|
|
1533
|
+
failOnMissingFileContent: true,
|
|
1534
|
+
fallbackTypeName: entry.typeName,
|
|
1535
|
+
skipTypeEntityResolution: true,
|
|
1536
|
+
});
|
|
1537
|
+
if (!loaded.state) {
|
|
1538
|
+
return {
|
|
1539
|
+
success: false,
|
|
1540
|
+
data: null,
|
|
1541
|
+
errorMessage: loaded.errorMessage || `Failed to reload artifact '${entry.artifactId}'.`,
|
|
1542
|
+
};
|
|
1543
|
+
}
|
|
1544
|
+
const state = loaded.state;
|
|
1545
|
+
const libClassName = entry.library.constructor.name;
|
|
1546
|
+
const isBinaryLibrary = libClassName === 'DocxToolLibrary' ||
|
|
1547
|
+
libClassName === 'PDFToolLibrary' ||
|
|
1548
|
+
libClassName === 'ExcelToolLibrary' ||
|
|
1549
|
+
libClassName === 'GenericBinaryToolLibrary';
|
|
1550
|
+
let nextEntryContent = state.content;
|
|
1551
|
+
if (isBinaryLibrary && typeof state.content === 'string') {
|
|
1552
|
+
nextEntryContent = DecodeBinaryArtifactContent(state.content);
|
|
1553
|
+
}
|
|
1554
|
+
else if (!isBinaryLibrary && !Buffer.isBuffer(entry.content) && Buffer.isBuffer(state.content)) {
|
|
1555
|
+
nextEntryContent = state.content.toString('utf-8');
|
|
1556
|
+
}
|
|
1557
|
+
// Commit reloaded state only after storage download & parsing succeeded
|
|
1558
|
+
entry.ownerUserId = state.ownerUserId ?? entry.ownerUserId;
|
|
1559
|
+
entry.versionId = state.versionId;
|
|
1560
|
+
entry.versionNumber = state.versionNumber;
|
|
1561
|
+
entry.baseVersionNumber = state.versionNumber;
|
|
1562
|
+
entry.currentVersionNumber = state.versionNumber;
|
|
1563
|
+
entry.agentRunVersionId = undefined;
|
|
1564
|
+
entry.agentRunVersionEntity = undefined;
|
|
1565
|
+
if (state.name && state.name !== 'Untitled Artifact') {
|
|
1566
|
+
entry.name = state.name;
|
|
1567
|
+
}
|
|
1568
|
+
if (state.mimeType) {
|
|
1569
|
+
entry.mimeType = state.mimeType;
|
|
1570
|
+
}
|
|
1571
|
+
entry.contentMode = state.contentMode;
|
|
1572
|
+
entry.originalXlsxBytes = state.originalXlsxBytes;
|
|
1573
|
+
entry.configuration = state.configuration;
|
|
1574
|
+
entry.content = nextEntryContent;
|
|
1575
|
+
return {
|
|
1576
|
+
success: true,
|
|
1577
|
+
data: {
|
|
1578
|
+
artifactId: entry.artifactId,
|
|
1579
|
+
alphaId: entry.alphaId,
|
|
1580
|
+
versionId: state.versionId,
|
|
1581
|
+
versionNumber: state.versionNumber,
|
|
1582
|
+
reloaded: true,
|
|
1583
|
+
},
|
|
1584
|
+
};
|
|
1585
|
+
}
|
|
1586
|
+
catch (err) {
|
|
1587
|
+
return {
|
|
1588
|
+
success: false,
|
|
1589
|
+
data: null,
|
|
1590
|
+
errorMessage: `Failed to reload artifact '${entry.artifactId}': ${err instanceof Error ? err.message : String(err)}`,
|
|
1591
|
+
};
|
|
553
1592
|
}
|
|
554
|
-
return {
|
|
555
|
-
shouldExternalize: true,
|
|
556
|
-
reason: 'Content exceeds ' + maxInlineChars + ' chars (' + contentLength + ' actual). Row data should be stored in MJStorage.',
|
|
557
|
-
};
|
|
558
1593
|
}
|
|
559
1594
|
/**
|
|
560
|
-
*
|
|
561
|
-
*
|
|
1595
|
+
* Persists or updates a single `MJ: Artifact Versions` record per agent run for an artifact (`A4`, `D5`),
|
|
1596
|
+
* enforcing concurrency checks against human edits and fail-closed `ContentMode === 'File'` storage semantics.
|
|
562
1597
|
*/
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
parsed = JSON.parse(contentJson);
|
|
567
|
-
}
|
|
568
|
-
catch {
|
|
569
|
-
return contentJson;
|
|
1598
|
+
async persistArtifactVersionMutation(entry, updatedContent, xlsxBase64, toolName, previousContentStr, configurationPatch) {
|
|
1599
|
+
if (!entry.artifactId || !this.contextUser || !this.provider) {
|
|
1600
|
+
return { persisted: false };
|
|
570
1601
|
}
|
|
571
|
-
const
|
|
572
|
-
if (
|
|
573
|
-
|
|
1602
|
+
const conflictBeforeSave = await this.checkConcurrentDatabaseModification(entry);
|
|
1603
|
+
if (conflictBeforeSave) {
|
|
1604
|
+
LogError(`ArtifactToolManager: concurrent modification detected before save for artifact '${entry.artifactId}': ${conflictBeforeSave}`);
|
|
1605
|
+
return { persisted: false, errorMessage: conflictBeforeSave };
|
|
574
1606
|
}
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
1607
|
+
const contentHash = createHash('sha256').update(updatedContent, 'utf8').digest('hex');
|
|
1608
|
+
const isFileMode = entry.contentMode === 'File';
|
|
1609
|
+
// Ensure .xlsx bytes exist when operating on a File-mode spreadsheet
|
|
1610
|
+
let effectiveXlsxBase64 = xlsxBase64;
|
|
1611
|
+
if (!effectiveXlsxBase64 && isFileMode) {
|
|
1612
|
+
if (!entry.originalXlsxBytes) {
|
|
1613
|
+
return {
|
|
1614
|
+
persisted: false,
|
|
1615
|
+
errorMessage: 'Failed to upload updated .xlsx binary to FileStorageEngine for File-mode artifact; refusing to downgrade ContentMode to Text',
|
|
1616
|
+
};
|
|
580
1617
|
}
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
tbl['metadata'] = {};
|
|
1618
|
+
if (!updatedContent.trim()) {
|
|
1619
|
+
effectiveXlsxBase64 = Buffer.from(entry.originalXlsxBytes).toString('base64');
|
|
584
1620
|
}
|
|
585
|
-
|
|
1621
|
+
else {
|
|
1622
|
+
try {
|
|
1623
|
+
const workbook = await SpreadsheetEngine.Instance.ParseWorkbookIsolated(updatedContent, undefined, {
|
|
1624
|
+
SkipEvaluate: true,
|
|
1625
|
+
});
|
|
1626
|
+
const bytes = await XlsxOpenXmlAdapter.Instance.PatchXlsxBytesIsolated(entry.originalXlsxBytes, workbook);
|
|
1627
|
+
entry.originalXlsxBytes = bytes;
|
|
1628
|
+
effectiveXlsxBase64 = Buffer.from(bytes).toString('base64');
|
|
1629
|
+
}
|
|
1630
|
+
catch (err) {
|
|
1631
|
+
return {
|
|
1632
|
+
persisted: false,
|
|
1633
|
+
errorMessage: `Failed to patch .xlsx binary for File-mode artifact: ${err instanceof Error ? err.message : String(err)}`,
|
|
1634
|
+
};
|
|
1635
|
+
}
|
|
1636
|
+
}
|
|
1637
|
+
}
|
|
1638
|
+
let uploadedFileId = null;
|
|
1639
|
+
let xlsxSizeBytes = null;
|
|
1640
|
+
if (effectiveXlsxBase64) {
|
|
1641
|
+
const xlsxBuf = Buffer.from(effectiveXlsxBase64, 'base64');
|
|
1642
|
+
xlsxSizeBytes = xlsxBuf.byteLength;
|
|
1643
|
+
try {
|
|
1644
|
+
await FileStorageEngine.Instance.Config(false, this.contextUser, this.provider);
|
|
1645
|
+
if (FileStorageEngine.Instance.HasStorageAccounts) {
|
|
1646
|
+
const safeFileName = entry.name.toLowerCase().endsWith('.xlsx') ? entry.name : `${entry.name || 'workbook'}.xlsx`;
|
|
1647
|
+
const uploadRes = await FileStorageEngine.Instance.UploadFile({
|
|
1648
|
+
content: xlsxBuf,
|
|
1649
|
+
fileName: safeFileName,
|
|
1650
|
+
mimeType: XLSX_MIME_TYPE,
|
|
1651
|
+
contextUser: this.contextUser,
|
|
1652
|
+
provider: this.provider,
|
|
1653
|
+
});
|
|
1654
|
+
uploadedFileId = uploadRes.FileID;
|
|
1655
|
+
}
|
|
1656
|
+
}
|
|
1657
|
+
catch {
|
|
1658
|
+
uploadedFileId = null;
|
|
1659
|
+
}
|
|
1660
|
+
}
|
|
1661
|
+
// Fail closed if the artifact is in File mode and the .xlsx upload did not succeed
|
|
1662
|
+
if (isFileMode && !uploadedFileId) {
|
|
1663
|
+
return {
|
|
1664
|
+
persisted: false,
|
|
1665
|
+
errorMessage: 'Failed to upload updated .xlsx binary to FileStorageEngine for File-mode artifact; refusing to downgrade ContentMode to Text',
|
|
1666
|
+
};
|
|
1667
|
+
}
|
|
1668
|
+
const activeAgentRunId = this.agentRunId ?? this.getAgentRun?.()?.ID;
|
|
1669
|
+
const activeAgentName = this.agentName ?? this.getAgentRun?.()?.Agent ?? undefined;
|
|
1670
|
+
const attributionConfig = activeAgentRunId || activeAgentName
|
|
1671
|
+
? JSON.stringify({
|
|
1672
|
+
agentRunId: activeAgentRunId ?? null,
|
|
1673
|
+
agentName: activeAgentName ?? null,
|
|
1674
|
+
lastTool: toolName,
|
|
1675
|
+
})
|
|
1676
|
+
: null;
|
|
1677
|
+
try {
|
|
1678
|
+
let versionEntity = entry.agentRunVersionEntity;
|
|
1679
|
+
const isReuse = Boolean(versionEntity && entry.agentRunVersionId);
|
|
1680
|
+
const previousReusedFileId = isReuse && versionEntity ? versionEntity.FileID : null;
|
|
1681
|
+
const targetVersionNumber = isReuse
|
|
1682
|
+
? (entry.currentVersionNumber ?? entry.versionNumber ?? 1)
|
|
1683
|
+
: (entry.currentVersionNumber ?? entry.versionNumber ?? 0) + 1;
|
|
1684
|
+
const rollbackSnapshot = {
|
|
1685
|
+
hadExistingAgentRunVersion: isReuse,
|
|
1686
|
+
entryVersionId: entry.versionId,
|
|
1687
|
+
entryVersionNumber: entry.versionNumber,
|
|
1688
|
+
entryCurrentVersionNumber: entry.currentVersionNumber,
|
|
1689
|
+
entryAgentRunVersionId: entry.agentRunVersionId,
|
|
1690
|
+
entryAgentRunVersionEntity: entry.agentRunVersionEntity,
|
|
1691
|
+
entryContentMode: entry.contentMode,
|
|
1692
|
+
entryContent: entry.content,
|
|
1693
|
+
entryConfiguration: entry.configuration,
|
|
1694
|
+
entryName: entry.name,
|
|
1695
|
+
entryDescription: entry.description,
|
|
1696
|
+
entryComments: entry.comments,
|
|
1697
|
+
entryDirty: entry.dirty,
|
|
1698
|
+
entityName: versionEntity ? versionEntity.Name : null,
|
|
1699
|
+
entityComments: versionEntity ? versionEntity.Comments : null,
|
|
1700
|
+
entityContent: versionEntity ? versionEntity.Content : null,
|
|
1701
|
+
entityConfiguration: versionEntity ? versionEntity.Configuration : null,
|
|
1702
|
+
entityContentHash: versionEntity ? versionEntity.ContentHash : null,
|
|
1703
|
+
entityContentSizeBytes: versionEntity ? versionEntity.ContentSizeBytes : null,
|
|
1704
|
+
entityContentMode: versionEntity ? versionEntity.ContentMode : null,
|
|
1705
|
+
entityFileID: versionEntity ? versionEntity.FileID : null,
|
|
1706
|
+
entityMimeType: versionEntity ? versionEntity.MimeType : null,
|
|
1707
|
+
entityFileName: versionEntity ? versionEntity.FileName : null,
|
|
1708
|
+
};
|
|
1709
|
+
if (!versionEntity) {
|
|
1710
|
+
versionEntity = await this.provider.GetEntityObject('MJ: Artifact Versions', this.contextUser);
|
|
1711
|
+
versionEntity.NewRecord();
|
|
1712
|
+
versionEntity.ArtifactID = entry.artifactId;
|
|
1713
|
+
versionEntity.VersionNumber = targetVersionNumber;
|
|
1714
|
+
versionEntity.UserID = this.contextUser.ID;
|
|
1715
|
+
}
|
|
1716
|
+
versionEntity.Name = entry.name;
|
|
1717
|
+
const runNote = activeAgentRunId ? ` (agentRunId: ${activeAgentRunId})` : '';
|
|
1718
|
+
versionEntity.Comments = activeAgentName
|
|
1719
|
+
? `Edited by ${activeAgentName} via '${toolName}'${runNote}`
|
|
1720
|
+
: `Updated via agent tool '${toolName}'${runNote}`;
|
|
1721
|
+
versionEntity.ContentHash = contentHash;
|
|
1722
|
+
if (uploadedFileId) {
|
|
1723
|
+
const safeFileName = entry.name.toLowerCase().endsWith('.xlsx') ? entry.name : `${entry.name || 'workbook'}.xlsx`;
|
|
1724
|
+
versionEntity.ContentMode = 'File';
|
|
1725
|
+
versionEntity.FileID = uploadedFileId;
|
|
1726
|
+
versionEntity.MimeType = XLSX_MIME_TYPE;
|
|
1727
|
+
versionEntity.FileName = safeFileName;
|
|
1728
|
+
versionEntity.ContentSizeBytes = xlsxSizeBytes;
|
|
1729
|
+
versionEntity.Content = null;
|
|
1730
|
+
versionEntity.Configuration = BuildMergedFileVersionConfiguration({
|
|
1731
|
+
existingConfiguration: versionEntity.Configuration ?? entry.configuration,
|
|
1732
|
+
contentConfigurationJson: updatedContent,
|
|
1733
|
+
configurationPatch,
|
|
1734
|
+
});
|
|
1735
|
+
entry.configuration = versionEntity.Configuration;
|
|
1736
|
+
entry.contentMode = 'File';
|
|
1737
|
+
}
|
|
1738
|
+
else {
|
|
1739
|
+
const resolvedTypeEntity = ArtifactMetadataEngine.Instance.FindArtifactType(entry.typeName);
|
|
1740
|
+
versionEntity.ContentMode = 'Text';
|
|
1741
|
+
versionEntity.FileID = null;
|
|
1742
|
+
versionEntity.MimeType = entry.mimeType ?? resolvedTypeEntity?.ContentType ?? null;
|
|
1743
|
+
versionEntity.Content = updatedContent;
|
|
1744
|
+
versionEntity.ContentSizeBytes = Buffer.byteLength(updatedContent, 'utf8');
|
|
1745
|
+
if (effectiveXlsxBase64) {
|
|
1746
|
+
versionEntity.Configuration = BuildMergedFileVersionConfiguration({
|
|
1747
|
+
existingConfiguration: versionEntity.Configuration ?? entry.configuration,
|
|
1748
|
+
contentConfigurationJson: updatedContent,
|
|
1749
|
+
configurationPatch,
|
|
1750
|
+
});
|
|
1751
|
+
entry.configuration = versionEntity.Configuration;
|
|
1752
|
+
}
|
|
1753
|
+
else {
|
|
1754
|
+
let existingConfig = {};
|
|
1755
|
+
if (entry.configuration) {
|
|
1756
|
+
const parsedConfig = CleanAndParseJSON(entry.configuration);
|
|
1757
|
+
if (parsedConfig && typeof parsedConfig === 'object' && !Array.isArray(parsedConfig)) {
|
|
1758
|
+
existingConfig = parsedConfig;
|
|
1759
|
+
}
|
|
1760
|
+
}
|
|
1761
|
+
const mergedConfigObj = {
|
|
1762
|
+
...existingConfig,
|
|
1763
|
+
...(configurationPatch ?? {}),
|
|
1764
|
+
...(activeAgentRunId || activeAgentName
|
|
1765
|
+
? {
|
|
1766
|
+
agentRunId: activeAgentRunId ?? null,
|
|
1767
|
+
agentName: activeAgentName ?? null,
|
|
1768
|
+
lastTool: toolName,
|
|
1769
|
+
}
|
|
1770
|
+
: {}),
|
|
1771
|
+
};
|
|
1772
|
+
const mergedJson = JSON.stringify(mergedConfigObj);
|
|
1773
|
+
const enrichedConfig = BuildArtifactVersionConfigurationWithPreview(mergedJson, updatedContent, entry.driverClass ?? resolvedTypeEntity?.DriverClass ?? null, entry.name, {
|
|
1774
|
+
ArtifactType: resolvedTypeEntity ?? undefined,
|
|
1775
|
+
AllArtifactTypes: ArtifactMetadataEngine.Instance.ArtifactTypes ?? [],
|
|
1776
|
+
});
|
|
1777
|
+
if (Object.keys(mergedConfigObj).length > 0 || enrichedConfig) {
|
|
1778
|
+
versionEntity.Configuration = enrichedConfig ?? mergedJson;
|
|
1779
|
+
entry.configuration = versionEntity.Configuration;
|
|
1780
|
+
}
|
|
1781
|
+
else if (attributionConfig) {
|
|
1782
|
+
versionEntity.Configuration = attributionConfig;
|
|
1783
|
+
entry.configuration = attributionConfig;
|
|
1784
|
+
}
|
|
1785
|
+
}
|
|
1786
|
+
entry.contentMode = 'Text';
|
|
1787
|
+
}
|
|
1788
|
+
this.markTrustedAgentDraftVersionSave(versionEntity);
|
|
1789
|
+
const saved = await versionEntity.Save();
|
|
1790
|
+
if (saved) {
|
|
1791
|
+
entry.versionId = versionEntity.ID;
|
|
1792
|
+
entry.versionNumber = targetVersionNumber;
|
|
1793
|
+
entry.currentVersionNumber = targetVersionNumber;
|
|
1794
|
+
entry.agentRunVersionId = versionEntity.ID;
|
|
1795
|
+
entry.agentRunVersionEntity = versionEntity;
|
|
1796
|
+
const supersededFileId = previousReusedFileId && uploadedFileId && !UUIDsEqual(previousReusedFileId, uploadedFileId)
|
|
1797
|
+
? previousReusedFileId
|
|
1798
|
+
: null;
|
|
1799
|
+
return {
|
|
1800
|
+
persisted: true,
|
|
1801
|
+
versionEntity,
|
|
1802
|
+
uploadedFileId,
|
|
1803
|
+
supersededFileId,
|
|
1804
|
+
rollbackSnapshot,
|
|
1805
|
+
};
|
|
1806
|
+
}
|
|
1807
|
+
await this.deleteUnreferencedArtifactFile(uploadedFileId);
|
|
1808
|
+
// If Save() returned false, check whether a concurrent human version was saved in the meantime
|
|
1809
|
+
const postSaveConflict = await this.checkConcurrentDatabaseModification(entry);
|
|
1810
|
+
if (postSaveConflict) {
|
|
1811
|
+
LogError(`ArtifactToolManager: concurrent modification detected after save for artifact '${entry.artifactId}': ${postSaveConflict}`);
|
|
1812
|
+
return { persisted: false, errorMessage: postSaveConflict };
|
|
1813
|
+
}
|
|
1814
|
+
const saveErrMsg = `Failed to save MJ: Artifact Versions record for '${entry.artifactId}'`;
|
|
1815
|
+
LogError(`ArtifactToolManager: ${saveErrMsg}`);
|
|
1816
|
+
return { persisted: false, errorMessage: saveErrMsg };
|
|
1817
|
+
}
|
|
1818
|
+
catch (err) {
|
|
1819
|
+
await this.deleteUnreferencedArtifactFile(uploadedFileId);
|
|
1820
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
1821
|
+
LogError(`ArtifactToolManager: failed to persist version for artifact '${entry.artifactId}': ${msg}`);
|
|
1822
|
+
return { persisted: false, errorMessage: msg };
|
|
1823
|
+
}
|
|
1824
|
+
}
|
|
1825
|
+
/**
|
|
1826
|
+
* Rolls back a persisted version record and reverts manager entry state when a deferred commit fails.
|
|
1827
|
+
*/
|
|
1828
|
+
async rollbackPersistedArtifactVersionMutation(entry, entityOrOutcome, snapshotOrPreviousContent, options) {
|
|
1829
|
+
let versionEntity;
|
|
1830
|
+
let snapshot;
|
|
1831
|
+
let previousContentStr;
|
|
1832
|
+
if (entityOrOutcome && 'persisted' in entityOrOutcome) {
|
|
1833
|
+
versionEntity = entityOrOutcome.versionEntity;
|
|
1834
|
+
snapshot = entityOrOutcome.rollbackSnapshot;
|
|
1835
|
+
previousContentStr = typeof snapshotOrPreviousContent === 'string' ? snapshotOrPreviousContent : undefined;
|
|
1836
|
+
}
|
|
1837
|
+
else {
|
|
1838
|
+
versionEntity = entityOrOutcome;
|
|
1839
|
+
snapshot = snapshotOrPreviousContent;
|
|
1840
|
+
previousContentStr = options?.previousContentStr;
|
|
1841
|
+
}
|
|
1842
|
+
if (!snapshot) {
|
|
1843
|
+
return false;
|
|
1844
|
+
}
|
|
1845
|
+
entry.versionId = snapshot.entryVersionId;
|
|
1846
|
+
entry.versionNumber = snapshot.entryVersionNumber;
|
|
1847
|
+
entry.currentVersionNumber = snapshot.entryCurrentVersionNumber;
|
|
1848
|
+
entry.agentRunVersionId = snapshot.entryAgentRunVersionId;
|
|
1849
|
+
entry.agentRunVersionEntity = snapshot.entryAgentRunVersionEntity;
|
|
1850
|
+
entry.contentMode = snapshot.entryContentMode;
|
|
1851
|
+
if (snapshot.entryContent !== undefined) {
|
|
1852
|
+
entry.content = snapshot.entryContent;
|
|
1853
|
+
}
|
|
1854
|
+
if (snapshot.entryConfiguration !== undefined) {
|
|
1855
|
+
entry.configuration = snapshot.entryConfiguration;
|
|
1856
|
+
}
|
|
1857
|
+
if (snapshot.entryName !== undefined) {
|
|
1858
|
+
entry.name = snapshot.entryName;
|
|
1859
|
+
}
|
|
1860
|
+
if (snapshot.entryDescription !== undefined) {
|
|
1861
|
+
entry.description = snapshot.entryDescription;
|
|
1862
|
+
}
|
|
1863
|
+
if (snapshot.entryComments !== undefined) {
|
|
1864
|
+
entry.comments = snapshot.entryComments;
|
|
1865
|
+
}
|
|
1866
|
+
if (snapshot.entryDirty !== undefined) {
|
|
1867
|
+
entry.dirty = snapshot.entryDirty;
|
|
1868
|
+
}
|
|
1869
|
+
if (!versionEntity) {
|
|
1870
|
+
return false;
|
|
1871
|
+
}
|
|
1872
|
+
const newerVersionExists = await this.hasNewerArtifactVersion(entry, versionEntity);
|
|
1873
|
+
// The rollback undoes this call's own write, so it runs as the system user: the agent's user may have
|
|
1874
|
+
// lost Edit or Delete during the call (`R15-2`), and the write is scoped to the one row we created or
|
|
1875
|
+
// reused. It never touches any other version.
|
|
1876
|
+
const rollbackEntity = await this.loadVersionForRollback(versionEntity);
|
|
1877
|
+
if (snapshot.hadExistingAgentRunVersion) {
|
|
1878
|
+
// A reused agent-run row held this run's earlier content before the failed call overwrote it. Put
|
|
1879
|
+
// it back even when a newer version exists: that newer version is a separate row, and leaving the
|
|
1880
|
+
// reused row changed would keep an edit the agent was told failed (`R15-4`).
|
|
1881
|
+
await this.revertReusedAgentRunVersion(entry, rollbackEntity, snapshot);
|
|
1882
|
+
return !newerVersionExists;
|
|
1883
|
+
}
|
|
1884
|
+
if (newerVersionExists) {
|
|
1885
|
+
// Someone saved or restored after the agent's version. Keep it as history and leave the room where
|
|
1886
|
+
// that newer version put it.
|
|
1887
|
+
return false;
|
|
1888
|
+
}
|
|
1889
|
+
await this.deleteOrRevertNewAgentVersion(entry, rollbackEntity, previousContentStr ?? '');
|
|
1890
|
+
return true;
|
|
1891
|
+
}
|
|
1892
|
+
/** True when the artifact has a version numbered above `versionEntity` (someone saved after the agent). */
|
|
1893
|
+
async hasNewerArtifactVersion(entry, versionEntity) {
|
|
1894
|
+
if (!this.provider || !entry.artifactId || versionEntity.VersionNumber == null) {
|
|
1895
|
+
return false;
|
|
1896
|
+
}
|
|
1897
|
+
try {
|
|
1898
|
+
const rv = RunView.FromMetadataProvider(this.provider);
|
|
1899
|
+
const newerCheck = await rv.RunView({
|
|
1900
|
+
EntityName: 'MJ: Artifact Versions',
|
|
1901
|
+
Fields: ['ID', 'VersionNumber'],
|
|
1902
|
+
ExtraFilter: `ArtifactID = '${EscapeSQLString(entry.artifactId)}' AND VersionNumber > ${versionEntity.VersionNumber}`,
|
|
1903
|
+
OrderBy: 'VersionNumber DESC',
|
|
1904
|
+
MaxRows: 1,
|
|
1905
|
+
ResultType: 'simple',
|
|
1906
|
+
}, this.contextUser);
|
|
1907
|
+
if (!newerCheck.Success) {
|
|
1908
|
+
LogError(`ArtifactToolManager: could not check for versions newer than '${versionEntity.ID}' before rollback: ${newerCheck.ErrorMessage}`);
|
|
1909
|
+
return false;
|
|
1910
|
+
}
|
|
1911
|
+
return (newerCheck.Results?.[0]?.VersionNumber ?? 0) > (versionEntity.VersionNumber ?? 0);
|
|
1912
|
+
}
|
|
1913
|
+
catch (err) {
|
|
1914
|
+
LogError(`ArtifactToolManager: exception checking for newer versions before rollback of '${versionEntity.ID}': ${err instanceof Error ? err.message : String(err)}`);
|
|
1915
|
+
return false;
|
|
1916
|
+
}
|
|
1917
|
+
}
|
|
1918
|
+
/**
|
|
1919
|
+
* The version row to undo, loaded as the server system user so the undo is not refused by the agent
|
|
1920
|
+
* user's (possibly revoked) Edit/Delete rights. Falls back to the caller's own entity, with a log, when
|
|
1921
|
+
* no provider or system user is available or the load fails.
|
|
1922
|
+
*/
|
|
1923
|
+
async loadVersionForRollback(versionEntity) {
|
|
1924
|
+
const systemUser = UserCache.Instance.GetSystemUser();
|
|
1925
|
+
if (!this.provider || !systemUser || !versionEntity.ID) {
|
|
1926
|
+
return versionEntity;
|
|
1927
|
+
}
|
|
1928
|
+
try {
|
|
1929
|
+
const systemEntity = await this.provider.GetEntityObject('MJ: Artifact Versions', systemUser);
|
|
1930
|
+
if (await systemEntity.Load(versionEntity.ID)) {
|
|
1931
|
+
return systemEntity;
|
|
1932
|
+
}
|
|
1933
|
+
LogError(`ArtifactToolManager: could not load version '${versionEntity.ID}' as the system user for rollback: ${systemEntity.LatestResult?.CompleteMessage ?? 'not found'}`);
|
|
1934
|
+
}
|
|
1935
|
+
catch (err) {
|
|
1936
|
+
LogError(`ArtifactToolManager: exception loading version '${versionEntity.ID}' as the system user for rollback: ${err instanceof Error ? err.message : String(err)}`);
|
|
1937
|
+
}
|
|
1938
|
+
return versionEntity;
|
|
1939
|
+
}
|
|
1940
|
+
/** Deletes the version row this call created; if that fails, puts the previous content back into it. */
|
|
1941
|
+
async deleteOrRevertNewAgentVersion(entry, versionEntity, previousContent) {
|
|
1942
|
+
const uploadedFileId = versionEntity.FileID;
|
|
1943
|
+
let deleted = false;
|
|
1944
|
+
try {
|
|
1945
|
+
deleted = await versionEntity.Delete();
|
|
1946
|
+
if (!deleted) {
|
|
1947
|
+
LogError(`ArtifactToolManager: failed to delete rolled-back version '${versionEntity.ID}' for artifact '${entry.artifactId}' (${versionEntity.LatestResult?.CompleteMessage ?? 'unknown error'}); restoring previous content instead`);
|
|
1948
|
+
}
|
|
1949
|
+
}
|
|
1950
|
+
catch (delErr) {
|
|
1951
|
+
LogError(`ArtifactToolManager: exception deleting rolled-back version '${versionEntity.ID}' for artifact '${entry.artifactId}': ${delErr instanceof Error ? delErr.message : String(delErr)}`);
|
|
1952
|
+
}
|
|
1953
|
+
if (!deleted) {
|
|
1954
|
+
versionEntity.Content = previousContent;
|
|
1955
|
+
versionEntity.ContentHash = createHash('sha256').update(previousContent, 'utf8').digest('hex');
|
|
1956
|
+
versionEntity.ContentSizeBytes = Buffer.byteLength(previousContent, 'utf8');
|
|
1957
|
+
await this.saveRollbackEntity(entry, versionEntity, 'restore previous content on');
|
|
1958
|
+
}
|
|
1959
|
+
if (uploadedFileId) {
|
|
1960
|
+
await this.deleteUnreferencedArtifactFile(uploadedFileId);
|
|
1961
|
+
}
|
|
1962
|
+
}
|
|
1963
|
+
/** Puts a reused agent-run version row back to the field values it had before this call. */
|
|
1964
|
+
async revertReusedAgentRunVersion(entry, versionEntity, snapshot) {
|
|
1965
|
+
const failedUploadFileId = versionEntity.FileID;
|
|
1966
|
+
versionEntity.Name = snapshot.entityName ?? '';
|
|
1967
|
+
versionEntity.Comments = snapshot.entityComments ?? null;
|
|
1968
|
+
versionEntity.Content = snapshot.entityContent ?? null;
|
|
1969
|
+
versionEntity.Configuration = snapshot.entityConfiguration ?? null;
|
|
1970
|
+
versionEntity.ContentHash = snapshot.entityContentHash ?? null;
|
|
1971
|
+
versionEntity.ContentSizeBytes = snapshot.entityContentSizeBytes ?? null;
|
|
1972
|
+
versionEntity.ContentMode = snapshot.entityContentMode ?? 'Text';
|
|
1973
|
+
versionEntity.FileID = snapshot.entityFileID ?? null;
|
|
1974
|
+
versionEntity.MimeType = snapshot.entityMimeType ?? null;
|
|
1975
|
+
versionEntity.FileName = snapshot.entityFileName ?? null;
|
|
1976
|
+
const reverted = await this.saveRollbackEntity(entry, versionEntity, 'revert reused');
|
|
1977
|
+
if (reverted && failedUploadFileId && !UUIDsEqual(failedUploadFileId, snapshot.entityFileID)) {
|
|
1978
|
+
await this.deleteUnreferencedArtifactFile(failedUploadFileId);
|
|
1979
|
+
}
|
|
1980
|
+
}
|
|
1981
|
+
/** Marks an already-saved in-run draft version so `MJArtifactVersionEntityServer.Save` accepts sequential draft updates (`B3`). */
|
|
1982
|
+
markTrustedAgentDraftVersionSave(versionEntity) {
|
|
1983
|
+
if (!versionEntity.IsSaved) {
|
|
1984
|
+
return;
|
|
1985
|
+
}
|
|
1986
|
+
const store = GetGlobalObjectStore();
|
|
1987
|
+
if (!store) {
|
|
1988
|
+
return;
|
|
1989
|
+
}
|
|
1990
|
+
let draftSet = store[GLOBAL_KEY_TRUSTED_AGENT_DRAFT];
|
|
1991
|
+
if (!(draftSet instanceof WeakSet)) {
|
|
1992
|
+
draftSet = new WeakSet();
|
|
1993
|
+
store[GLOBAL_KEY_TRUSTED_AGENT_DRAFT] = draftSet;
|
|
1994
|
+
}
|
|
1995
|
+
draftSet.add(versionEntity);
|
|
1996
|
+
}
|
|
1997
|
+
/** Saves a rollback write and logs any failure; returns whether it saved. */
|
|
1998
|
+
async saveRollbackEntity(entry, versionEntity, action) {
|
|
1999
|
+
try {
|
|
2000
|
+
this.markTrustedAgentDraftVersionSave(versionEntity);
|
|
2001
|
+
const saved = await versionEntity.Save();
|
|
2002
|
+
if (!saved) {
|
|
2003
|
+
LogError(`ArtifactToolManager: failed to ${action} version '${versionEntity.ID}' for artifact '${entry.artifactId}' during rollback: ${versionEntity.LatestResult?.CompleteMessage ?? 'unknown error'}`);
|
|
2004
|
+
}
|
|
2005
|
+
return saved;
|
|
2006
|
+
}
|
|
2007
|
+
catch (err) {
|
|
2008
|
+
LogError(`ArtifactToolManager: exception trying to ${action} version '${versionEntity.ID}' for artifact '${entry.artifactId}' during rollback: ${err instanceof Error ? err.message : String(err)}`);
|
|
2009
|
+
return false;
|
|
2010
|
+
}
|
|
2011
|
+
}
|
|
2012
|
+
/**
|
|
2013
|
+
* Safely deletes an unreferenced file record from storage after verifying no MJ: Artifact Versions reference it.
|
|
2014
|
+
*/
|
|
2015
|
+
async deleteUnreferencedArtifactFile(fileId) {
|
|
2016
|
+
if (!this.provider || !this.contextUser) {
|
|
2017
|
+
return;
|
|
2018
|
+
}
|
|
2019
|
+
const trimmedFileId = (fileId ?? '').trim();
|
|
2020
|
+
if (!IsValidUUID(trimmedFileId)) {
|
|
2021
|
+
LogError(`ArtifactToolManager: refusing to delete artifact file — '${fileId}' is not a valid UUID`);
|
|
2022
|
+
return;
|
|
2023
|
+
}
|
|
2024
|
+
try {
|
|
2025
|
+
const rv = RunView.FromMetadataProvider(this.provider);
|
|
2026
|
+
const refParams = {
|
|
2027
|
+
EntityName: 'MJ: Artifact Versions',
|
|
2028
|
+
ExtraFilter: `FileID = '${EscapeSQLString(trimmedFileId)}'`,
|
|
2029
|
+
Fields: ['ID'],
|
|
2030
|
+
MaxRows: 1,
|
|
2031
|
+
SkipTotalRowCount: true,
|
|
2032
|
+
ResultType: 'simple',
|
|
2033
|
+
};
|
|
2034
|
+
const refRes = await rv.RunView(refParams, this.contextUser);
|
|
2035
|
+
if (!refRes.Success) {
|
|
2036
|
+
LogError(`ArtifactToolManager: failed checking MJ: Artifact Versions references before deleting FileID '${trimmedFileId}': ${refRes.ErrorMessage || 'RunView failed'}`);
|
|
2037
|
+
return;
|
|
2038
|
+
}
|
|
2039
|
+
if ((refRes.Results?.length ?? 0) > 0) {
|
|
2040
|
+
return;
|
|
2041
|
+
}
|
|
2042
|
+
const oldFile = await this.provider.GetEntityObject('MJ: Files', this.contextUser);
|
|
2043
|
+
if (await oldFile.Load(trimmedFileId)) {
|
|
2044
|
+
const deleted = await oldFile.Delete();
|
|
2045
|
+
if (!deleted) {
|
|
2046
|
+
LogError(`ArtifactToolManager: failed to delete superseded MJ: Files record '${trimmedFileId}': ${oldFile.LatestResult?.CompleteMessage || 'Delete() returned false'}`);
|
|
2047
|
+
}
|
|
2048
|
+
}
|
|
2049
|
+
}
|
|
2050
|
+
catch (err) {
|
|
2051
|
+
LogError(`ArtifactToolManager: exception deleting superseded MJ: Files record '${trimmedFileId}': ${err instanceof Error ? err.message : String(err)}`);
|
|
2052
|
+
}
|
|
2053
|
+
}
|
|
2054
|
+
/**
|
|
2055
|
+
* Execute a batch of tool calls in parallel. Each call's StoredToolResult is
|
|
2056
|
+
* also returned by {@link ExecuteSingleToolCall} for callers that wrap each
|
|
2057
|
+
* invocation in its own AIAgentRunStep. Returns void to preserve the
|
|
2058
|
+
* original contract.
|
|
2059
|
+
*/
|
|
2060
|
+
async ExecuteToolCalls(calls) {
|
|
2061
|
+
await Promise.all(calls.map((c) => this.ExecuteSingleToolCall(c)));
|
|
2062
|
+
}
|
|
2063
|
+
// ─── SERIALIZATION ───
|
|
2064
|
+
/** Snapshot for persistence */
|
|
2065
|
+
ToJSON() {
|
|
2066
|
+
return {
|
|
2067
|
+
artifacts: Array.from(this.artifacts.values()).map((a) => ({
|
|
2068
|
+
alphaId: a.alphaId,
|
|
2069
|
+
name: a.name,
|
|
2070
|
+
typeName: a.typeName,
|
|
2071
|
+
artifactId: a.artifactId,
|
|
2072
|
+
versionNumber: a.versionNumber,
|
|
2073
|
+
})),
|
|
2074
|
+
resultCount: this.toolResults.length,
|
|
2075
|
+
};
|
|
2076
|
+
}
|
|
2077
|
+
// ─── STATIC HELPERS ───
|
|
2078
|
+
/**
|
|
2079
|
+
* Determines whether artifact content should be externalized to MJStorage
|
|
2080
|
+
* instead of being stored inline.
|
|
2081
|
+
*/
|
|
2082
|
+
static ShouldExternalizeContent(contentLength, options) {
|
|
2083
|
+
const maxInlineChars = options?.maxInlineChars ?? 50_000;
|
|
2084
|
+
if (contentLength <= maxInlineChars) {
|
|
2085
|
+
return { shouldExternalize: false, reason: 'Content within inline limit' };
|
|
2086
|
+
}
|
|
2087
|
+
return {
|
|
2088
|
+
shouldExternalize: true,
|
|
2089
|
+
reason: 'Content exceeds ' + maxInlineChars + ' chars (' + contentLength + ' actual). Row data should be stored in MJStorage.',
|
|
2090
|
+
};
|
|
2091
|
+
}
|
|
2092
|
+
/**
|
|
2093
|
+
* Builds a truncated inline preview of a tables-based content JSON by keeping
|
|
2094
|
+
* only the first `maxRowsPerTable` rows per table and attaching truncation metadata.
|
|
2095
|
+
*/
|
|
2096
|
+
static BuildInlinePreview(contentJson, maxRowsPerTable = 30) {
|
|
2097
|
+
let parsed;
|
|
2098
|
+
try {
|
|
2099
|
+
const raw = JSON.parse(contentJson);
|
|
2100
|
+
if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {
|
|
2101
|
+
return contentJson;
|
|
2102
|
+
}
|
|
2103
|
+
parsed = raw;
|
|
2104
|
+
}
|
|
2105
|
+
catch {
|
|
2106
|
+
return contentJson;
|
|
2107
|
+
}
|
|
2108
|
+
const tables = parsed['tables'];
|
|
2109
|
+
if (!Array.isArray(tables)) {
|
|
2110
|
+
return contentJson;
|
|
2111
|
+
}
|
|
2112
|
+
let modified = false;
|
|
2113
|
+
for (const table of tables) {
|
|
2114
|
+
if (table === null || typeof table !== 'object' || Array.isArray(table)) {
|
|
2115
|
+
continue;
|
|
2116
|
+
}
|
|
2117
|
+
const tbl = table;
|
|
2118
|
+
const rows = tbl['rows'];
|
|
2119
|
+
if (!Array.isArray(rows) || rows.length <= maxRowsPerTable) {
|
|
2120
|
+
continue;
|
|
2121
|
+
}
|
|
2122
|
+
const existingMeta = tbl['metadata'];
|
|
2123
|
+
const metadata = existingMeta !== null && typeof existingMeta === 'object' && !Array.isArray(existingMeta)
|
|
2124
|
+
? existingMeta
|
|
2125
|
+
: {};
|
|
586
2126
|
metadata['totalRowCount'] = rows.length;
|
|
587
2127
|
metadata['truncatedForStorage'] = true;
|
|
2128
|
+
tbl['metadata'] = metadata;
|
|
588
2129
|
tbl['rows'] = rows.slice(0, maxRowsPerTable);
|
|
589
2130
|
modified = true;
|
|
590
2131
|
}
|
|
591
2132
|
return modified ? JSON.stringify(parsed) : contentJson;
|
|
592
2133
|
}
|
|
2134
|
+
// ─── CROSS-ARTIFACT & SYNTHESIS TOOLS ───
|
|
2135
|
+
recordToolResult(call, startedAt, result) {
|
|
2136
|
+
const stored = {
|
|
2137
|
+
artifactId: call.artifactId,
|
|
2138
|
+
tool: call.tool,
|
|
2139
|
+
input: call.input,
|
|
2140
|
+
result,
|
|
2141
|
+
timestamp: new Date(),
|
|
2142
|
+
durationMs: Date.now() - startedAt,
|
|
2143
|
+
};
|
|
2144
|
+
this.toolResults.push(stored);
|
|
2145
|
+
return stored;
|
|
2146
|
+
}
|
|
2147
|
+
parseInitialOperationsInput(input) {
|
|
2148
|
+
let rawOps = input['initialOperations'] ??
|
|
2149
|
+
input['InitialOperations'] ??
|
|
2150
|
+
input['operations'] ??
|
|
2151
|
+
input['Operations'];
|
|
2152
|
+
if (rawOps === undefined || rawOps === null) {
|
|
2153
|
+
return {};
|
|
2154
|
+
}
|
|
2155
|
+
if (typeof rawOps === 'string') {
|
|
2156
|
+
const trimmed = rawOps.trim();
|
|
2157
|
+
if (!trimmed) {
|
|
2158
|
+
return {};
|
|
2159
|
+
}
|
|
2160
|
+
try {
|
|
2161
|
+
rawOps = JSON.parse(trimmed);
|
|
2162
|
+
}
|
|
2163
|
+
catch (err) {
|
|
2164
|
+
return {
|
|
2165
|
+
errorMessage: `initialOperations is not valid JSON (${err instanceof Error ? err.message : String(err)}). Expected an array of { tool, input? } items.`,
|
|
2166
|
+
};
|
|
2167
|
+
}
|
|
2168
|
+
}
|
|
2169
|
+
if (!Array.isArray(rawOps)) {
|
|
2170
|
+
return {
|
|
2171
|
+
errorMessage: 'initialOperations must be an array of { tool: string, input?: object } items.',
|
|
2172
|
+
};
|
|
2173
|
+
}
|
|
2174
|
+
if (rawOps.length > MAX_INITIAL_OPERATIONS) {
|
|
2175
|
+
return {
|
|
2176
|
+
errorMessage: `initialOperations exceeds the maximum allowed ${MAX_INITIAL_OPERATIONS} operations per request.`,
|
|
2177
|
+
};
|
|
2178
|
+
}
|
|
2179
|
+
const ops = [];
|
|
2180
|
+
for (let i = 0; i < rawOps.length; i++) {
|
|
2181
|
+
const entry = rawOps[i];
|
|
2182
|
+
if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
|
|
2183
|
+
return { errorMessage: `initialOperations[${i}] must be an object with required string field 'tool'.` };
|
|
2184
|
+
}
|
|
2185
|
+
const record = entry;
|
|
2186
|
+
const rawToolName = record['tool'] ?? record['Tool'];
|
|
2187
|
+
if (typeof rawToolName !== 'string' || !rawToolName.trim()) {
|
|
2188
|
+
return { errorMessage: `initialOperations[${i}] is missing required non-empty string field 'tool'.` };
|
|
2189
|
+
}
|
|
2190
|
+
let opInput = record['input'] ?? record['Input'];
|
|
2191
|
+
if (typeof opInput === 'string') {
|
|
2192
|
+
const trimmedInput = opInput.trim();
|
|
2193
|
+
if (trimmedInput) {
|
|
2194
|
+
try {
|
|
2195
|
+
opInput = JSON.parse(trimmedInput);
|
|
2196
|
+
}
|
|
2197
|
+
catch (err) {
|
|
2198
|
+
return {
|
|
2199
|
+
errorMessage: `initialOperations[${i}].input is not valid JSON (${err instanceof Error ? err.message : String(err)}).`,
|
|
2200
|
+
};
|
|
2201
|
+
}
|
|
2202
|
+
}
|
|
2203
|
+
else {
|
|
2204
|
+
opInput = undefined;
|
|
2205
|
+
}
|
|
2206
|
+
}
|
|
2207
|
+
if (opInput !== undefined && opInput !== null && (typeof opInput !== 'object' || Array.isArray(opInput))) {
|
|
2208
|
+
return { errorMessage: `initialOperations[${i}].input must be an object.` };
|
|
2209
|
+
}
|
|
2210
|
+
ops.push({
|
|
2211
|
+
tool: rawToolName.trim(),
|
|
2212
|
+
input: opInput ? opInput : undefined,
|
|
2213
|
+
});
|
|
2214
|
+
}
|
|
2215
|
+
return { operations: ops.length > 0 ? ops : undefined };
|
|
2216
|
+
}
|
|
2217
|
+
async handleCreateArtifactTool(call, startedAt) {
|
|
2218
|
+
const input = call.input ?? {};
|
|
2219
|
+
const pickStr = (...keys) => {
|
|
2220
|
+
for (const k of keys) {
|
|
2221
|
+
const v = input[k];
|
|
2222
|
+
if (typeof v === 'string' && v.trim()) {
|
|
2223
|
+
return v.trim();
|
|
2224
|
+
}
|
|
2225
|
+
}
|
|
2226
|
+
return undefined;
|
|
2227
|
+
};
|
|
2228
|
+
const rawType = pickStr('artifactType', 'ArtifactType', 'type', 'Type', 'targetKind', 'TargetKind') ?? 'Markdown Document';
|
|
2229
|
+
const normalizedTypeName = GovernedArtifactService.Instance.NormalizeArtifactTypeName(rawType);
|
|
2230
|
+
const title = pickStr('title', 'Title') ?? `Untitled ${normalizedTypeName}`;
|
|
2231
|
+
const description = pickStr('description', 'Description');
|
|
2232
|
+
const collectionId = pickStr('collectionId', 'CollectionID');
|
|
2233
|
+
const rawSheetNames = input['sheetNames'] ?? input['SheetNames'];
|
|
2234
|
+
const sheetNames = Array.isArray(rawSheetNames)
|
|
2235
|
+
? rawSheetNames.filter((s) => typeof s === 'string' && s.trim().length > 0)
|
|
2236
|
+
: undefined;
|
|
2237
|
+
const rawContent = input['content'] ?? input['Content'];
|
|
2238
|
+
const providedContent = typeof rawContent === 'string' || (rawContent !== null && typeof rawContent === 'object' && !Array.isArray(rawContent))
|
|
2239
|
+
? rawContent
|
|
2240
|
+
: undefined;
|
|
2241
|
+
const parsedInitOps = this.parseInitialOperationsInput(input);
|
|
2242
|
+
if (parsedInitOps.errorMessage) {
|
|
2243
|
+
return this.recordToolResult(call, startedAt, {
|
|
2244
|
+
success: false,
|
|
2245
|
+
data: null,
|
|
2246
|
+
errorMessage: parsedInitOps.errorMessage,
|
|
2247
|
+
});
|
|
2248
|
+
}
|
|
2249
|
+
const activeRunId = this.agentRunId ?? this.getAgentRun?.()?.ID;
|
|
2250
|
+
const activeAgentName = this.agentName ?? this.getAgentRun?.()?.Agent ?? undefined;
|
|
2251
|
+
if (this.provider && this.contextUser) {
|
|
2252
|
+
const outcome = await GovernedArtifactService.Instance.CreateGovernedArtifact({
|
|
2253
|
+
provider: this.provider,
|
|
2254
|
+
contextUser: this.contextUser,
|
|
2255
|
+
title,
|
|
2256
|
+
artifactType: rawType,
|
|
2257
|
+
description,
|
|
2258
|
+
content: providedContent,
|
|
2259
|
+
sheetNames,
|
|
2260
|
+
initialOperations: parsedInitOps.operations,
|
|
2261
|
+
collectionId,
|
|
2262
|
+
agentRunId: activeRunId,
|
|
2263
|
+
agentName: activeAgentName,
|
|
2264
|
+
});
|
|
2265
|
+
if (!outcome.success || !outcome.artifactId) {
|
|
2266
|
+
return this.recordToolResult(call, startedAt, {
|
|
2267
|
+
success: false,
|
|
2268
|
+
data: null,
|
|
2269
|
+
errorMessage: outcome.errorMessage || 'Failed to create governed artifact.',
|
|
2270
|
+
});
|
|
2271
|
+
}
|
|
2272
|
+
const alphaId = this.RegisterArtifact({
|
|
2273
|
+
name: outcome.name ?? title,
|
|
2274
|
+
typeName: outcome.typeName ?? normalizedTypeName,
|
|
2275
|
+
artifactId: outcome.artifactId,
|
|
2276
|
+
versionId: outcome.versionId,
|
|
2277
|
+
versionNumber: outcome.versionNumber ?? 1,
|
|
2278
|
+
description,
|
|
2279
|
+
mimeType: outcome.mimeType,
|
|
2280
|
+
toolLibraryClass: outcome.toolLibraryClass,
|
|
2281
|
+
content: outcome.content ?? '',
|
|
2282
|
+
});
|
|
2283
|
+
const registeredEntry = this.artifacts.get(alphaId);
|
|
2284
|
+
if (registeredEntry) {
|
|
2285
|
+
registeredEntry.driverClass = outcome.driverClass;
|
|
2286
|
+
registeredEntry.configuration = outcome.configuration;
|
|
2287
|
+
registeredEntry.ownerUserId = this.contextUser.ID;
|
|
2288
|
+
}
|
|
2289
|
+
const touchedSummary = {
|
|
2290
|
+
ArtifactID: outcome.artifactId,
|
|
2291
|
+
ArtifactVersionID: outcome.versionId ?? '',
|
|
2292
|
+
VersionNumber: outcome.versionNumber ?? 1,
|
|
2293
|
+
Name: outcome.name ?? title,
|
|
2294
|
+
ArtifactTypeName: outcome.typeName ?? normalizedTypeName,
|
|
2295
|
+
DriverClass: outcome.driverClass,
|
|
2296
|
+
Operation: 'created',
|
|
2297
|
+
};
|
|
2298
|
+
this.recordTouchedArtifactSummary(touchedSummary);
|
|
2299
|
+
this.enteredPresenceArtifactIds.add(outcome.artifactId);
|
|
2300
|
+
const availableTools = registeredEntry?.library.GetToolList().map((t) => t.name) ?? [];
|
|
2301
|
+
return this.recordToolResult(call, startedAt, {
|
|
2302
|
+
success: true,
|
|
2303
|
+
data: {
|
|
2304
|
+
alphaId,
|
|
2305
|
+
artifactId: outcome.artifactId,
|
|
2306
|
+
versionId: outcome.versionId,
|
|
2307
|
+
versionNumber: outcome.versionNumber ?? 1,
|
|
2308
|
+
title: outcome.name ?? title,
|
|
2309
|
+
artifactTypeName: outcome.typeName ?? normalizedTypeName,
|
|
2310
|
+
driverClass: outcome.driverClass,
|
|
2311
|
+
persisted: true,
|
|
2312
|
+
...(outcome.results?.length
|
|
2313
|
+
? {
|
|
2314
|
+
initialOperationResults: outcome.results.map((r) => ({
|
|
2315
|
+
tool: r.tool,
|
|
2316
|
+
data: r.data ?? null,
|
|
2317
|
+
})),
|
|
2318
|
+
}
|
|
2319
|
+
: {}),
|
|
2320
|
+
availableTools,
|
|
2321
|
+
},
|
|
2322
|
+
});
|
|
2323
|
+
}
|
|
2324
|
+
// In-memory test fallback when no database provider/user is bound
|
|
2325
|
+
const built = await GovernedArtifactService.Instance.BuildInitialContentIsolated(normalizedTypeName, title, providedContent, sheetNames);
|
|
2326
|
+
const alphaId = this.RegisterArtifact({
|
|
2327
|
+
name: title,
|
|
2328
|
+
typeName: normalizedTypeName,
|
|
2329
|
+
versionNumber: 1,
|
|
2330
|
+
description,
|
|
2331
|
+
mimeType: built.mimeType,
|
|
2332
|
+
content: built.content,
|
|
2333
|
+
});
|
|
2334
|
+
const registeredEntry = this.artifacts.get(alphaId);
|
|
2335
|
+
const initialResults = [];
|
|
2336
|
+
if (parsedInitOps.operations && registeredEntry) {
|
|
2337
|
+
let workingContent = registeredEntry.content;
|
|
2338
|
+
for (const op of parsedInitOps.operations) {
|
|
2339
|
+
const opRes = await registeredEntry.library.InvokeTool(op.tool, op.input ?? {}, workingContent, { artifactId: alphaId });
|
|
2340
|
+
if (!opRes.success) {
|
|
2341
|
+
this.artifacts.delete(alphaId);
|
|
2342
|
+
return this.recordToolResult(call, startedAt, {
|
|
2343
|
+
success: false,
|
|
2344
|
+
data: null,
|
|
2345
|
+
errorMessage: `Initial operation '${op.tool}' failed: ${opRes.errorMessage || 'Unknown error'}`,
|
|
2346
|
+
});
|
|
2347
|
+
}
|
|
2348
|
+
const dataObj = opRes.data && typeof opRes.data === 'object' && !Array.isArray(opRes.data)
|
|
2349
|
+
? opRes.data
|
|
2350
|
+
: undefined;
|
|
2351
|
+
if (typeof dataObj?.updatedContent === 'string') {
|
|
2352
|
+
workingContent = dataObj.updatedContent;
|
|
2353
|
+
}
|
|
2354
|
+
initialResults.push({ tool: op.tool, data: opRes.data });
|
|
2355
|
+
}
|
|
2356
|
+
registeredEntry.content = workingContent;
|
|
2357
|
+
}
|
|
2358
|
+
const availableTools = registeredEntry?.library.GetToolList().map((t) => t.name) ?? [];
|
|
2359
|
+
return this.recordToolResult(call, startedAt, {
|
|
2360
|
+
success: true,
|
|
2361
|
+
data: {
|
|
2362
|
+
alphaId,
|
|
2363
|
+
artifactId: alphaId,
|
|
2364
|
+
versionNumber: 1,
|
|
2365
|
+
title,
|
|
2366
|
+
artifactTypeName: normalizedTypeName,
|
|
2367
|
+
persisted: false,
|
|
2368
|
+
...(initialResults.length > 0
|
|
2369
|
+
? {
|
|
2370
|
+
initialOperationResults: initialResults.map((r) => ({
|
|
2371
|
+
tool: r.tool,
|
|
2372
|
+
data: r.data ?? null,
|
|
2373
|
+
})),
|
|
2374
|
+
}
|
|
2375
|
+
: {}),
|
|
2376
|
+
availableTools,
|
|
2377
|
+
},
|
|
2378
|
+
});
|
|
2379
|
+
}
|
|
2380
|
+
async handleOpenArtifactTool(call, startedAt) {
|
|
2381
|
+
const input = call.input ?? {};
|
|
2382
|
+
const requestedId = typeof input['artifactId'] === 'string' && input['artifactId'].trim()
|
|
2383
|
+
? input['artifactId'].trim()
|
|
2384
|
+
: (call.artifactId ?? '').trim();
|
|
2385
|
+
if (!requestedId) {
|
|
2386
|
+
return this.recordToolResult(call, startedAt, {
|
|
2387
|
+
success: false,
|
|
2388
|
+
data: null,
|
|
2389
|
+
errorMessage: 'open_artifact requires an artifactId UUID.',
|
|
2390
|
+
});
|
|
2391
|
+
}
|
|
2392
|
+
if (!this.provider || !this.contextUser) {
|
|
2393
|
+
for (const entry of this.artifacts.values()) {
|
|
2394
|
+
if (entry.artifactId && UUIDsEqual(entry.artifactId, requestedId)) {
|
|
2395
|
+
return this.recordToolResult(call, startedAt, {
|
|
2396
|
+
success: true,
|
|
2397
|
+
data: {
|
|
2398
|
+
alphaId: entry.alphaId,
|
|
2399
|
+
artifactId: entry.artifactId,
|
|
2400
|
+
versionId: entry.versionId,
|
|
2401
|
+
versionNumber: entry.currentVersionNumber ?? entry.versionNumber,
|
|
2402
|
+
name: entry.name,
|
|
2403
|
+
typeName: entry.typeName,
|
|
2404
|
+
availableTools: entry.library.GetToolList().map((t) => t.name),
|
|
2405
|
+
},
|
|
2406
|
+
});
|
|
2407
|
+
}
|
|
2408
|
+
}
|
|
2409
|
+
return this.recordToolResult(call, startedAt, {
|
|
2410
|
+
success: false,
|
|
2411
|
+
data: null,
|
|
2412
|
+
errorMessage: 'Cannot open external artifact without contextUser and provider.',
|
|
2413
|
+
});
|
|
2414
|
+
}
|
|
2415
|
+
const loaded = await GovernedArtifactService.Instance.LoadReadableArtifactState(this.provider, this.contextUser, requestedId);
|
|
2416
|
+
if (!loaded.state) {
|
|
2417
|
+
return this.recordToolResult(call, startedAt, {
|
|
2418
|
+
success: false,
|
|
2419
|
+
data: null,
|
|
2420
|
+
errorMessage: loaded.errorMessage || `Failed to open artifact '${requestedId}'.`,
|
|
2421
|
+
});
|
|
2422
|
+
}
|
|
2423
|
+
const state = loaded.state;
|
|
2424
|
+
let matchedEntry;
|
|
2425
|
+
for (const entry of this.artifacts.values()) {
|
|
2426
|
+
if (entry.artifactId && UUIDsEqual(entry.artifactId, state.artifactId)) {
|
|
2427
|
+
matchedEntry = entry;
|
|
2428
|
+
break;
|
|
2429
|
+
}
|
|
2430
|
+
}
|
|
2431
|
+
if (matchedEntry) {
|
|
2432
|
+
matchedEntry.ownerUserId = state.ownerUserId;
|
|
2433
|
+
matchedEntry.versionId = state.versionId;
|
|
2434
|
+
matchedEntry.versionNumber = state.versionNumber;
|
|
2435
|
+
matchedEntry.baseVersionNumber = state.versionNumber;
|
|
2436
|
+
matchedEntry.currentVersionNumber = state.versionNumber;
|
|
2437
|
+
matchedEntry.contentMode = state.contentMode;
|
|
2438
|
+
matchedEntry.originalXlsxBytes = state.originalXlsxBytes;
|
|
2439
|
+
matchedEntry.content = state.content;
|
|
2440
|
+
matchedEntry.configuration = state.configuration;
|
|
2441
|
+
matchedEntry.driverClass = state.driverClass;
|
|
2442
|
+
matchedEntry.toolLibraryClass = state.toolLibraryClass;
|
|
2443
|
+
}
|
|
2444
|
+
else {
|
|
2445
|
+
const alphaId = this.RegisterArtifact({
|
|
2446
|
+
name: state.name,
|
|
2447
|
+
typeName: state.typeName,
|
|
2448
|
+
artifactId: state.artifactId,
|
|
2449
|
+
versionId: state.versionId,
|
|
2450
|
+
versionNumber: state.versionNumber,
|
|
2451
|
+
description: state.description,
|
|
2452
|
+
mimeType: state.mimeType,
|
|
2453
|
+
toolLibraryClass: state.toolLibraryClass,
|
|
2454
|
+
content: state.content,
|
|
2455
|
+
});
|
|
2456
|
+
matchedEntry = this.artifacts.get(alphaId);
|
|
2457
|
+
if (matchedEntry) {
|
|
2458
|
+
matchedEntry.ownerUserId = state.ownerUserId;
|
|
2459
|
+
matchedEntry.contentMode = state.contentMode;
|
|
2460
|
+
matchedEntry.originalXlsxBytes = state.originalXlsxBytes;
|
|
2461
|
+
matchedEntry.configuration = state.configuration;
|
|
2462
|
+
matchedEntry.driverClass = state.driverClass;
|
|
2463
|
+
}
|
|
2464
|
+
}
|
|
2465
|
+
const activeRunId = this.agentRunId ?? this.getAgentRun?.()?.ID;
|
|
2466
|
+
const activeAgentName = this.agentName ?? this.getAgentRun?.()?.Agent ?? undefined;
|
|
2467
|
+
this.enteredPresenceArtifactIds.add(state.artifactId);
|
|
2468
|
+
await GovernedArtifactService.Instance.EmitAgentPresence({
|
|
2469
|
+
artifactId: state.artifactId,
|
|
2470
|
+
phase: 'enter',
|
|
2471
|
+
contextUser: this.contextUser,
|
|
2472
|
+
agentRunId: activeRunId,
|
|
2473
|
+
agentName: activeAgentName,
|
|
2474
|
+
toolName: 'open_artifact',
|
|
2475
|
+
actionSummary: `Opened "${state.name}"`,
|
|
2476
|
+
location: { Domain: ResolvePresenceDomain(state.typeName) },
|
|
2477
|
+
});
|
|
2478
|
+
return this.recordToolResult(call, startedAt, {
|
|
2479
|
+
success: true,
|
|
2480
|
+
data: {
|
|
2481
|
+
alphaId: matchedEntry?.alphaId,
|
|
2482
|
+
artifactId: state.artifactId,
|
|
2483
|
+
versionId: state.versionId,
|
|
2484
|
+
versionNumber: state.versionNumber,
|
|
2485
|
+
name: state.name,
|
|
2486
|
+
typeName: state.typeName,
|
|
2487
|
+
driverClass: state.driverClass,
|
|
2488
|
+
canEdit: state.permissions.CanEdit,
|
|
2489
|
+
liveRoomHydrated: state.liveRoomHydrated,
|
|
2490
|
+
availableTools: matchedEntry?.library.GetToolList().map((t) => t.name) ?? [],
|
|
2491
|
+
},
|
|
2492
|
+
});
|
|
2493
|
+
}
|
|
2494
|
+
async checkCollectionPermission(collectionId, required) {
|
|
2495
|
+
if (!this.provider || !this.contextUser) {
|
|
2496
|
+
return IsValidUUID(collectionId.trim())
|
|
2497
|
+
? { allowed: true }
|
|
2498
|
+
: { allowed: false, reason: `Invalid collectionId UUID '${collectionId}'.` };
|
|
2499
|
+
}
|
|
2500
|
+
return GovernedArtifactService.Instance.CheckCollectionPermission(this.provider, this.contextUser, collectionId, required);
|
|
2501
|
+
}
|
|
2502
|
+
entryToSynthesisSourceInput(entry) {
|
|
2503
|
+
return {
|
|
2504
|
+
ArtifactID: entry.artifactId || entry.alphaId,
|
|
2505
|
+
Name: entry.name,
|
|
2506
|
+
ArtifactType: entry.typeName,
|
|
2507
|
+
VersionNumber: entry.currentVersionNumber ?? entry.versionNumber,
|
|
2508
|
+
ContentMode: entry.contentMode,
|
|
2509
|
+
Content: Buffer.isBuffer(entry.content) ? null : String(entry.content ?? ''),
|
|
2510
|
+
Configuration: entry.configuration ?? null,
|
|
2511
|
+
Description: entry.description ?? null,
|
|
2512
|
+
MimeType: entry.mimeType ?? null,
|
|
2513
|
+
};
|
|
2514
|
+
}
|
|
2515
|
+
async loadExternalReadableArtifact(artifactId) {
|
|
2516
|
+
if (!this.provider || !this.contextUser) {
|
|
2517
|
+
return { errorMessage: `Unknown source artifact '${artifactId}' (no database provider available).` };
|
|
2518
|
+
}
|
|
2519
|
+
const loaded = await GovernedArtifactService.Instance.LoadReadableArtifactState(this.provider, this.contextUser, artifactId);
|
|
2520
|
+
if (!loaded.state) {
|
|
2521
|
+
return { errorMessage: loaded.errorMessage || `Source artifact '${artifactId}' was not found.` };
|
|
2522
|
+
}
|
|
2523
|
+
const state = loaded.state;
|
|
2524
|
+
return {
|
|
2525
|
+
environmentId: state.environmentId ?? null,
|
|
2526
|
+
source: {
|
|
2527
|
+
ArtifactID: state.artifactId,
|
|
2528
|
+
Name: state.name,
|
|
2529
|
+
ArtifactType: state.typeName,
|
|
2530
|
+
VersionNumber: state.versionNumber,
|
|
2531
|
+
ContentMode: state.contentMode,
|
|
2532
|
+
Content: Buffer.isBuffer(state.content) ? null : state.content,
|
|
2533
|
+
Configuration: state.configuration ?? null,
|
|
2534
|
+
Description: state.description ?? null,
|
|
2535
|
+
MimeType: state.mimeType ?? null,
|
|
2536
|
+
},
|
|
2537
|
+
};
|
|
2538
|
+
}
|
|
2539
|
+
async handleListWorkspaceArtifactsTool(call, startedAt) {
|
|
2540
|
+
const input = call.input ?? {};
|
|
2541
|
+
const rawTypeFilter = typeof input['typeFilter'] === 'string' ? input['typeFilter'].trim() : '';
|
|
2542
|
+
const typeFilter = rawTypeFilter.toLowerCase();
|
|
2543
|
+
const normalizedTypeFilter = typeFilter
|
|
2544
|
+
? GovernedArtifactService.Instance.NormalizeArtifactTypeName(rawTypeFilter).toLowerCase()
|
|
2545
|
+
: '';
|
|
2546
|
+
const rawSearch = typeof input['search'] === 'string' ? input['search'].trim() : '';
|
|
2547
|
+
const search = rawSearch.toLowerCase();
|
|
2548
|
+
const collectionId = typeof input['collectionId'] === 'string' ? input['collectionId'].trim() : '';
|
|
2549
|
+
const maxResults = typeof input['maxResults'] === 'number' && Number.isFinite(input['maxResults'])
|
|
2550
|
+
? Math.min(Math.max(Math.trunc(input['maxResults']), 1), 100)
|
|
2551
|
+
: 25;
|
|
2552
|
+
const items = [];
|
|
2553
|
+
const seenArtifactIds = new Set();
|
|
2554
|
+
for (const entry of this.artifacts.values()) {
|
|
2555
|
+
if (entry.artifactId && this.contextUser && this.provider) {
|
|
2556
|
+
const perms = await ArtifactPermissionEngine.Instance.ResolvePermissions(this.provider, entry.artifactId, this.contextUser);
|
|
2557
|
+
if (!perms.CanRead)
|
|
2558
|
+
continue;
|
|
2559
|
+
}
|
|
2560
|
+
const entryTypeLower = entry.typeName.toLowerCase();
|
|
2561
|
+
if (typeFilter && !entryTypeLower.includes(typeFilter) && entryTypeLower !== normalizedTypeFilter)
|
|
2562
|
+
continue;
|
|
2563
|
+
if (search && !entry.name.toLowerCase().includes(search))
|
|
2564
|
+
continue;
|
|
2565
|
+
const digest = ArtifactSynthesisEngine.Instance.ExtractSourceDigest(this.entryToSynthesisSourceInput(entry), 1200);
|
|
2566
|
+
if (entry.artifactId) {
|
|
2567
|
+
seenArtifactIds.add(NormalizeUUID(entry.artifactId));
|
|
2568
|
+
}
|
|
2569
|
+
items.push({
|
|
2570
|
+
alphaId: entry.alphaId,
|
|
2571
|
+
artifactId: entry.artifactId,
|
|
2572
|
+
name: entry.name,
|
|
2573
|
+
typeName: entry.typeName,
|
|
2574
|
+
versionNumber: entry.currentVersionNumber ?? entry.versionNumber,
|
|
2575
|
+
sections: digest.Sections,
|
|
2576
|
+
embeddedCharts: digest.EmbeddedCharts,
|
|
2577
|
+
summaryPreview: digest.SummaryText.slice(0, 400),
|
|
2578
|
+
});
|
|
2579
|
+
}
|
|
2580
|
+
if (this.provider && this.contextUser) {
|
|
2581
|
+
const dbResult = await GovernedArtifactService.Instance.ListWorkspaceArtifacts({
|
|
2582
|
+
provider: this.provider,
|
|
2583
|
+
contextUser: this.contextUser,
|
|
2584
|
+
collectionId: collectionId || undefined,
|
|
2585
|
+
typeFilter: rawTypeFilter || undefined,
|
|
2586
|
+
search: rawSearch || undefined,
|
|
2587
|
+
maxResults,
|
|
2588
|
+
});
|
|
2589
|
+
if (!dbResult.success) {
|
|
2590
|
+
return this.recordToolResult(call, startedAt, {
|
|
2591
|
+
success: false,
|
|
2592
|
+
data: null,
|
|
2593
|
+
errorMessage: dbResult.errorMessage || 'Permission denied reading workspace artifacts.',
|
|
2594
|
+
});
|
|
2595
|
+
}
|
|
2596
|
+
for (const dbItem of dbResult.artifacts) {
|
|
2597
|
+
if (items.length >= maxResults)
|
|
2598
|
+
break;
|
|
2599
|
+
const normId = NormalizeUUID(dbItem.artifactId);
|
|
2600
|
+
if (seenArtifactIds.has(normId))
|
|
2601
|
+
continue;
|
|
2602
|
+
seenArtifactIds.add(normId);
|
|
2603
|
+
items.push({
|
|
2604
|
+
artifactId: dbItem.artifactId,
|
|
2605
|
+
name: dbItem.name,
|
|
2606
|
+
typeName: dbItem.typeName,
|
|
2607
|
+
versionNumber: dbItem.versionNumber,
|
|
2608
|
+
sections: dbItem.sections,
|
|
2609
|
+
embeddedCharts: dbItem.embeddedCharts,
|
|
2610
|
+
summaryPreview: dbItem.summaryPreview,
|
|
2611
|
+
});
|
|
2612
|
+
}
|
|
2613
|
+
}
|
|
2614
|
+
return this.recordToolResult(call, startedAt, {
|
|
2615
|
+
success: true,
|
|
2616
|
+
data: {
|
|
2617
|
+
count: items.length,
|
|
2618
|
+
artifacts: items,
|
|
2619
|
+
},
|
|
2620
|
+
});
|
|
2621
|
+
}
|
|
2622
|
+
async handleCreateSynthesizedArtifactTool(call, startedAt) {
|
|
2623
|
+
const input = call.input ?? {};
|
|
2624
|
+
const targetKind = ArtifactSynthesisEngine.Instance.NormalizeTargetKind(typeof input['targetKind'] === 'string' ? input['targetKind'] : 'presentation');
|
|
2625
|
+
const title = typeof input['title'] === 'string' && input['title'].trim()
|
|
2626
|
+
? input['title'].trim()
|
|
2627
|
+
: `Synthesized ${targetKind === 'presentation' ? 'Presentation' : targetKind === 'spreadsheet' ? 'Spreadsheet' : 'Document'}`;
|
|
2628
|
+
const goal = typeof input['goal'] === 'string' ? input['goal'].trim() : '';
|
|
2629
|
+
const customDescription = typeof input['description'] === 'string' && input['description'].trim()
|
|
2630
|
+
? input['description'].trim()
|
|
2631
|
+
: '';
|
|
2632
|
+
const linkChartsAndRanges = input['linkChartsAndRanges'] !== false;
|
|
2633
|
+
const collectionId = typeof input['collectionId'] === 'string' ? input['collectionId'].trim() : '';
|
|
2634
|
+
if (collectionId) {
|
|
2635
|
+
const colCheck = await this.checkCollectionPermission(collectionId, 'edit');
|
|
2636
|
+
if (!colCheck.allowed) {
|
|
2637
|
+
return this.recordToolResult(call, startedAt, {
|
|
2638
|
+
success: false,
|
|
2639
|
+
data: null,
|
|
2640
|
+
errorMessage: colCheck.reason || 'Permission denied: cannot link artifact into collection.',
|
|
2641
|
+
});
|
|
2642
|
+
}
|
|
2643
|
+
}
|
|
2644
|
+
const requestedIdsRaw = Array.isArray(input['sourceArtifactIds'])
|
|
2645
|
+
? input['sourceArtifactIds'].filter((x) => typeof x === 'string' && x.trim().length > 0)
|
|
2646
|
+
: typeof input['sourceArtifactIds'] === 'string' && input['sourceArtifactIds'].trim().length > 0
|
|
2647
|
+
? [input['sourceArtifactIds'].trim()]
|
|
2648
|
+
: [];
|
|
2649
|
+
const sourceInputs = [];
|
|
2650
|
+
const seenIds = new Set();
|
|
2651
|
+
let resolvedEnvironmentId = null;
|
|
2652
|
+
if (requestedIdsRaw.length > 0) {
|
|
2653
|
+
const entriesByArtifactId = IndexByUUID(Array.from(this.artifacts.values()).filter((e) => Boolean(e.artifactId)), (e) => e.artifactId);
|
|
2654
|
+
for (const rawRef of requestedIdsRaw) {
|
|
2655
|
+
const ref = rawRef.trim();
|
|
2656
|
+
const byAlpha = this.artifacts.get(ref) ?? this.artifacts.get(ref.toUpperCase());
|
|
2657
|
+
const matchedEntry = byAlpha ?? entriesByArtifactId.Get(ref);
|
|
2658
|
+
if (matchedEntry) {
|
|
2659
|
+
if (matchedEntry.artifactId && this.contextUser && this.provider) {
|
|
2660
|
+
const perms = await ArtifactPermissionEngine.Instance.ResolvePermissions(this.provider, matchedEntry.artifactId, this.contextUser);
|
|
2661
|
+
if (!perms.CanRead) {
|
|
2662
|
+
return this.recordToolResult(call, startedAt, {
|
|
2663
|
+
success: false,
|
|
2664
|
+
data: null,
|
|
2665
|
+
errorMessage: `Permission denied: user lacks Read access to source artifact '${matchedEntry.name}'.`,
|
|
2666
|
+
});
|
|
2667
|
+
}
|
|
2668
|
+
}
|
|
2669
|
+
const srcInput = this.entryToSynthesisSourceInput(matchedEntry);
|
|
2670
|
+
const dedupKey = srcInput.ArtifactID.toLowerCase();
|
|
2671
|
+
if (!seenIds.has(dedupKey)) {
|
|
2672
|
+
seenIds.add(dedupKey);
|
|
2673
|
+
sourceInputs.push(srcInput);
|
|
2674
|
+
}
|
|
2675
|
+
}
|
|
2676
|
+
else {
|
|
2677
|
+
const loaded = await this.loadExternalReadableArtifact(ref);
|
|
2678
|
+
if (!loaded.source) {
|
|
2679
|
+
return this.recordToolResult(call, startedAt, {
|
|
2680
|
+
success: false,
|
|
2681
|
+
data: null,
|
|
2682
|
+
errorMessage: loaded.errorMessage || `Unable to access source artifact '${ref}'.`,
|
|
2683
|
+
});
|
|
2684
|
+
}
|
|
2685
|
+
if (!resolvedEnvironmentId && loaded.environmentId) {
|
|
2686
|
+
resolvedEnvironmentId = loaded.environmentId;
|
|
2687
|
+
}
|
|
2688
|
+
const dedupKey = loaded.source.ArtifactID.toLowerCase();
|
|
2689
|
+
if (!seenIds.has(dedupKey)) {
|
|
2690
|
+
seenIds.add(dedupKey);
|
|
2691
|
+
sourceInputs.push(loaded.source);
|
|
2692
|
+
}
|
|
2693
|
+
}
|
|
2694
|
+
}
|
|
2695
|
+
}
|
|
2696
|
+
else {
|
|
2697
|
+
for (const entry of this.artifacts.values()) {
|
|
2698
|
+
if (entry.artifactId && this.contextUser && this.provider) {
|
|
2699
|
+
const perms = await ArtifactPermissionEngine.Instance.ResolvePermissions(this.provider, entry.artifactId, this.contextUser);
|
|
2700
|
+
if (!perms.CanRead)
|
|
2701
|
+
continue;
|
|
2702
|
+
}
|
|
2703
|
+
const srcInput = this.entryToSynthesisSourceInput(entry);
|
|
2704
|
+
const dedupKey = srcInput.ArtifactID.toLowerCase();
|
|
2705
|
+
if (!seenIds.has(dedupKey)) {
|
|
2706
|
+
seenIds.add(dedupKey);
|
|
2707
|
+
sourceInputs.push(srcInput);
|
|
2708
|
+
}
|
|
2709
|
+
}
|
|
2710
|
+
}
|
|
2711
|
+
const digests = [];
|
|
2712
|
+
for (let i = 0; i < sourceInputs.length; i += 4) {
|
|
2713
|
+
const batch = await Promise.all(sourceInputs.slice(i, i + 4).map((s) => ArtifactSynthesisEngine.Instance.ExtractSourceDigestIsolated(s)));
|
|
2714
|
+
digests.push(...batch);
|
|
2715
|
+
}
|
|
2716
|
+
const allowedIds = digests.map((d) => d.ArtifactID);
|
|
2717
|
+
const availableCharts = digests.flatMap((d) => d.EmbeddedCharts);
|
|
2718
|
+
const rawContentInput = input['content'];
|
|
2719
|
+
const rawContentStr = typeof rawContentInput === 'string'
|
|
2720
|
+
? rawContentInput.trim()
|
|
2721
|
+
: rawContentInput && typeof rawContentInput === 'object'
|
|
2722
|
+
? JSON.stringify(rawContentInput)
|
|
2723
|
+
: '';
|
|
2724
|
+
if (!rawContentStr && digests.length === 0) {
|
|
2725
|
+
return this.recordToolResult(call, startedAt, {
|
|
2726
|
+
success: false,
|
|
2727
|
+
data: null,
|
|
2728
|
+
errorMessage: 'No authorized source artifacts or content were provided for synthesis.',
|
|
2729
|
+
});
|
|
2730
|
+
}
|
|
2731
|
+
const normalized = rawContentStr
|
|
2732
|
+
? await ArtifactSynthesisEngine.Instance.NormalizeSynthesizedOutputIsolated({
|
|
2733
|
+
TargetKind: targetKind,
|
|
2734
|
+
RawOutput: rawContentStr,
|
|
2735
|
+
FallbackTitle: title,
|
|
2736
|
+
AllowedSourceArtifactIds: allowedIds,
|
|
2737
|
+
AvailableChartRefs: availableCharts,
|
|
2738
|
+
})
|
|
2739
|
+
: ArtifactSynthesisEngine.Instance.BuildDeterministicFallbackSynthesis(digests, targetKind, title, goal, linkChartsAndRanges);
|
|
2740
|
+
const finalDescription = customDescription || normalized.Description;
|
|
2741
|
+
let persistedArtifactId;
|
|
2742
|
+
let persistedVersionId;
|
|
2743
|
+
let persistedDriverClass;
|
|
2744
|
+
let persisted = false;
|
|
2745
|
+
if (this.provider && this.contextUser) {
|
|
2746
|
+
if (!resolvedEnvironmentId && digests[0]?.ArtifactID && IsValidUUID(digests[0].ArtifactID)) {
|
|
2747
|
+
const srcCheck = await this.loadExternalReadableArtifact(digests[0].ArtifactID);
|
|
2748
|
+
resolvedEnvironmentId = srcCheck.environmentId ?? null;
|
|
2749
|
+
}
|
|
2750
|
+
const activeRunId = this.agentRunId ?? this.getAgentRun?.()?.ID;
|
|
2751
|
+
const activeAgentName = this.agentName ?? this.getAgentRun?.()?.Agent ?? undefined;
|
|
2752
|
+
const synthComments = activeAgentName
|
|
2753
|
+
? `Synthesized by ${activeAgentName} from ${digests.length} artifact(s)`
|
|
2754
|
+
: `Synthesized via create_synthesized_artifact from ${digests.length} artifact(s)`;
|
|
2755
|
+
const outcome = await GovernedArtifactService.Instance.CreateGovernedArtifact({
|
|
2756
|
+
provider: this.provider,
|
|
2757
|
+
contextUser: this.contextUser,
|
|
2758
|
+
title: normalized.Title,
|
|
2759
|
+
artifactType: normalized.ArtifactTypeName,
|
|
2760
|
+
description: finalDescription,
|
|
2761
|
+
content: normalized.Content,
|
|
2762
|
+
collectionId,
|
|
2763
|
+
environmentId: resolvedEnvironmentId ?? undefined,
|
|
2764
|
+
agentRunId: activeRunId,
|
|
2765
|
+
agentName: activeAgentName,
|
|
2766
|
+
additionalConfig: { synthesizedFromArtifactIds: allowedIds },
|
|
2767
|
+
comments: synthComments,
|
|
2768
|
+
});
|
|
2769
|
+
if (!outcome.success || !outcome.artifactId) {
|
|
2770
|
+
return this.recordToolResult(call, startedAt, {
|
|
2771
|
+
success: false,
|
|
2772
|
+
data: null,
|
|
2773
|
+
errorMessage: outcome.errorMessage || 'Failed to create synthesized artifact.',
|
|
2774
|
+
});
|
|
2775
|
+
}
|
|
2776
|
+
persistedArtifactId = outcome.artifactId;
|
|
2777
|
+
persistedVersionId = outcome.versionId;
|
|
2778
|
+
persistedDriverClass = outcome.driverClass;
|
|
2779
|
+
persisted = true;
|
|
2780
|
+
}
|
|
2781
|
+
const newAlphaId = this.RegisterArtifact({
|
|
2782
|
+
name: normalized.Title,
|
|
2783
|
+
typeName: normalized.ArtifactTypeName,
|
|
2784
|
+
artifactId: persistedArtifactId,
|
|
2785
|
+
versionId: persistedVersionId,
|
|
2786
|
+
versionNumber: 1,
|
|
2787
|
+
description: finalDescription,
|
|
2788
|
+
content: normalized.Content,
|
|
2789
|
+
});
|
|
2790
|
+
if (persistedDriverClass) {
|
|
2791
|
+
const registeredEntry = this.artifacts.get(newAlphaId);
|
|
2792
|
+
if (registeredEntry) {
|
|
2793
|
+
registeredEntry.driverClass = persistedDriverClass;
|
|
2794
|
+
}
|
|
2795
|
+
}
|
|
2796
|
+
if (persistedArtifactId) {
|
|
2797
|
+
const synthRunId = this.agentRunId ?? this.getAgentRun?.()?.ID;
|
|
2798
|
+
const synthType = ArtifactMetadataEngine.Instance.FindArtifactType(normalized.ArtifactTypeName);
|
|
2799
|
+
const summary = {
|
|
2800
|
+
ArtifactID: persistedArtifactId,
|
|
2801
|
+
ArtifactVersionID: persistedVersionId ?? '',
|
|
2802
|
+
VersionNumber: 1,
|
|
2803
|
+
Name: normalized.Title,
|
|
2804
|
+
ArtifactTypeName: normalized.ArtifactTypeName,
|
|
2805
|
+
DriverClass: persistedDriverClass ?? synthType?.DriverClass ?? undefined,
|
|
2806
|
+
Operation: 'synthesized',
|
|
2807
|
+
};
|
|
2808
|
+
this.recordTouchedArtifactSummary(summary);
|
|
2809
|
+
GovernedArtifactService.Instance.RecordTouchedArtifact(synthRunId, summary);
|
|
2810
|
+
}
|
|
2811
|
+
return this.recordToolResult(call, startedAt, {
|
|
2812
|
+
success: true,
|
|
2813
|
+
data: {
|
|
2814
|
+
alphaId: newAlphaId,
|
|
2815
|
+
artifactId: persistedArtifactId ?? newAlphaId,
|
|
2816
|
+
versionId: persistedVersionId,
|
|
2817
|
+
versionNumber: 1,
|
|
2818
|
+
title: normalized.Title,
|
|
2819
|
+
artifactTypeName: normalized.ArtifactTypeName,
|
|
2820
|
+
targetKind: normalized.TargetKind,
|
|
2821
|
+
linkedChartCount: normalized.LinkedChartCount,
|
|
2822
|
+
sourceCount: digests.length,
|
|
2823
|
+
persisted,
|
|
2824
|
+
warnings: normalized.Warnings,
|
|
2825
|
+
},
|
|
2826
|
+
});
|
|
2827
|
+
}
|
|
2828
|
+
async handleRefreshAndSnapshotArtifactTool(call, startedAt) {
|
|
2829
|
+
if (!this.provider || !this.contextUser) {
|
|
2830
|
+
return this.recordToolResult(call, startedAt, {
|
|
2831
|
+
success: false,
|
|
2832
|
+
data: null,
|
|
2833
|
+
errorMessage: 'refresh_and_snapshot_artifact requires provider and contextUser.',
|
|
2834
|
+
});
|
|
2835
|
+
}
|
|
2836
|
+
const input = call.input ?? {};
|
|
2837
|
+
const targetRef = typeof input['targetArtifactId'] === 'string' && input['targetArtifactId'].trim()
|
|
2838
|
+
? input['targetArtifactId'].trim()
|
|
2839
|
+
: typeof input['artifactId'] === 'string' && input['artifactId'].trim()
|
|
2840
|
+
? input['artifactId'].trim()
|
|
2841
|
+
: (call.artifactId ?? '').trim();
|
|
2842
|
+
let resolvedArtifactId = targetRef;
|
|
2843
|
+
if (!IsValidUUID(resolvedArtifactId)) {
|
|
2844
|
+
const matchedEntry = this.resolveExistingArtifactEntry(targetRef);
|
|
2845
|
+
if (matchedEntry?.artifactId && IsValidUUID(matchedEntry.artifactId)) {
|
|
2846
|
+
resolvedArtifactId = matchedEntry.artifactId;
|
|
2847
|
+
}
|
|
2848
|
+
}
|
|
2849
|
+
if (!IsValidUUID(resolvedArtifactId)) {
|
|
2850
|
+
return this.recordToolResult(call, startedAt, {
|
|
2851
|
+
success: false,
|
|
2852
|
+
data: null,
|
|
2853
|
+
errorMessage: `refresh_and_snapshot_artifact requires a valid targetArtifactId (UUID or loaded artifact alpha ID), received '${targetRef}'.`,
|
|
2854
|
+
});
|
|
2855
|
+
}
|
|
2856
|
+
const modeRaw = typeof input['mode'] === 'string' ? input['mode'].trim().toLowerCase() : 'live_refresh';
|
|
2857
|
+
const freezeRefreshedBlocks = modeRaw === 'freeze_all_blocks' || input['freezeRefreshedBlocks'] === true;
|
|
2858
|
+
if (freezeRefreshedBlocks && !this.allowFreezeFromUserConfirmation) {
|
|
2859
|
+
return this.recordToolResult(call, startedAt, {
|
|
2860
|
+
success: false,
|
|
2861
|
+
data: null,
|
|
2862
|
+
errorMessage: 'Permission denied: agents cannot freeze live artifact blocks without explicit out-of-band user confirmation of the RLS/FLS snapshot security warning.',
|
|
2863
|
+
});
|
|
2864
|
+
}
|
|
2865
|
+
const skipIfUnchanged = input['skipIfUnchanged'] !== false;
|
|
2866
|
+
const forceRefreshFrozen = input['forceRefreshFrozen'] === true;
|
|
2867
|
+
const versionComments = typeof input['versionComment'] === 'string'
|
|
2868
|
+
? input['versionComment'].trim()
|
|
2869
|
+
: typeof input['versionComments'] === 'string'
|
|
2870
|
+
? input['versionComments'].trim()
|
|
2871
|
+
: undefined;
|
|
2872
|
+
const activeRunId = this.agentRunId ?? this.getAgentRun?.()?.ID;
|
|
2873
|
+
const activeAgentName = this.agentName ?? this.getAgentRun?.()?.Agent ?? undefined;
|
|
2874
|
+
const outcome = await GovernedArtifactService.Instance.RefreshAndSnapshotArtifact({
|
|
2875
|
+
provider: this.provider,
|
|
2876
|
+
contextUser: this.contextUser,
|
|
2877
|
+
artifactId: resolvedArtifactId,
|
|
2878
|
+
freezeRefreshedBlocks,
|
|
2879
|
+
forceSaveIfUnchanged: !skipIfUnchanged,
|
|
2880
|
+
forceRefreshFrozen,
|
|
2881
|
+
versionComments,
|
|
2882
|
+
agentRunId: activeRunId,
|
|
2883
|
+
agentName: activeAgentName,
|
|
2884
|
+
});
|
|
2885
|
+
if (!outcome.success) {
|
|
2886
|
+
return this.recordToolResult(call, startedAt, {
|
|
2887
|
+
success: false,
|
|
2888
|
+
data: null,
|
|
2889
|
+
errorMessage: outcome.errorMessage || outcome.message,
|
|
2890
|
+
});
|
|
2891
|
+
}
|
|
2892
|
+
// Keep loaded session entry synchronized if open in this ArtifactToolManager
|
|
2893
|
+
const openEntry = this.resolveExistingArtifactEntry(resolvedArtifactId);
|
|
2894
|
+
if (openEntry && outcome.changed && this.contextUser && this.provider) {
|
|
2895
|
+
await this.reloadArtifactFromDatabase(openEntry);
|
|
2896
|
+
}
|
|
2897
|
+
if (outcome.changed && outcome.versionId) {
|
|
2898
|
+
const touchedSummary = {
|
|
2899
|
+
ArtifactID: outcome.artifactId,
|
|
2900
|
+
ArtifactVersionID: outcome.versionId,
|
|
2901
|
+
VersionNumber: outcome.versionNumber ?? 1,
|
|
2902
|
+
Name: outcome.artifactName ?? 'Artifact',
|
|
2903
|
+
ArtifactTypeName: outcome.artifactTypeName ?? 'Document',
|
|
2904
|
+
DriverClass: outcome.driverClass,
|
|
2905
|
+
Operation: 'mutated',
|
|
2906
|
+
};
|
|
2907
|
+
this.recordTouchedArtifactSummary(touchedSummary);
|
|
2908
|
+
GovernedArtifactService.Instance.RecordTouchedArtifact(activeRunId, touchedSummary);
|
|
2909
|
+
}
|
|
2910
|
+
return this.recordToolResult(call, startedAt, {
|
|
2911
|
+
success: true,
|
|
2912
|
+
data: {
|
|
2913
|
+
changed: outcome.changed,
|
|
2914
|
+
resultCode: outcome.resultCode,
|
|
2915
|
+
artifactId: outcome.artifactId,
|
|
2916
|
+
versionId: outcome.versionId ?? null,
|
|
2917
|
+
versionNumber: outcome.versionNumber ?? null,
|
|
2918
|
+
diffSummary: outcome.diffSummary ?? outcome.message,
|
|
2919
|
+
signedFrozenBlocksCount: outcome.signedFrozenBlocksCount ?? 0,
|
|
2920
|
+
},
|
|
2921
|
+
});
|
|
2922
|
+
}
|
|
2923
|
+
async handleFollowSourceLinkRuntime(rawData, activeRunId) {
|
|
2924
|
+
const entityName = typeof rawData['entityName'] === 'string' ? rawData['entityName'].trim() : '';
|
|
2925
|
+
const recordId = typeof rawData['recordId'] === 'string' ? rawData['recordId'].trim() : '';
|
|
2926
|
+
if (!entityName || !recordId) {
|
|
2927
|
+
return {
|
|
2928
|
+
success: false,
|
|
2929
|
+
data: null,
|
|
2930
|
+
errorMessage: 'follow_source_link result is missing entityName or recordId.',
|
|
2931
|
+
};
|
|
2932
|
+
}
|
|
2933
|
+
if (!this.provider || !this.contextUser) {
|
|
2934
|
+
return {
|
|
2935
|
+
success: true,
|
|
2936
|
+
data: {
|
|
2937
|
+
...rawData,
|
|
2938
|
+
rlsVerified: false,
|
|
2939
|
+
},
|
|
2940
|
+
};
|
|
2941
|
+
}
|
|
2942
|
+
try {
|
|
2943
|
+
const rv = RunView.FromMetadataProvider(this.provider);
|
|
2944
|
+
const entityInfo = typeof this.provider.EntityByName === 'function' ? this.provider.EntityByName(entityName) : undefined;
|
|
2945
|
+
let idCondition;
|
|
2946
|
+
if (entityInfo && Array.isArray(entityInfo.PrimaryKeys) && entityInfo.PrimaryKeys.length > 0) {
|
|
2947
|
+
idCondition = CompositeKey.FromURLSegment(entityInfo, recordId).ToWhereClause();
|
|
2948
|
+
}
|
|
2949
|
+
else {
|
|
2950
|
+
const pkFieldName = entityInfo?.FirstPrimaryKey?.Name?.trim() || 'ID'; // first-pk-ok: fallback when provider/mock lacks EntityInfo.PrimaryKeys[]
|
|
2951
|
+
const quotedPk = /^[A-Za-z_][A-Za-z0-9_]*$/.test(pkFieldName) ? pkFieldName : `[${pkFieldName}]`;
|
|
2952
|
+
idCondition = `${quotedPk}='${EscapeSQLString(recordId)}'`;
|
|
2953
|
+
}
|
|
2954
|
+
const res = await rv.RunView({
|
|
2955
|
+
EntityName: entityName,
|
|
2956
|
+
ExtraFilter: idCondition,
|
|
2957
|
+
MaxRows: 1,
|
|
2958
|
+
SkipTotalRowCount: true,
|
|
2959
|
+
ResultType: 'simple',
|
|
2960
|
+
}, this.contextUser);
|
|
2961
|
+
if (!res.Success) {
|
|
2962
|
+
return {
|
|
2963
|
+
success: false,
|
|
2964
|
+
data: null,
|
|
2965
|
+
errorMessage: `RLS verification failed for ${entityName}.${recordId}: ${res.ErrorMessage || 'query error'}`,
|
|
2966
|
+
};
|
|
2967
|
+
}
|
|
2968
|
+
if (!res.Results || res.Results.length === 0) {
|
|
2969
|
+
return {
|
|
2970
|
+
success: false,
|
|
2971
|
+
data: null,
|
|
2972
|
+
errorMessage: `Access denied or record not found for ${entityName} (${recordId}).`,
|
|
2973
|
+
};
|
|
2974
|
+
}
|
|
2975
|
+
const recordPayload = res.Results[0];
|
|
2976
|
+
const serializedRecord = JSON.stringify(recordPayload, null, 2);
|
|
2977
|
+
const registeredAlphaId = this.RegisterArtifact({
|
|
2978
|
+
name: `${entityName}: ${recordId.slice(0, 8)}`,
|
|
2979
|
+
typeName: 'JSON',
|
|
2980
|
+
content: serializedRecord,
|
|
2981
|
+
description: `Source record ${entityName} (${recordId}) opened via follow_source_link${activeRunId ? ` [run ${activeRunId}]` : ''}`,
|
|
2982
|
+
});
|
|
2983
|
+
return {
|
|
2984
|
+
success: true,
|
|
2985
|
+
data: {
|
|
2986
|
+
rowId: rawData['rowId'] ?? null,
|
|
2987
|
+
entityName,
|
|
2988
|
+
recordId,
|
|
2989
|
+
rlsVerified: true,
|
|
2990
|
+
registeredAlphaId,
|
|
2991
|
+
record: recordPayload,
|
|
2992
|
+
},
|
|
2993
|
+
};
|
|
2994
|
+
}
|
|
2995
|
+
catch (err) {
|
|
2996
|
+
return {
|
|
2997
|
+
success: false,
|
|
2998
|
+
data: null,
|
|
2999
|
+
errorMessage: `follow_source_link failed: ${err instanceof Error ? err.message : String(err)}`,
|
|
3000
|
+
};
|
|
3001
|
+
}
|
|
3002
|
+
}
|
|
3003
|
+
async handleRerankRuntime(entry, rawData, activeRunId) {
|
|
3004
|
+
if (!this.contextUser) {
|
|
3005
|
+
return {
|
|
3006
|
+
success: true,
|
|
3007
|
+
data: {
|
|
3008
|
+
...rawData,
|
|
3009
|
+
reranked: false,
|
|
3010
|
+
note: 'Rerank deferred: no ContextUser is configured in ArtifactToolManager.',
|
|
3011
|
+
},
|
|
3012
|
+
};
|
|
3013
|
+
}
|
|
3014
|
+
const rawContent = typeof entry.content === 'string' ? entry.content : '';
|
|
3015
|
+
const parsedSpec = CleanAndParseJSON(rawContent);
|
|
3016
|
+
const results = Array.isArray(parsedSpec?.Results) ? parsedSpec.Results : [];
|
|
3017
|
+
if (results.length === 0) {
|
|
3018
|
+
return {
|
|
3019
|
+
success: true,
|
|
3020
|
+
data: { ...rawData, reranked: false, count: 0 },
|
|
3021
|
+
};
|
|
3022
|
+
}
|
|
3023
|
+
const queryText = (parsedSpec?.Query ?? '').trim() || entry.name;
|
|
3024
|
+
const documents = results.map((r, idx) => ({
|
|
3025
|
+
id: r.AlphaID || String(idx),
|
|
3026
|
+
text: (r.Chunk ?? r.Snippet ?? r.Title ?? '').slice(0, 4000),
|
|
3027
|
+
metadata: { alphaId: r.AlphaID },
|
|
3028
|
+
}));
|
|
3029
|
+
const rerankerName = typeof rawData['rerankerName'] === 'string' ? rawData['rerankerName'].trim() : '';
|
|
3030
|
+
let resolvedModelId;
|
|
3031
|
+
let resolvedPromptId;
|
|
3032
|
+
if (rerankerName) {
|
|
3033
|
+
if (IsValidUUID(rerankerName)) {
|
|
3034
|
+
const byModelId = AIEngine.Instance.ModelsByID?.get(NormalizeUUID(rerankerName));
|
|
3035
|
+
if (byModelId) {
|
|
3036
|
+
resolvedModelId = byModelId.ID;
|
|
3037
|
+
}
|
|
3038
|
+
else {
|
|
3039
|
+
const byPromptId = (AIEngine.Instance.Prompts ?? []).find((p) => UUIDsEqual(p.ID, rerankerName));
|
|
3040
|
+
if (byPromptId) {
|
|
3041
|
+
resolvedPromptId = byPromptId.ID;
|
|
3042
|
+
}
|
|
3043
|
+
}
|
|
3044
|
+
}
|
|
3045
|
+
else {
|
|
3046
|
+
const targetLower = rerankerName.toLowerCase();
|
|
3047
|
+
const models = AIEngine.Instance.Models ?? [];
|
|
3048
|
+
const matchedModel = models.find((m) => (m.Name?.trim().toLowerCase() === targetLower || m.APIName?.trim().toLowerCase() === targetLower) &&
|
|
3049
|
+
(m.AIModelType?.trim().toLowerCase() === 'reranker' || targetLower.includes('rerank'))) ??
|
|
3050
|
+
models.find((m) => m.Name?.trim().toLowerCase() === targetLower || m.APIName?.trim().toLowerCase() === targetLower);
|
|
3051
|
+
if (matchedModel) {
|
|
3052
|
+
resolvedModelId = matchedModel.ID;
|
|
3053
|
+
}
|
|
3054
|
+
else {
|
|
3055
|
+
const matchedPrompt = (AIEngine.Instance.Prompts ?? []).find((p) => p.Name?.trim().toLowerCase() === targetLower);
|
|
3056
|
+
if (matchedPrompt) {
|
|
3057
|
+
resolvedPromptId = matchedPrompt.ID;
|
|
3058
|
+
}
|
|
3059
|
+
}
|
|
3060
|
+
}
|
|
3061
|
+
}
|
|
3062
|
+
const runner = new AIRerankerRunner();
|
|
3063
|
+
const rerankOutcome = await runner.RunRerank({
|
|
3064
|
+
query: queryText,
|
|
3065
|
+
documents,
|
|
3066
|
+
topK: documents.length,
|
|
3067
|
+
ContextUser: this.contextUser,
|
|
3068
|
+
AgentRunID: activeRunId,
|
|
3069
|
+
...(resolvedModelId ? { ModelID: resolvedModelId } : {}),
|
|
3070
|
+
...(resolvedPromptId ? { PromptID: resolvedPromptId } : {}),
|
|
3071
|
+
...(rerankerName ? { options: { rerankerName } } : {}),
|
|
3072
|
+
});
|
|
3073
|
+
if (!rerankOutcome.Success || !rerankOutcome.Response?.results) {
|
|
3074
|
+
return {
|
|
3075
|
+
success: false,
|
|
3076
|
+
data: null,
|
|
3077
|
+
errorMessage: rerankOutcome.ErrorMessage || `Reranker '${rerankerName || 'default'}' failed to rank results.`,
|
|
3078
|
+
};
|
|
3079
|
+
}
|
|
3080
|
+
const scoreById = new Map();
|
|
3081
|
+
const rankOrder = [];
|
|
3082
|
+
for (const item of rerankOutcome.Response.results) {
|
|
3083
|
+
const id = item.id;
|
|
3084
|
+
if (!scoreById.has(id)) {
|
|
3085
|
+
scoreById.set(id, item.relevanceScore);
|
|
3086
|
+
rankOrder.push(id);
|
|
3087
|
+
}
|
|
3088
|
+
}
|
|
3089
|
+
const byAlpha = new Map(results.map((r) => [r.AlphaID, r]));
|
|
3090
|
+
const reordered = [];
|
|
3091
|
+
for (const id of rankOrder) {
|
|
3092
|
+
const row = byAlpha.get(id);
|
|
3093
|
+
if (row) {
|
|
3094
|
+
reordered.push({ ...row, Score: scoreById.get(id) ?? row.Score });
|
|
3095
|
+
byAlpha.delete(id);
|
|
3096
|
+
}
|
|
3097
|
+
}
|
|
3098
|
+
for (const leftover of byAlpha.values()) {
|
|
3099
|
+
reordered.push(leftover);
|
|
3100
|
+
}
|
|
3101
|
+
entry.content = JSON.stringify({
|
|
3102
|
+
...parsedSpec,
|
|
3103
|
+
Reranker: rerankOutcome.ModelName ?? (rerankerName || parsedSpec?.Reranker || null),
|
|
3104
|
+
Results: reordered,
|
|
3105
|
+
});
|
|
3106
|
+
return {
|
|
3107
|
+
success: true,
|
|
3108
|
+
data: {
|
|
3109
|
+
reranked: true,
|
|
3110
|
+
rerankerName: rerankOutcome.ModelName ?? rerankerName,
|
|
3111
|
+
promptRunId: rerankOutcome.PromptRunID ?? null,
|
|
3112
|
+
newOrder: reordered.map((r) => r.AlphaID),
|
|
3113
|
+
count: reordered.length,
|
|
3114
|
+
},
|
|
3115
|
+
};
|
|
3116
|
+
}
|
|
593
3117
|
// ─── PRIVATE ───
|
|
594
3118
|
/** Generate next alpha-sequence ID: A, B, ... Z, AA, AB, ... */
|
|
595
3119
|
nextAlphaId() {
|
|
@@ -602,92 +3126,8 @@ export class ArtifactToolManager {
|
|
|
602
3126
|
const second = (index - 26) % 26;
|
|
603
3127
|
return String.fromCharCode(65 + first) + String.fromCharCode(65 + second);
|
|
604
3128
|
}
|
|
605
|
-
/**
|
|
606
|
-
* Resolve a tool library for an artifact type, walking the ParentID chain
|
|
607
|
-
* of `MJ: Artifact Types` to collect libraries from the leaf type and all
|
|
608
|
-
* ancestors. Child libraries override parent libraries for same-named tools.
|
|
609
|
-
*
|
|
610
|
-
* Resolution order:
|
|
611
|
-
* 1. If the metadata engine is loaded, walk `typeName → parent → ...` via
|
|
612
|
-
* `ArtifactMetadataEngine`, instantiating each level's `ToolLibraryClass`
|
|
613
|
-
* via ClassFactory. Returns a CompositeArtifactToolLibrary.
|
|
614
|
-
* 2. If the engine isn't loaded or the type isn't found, resolve the single
|
|
615
|
-
* leaf library using the `toolLibraryClass` hint plus name-based fallback.
|
|
616
|
-
*
|
|
617
|
-
* The engine is expected to be configured by AgentRunner before Initialize
|
|
618
|
-
* is called, so path (1) is the normal case.
|
|
619
|
-
*/
|
|
620
3129
|
resolveLibrary(typeName, toolLibraryClass) {
|
|
621
|
-
|
|
622
|
-
if (chain.length > 1)
|
|
623
|
-
return new CompositeArtifactToolLibrary(chain);
|
|
624
|
-
if (chain.length === 1)
|
|
625
|
-
return chain[0];
|
|
626
|
-
// Engine didn't yield anything — fall back to a single leaf library.
|
|
627
|
-
return this.resolveLeafLibrary(typeName, toolLibraryClass);
|
|
628
|
-
}
|
|
629
|
-
/**
|
|
630
|
-
* Walk the ParentID chain for `typeName` in ArtifactMetadataEngine,
|
|
631
|
-
* instantiating each level's ToolLibraryClass via ClassFactory.
|
|
632
|
-
* Returns the chain leaf-first. Levels without a ToolLibraryClass are
|
|
633
|
-
* skipped. Returns [] if the engine isn't loaded or the type isn't found.
|
|
634
|
-
*/
|
|
635
|
-
resolveLibraryChain(typeName) {
|
|
636
|
-
const engine = ArtifactMetadataEngine.Instance;
|
|
637
|
-
if (!engine.ArtifactTypes?.length)
|
|
638
|
-
return [];
|
|
639
|
-
const chain = [];
|
|
640
|
-
const visited = new Set();
|
|
641
|
-
let current = engine.FindArtifactType(typeName);
|
|
642
|
-
while (current && !visited.has(current.ID)) {
|
|
643
|
-
visited.add(current.ID);
|
|
644
|
-
const className = current.ToolLibraryClass;
|
|
645
|
-
if (className) {
|
|
646
|
-
const lib = MJGlobal.Instance.ClassFactory.CreateInstance(BaseArtifactToolLibrary, className);
|
|
647
|
-
if (lib)
|
|
648
|
-
chain.push(lib);
|
|
649
|
-
}
|
|
650
|
-
current = current.ParentID
|
|
651
|
-
? engine.ArtifactTypes.find((t) => UUIDsEqual(t.ID, current.ParentID))
|
|
652
|
-
: undefined;
|
|
653
|
-
}
|
|
654
|
-
return chain;
|
|
655
|
-
}
|
|
656
|
-
/**
|
|
657
|
-
* Single-library fallback when the metadata engine isn't available.
|
|
658
|
-
* Uses the provided `toolLibraryClass` hint first, then name-based heuristics.
|
|
659
|
-
*/
|
|
660
|
-
resolveLeafLibrary(typeName, toolLibraryClass) {
|
|
661
|
-
if (toolLibraryClass) {
|
|
662
|
-
const instance = MJGlobal.Instance.ClassFactory.CreateInstance(BaseArtifactToolLibrary, toolLibraryClass);
|
|
663
|
-
if (instance)
|
|
664
|
-
return instance;
|
|
665
|
-
}
|
|
666
|
-
const lower = typeName.toLowerCase();
|
|
667
|
-
if (lower.includes('data') || lower.includes('snapshot')) {
|
|
668
|
-
return new DataSnapshotToolLibrary();
|
|
669
|
-
}
|
|
670
|
-
if (lower.includes('json')) {
|
|
671
|
-
return new JSONToolLibrary();
|
|
672
|
-
}
|
|
673
|
-
// File-based types: try ClassFactory for dynamically registered libraries
|
|
674
|
-
// (PDFToolLibrary, ExcelToolLibrary, DocxToolLibrary are registered by CoreActions)
|
|
675
|
-
if (lower.includes('pdf')) {
|
|
676
|
-
const lib = MJGlobal.Instance.ClassFactory.CreateInstance(BaseArtifactToolLibrary, 'PDFToolLibrary');
|
|
677
|
-
if (lib)
|
|
678
|
-
return lib;
|
|
679
|
-
}
|
|
680
|
-
if (lower.includes('excel') || lower.includes('xlsx') || lower.includes('spreadsheet')) {
|
|
681
|
-
const lib = MJGlobal.Instance.ClassFactory.CreateInstance(BaseArtifactToolLibrary, 'ExcelToolLibrary');
|
|
682
|
-
if (lib)
|
|
683
|
-
return lib;
|
|
684
|
-
}
|
|
685
|
-
if (lower.includes('word') || lower.includes('docx') || lower.includes('document')) {
|
|
686
|
-
const lib = MJGlobal.Instance.ClassFactory.CreateInstance(BaseArtifactToolLibrary, 'DocxToolLibrary');
|
|
687
|
-
if (lib)
|
|
688
|
-
return lib;
|
|
689
|
-
}
|
|
690
|
-
return new TextToolLibrary();
|
|
3130
|
+
return GovernedArtifactService.Instance.ResolveLibrary(typeName, toolLibraryClass);
|
|
691
3131
|
}
|
|
692
3132
|
}
|
|
693
3133
|
//# sourceMappingURL=ArtifactToolManager.js.map
|