@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
|
@@ -0,0 +1,2569 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { BaseSingleton, CleanAndParseJSON, EscapeSQLString, GetGlobalObjectStore, IndexByUUID, IsValidUUID, MJEventType, MJGlobal, MJLruCache, NormalizeUUID, UUIDsEqual, } from '@memberjunction/global';
|
|
3
|
+
import { LogError, RunView } from '@memberjunction/core';
|
|
4
|
+
import { ArtifactMetadataEngine, ArtifactPermissionEngine, ArtifactSynthesisEngine, BuildArtifactVersionConfigurationWithPreview, DocumentLiveBlockEngine, MJEnvironmentEntityExtended, ParseArtifactVersionConfiguration, ParseRangeAddress, SlideDeckEngine, SpreadsheetEngine, ValidateArtifactContentMutationAgainstLocks, XlsxOpenXmlAdapter, } from '@memberjunction/core-entities';
|
|
5
|
+
import { FileStorageEngine } from '@memberjunction/storage';
|
|
6
|
+
import { BaseArtifactToolLibrary, } from '@memberjunction/ai-core-plus';
|
|
7
|
+
import { ARTIFACT_LIVE_MUTATION_EVENT_CODE, ExtractAgentTargetLocation, FormatAgentActionSummary, GetArtifactAgentPresenceHook, GetArtifactLiveContentReaderHook, GetArtifactLiveMutationHook, MUTATING_ARTIFACT_TOOL_NAMES, ResolvePresenceDomain, } from './artifact-presence-locator.js';
|
|
8
|
+
import { CSVToolLibrary } from './artifact-tools/CSVToolLibrary.js';
|
|
9
|
+
import { DataSnapshotToolLibrary } from './artifact-tools/DataSnapshotToolLibrary.js';
|
|
10
|
+
import { DocumentToolLibrary } from './artifact-tools/DocumentToolLibrary.js';
|
|
11
|
+
import { DocxToolLibrary } from './artifact-tools/DocxToolLibrary.js';
|
|
12
|
+
import { JSONToolLibrary } from './artifact-tools/JSONToolLibrary.js';
|
|
13
|
+
import { PDFToolLibrary } from './artifact-tools/PDFToolLibrary.js';
|
|
14
|
+
import { SearchResultSetToolLibrary } from './artifact-tools/SearchResultSetToolLibrary.js';
|
|
15
|
+
import { SlideDeckToolLibrary } from './artifact-tools/SlideDeckToolLibrary.js';
|
|
16
|
+
import { SpreadsheetToolLibrary } from './artifact-tools/SpreadsheetToolLibrary.js';
|
|
17
|
+
import { TextToolLibrary } from './artifact-tools/TextToolLibrary.js';
|
|
18
|
+
import { WhiteboardToolLibrary } from './artifact-tools/WhiteboardToolLibrary.js';
|
|
19
|
+
const GOVERNED_ARTIFACT_LOCKS_STORE_KEY = '___MJ_GOVERNED_ARTIFACT_LOCKS___';
|
|
20
|
+
const XLSX_MIME_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
|
|
21
|
+
const MARKDOWN_MIME_TYPE = 'text/markdown';
|
|
22
|
+
const PRESENTATION_MIME_TYPE = 'application/vnd.mj.presentation+json';
|
|
23
|
+
const SPREADSHEET_JSON_MIME_TYPE = 'application/vnd.mj.spreadsheet+json';
|
|
24
|
+
/**
|
|
25
|
+
* Spreadsheet tools that alter workbook structure, sheet order, or sheet layout rather than
|
|
26
|
+
* cell values/formulas. Refused on `File`-mode `.xlsx` workbooks because `PatchXlsxBytes`
|
|
27
|
+
* preserves non-`<sheetData>` OpenXML parts in-place instead of regenerating `workbook.xml`
|
|
28
|
+
* or worksheet layout XML.
|
|
29
|
+
*/
|
|
30
|
+
export const STRUCTURAL_SPREADSHEET_TOOLS = new Set([
|
|
31
|
+
'insert_rows',
|
|
32
|
+
'delete_rows',
|
|
33
|
+
'insert_columns',
|
|
34
|
+
'delete_columns',
|
|
35
|
+
'add_sheet',
|
|
36
|
+
'delete_sheet',
|
|
37
|
+
'rename_sheet',
|
|
38
|
+
'duplicate_sheet',
|
|
39
|
+
'reorder_sheets',
|
|
40
|
+
'set_sheet_layout',
|
|
41
|
+
'merge_cells',
|
|
42
|
+
'unmerge_cells',
|
|
43
|
+
]);
|
|
44
|
+
/** Formats the shared refusal message for structural spreadsheet tools on `File`-mode `.xlsx` workbooks. */
|
|
45
|
+
export function FormatFileModeStructuralToolError(toolName) {
|
|
46
|
+
return `Structural spreadsheet tool "${toolName}" is not supported on File-mode .xlsx workbooks to preserve OpenXML fidelity. Only cell value/formula updates (e.g. write_cells) are allowed on uploaded .xlsx files.`;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Merges two {@link GovernedRunArtifactSummary} records for the same artifact, keeping the
|
|
50
|
+
* higher `VersionNumber` snapshot while preserving `Operation: 'created'` if either entry
|
|
51
|
+
* created the artifact during the run.
|
|
52
|
+
*/
|
|
53
|
+
export function MergeTouchedArtifactSummary(existing, incoming) {
|
|
54
|
+
if (!existing) {
|
|
55
|
+
return { ...incoming };
|
|
56
|
+
}
|
|
57
|
+
const winner = incoming.VersionNumber >= existing.VersionNumber ? incoming : existing;
|
|
58
|
+
const other = winner === incoming ? existing : incoming;
|
|
59
|
+
return {
|
|
60
|
+
...other,
|
|
61
|
+
...winner,
|
|
62
|
+
DriverClass: winner.DriverClass ?? other.DriverClass,
|
|
63
|
+
Operation: existing.Operation === 'created' || incoming.Operation === 'created'
|
|
64
|
+
? 'created'
|
|
65
|
+
: winner.Operation,
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Merges tool libraries from an artifact type's inheritance chain (leaf-first).
|
|
70
|
+
*/
|
|
71
|
+
export class CompositeArtifactToolLibrary extends BaseArtifactToolLibrary {
|
|
72
|
+
constructor(chain) {
|
|
73
|
+
super();
|
|
74
|
+
this.chain = chain;
|
|
75
|
+
}
|
|
76
|
+
GetToolList() {
|
|
77
|
+
const seen = new Set();
|
|
78
|
+
const merged = [];
|
|
79
|
+
for (const lib of this.chain) {
|
|
80
|
+
for (const tool of lib.GetToolList()) {
|
|
81
|
+
if (seen.has(tool.name))
|
|
82
|
+
continue;
|
|
83
|
+
seen.add(tool.name);
|
|
84
|
+
merged.push(tool);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return merged;
|
|
88
|
+
}
|
|
89
|
+
async InvokeTool(toolName, input, artifactContent, context) {
|
|
90
|
+
for (const lib of this.chain) {
|
|
91
|
+
if (lib.GetToolList().some((t) => t.name === toolName)) {
|
|
92
|
+
return lib.InvokeTool(toolName, input, artifactContent, context);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return {
|
|
96
|
+
success: false,
|
|
97
|
+
data: null,
|
|
98
|
+
errorMessage: `Tool "${toolName}" is not defined by any library in this artifact type's chain.`,
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
ComputeRevisionHash(content) {
|
|
102
|
+
for (const lib of this.chain) {
|
|
103
|
+
const candidate = lib;
|
|
104
|
+
if (typeof candidate.ComputeRevisionHash === 'function') {
|
|
105
|
+
return candidate.ComputeRevisionHash(content);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return undefined;
|
|
109
|
+
}
|
|
110
|
+
getSubclassToolList() {
|
|
111
|
+
return [];
|
|
112
|
+
}
|
|
113
|
+
async invokeSubclassTool() {
|
|
114
|
+
return { success: false, data: null, errorMessage: 'CompositeArtifactToolLibrary does not dispatch via invokeSubclassTool.' };
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
function parseConfigurationRecord(raw) {
|
|
118
|
+
if (!raw) {
|
|
119
|
+
return {};
|
|
120
|
+
}
|
|
121
|
+
const parsed = CleanAndParseJSON(raw);
|
|
122
|
+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
|
123
|
+
return parsed;
|
|
124
|
+
}
|
|
125
|
+
return {};
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Merges an existing version's `Configuration` JSON, updated workbook/content configuration JSON,
|
|
129
|
+
* and incremental `configurationPatch` keys (e.g. `suggestions`, `comments`) so `File`-mode
|
|
130
|
+
* artifact saves never drop existing review metadata.
|
|
131
|
+
*/
|
|
132
|
+
export function BuildMergedFileVersionConfiguration(params) {
|
|
133
|
+
const existingObj = parseConfigurationRecord(params.existingConfiguration);
|
|
134
|
+
const contentObj = parseConfigurationRecord(params.contentConfigurationJson);
|
|
135
|
+
const patchObj = params.configurationPatch && typeof params.configurationPatch === 'object' && !Array.isArray(params.configurationPatch)
|
|
136
|
+
? params.configurationPatch
|
|
137
|
+
: {};
|
|
138
|
+
if (Object.keys(existingObj).length === 0 &&
|
|
139
|
+
Object.keys(patchObj).length === 0 &&
|
|
140
|
+
typeof params.contentConfigurationJson === 'string' &&
|
|
141
|
+
params.contentConfigurationJson.length > 0) {
|
|
142
|
+
return params.contentConfigurationJson;
|
|
143
|
+
}
|
|
144
|
+
return JSON.stringify({
|
|
145
|
+
...existingObj,
|
|
146
|
+
...contentObj,
|
|
147
|
+
...patchObj,
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* Shared server-side governed artifact service unifying native `BaseAgent` / `ArtifactToolManager`
|
|
152
|
+
* tools and reusable `CoreActions`. Handles permission enforcement, live Yjs room hydration and
|
|
153
|
+
* reconciliation, server-emitted agent presence awareness, and run-scoped touched artifact tracking.
|
|
154
|
+
*/
|
|
155
|
+
export class GovernedArtifactService extends BaseSingleton {
|
|
156
|
+
constructor() {
|
|
157
|
+
super();
|
|
158
|
+
this.runTouchedArtifacts = new MJLruCache({
|
|
159
|
+
maxSize: 500,
|
|
160
|
+
ttlMs: 2 * 60 * 60 * 1000,
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
getSharedArtifactLocks() {
|
|
164
|
+
const store = GetGlobalObjectStore();
|
|
165
|
+
const existing = store[GOVERNED_ARTIFACT_LOCKS_STORE_KEY];
|
|
166
|
+
if (existing instanceof Map) {
|
|
167
|
+
return existing;
|
|
168
|
+
}
|
|
169
|
+
const created = new Map();
|
|
170
|
+
store[GOVERNED_ARTIFACT_LOCKS_STORE_KEY] = created;
|
|
171
|
+
return created;
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* Acquires the process-wide per-artifact mutex stored in `GetGlobalObjectStore()` so
|
|
175
|
+
* `ArtifactToolManager`, `GovernedArtifactService`, and CoreActions serialize writes
|
|
176
|
+
* to the same `ArtifactID`.
|
|
177
|
+
*/
|
|
178
|
+
async WithArtifactLock(artifactId, fn) {
|
|
179
|
+
const locks = this.getSharedArtifactLocks();
|
|
180
|
+
const key = NormalizeUUID(artifactId) || (artifactId ?? '').trim().toLowerCase();
|
|
181
|
+
const prev = locks.get(key) ?? Promise.resolve();
|
|
182
|
+
let release;
|
|
183
|
+
const current = new Promise((resolve) => {
|
|
184
|
+
release = resolve;
|
|
185
|
+
});
|
|
186
|
+
const chain = prev.then(() => current, () => current);
|
|
187
|
+
locks.set(key, chain);
|
|
188
|
+
try {
|
|
189
|
+
await prev;
|
|
190
|
+
return await fn();
|
|
191
|
+
}
|
|
192
|
+
finally {
|
|
193
|
+
release();
|
|
194
|
+
if (locks.get(key) === chain) {
|
|
195
|
+
locks.delete(key);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
async withArtifactLock(artifactId, fn) {
|
|
200
|
+
return this.WithArtifactLock(artifactId, fn);
|
|
201
|
+
}
|
|
202
|
+
sanitizeToolInput(input) {
|
|
203
|
+
if (!input)
|
|
204
|
+
return {};
|
|
205
|
+
const sanitized = {};
|
|
206
|
+
for (const [k, v] of Object.entries(input)) {
|
|
207
|
+
if (k === '_actorUserId' || k === '_ownerUserId' || k === '_isEditor')
|
|
208
|
+
continue;
|
|
209
|
+
sanitized[k] = v;
|
|
210
|
+
}
|
|
211
|
+
return sanitized;
|
|
212
|
+
}
|
|
213
|
+
escapeSqlLike(term) {
|
|
214
|
+
return term.replace(/[\[%_]/g, (ch) => `[${ch}]`);
|
|
215
|
+
}
|
|
216
|
+
static get Instance() {
|
|
217
|
+
return super.getInstance();
|
|
218
|
+
}
|
|
219
|
+
IsMutatingTool(toolName) {
|
|
220
|
+
return MUTATING_ARTIFACT_TOOL_NAMES.has(toolName);
|
|
221
|
+
}
|
|
222
|
+
/**
|
|
223
|
+
* Maps user/agent aliases (`'spreadsheet'`, `'sheets'`, `'document'`, `'markdown'`, `'slides'`,
|
|
224
|
+
* `'presentation'`, etc.) onto canonical `MJ: Artifact Types` names.
|
|
225
|
+
*/
|
|
226
|
+
NormalizeArtifactTypeName(rawType) {
|
|
227
|
+
const cleaned = (rawType ?? '').trim();
|
|
228
|
+
const lower = cleaned.toLowerCase();
|
|
229
|
+
if (lower === 'spreadsheet' ||
|
|
230
|
+
lower === 'sheet' ||
|
|
231
|
+
lower === 'sheets' ||
|
|
232
|
+
lower === 'excel' ||
|
|
233
|
+
lower === 'xlsx' ||
|
|
234
|
+
lower === 'excel spreadsheet') {
|
|
235
|
+
return 'Excel Spreadsheet';
|
|
236
|
+
}
|
|
237
|
+
if (lower === 'document' ||
|
|
238
|
+
lower === 'doc' ||
|
|
239
|
+
lower === 'docs' ||
|
|
240
|
+
lower === 'markdown' ||
|
|
241
|
+
lower === 'md' ||
|
|
242
|
+
lower === 'markdown document') {
|
|
243
|
+
return 'Markdown Document';
|
|
244
|
+
}
|
|
245
|
+
if (lower === 'presentation' ||
|
|
246
|
+
lower === 'slides' ||
|
|
247
|
+
lower === 'slide' ||
|
|
248
|
+
lower === 'deck' ||
|
|
249
|
+
lower === 'slide deck') {
|
|
250
|
+
return 'Presentation';
|
|
251
|
+
}
|
|
252
|
+
return cleaned || 'Markdown Document';
|
|
253
|
+
}
|
|
254
|
+
/**
|
|
255
|
+
* Records a touched artifact against an active `agentRunId` so `BaseAgent`, `AgentRunner`, and
|
|
256
|
+
* realtime delegation can surface collaborative artifacts even when the final payload is empty.
|
|
257
|
+
*/
|
|
258
|
+
RecordTouchedArtifact(agentRunId, summary) {
|
|
259
|
+
const key = (agentRunId ?? '').trim().toLowerCase();
|
|
260
|
+
if (!key || !summary.ArtifactID)
|
|
261
|
+
return;
|
|
262
|
+
const existing = this.runTouchedArtifacts.Get(key) ?? [];
|
|
263
|
+
const targetLower = summary.ArtifactID.trim().toLowerCase();
|
|
264
|
+
const idx = existing.findIndex((item) => item.ArtifactID.trim().toLowerCase() === targetLower);
|
|
265
|
+
const next = [...existing];
|
|
266
|
+
if (idx >= 0) {
|
|
267
|
+
next[idx] = MergeTouchedArtifactSummary(next[idx], summary);
|
|
268
|
+
}
|
|
269
|
+
else {
|
|
270
|
+
next.push({ ...summary });
|
|
271
|
+
}
|
|
272
|
+
this.runTouchedArtifacts.Set(key, next);
|
|
273
|
+
}
|
|
274
|
+
PeekTouchedArtifacts(agentRunId) {
|
|
275
|
+
const key = (agentRunId ?? '').trim().toLowerCase();
|
|
276
|
+
if (!key)
|
|
277
|
+
return [];
|
|
278
|
+
return [...(this.runTouchedArtifacts.Get(key) ?? [])];
|
|
279
|
+
}
|
|
280
|
+
ConsumeTouchedArtifacts(agentRunId) {
|
|
281
|
+
const key = (agentRunId ?? '').trim().toLowerCase();
|
|
282
|
+
if (!key)
|
|
283
|
+
return [];
|
|
284
|
+
const items = [...(this.runTouchedArtifacts.Get(key) ?? [])];
|
|
285
|
+
this.runTouchedArtifacts.Delete(key);
|
|
286
|
+
return items;
|
|
287
|
+
}
|
|
288
|
+
/**
|
|
289
|
+
* Best-effort emission of server-owned Yjs agent awareness into the live collaboration room.
|
|
290
|
+
*/
|
|
291
|
+
async EmitAgentPresence(params) {
|
|
292
|
+
const hook = GetArtifactAgentPresenceHook();
|
|
293
|
+
if (!hook || !params.artifactId)
|
|
294
|
+
return;
|
|
295
|
+
const agentName = (params.agentName ?? '').trim() || 'MJ Agent';
|
|
296
|
+
const runKey = (params.agentRunId ?? '').trim();
|
|
297
|
+
const presenceKey = runKey || `action:${agentName.toLowerCase()}:${params.contextUser.ID}`;
|
|
298
|
+
const actingName = (params.contextUser.Name ?? '').trim() ||
|
|
299
|
+
[params.contextUser.FirstName, params.contextUser.LastName].filter(Boolean).join(' ').trim() ||
|
|
300
|
+
params.contextUser.Email ||
|
|
301
|
+
'User';
|
|
302
|
+
try {
|
|
303
|
+
await hook({
|
|
304
|
+
ArtifactID: params.artifactId,
|
|
305
|
+
Phase: params.phase,
|
|
306
|
+
AgentPresenceKey: presenceKey,
|
|
307
|
+
AgentRunID: runKey || undefined,
|
|
308
|
+
AgentName: agentName,
|
|
309
|
+
ActingForUserID: params.contextUser.ID,
|
|
310
|
+
ActingForUserName: actingName,
|
|
311
|
+
ActingForUserEmail: params.contextUser.Email ?? undefined,
|
|
312
|
+
ToolName: params.toolName,
|
|
313
|
+
ActionSummary: params.actionSummary,
|
|
314
|
+
Location: params.location,
|
|
315
|
+
TimestampMs: Date.now(),
|
|
316
|
+
});
|
|
317
|
+
}
|
|
318
|
+
catch (err) {
|
|
319
|
+
LogError(`GovernedArtifactService: agent presence hook failed for '${params.artifactId}': ${err instanceof Error ? err.message : String(err)}`);
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
/**
|
|
323
|
+
* Resolves a tool library (single or inheritance chain) for an artifact type.
|
|
324
|
+
*/
|
|
325
|
+
ResolveLibrary(typeName, toolLibraryClass) {
|
|
326
|
+
const chain = this.resolveLibraryChain(typeName);
|
|
327
|
+
if (chain.length > 1) {
|
|
328
|
+
return new CompositeArtifactToolLibrary(chain);
|
|
329
|
+
}
|
|
330
|
+
if (chain.length === 1) {
|
|
331
|
+
return chain[0];
|
|
332
|
+
}
|
|
333
|
+
return this.resolveLeafLibrary(typeName, toolLibraryClass);
|
|
334
|
+
}
|
|
335
|
+
async ResolveArtifactType(provider, contextUser, rawTypeName) {
|
|
336
|
+
const normalizedName = this.NormalizeArtifactTypeName(rawTypeName);
|
|
337
|
+
try {
|
|
338
|
+
await ArtifactMetadataEngine.Instance.Config(false, contextUser, provider);
|
|
339
|
+
const cached = ArtifactMetadataEngine.Instance.FindArtifactType(normalizedName) ??
|
|
340
|
+
ArtifactMetadataEngine.Instance.FindArtifactType(rawTypeName);
|
|
341
|
+
if (cached)
|
|
342
|
+
return cached;
|
|
343
|
+
}
|
|
344
|
+
catch {
|
|
345
|
+
// Fall back to direct RunView query
|
|
346
|
+
}
|
|
347
|
+
const rv = RunView.FromMetadataProvider(provider);
|
|
348
|
+
const res = await rv.RunView({
|
|
349
|
+
EntityName: 'MJ: Artifact Types',
|
|
350
|
+
ExtraFilter: `Name='${EscapeSQLString(normalizedName)}' AND IsEnabled=1`,
|
|
351
|
+
MaxRows: 1,
|
|
352
|
+
ResultType: 'entity_object',
|
|
353
|
+
}, contextUser);
|
|
354
|
+
return res.Success && res.Results?.length ? res.Results[0] : null;
|
|
355
|
+
}
|
|
356
|
+
async CheckCollectionPermission(provider, contextUser, collectionId, required) {
|
|
357
|
+
const trimmedId = (collectionId ?? '').trim();
|
|
358
|
+
if (!IsValidUUID(trimmedId)) {
|
|
359
|
+
return { allowed: false, reason: `Invalid collectionId '${collectionId}'.` };
|
|
360
|
+
}
|
|
361
|
+
const rv = RunView.FromMetadataProvider(provider);
|
|
362
|
+
const colRes = await rv.RunView({
|
|
363
|
+
EntityName: 'MJ: Collections',
|
|
364
|
+
ExtraFilter: `ID='${EscapeSQLString(trimmedId)}'`,
|
|
365
|
+
Fields: ['ID', 'EnvironmentID'],
|
|
366
|
+
MaxRows: 1,
|
|
367
|
+
SkipTotalRowCount: true,
|
|
368
|
+
ResultType: 'simple',
|
|
369
|
+
}, contextUser);
|
|
370
|
+
if (!colRes.Success || !colRes.Results?.length) {
|
|
371
|
+
return { allowed: false, reason: `Collection '${trimmedId}' was not found.` };
|
|
372
|
+
}
|
|
373
|
+
const collectionRow = colRes.Results[0];
|
|
374
|
+
const resolved = await ArtifactPermissionEngine.Instance.ResolveCollectionAncestryPermissions(provider, trimmedId, contextUser);
|
|
375
|
+
const normalizedRequired = (required ?? 'read').trim().toLowerCase();
|
|
376
|
+
const allowed = normalizedRequired === 'edit' ? resolved.CanEdit : resolved.CanRead;
|
|
377
|
+
if (!allowed) {
|
|
378
|
+
const reason = resolved.Source === 'Denied' && resolved.Reason && /not found|permission denied|invalid|must be valid/i.test(resolved.Reason)
|
|
379
|
+
? resolved.Reason
|
|
380
|
+
: `Permission denied: user lacks ${normalizedRequired === 'edit' ? 'Edit' : 'Read'} access to collection '${trimmedId}'.`;
|
|
381
|
+
return {
|
|
382
|
+
allowed: false,
|
|
383
|
+
reason,
|
|
384
|
+
};
|
|
385
|
+
}
|
|
386
|
+
return { allowed: true, environmentId: collectionRow.EnvironmentID ?? null };
|
|
387
|
+
}
|
|
388
|
+
async DownloadArtifactFileContent(provider, contextUser, fileId) {
|
|
389
|
+
const trimmedFileId = (fileId ?? '').trim();
|
|
390
|
+
if (!IsValidUUID(trimmedFileId)) {
|
|
391
|
+
return null;
|
|
392
|
+
}
|
|
393
|
+
try {
|
|
394
|
+
await FileStorageEngine.Instance.Config(false, contextUser, provider);
|
|
395
|
+
const rv = RunView.FromMetadataProvider(provider);
|
|
396
|
+
const fileResult = await rv.RunView({
|
|
397
|
+
EntityName: 'MJ: Files',
|
|
398
|
+
ExtraFilter: `ID = '${EscapeSQLString(trimmedFileId)}'`,
|
|
399
|
+
Fields: ['ID', 'Name', 'ContentType', 'ProviderID', 'ProviderKey'],
|
|
400
|
+
ResultType: 'simple',
|
|
401
|
+
}, contextUser);
|
|
402
|
+
if (!fileResult.Success || !fileResult.Results?.length) {
|
|
403
|
+
return null;
|
|
404
|
+
}
|
|
405
|
+
const resolved = await FileStorageEngine.Instance.ResolveFileObject(fileResult.Results[0], contextUser, 'Read', provider);
|
|
406
|
+
if (!resolved) {
|
|
407
|
+
return null;
|
|
408
|
+
}
|
|
409
|
+
const rawContent = await resolved.Driver.GetObject({ fullPath: resolved.ObjectKey });
|
|
410
|
+
if (Buffer.isBuffer(rawContent))
|
|
411
|
+
return rawContent;
|
|
412
|
+
if (rawContent instanceof Uint8Array)
|
|
413
|
+
return Buffer.from(rawContent);
|
|
414
|
+
if (typeof rawContent === 'string')
|
|
415
|
+
return Buffer.from(rawContent);
|
|
416
|
+
return null;
|
|
417
|
+
}
|
|
418
|
+
catch (err) {
|
|
419
|
+
LogError(`GovernedArtifactService: failed to download FileID '${trimmedFileId}': ${err instanceof Error ? err.message : String(err)}`);
|
|
420
|
+
return null;
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
/**
|
|
424
|
+
* Loads a readable governed artifact from DB, preferring uncompacted live Yjs room content
|
|
425
|
+
* whenever a collaboration room is currently active.
|
|
426
|
+
*/
|
|
427
|
+
async LoadReadableArtifactState(provider, contextUser, artifactId, options) {
|
|
428
|
+
const trimmedId = (artifactId ?? '').trim();
|
|
429
|
+
if (!IsValidUUID(trimmedId)) {
|
|
430
|
+
return { errorMessage: `Invalid artifact identifier '${artifactId}'.` };
|
|
431
|
+
}
|
|
432
|
+
const perms = await ArtifactPermissionEngine.Instance.ResolvePermissions(provider, trimmedId, contextUser);
|
|
433
|
+
if (!perms.CanRead) {
|
|
434
|
+
return { errorMessage: `Permission denied: user does not have Read access to artifact '${trimmedId}'.` };
|
|
435
|
+
}
|
|
436
|
+
const rv = RunView.FromMetadataProvider(provider);
|
|
437
|
+
const artRes = await rv.RunView({
|
|
438
|
+
EntityName: 'MJ: Artifacts',
|
|
439
|
+
ExtraFilter: `ID='${EscapeSQLString(trimmedId)}'`,
|
|
440
|
+
Fields: ['ID', 'UserID', 'Name', 'Description', 'EnvironmentID', 'Type'],
|
|
441
|
+
MaxRows: 1,
|
|
442
|
+
SkipTotalRowCount: true,
|
|
443
|
+
ResultType: 'simple',
|
|
444
|
+
}, contextUser);
|
|
445
|
+
if (!artRes.Success || !artRes.Results?.length) {
|
|
446
|
+
return { errorMessage: `Artifact '${trimmedId}' was not found.` };
|
|
447
|
+
}
|
|
448
|
+
const artRow = artRes.Results[0];
|
|
449
|
+
const typeName = (artRow.Type ?? options?.fallbackTypeName ?? 'Markdown Document').trim();
|
|
450
|
+
const typeEntity = options?.skipTypeEntityResolution
|
|
451
|
+
? null
|
|
452
|
+
: await this.ResolveArtifactType(provider, contextUser, typeName);
|
|
453
|
+
const verRes = await rv.RunView({
|
|
454
|
+
EntityName: 'MJ: Artifact Versions',
|
|
455
|
+
ExtraFilter: `ArtifactID='${EscapeSQLString(trimmedId)}'`,
|
|
456
|
+
OrderBy: 'VersionNumber DESC',
|
|
457
|
+
Fields: ['ID', 'VersionNumber', 'Name', 'ContentMode', 'Content', 'Configuration', 'FileID', 'MimeType'],
|
|
458
|
+
MaxRows: 1,
|
|
459
|
+
SkipTotalRowCount: true,
|
|
460
|
+
ResultType: 'simple',
|
|
461
|
+
}, contextUser);
|
|
462
|
+
if (options?.failOnMissingFileContent && (!verRes.Success || !verRes.Results?.length)) {
|
|
463
|
+
return {
|
|
464
|
+
errorMessage: verRes.ErrorMessage || `No persisted versions found for artifact '${trimmedId}'.`,
|
|
465
|
+
};
|
|
466
|
+
}
|
|
467
|
+
const ver = verRes.Success && verRes.Results?.length ? verRes.Results[0] : undefined;
|
|
468
|
+
const latestFileId = (ver?.FileID ?? '').trim();
|
|
469
|
+
let content = ver?.Content ?? (ver?.Configuration ?? '');
|
|
470
|
+
let contentMode = ver?.ContentMode === 'File' || Boolean(latestFileId) ? 'File' : 'Text';
|
|
471
|
+
let originalXlsxBytes;
|
|
472
|
+
let liveRoomHydrated = false;
|
|
473
|
+
const dbVersionNumber = ver?.VersionNumber ?? 1;
|
|
474
|
+
let versionNumber = dbVersionNumber;
|
|
475
|
+
let versionId = ver?.ID;
|
|
476
|
+
// 1. Prefer uncompacted live Yjs collaboration room snapshot if active
|
|
477
|
+
const liveReader = GetArtifactLiveContentReaderHook();
|
|
478
|
+
if (liveReader) {
|
|
479
|
+
try {
|
|
480
|
+
const liveSnap = await liveReader(trimmedId, contextUser);
|
|
481
|
+
if (liveSnap && typeof liveSnap.Content === 'string') {
|
|
482
|
+
content = liveSnap.Content;
|
|
483
|
+
liveRoomHydrated = true;
|
|
484
|
+
if (typeof liveSnap.VersionNumber === 'number') {
|
|
485
|
+
versionNumber = liveSnap.VersionNumber;
|
|
486
|
+
}
|
|
487
|
+
if (liveSnap.VersionID) {
|
|
488
|
+
versionId = liveSnap.VersionID;
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
catch (err) {
|
|
493
|
+
LogError(`GovernedArtifactService: live room reader failed for '${trimmedId}': ${err instanceof Error ? err.message : String(err)}`);
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
if (options?.failOnMissingFileContent && !latestFileId && ver?.ContentMode === 'File') {
|
|
497
|
+
return {
|
|
498
|
+
errorMessage: `Latest version v${versionNumber} of artifact '${trimmedId}' has ContentMode='File' without a FileID.`,
|
|
499
|
+
};
|
|
500
|
+
}
|
|
501
|
+
// 2. If File-mode .xlsx is needed (or not hydrated from live room), download and hydrate binary bytes
|
|
502
|
+
if (latestFileId && !options?.skipBinaryDownload) {
|
|
503
|
+
const downloaded = await this.DownloadArtifactFileContent(provider, contextUser, latestFileId);
|
|
504
|
+
if (downloaded && downloaded.byteLength > 0) {
|
|
505
|
+
const isZip = downloaded.length > 4 && downloaded[0] === 0x50 && downloaded[1] === 0x4b;
|
|
506
|
+
const toolLib = (typeEntity?.ToolLibraryClass ?? '').trim();
|
|
507
|
+
const typeLower = typeName.toLowerCase();
|
|
508
|
+
const isSpreadsheet = toolLib === 'SpreadsheetToolLibrary' ||
|
|
509
|
+
typeEntity?.DriverClass === 'SpreadsheetArtifactViewerPlugin' ||
|
|
510
|
+
typeLower.includes('excel') ||
|
|
511
|
+
typeLower.includes('spreadsheet');
|
|
512
|
+
if (isSpreadsheet && isZip) {
|
|
513
|
+
originalXlsxBytes = new Uint8Array(downloaded);
|
|
514
|
+
if (!liveRoomHydrated) {
|
|
515
|
+
const imported = await SpreadsheetEngine.Instance.ImportFromXlsxBytesIsolated(originalXlsxBytes, ver?.Configuration ?? undefined);
|
|
516
|
+
await SpreadsheetEngine.Instance.EvaluateWorkbookIsolated(imported);
|
|
517
|
+
content = SpreadsheetEngine.Instance.SerializeWorkbook(imported);
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
else if (!liveRoomHydrated) {
|
|
521
|
+
content = downloaded;
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
else if (options?.failOnMissingFileContent) {
|
|
525
|
+
return {
|
|
526
|
+
errorMessage: `Failed to download file content for FileID '${latestFileId}' while reloading artifact '${trimmedId}'.`,
|
|
527
|
+
};
|
|
528
|
+
}
|
|
529
|
+
else if (!liveRoomHydrated && !content) {
|
|
530
|
+
contentMode = 'Text';
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
else if (options?.failOnMissingFileContent &&
|
|
534
|
+
!liveRoomHydrated &&
|
|
535
|
+
typeof ver?.Content !== 'string' &&
|
|
536
|
+
typeof ver?.Configuration !== 'string') {
|
|
537
|
+
return {
|
|
538
|
+
errorMessage: `Latest version v${versionNumber} of artifact '${trimmedId}' has no loadable content.`,
|
|
539
|
+
};
|
|
540
|
+
}
|
|
541
|
+
return {
|
|
542
|
+
state: {
|
|
543
|
+
artifactId: artRow.ID,
|
|
544
|
+
ownerUserId: artRow.UserID ?? undefined,
|
|
545
|
+
name: (ver?.Name ?? artRow.Name ?? 'Untitled Artifact').trim(),
|
|
546
|
+
description: artRow.Description ?? undefined,
|
|
547
|
+
typeName,
|
|
548
|
+
typeEntity,
|
|
549
|
+
driverClass: typeEntity?.DriverClass ?? undefined,
|
|
550
|
+
toolLibraryClass: typeEntity?.ToolLibraryClass ?? undefined,
|
|
551
|
+
environmentId: artRow.EnvironmentID ?? null,
|
|
552
|
+
versionId,
|
|
553
|
+
versionNumber,
|
|
554
|
+
dbVersionNumber,
|
|
555
|
+
contentMode,
|
|
556
|
+
content,
|
|
557
|
+
configuration: ver?.Configuration ?? undefined,
|
|
558
|
+
mimeType: ver?.MimeType ?? typeEntity?.ContentType ?? undefined,
|
|
559
|
+
originalXlsxBytes,
|
|
560
|
+
permissions: perms,
|
|
561
|
+
liveRoomHydrated,
|
|
562
|
+
},
|
|
563
|
+
};
|
|
564
|
+
}
|
|
565
|
+
BuildInitialContent(normalizedTypeName, title, providedContent, sheetNames) {
|
|
566
|
+
if (normalizedTypeName === 'Excel Spreadsheet') {
|
|
567
|
+
if (typeof providedContent === 'string' && providedContent.trim()) {
|
|
568
|
+
const parsed = SpreadsheetEngine.Instance.ParseWorkbook(providedContent, undefined, { SkipEvaluate: true });
|
|
569
|
+
return {
|
|
570
|
+
content: SpreadsheetEngine.Instance.SerializeWorkbook(parsed),
|
|
571
|
+
mimeType: SPREADSHEET_JSON_MIME_TYPE,
|
|
572
|
+
};
|
|
573
|
+
}
|
|
574
|
+
if (providedContent && typeof providedContent === 'object') {
|
|
575
|
+
const parsed = SpreadsheetEngine.Instance.ParseWorkbook(JSON.stringify(providedContent), undefined, {
|
|
576
|
+
SkipEvaluate: true,
|
|
577
|
+
});
|
|
578
|
+
return {
|
|
579
|
+
content: SpreadsheetEngine.Instance.SerializeWorkbook(parsed),
|
|
580
|
+
mimeType: SPREADSHEET_JSON_MIME_TYPE,
|
|
581
|
+
};
|
|
582
|
+
}
|
|
583
|
+
const wb = SpreadsheetEngine.Instance.CreateEmptyWorkbook(title, sheetNames);
|
|
584
|
+
return {
|
|
585
|
+
content: SpreadsheetEngine.Instance.SerializeWorkbook(wb),
|
|
586
|
+
mimeType: SPREADSHEET_JSON_MIME_TYPE,
|
|
587
|
+
};
|
|
588
|
+
}
|
|
589
|
+
if (normalizedTypeName === 'Presentation') {
|
|
590
|
+
if (typeof providedContent === 'string' && providedContent.trim()) {
|
|
591
|
+
return { content: providedContent, mimeType: PRESENTATION_MIME_TYPE };
|
|
592
|
+
}
|
|
593
|
+
if (providedContent && typeof providedContent === 'object') {
|
|
594
|
+
return { content: JSON.stringify(providedContent, null, 2), mimeType: PRESENTATION_MIME_TYPE };
|
|
595
|
+
}
|
|
596
|
+
const deck = SlideDeckEngine.Instance.CreateDefaultDeck(title);
|
|
597
|
+
return { content: JSON.stringify(deck, null, 2), mimeType: PRESENTATION_MIME_TYPE };
|
|
598
|
+
}
|
|
599
|
+
const mdContent = typeof providedContent === 'string' && providedContent.trim().length > 0
|
|
600
|
+
? providedContent
|
|
601
|
+
: providedContent && typeof providedContent === 'object'
|
|
602
|
+
? JSON.stringify(providedContent, null, 2)
|
|
603
|
+
: `# ${title}\n\n`;
|
|
604
|
+
return { content: mdContent, mimeType: MARKDOWN_MIME_TYPE };
|
|
605
|
+
}
|
|
606
|
+
/**
|
|
607
|
+
* Worker-isolated async variant of {@link BuildInitialContent} (`R7-1`) for server callers.
|
|
608
|
+
*/
|
|
609
|
+
async BuildInitialContentIsolated(normalizedTypeName, title, providedContent, sheetNames) {
|
|
610
|
+
if (normalizedTypeName === 'Excel Spreadsheet') {
|
|
611
|
+
if (typeof providedContent === 'string' && providedContent.trim()) {
|
|
612
|
+
const parsed = await SpreadsheetEngine.Instance.ParseWorkbookIsolated(providedContent);
|
|
613
|
+
return {
|
|
614
|
+
content: SpreadsheetEngine.Instance.SerializeWorkbook(parsed),
|
|
615
|
+
mimeType: SPREADSHEET_JSON_MIME_TYPE,
|
|
616
|
+
};
|
|
617
|
+
}
|
|
618
|
+
if (providedContent && typeof providedContent === 'object') {
|
|
619
|
+
const parsed = await SpreadsheetEngine.Instance.ParseWorkbookIsolated(JSON.stringify(providedContent));
|
|
620
|
+
return {
|
|
621
|
+
content: SpreadsheetEngine.Instance.SerializeWorkbook(parsed),
|
|
622
|
+
mimeType: SPREADSHEET_JSON_MIME_TYPE,
|
|
623
|
+
};
|
|
624
|
+
}
|
|
625
|
+
const wb = SpreadsheetEngine.Instance.CreateEmptyWorkbook(title, sheetNames);
|
|
626
|
+
await SpreadsheetEngine.Instance.EvaluateWorkbookIsolated(wb);
|
|
627
|
+
return {
|
|
628
|
+
content: SpreadsheetEngine.Instance.SerializeWorkbook(wb),
|
|
629
|
+
mimeType: SPREADSHEET_JSON_MIME_TYPE,
|
|
630
|
+
};
|
|
631
|
+
}
|
|
632
|
+
return this.BuildInitialContent(normalizedTypeName, title, providedContent, sheetNames);
|
|
633
|
+
}
|
|
634
|
+
/**
|
|
635
|
+
* Creates and persists a new governed artifact + version 1 (`MJ: Artifacts`, `MJ: Artifact Versions`),
|
|
636
|
+
* optionally linking into a collection and recording/emitting run metadata and live presence.
|
|
637
|
+
*/
|
|
638
|
+
async CreateGovernedArtifact(params) {
|
|
639
|
+
const normalizedTypeName = this.NormalizeArtifactTypeName(params.artifactType);
|
|
640
|
+
const title = (params.title ?? '').trim() || `Untitled ${normalizedTypeName}`;
|
|
641
|
+
const collectionId = (params.collectionId ?? '').trim();
|
|
642
|
+
let collectionEnvId = null;
|
|
643
|
+
if (collectionId) {
|
|
644
|
+
const colCheck = await this.CheckCollectionPermission(params.provider, params.contextUser, collectionId, 'edit');
|
|
645
|
+
if (!colCheck.allowed) {
|
|
646
|
+
return { success: false, errorMessage: colCheck.reason || 'Permission denied: cannot link artifact to collection.' };
|
|
647
|
+
}
|
|
648
|
+
collectionEnvId = colCheck.environmentId ?? null;
|
|
649
|
+
}
|
|
650
|
+
const artifactType = await this.ResolveArtifactType(params.provider, params.contextUser, normalizedTypeName);
|
|
651
|
+
if (!artifactType) {
|
|
652
|
+
return {
|
|
653
|
+
success: false,
|
|
654
|
+
errorMessage: `Artifact type '${normalizedTypeName}' was not found or is disabled.`,
|
|
655
|
+
};
|
|
656
|
+
}
|
|
657
|
+
const built = await this.BuildInitialContentIsolated(artifactType.Name, title, params.content, params.sheetNames);
|
|
658
|
+
let finalContent = built.content;
|
|
659
|
+
let initialConfigPatch;
|
|
660
|
+
const initialResults = [];
|
|
661
|
+
if (params.initialOperations && params.initialOperations.length > 100) {
|
|
662
|
+
return {
|
|
663
|
+
success: false,
|
|
664
|
+
errorMessage: `initialOperations exceeds the maximum allowed 100 operations per request (received ${params.initialOperations.length}).`,
|
|
665
|
+
};
|
|
666
|
+
}
|
|
667
|
+
if (params.initialOperations && params.initialOperations.length > 0) {
|
|
668
|
+
const lib = this.ResolveLibrary(artifactType.Name, artifactType.ToolLibraryClass ?? undefined);
|
|
669
|
+
const execOutcome = await this.executeToolOperations({
|
|
670
|
+
ops: params.initialOperations,
|
|
671
|
+
initialContent: built.content,
|
|
672
|
+
lib,
|
|
673
|
+
toolContext: {
|
|
674
|
+
contextUser: params.contextUser,
|
|
675
|
+
actorUserId: params.contextUser.ID,
|
|
676
|
+
ownerUserId: params.contextUser.ID,
|
|
677
|
+
isEditor: true,
|
|
678
|
+
provider: params.provider,
|
|
679
|
+
agentRunId: params.agentRunId,
|
|
680
|
+
agentName: params.agentName,
|
|
681
|
+
},
|
|
682
|
+
artifactTypeName: artifactType.Name,
|
|
683
|
+
});
|
|
684
|
+
if (execOutcome.success === false) {
|
|
685
|
+
return {
|
|
686
|
+
success: false,
|
|
687
|
+
errorMessage: execOutcome.errorMessage,
|
|
688
|
+
};
|
|
689
|
+
}
|
|
690
|
+
finalContent = Buffer.isBuffer(execOutcome.workingContent)
|
|
691
|
+
? execOutcome.workingContent.toString('utf8')
|
|
692
|
+
: String(execOutcome.workingContent ?? built.content);
|
|
693
|
+
initialConfigPatch = execOutcome.latestConfigurationPatch;
|
|
694
|
+
initialResults.push(...execOutcome.stepResults);
|
|
695
|
+
}
|
|
696
|
+
const targetEnvId = (params.environmentId && IsValidUUID(params.environmentId) ? params.environmentId : null) ||
|
|
697
|
+
collectionEnvId ||
|
|
698
|
+
MJEnvironmentEntityExtended.DefaultEnvironmentID;
|
|
699
|
+
const artifactEntity = await params.provider.GetEntityObject('MJ: Artifacts', params.contextUser);
|
|
700
|
+
artifactEntity.NewRecord();
|
|
701
|
+
artifactEntity.Name = title;
|
|
702
|
+
artifactEntity.Description = (params.description ?? '').trim() || `Created by ${params.agentName || 'agent'}`;
|
|
703
|
+
artifactEntity.TypeID = artifactType.ID;
|
|
704
|
+
artifactEntity.EnvironmentID = targetEnvId;
|
|
705
|
+
artifactEntity.UserID = params.contextUser.ID;
|
|
706
|
+
if (!(await artifactEntity.Save())) {
|
|
707
|
+
return {
|
|
708
|
+
success: false,
|
|
709
|
+
errorMessage: artifactEntity.LatestResult?.CompleteMessage || 'Failed to save MJ: Artifacts record.',
|
|
710
|
+
};
|
|
711
|
+
}
|
|
712
|
+
const versionEntity = await params.provider.GetEntityObject('MJ: Artifact Versions', params.contextUser);
|
|
713
|
+
versionEntity.NewRecord();
|
|
714
|
+
versionEntity.ArtifactID = artifactEntity.ID;
|
|
715
|
+
versionEntity.VersionNumber = 1;
|
|
716
|
+
versionEntity.Name = title;
|
|
717
|
+
versionEntity.Description = artifactEntity.Description;
|
|
718
|
+
versionEntity.UserID = params.contextUser.ID;
|
|
719
|
+
versionEntity.ContentMode = 'Text';
|
|
720
|
+
versionEntity.MimeType = built.mimeType;
|
|
721
|
+
versionEntity.Content = finalContent;
|
|
722
|
+
versionEntity.ContentHash = createHash('sha256').update(finalContent, 'utf8').digest('hex');
|
|
723
|
+
versionEntity.ContentSizeBytes = Buffer.byteLength(finalContent, 'utf8');
|
|
724
|
+
versionEntity.Comments =
|
|
725
|
+
(params.comments ?? '').trim() ||
|
|
726
|
+
(params.agentName ? `Created by ${params.agentName}` : 'Created via GovernedArtifactService');
|
|
727
|
+
const baseConfig = JSON.stringify({
|
|
728
|
+
...(params.additionalConfig ?? {}),
|
|
729
|
+
...(initialConfigPatch ?? {}),
|
|
730
|
+
agentRunId: params.agentRunId ?? null,
|
|
731
|
+
agentName: params.agentName ?? null,
|
|
732
|
+
});
|
|
733
|
+
const enrichedConfig = BuildArtifactVersionConfigurationWithPreview(baseConfig, finalContent, artifactType.DriverClass ?? null, title, {
|
|
734
|
+
ArtifactType: artifactType,
|
|
735
|
+
AllArtifactTypes: ArtifactMetadataEngine.Instance.ArtifactTypes ?? [],
|
|
736
|
+
});
|
|
737
|
+
if (enrichedConfig) {
|
|
738
|
+
versionEntity.Configuration = enrichedConfig;
|
|
739
|
+
}
|
|
740
|
+
if (!(await versionEntity.Save())) {
|
|
741
|
+
await artifactEntity.Delete();
|
|
742
|
+
return {
|
|
743
|
+
success: false,
|
|
744
|
+
errorMessage: versionEntity.LatestResult?.CompleteMessage || 'Failed to save MJ: Artifact Versions v1.',
|
|
745
|
+
};
|
|
746
|
+
}
|
|
747
|
+
if (collectionId) {
|
|
748
|
+
const link = await params.provider.GetEntityObject('MJ: Collection Artifacts', params.contextUser);
|
|
749
|
+
link.NewRecord();
|
|
750
|
+
link.CollectionID = collectionId;
|
|
751
|
+
link.ArtifactVersionID = versionEntity.ID;
|
|
752
|
+
if (!(await link.Save())) {
|
|
753
|
+
await versionEntity.Delete();
|
|
754
|
+
await artifactEntity.Delete();
|
|
755
|
+
return {
|
|
756
|
+
success: false,
|
|
757
|
+
errorMessage: link.LatestResult?.CompleteMessage || 'Failed to link artifact to collection.',
|
|
758
|
+
};
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
const driverClass = artifactType.DriverClass ?? undefined;
|
|
762
|
+
this.RecordTouchedArtifact(params.agentRunId, {
|
|
763
|
+
ArtifactID: artifactEntity.ID,
|
|
764
|
+
ArtifactVersionID: versionEntity.ID,
|
|
765
|
+
VersionNumber: 1,
|
|
766
|
+
Name: title,
|
|
767
|
+
ArtifactTypeName: artifactType.Name,
|
|
768
|
+
DriverClass: driverClass,
|
|
769
|
+
Operation: 'created',
|
|
770
|
+
});
|
|
771
|
+
try {
|
|
772
|
+
await this.EmitAgentPresence({
|
|
773
|
+
artifactId: artifactEntity.ID,
|
|
774
|
+
phase: 'enter',
|
|
775
|
+
contextUser: params.contextUser,
|
|
776
|
+
agentRunId: params.agentRunId,
|
|
777
|
+
agentName: params.agentName,
|
|
778
|
+
toolName: 'create_artifact',
|
|
779
|
+
actionSummary: `Created "${title}"`,
|
|
780
|
+
location: { Domain: ResolvePresenceDomain(artifactType.Name) },
|
|
781
|
+
});
|
|
782
|
+
return {
|
|
783
|
+
success: true,
|
|
784
|
+
artifactId: artifactEntity.ID,
|
|
785
|
+
versionId: versionEntity.ID,
|
|
786
|
+
versionNumber: 1,
|
|
787
|
+
name: title,
|
|
788
|
+
typeName: artifactType.Name,
|
|
789
|
+
driverClass,
|
|
790
|
+
toolLibraryClass: artifactType.ToolLibraryClass ?? undefined,
|
|
791
|
+
mimeType: built.mimeType,
|
|
792
|
+
contentMode: 'Text',
|
|
793
|
+
content: finalContent,
|
|
794
|
+
configuration: versionEntity.Configuration ?? undefined,
|
|
795
|
+
...(initialResults.length > 0 ? { results: initialResults } : {}),
|
|
796
|
+
};
|
|
797
|
+
}
|
|
798
|
+
finally {
|
|
799
|
+
await this.EmitAgentPresence({
|
|
800
|
+
artifactId: artifactEntity.ID,
|
|
801
|
+
phase: 'exit',
|
|
802
|
+
contextUser: params.contextUser,
|
|
803
|
+
agentRunId: params.agentRunId,
|
|
804
|
+
agentName: params.agentName,
|
|
805
|
+
});
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
/**
|
|
809
|
+
* Read-only inspection of a governed artifact, supporting optional read-only tool invocation
|
|
810
|
+
* (e.g. `get_sheet_summary`, `get_outline`, `read_range`, `search`) with permission checks
|
|
811
|
+
* and live Yjs room hydration.
|
|
812
|
+
*/
|
|
813
|
+
async InspectGovernedArtifact(params) {
|
|
814
|
+
const loaded = await this.LoadReadableArtifactState(params.provider, params.contextUser, params.artifactId);
|
|
815
|
+
if (!loaded.state) {
|
|
816
|
+
return { success: false, errorMessage: loaded.errorMessage };
|
|
817
|
+
}
|
|
818
|
+
const state = loaded.state;
|
|
819
|
+
const requestedTool = (params.tool ?? '').trim();
|
|
820
|
+
if (requestedTool && this.IsMutatingTool(requestedTool)) {
|
|
821
|
+
return {
|
|
822
|
+
success: false,
|
|
823
|
+
errorMessage: `InspectGovernedArtifact refuses mutating tool '${requestedTool}'. Use MutateGovernedArtifact instead.`,
|
|
824
|
+
};
|
|
825
|
+
}
|
|
826
|
+
const toolInput = this.sanitizeToolInput(params.input);
|
|
827
|
+
const domain = ResolvePresenceDomain(state.typeName);
|
|
828
|
+
const location = ExtractAgentTargetLocation(requestedTool || 'inspect', toolInput, state.content, state.typeName);
|
|
829
|
+
let workingEmitted = false;
|
|
830
|
+
try {
|
|
831
|
+
await this.EmitAgentPresence({
|
|
832
|
+
artifactId: state.artifactId,
|
|
833
|
+
phase: 'working',
|
|
834
|
+
contextUser: params.contextUser,
|
|
835
|
+
agentRunId: params.agentRunId,
|
|
836
|
+
agentName: params.agentName,
|
|
837
|
+
toolName: requestedTool || 'inspect',
|
|
838
|
+
actionSummary: requestedTool ? FormatAgentActionSummary(requestedTool, toolInput, location) : `Inspecting "${state.name}"`,
|
|
839
|
+
location: location ?? { Domain: domain },
|
|
840
|
+
});
|
|
841
|
+
workingEmitted = true;
|
|
842
|
+
let data;
|
|
843
|
+
if (requestedTool) {
|
|
844
|
+
const lib = this.ResolveLibrary(state.typeName, state.toolLibraryClass);
|
|
845
|
+
const toolContext = {
|
|
846
|
+
contextUser: params.contextUser,
|
|
847
|
+
actorUserId: params.contextUser.ID,
|
|
848
|
+
ownerUserId: state.ownerUserId,
|
|
849
|
+
isEditor: state.permissions.CanEdit,
|
|
850
|
+
provider: params.provider,
|
|
851
|
+
artifactId: state.artifactId,
|
|
852
|
+
agentRunId: params.agentRunId,
|
|
853
|
+
agentName: params.agentName,
|
|
854
|
+
};
|
|
855
|
+
const res = await lib.InvokeTool(requestedTool, toolInput, state.content, toolContext);
|
|
856
|
+
if (!res.success) {
|
|
857
|
+
return {
|
|
858
|
+
success: false,
|
|
859
|
+
artifactId: state.artifactId,
|
|
860
|
+
errorMessage: res.errorMessage || `Inspection tool '${requestedTool}' failed.`,
|
|
861
|
+
};
|
|
862
|
+
}
|
|
863
|
+
if (res.data !== null && typeof res.data === 'object' && !Array.isArray(res.data)) {
|
|
864
|
+
const dataObj = res.data;
|
|
865
|
+
if (dataObj.updatedContent !== undefined || dataObj.xlsxBase64 !== undefined) {
|
|
866
|
+
return {
|
|
867
|
+
success: false,
|
|
868
|
+
artifactId: state.artifactId,
|
|
869
|
+
errorMessage: `InspectGovernedArtifact blocked tool '${requestedTool}' because it attempted to return mutated artifact content.`,
|
|
870
|
+
};
|
|
871
|
+
}
|
|
872
|
+
}
|
|
873
|
+
data = res.data;
|
|
874
|
+
}
|
|
875
|
+
else {
|
|
876
|
+
const lib = this.ResolveLibrary(state.typeName, state.toolLibraryClass);
|
|
877
|
+
const digest = ArtifactSynthesisEngine.Instance.ExtractSourceDigest({
|
|
878
|
+
ArtifactID: state.artifactId,
|
|
879
|
+
Name: state.name,
|
|
880
|
+
ArtifactType: state.typeName,
|
|
881
|
+
VersionNumber: state.versionNumber,
|
|
882
|
+
ContentMode: state.contentMode,
|
|
883
|
+
Content: Buffer.isBuffer(state.content) ? null : state.content,
|
|
884
|
+
Configuration: state.configuration ?? null,
|
|
885
|
+
Description: state.description ?? null,
|
|
886
|
+
MimeType: state.mimeType ?? null,
|
|
887
|
+
}, 2000);
|
|
888
|
+
data = {
|
|
889
|
+
availableTools: lib.GetToolList().map((t) => t.name),
|
|
890
|
+
sections: digest.Sections,
|
|
891
|
+
embeddedCharts: digest.EmbeddedCharts,
|
|
892
|
+
summaryPreview: digest.SummaryText,
|
|
893
|
+
};
|
|
894
|
+
}
|
|
895
|
+
await this.EmitAgentPresence({
|
|
896
|
+
artifactId: state.artifactId,
|
|
897
|
+
phase: 'settled',
|
|
898
|
+
contextUser: params.contextUser,
|
|
899
|
+
agentRunId: params.agentRunId,
|
|
900
|
+
agentName: params.agentName,
|
|
901
|
+
toolName: requestedTool || 'inspect',
|
|
902
|
+
actionSummary: `Inspected "${state.name}"`,
|
|
903
|
+
location: location ?? { Domain: domain },
|
|
904
|
+
});
|
|
905
|
+
return {
|
|
906
|
+
success: true,
|
|
907
|
+
artifactId: state.artifactId,
|
|
908
|
+
versionId: state.versionId,
|
|
909
|
+
versionNumber: state.versionNumber,
|
|
910
|
+
name: state.name,
|
|
911
|
+
typeName: state.typeName,
|
|
912
|
+
driverClass: state.driverClass,
|
|
913
|
+
canEdit: state.permissions.CanEdit,
|
|
914
|
+
liveRoomHydrated: state.liveRoomHydrated,
|
|
915
|
+
data,
|
|
916
|
+
};
|
|
917
|
+
}
|
|
918
|
+
catch (err) {
|
|
919
|
+
return {
|
|
920
|
+
success: false,
|
|
921
|
+
artifactId: state.artifactId,
|
|
922
|
+
errorMessage: `InspectGovernedArtifact error: ${err instanceof Error ? err.message : String(err)}`,
|
|
923
|
+
};
|
|
924
|
+
}
|
|
925
|
+
finally {
|
|
926
|
+
if (workingEmitted) {
|
|
927
|
+
await this.EmitAgentPresence({
|
|
928
|
+
artifactId: state.artifactId,
|
|
929
|
+
phase: 'exit',
|
|
930
|
+
contextUser: params.contextUser,
|
|
931
|
+
agentRunId: params.agentRunId,
|
|
932
|
+
agentName: params.agentName,
|
|
933
|
+
});
|
|
934
|
+
}
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
/**
|
|
938
|
+
* Executes one or more governed artifact mutation tools via an action/direct path, reconciling with
|
|
939
|
+
* live Yjs collaboration rooms, persisting a new version, and emitting real-time presence awareness.
|
|
940
|
+
*/
|
|
941
|
+
async MutateGovernedArtifact(params) {
|
|
942
|
+
return this.withArtifactLock(params.artifactId, () => this.mutateGovernedArtifactLocked(params));
|
|
943
|
+
}
|
|
944
|
+
async safeRollbackHook(rollbackFn, versionId) {
|
|
945
|
+
if (!rollbackFn)
|
|
946
|
+
return;
|
|
947
|
+
try {
|
|
948
|
+
await rollbackFn(versionId);
|
|
949
|
+
}
|
|
950
|
+
catch (err) {
|
|
951
|
+
LogError(`GovernedArtifactService: live hook rollback failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
952
|
+
}
|
|
953
|
+
}
|
|
954
|
+
async safeDeleteVersionEntity(versionEntity) {
|
|
955
|
+
try {
|
|
956
|
+
await versionEntity.Delete();
|
|
957
|
+
}
|
|
958
|
+
catch (err) {
|
|
959
|
+
LogError(`GovernedArtifactService: failed to delete rolled-back version entity '${versionEntity.ID}': ${err instanceof Error ? err.message : String(err)}`);
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
/**
|
|
963
|
+
* Deletes an uploaded `MJ: Files` row (and backing storage object when supported) if no
|
|
964
|
+
* `MJ: Artifact Versions` record references it. Best-effort cleanup for aborted/rolled-back writes.
|
|
965
|
+
*/
|
|
966
|
+
async DeleteUnreferencedArtifactFile(provider, contextUser, fileId) {
|
|
967
|
+
const trimmedFileId = (fileId ?? '').trim();
|
|
968
|
+
if (!IsValidUUID(trimmedFileId)) {
|
|
969
|
+
return;
|
|
970
|
+
}
|
|
971
|
+
try {
|
|
972
|
+
const rv = RunView.FromMetadataProvider(provider);
|
|
973
|
+
const refRes = await rv.RunView({
|
|
974
|
+
EntityName: 'MJ: Artifact Versions',
|
|
975
|
+
ExtraFilter: `FileID='${EscapeSQLString(trimmedFileId)}'`,
|
|
976
|
+
Fields: ['ID'],
|
|
977
|
+
MaxRows: 1,
|
|
978
|
+
SkipTotalRowCount: true,
|
|
979
|
+
ResultType: 'simple',
|
|
980
|
+
}, contextUser);
|
|
981
|
+
if (!refRes.Success || (refRes.Results?.length ?? 0) > 0) {
|
|
982
|
+
return;
|
|
983
|
+
}
|
|
984
|
+
const fileEntity = await provider.GetEntityObject('MJ: Files', contextUser);
|
|
985
|
+
if (await fileEntity.Load(trimmedFileId)) {
|
|
986
|
+
const deleted = await fileEntity.Delete();
|
|
987
|
+
if (!deleted) {
|
|
988
|
+
LogError(`GovernedArtifactService: failed to delete unreferenced MJ: Files record '${trimmedFileId}': ${fileEntity.LatestResult?.CompleteMessage || 'Delete() returned false'}`);
|
|
989
|
+
}
|
|
990
|
+
}
|
|
991
|
+
}
|
|
992
|
+
catch (err) {
|
|
993
|
+
LogError(`GovernedArtifactService: exception deleting unreferenced MJ: Files record '${trimmedFileId}': ${err instanceof Error ? err.message : String(err)}`);
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
async materializeXlsxForContent(contentStr, workingXlsxBytes) {
|
|
997
|
+
try {
|
|
998
|
+
const parsedWorkbook = await SpreadsheetEngine.Instance.ParseWorkbookIsolated(contentStr);
|
|
999
|
+
const patched = workingXlsxBytes
|
|
1000
|
+
? await XlsxOpenXmlAdapter.Instance.PatchXlsxBytesIsolated(workingXlsxBytes, parsedWorkbook)
|
|
1001
|
+
: SpreadsheetEngine.Instance.ExportToXlsxBytes(parsedWorkbook, true, { SkipEvaluate: true });
|
|
1002
|
+
return {
|
|
1003
|
+
xlsxBytes: patched,
|
|
1004
|
+
xlsxBase64: Buffer.from(patched).toString('base64'),
|
|
1005
|
+
};
|
|
1006
|
+
}
|
|
1007
|
+
catch {
|
|
1008
|
+
return {};
|
|
1009
|
+
}
|
|
1010
|
+
}
|
|
1011
|
+
async uploadXlsxBuffer(params, artifactName, xlsxBase64) {
|
|
1012
|
+
const xlsxBuf = Buffer.from(xlsxBase64, 'base64');
|
|
1013
|
+
let uploadedFileId = null;
|
|
1014
|
+
try {
|
|
1015
|
+
await FileStorageEngine.Instance.Config(false, params.contextUser, params.provider);
|
|
1016
|
+
if (FileStorageEngine.Instance.HasStorageAccounts) {
|
|
1017
|
+
const safeFileName = artifactName.toLowerCase().endsWith('.xlsx')
|
|
1018
|
+
? artifactName
|
|
1019
|
+
: `${artifactName || 'workbook'}.xlsx`;
|
|
1020
|
+
const uploadRes = await FileStorageEngine.Instance.UploadFile({
|
|
1021
|
+
content: xlsxBuf,
|
|
1022
|
+
fileName: safeFileName,
|
|
1023
|
+
mimeType: XLSX_MIME_TYPE,
|
|
1024
|
+
contextUser: params.contextUser,
|
|
1025
|
+
provider: params.provider,
|
|
1026
|
+
});
|
|
1027
|
+
uploadedFileId = uploadRes.FileID;
|
|
1028
|
+
}
|
|
1029
|
+
}
|
|
1030
|
+
catch {
|
|
1031
|
+
uploadedFileId = null;
|
|
1032
|
+
}
|
|
1033
|
+
return { fileId: uploadedFileId, sizeBytes: xlsxBuf.byteLength };
|
|
1034
|
+
}
|
|
1035
|
+
applyVersionPayload(versionEntity, state, finalContentStr, lastToolName, params, uploadedFileId, xlsxSizeBytes, configurationPatch) {
|
|
1036
|
+
versionEntity.ContentHash = createHash('sha256').update(finalContentStr, 'utf8').digest('hex');
|
|
1037
|
+
if (uploadedFileId) {
|
|
1038
|
+
const safeFileName = state.name.toLowerCase().endsWith('.xlsx')
|
|
1039
|
+
? state.name
|
|
1040
|
+
: `${state.name || 'workbook'}.xlsx`;
|
|
1041
|
+
versionEntity.ContentMode = 'File';
|
|
1042
|
+
versionEntity.FileID = uploadedFileId;
|
|
1043
|
+
versionEntity.MimeType = XLSX_MIME_TYPE;
|
|
1044
|
+
versionEntity.FileName = safeFileName;
|
|
1045
|
+
versionEntity.ContentSizeBytes = xlsxSizeBytes;
|
|
1046
|
+
versionEntity.Content = null;
|
|
1047
|
+
versionEntity.Configuration = BuildMergedFileVersionConfiguration({
|
|
1048
|
+
existingConfiguration: versionEntity.Configuration ?? state.configuration,
|
|
1049
|
+
contentConfigurationJson: finalContentStr,
|
|
1050
|
+
configurationPatch,
|
|
1051
|
+
});
|
|
1052
|
+
return;
|
|
1053
|
+
}
|
|
1054
|
+
versionEntity.ContentMode = 'Text';
|
|
1055
|
+
versionEntity.FileID = null;
|
|
1056
|
+
versionEntity.MimeType = state.mimeType ?? null;
|
|
1057
|
+
versionEntity.Content = finalContentStr;
|
|
1058
|
+
versionEntity.ContentSizeBytes = Buffer.byteLength(finalContentStr, 'utf8');
|
|
1059
|
+
const existingConfig = parseConfigurationRecord(state.configuration);
|
|
1060
|
+
const mergedConfig = JSON.stringify({
|
|
1061
|
+
...existingConfig,
|
|
1062
|
+
...(configurationPatch ?? {}),
|
|
1063
|
+
agentRunId: params.agentRunId ?? null,
|
|
1064
|
+
agentName: params.agentName ?? null,
|
|
1065
|
+
lastTool: lastToolName,
|
|
1066
|
+
});
|
|
1067
|
+
const enrichedConfig = BuildArtifactVersionConfigurationWithPreview(mergedConfig, finalContentStr, state.driverClass ?? null, state.name, {
|
|
1068
|
+
ArtifactType: state.typeEntity ?? undefined,
|
|
1069
|
+
AllArtifactTypes: ArtifactMetadataEngine.Instance.ArtifactTypes ?? [],
|
|
1070
|
+
});
|
|
1071
|
+
versionEntity.Configuration = enrichedConfig ?? mergedConfig;
|
|
1072
|
+
}
|
|
1073
|
+
async mutateGovernedArtifactLocked(params) {
|
|
1074
|
+
const loaded = await this.LoadReadableArtifactState(params.provider, params.contextUser, params.artifactId);
|
|
1075
|
+
if (!loaded.state) {
|
|
1076
|
+
return { success: false, errorMessage: loaded.errorMessage };
|
|
1077
|
+
}
|
|
1078
|
+
const state = loaded.state;
|
|
1079
|
+
if (!state.permissions.CanEdit) {
|
|
1080
|
+
return {
|
|
1081
|
+
success: false,
|
|
1082
|
+
artifactId: state.artifactId,
|
|
1083
|
+
errorMessage: `Permission denied: user lacks Edit access to artifact '${state.artifactId}'.`,
|
|
1084
|
+
};
|
|
1085
|
+
}
|
|
1086
|
+
const ops = params.operations && params.operations.length > 0
|
|
1087
|
+
? params.operations
|
|
1088
|
+
: params.tool
|
|
1089
|
+
? [{ tool: params.tool, input: params.input }]
|
|
1090
|
+
: [];
|
|
1091
|
+
if (ops.length === 0) {
|
|
1092
|
+
return { success: false, errorMessage: 'MutateGovernedArtifact requires either tool or operations.' };
|
|
1093
|
+
}
|
|
1094
|
+
if (ops.length > 100) {
|
|
1095
|
+
return {
|
|
1096
|
+
success: false,
|
|
1097
|
+
artifactId: state.artifactId,
|
|
1098
|
+
errorMessage: `MutateGovernedArtifact operations exceed the maximum allowed 100 operations per request (received ${ops.length}).`,
|
|
1099
|
+
};
|
|
1100
|
+
}
|
|
1101
|
+
if (state.contentMode === 'File' || Boolean(state.originalXlsxBytes)) {
|
|
1102
|
+
const refusedOp = ops.find((op) => STRUCTURAL_SPREADSHEET_TOOLS.has(op.tool));
|
|
1103
|
+
if (refusedOp) {
|
|
1104
|
+
return {
|
|
1105
|
+
success: false,
|
|
1106
|
+
artifactId: state.artifactId,
|
|
1107
|
+
errorMessage: FormatFileModeStructuralToolError(refusedOp.tool),
|
|
1108
|
+
};
|
|
1109
|
+
}
|
|
1110
|
+
}
|
|
1111
|
+
const lib = this.ResolveLibrary(state.typeName, state.toolLibraryClass);
|
|
1112
|
+
const toolContext = {
|
|
1113
|
+
contextUser: params.contextUser,
|
|
1114
|
+
actorUserId: params.contextUser.ID,
|
|
1115
|
+
ownerUserId: state.ownerUserId,
|
|
1116
|
+
isEditor: state.permissions.CanEdit,
|
|
1117
|
+
provider: params.provider,
|
|
1118
|
+
artifactId: state.artifactId,
|
|
1119
|
+
agentRunId: params.agentRunId,
|
|
1120
|
+
agentName: params.agentName,
|
|
1121
|
+
};
|
|
1122
|
+
const previousContentStr = Buffer.isBuffer(state.content) ? undefined : String(state.content ?? '');
|
|
1123
|
+
let workingXlsxBytes = state.originalXlsxBytes;
|
|
1124
|
+
const warnings = [];
|
|
1125
|
+
let workingEmitted = false;
|
|
1126
|
+
try {
|
|
1127
|
+
const execOutcome = await this.executeToolOperations({
|
|
1128
|
+
ops,
|
|
1129
|
+
initialContent: state.content,
|
|
1130
|
+
lib,
|
|
1131
|
+
toolContext,
|
|
1132
|
+
artifactTypeName: state.typeName,
|
|
1133
|
+
emitPresenceArtifactId: state.artifactId,
|
|
1134
|
+
onWorkingEmitted: () => {
|
|
1135
|
+
workingEmitted = true;
|
|
1136
|
+
},
|
|
1137
|
+
});
|
|
1138
|
+
if (execOutcome.success === false) {
|
|
1139
|
+
return {
|
|
1140
|
+
success: false,
|
|
1141
|
+
artifactId: state.artifactId,
|
|
1142
|
+
errorMessage: execOutcome.errorMessage,
|
|
1143
|
+
};
|
|
1144
|
+
}
|
|
1145
|
+
const { workingContent, latestXlsxBase64: execXlsxBase64, lastLocation, lastToolName, lastToolInput, latestConfigurationPatch, stepResults, appliedComments, } = execOutcome;
|
|
1146
|
+
let latestXlsxBase64 = execXlsxBase64;
|
|
1147
|
+
const isUntouchedBinaryBuffer = Buffer.isBuffer(workingContent) && workingContent === state.content;
|
|
1148
|
+
let finalContentStr = Buffer.isBuffer(workingContent) ? '' : String(workingContent ?? '');
|
|
1149
|
+
const hasContentChange = workingContent !== undefined &&
|
|
1150
|
+
workingContent !== null &&
|
|
1151
|
+
!isUntouchedBinaryBuffer &&
|
|
1152
|
+
(Buffer.isBuffer(workingContent) || finalContentStr !== previousContentStr);
|
|
1153
|
+
if (!hasContentChange && !latestConfigurationPatch) {
|
|
1154
|
+
return {
|
|
1155
|
+
success: true,
|
|
1156
|
+
artifactId: state.artifactId,
|
|
1157
|
+
versionId: state.versionId,
|
|
1158
|
+
versionNumber: state.versionNumber,
|
|
1159
|
+
name: state.name,
|
|
1160
|
+
typeName: state.typeName,
|
|
1161
|
+
driverClass: state.driverClass,
|
|
1162
|
+
results: stepResults,
|
|
1163
|
+
};
|
|
1164
|
+
}
|
|
1165
|
+
if (workingXlsxBytes || state.contentMode === 'File') {
|
|
1166
|
+
const materialized = await this.materializeXlsxForContent(finalContentStr, workingXlsxBytes);
|
|
1167
|
+
if (materialized.xlsxBytes) {
|
|
1168
|
+
workingXlsxBytes = materialized.xlsxBytes;
|
|
1169
|
+
latestXlsxBase64 = materialized.xlsxBase64;
|
|
1170
|
+
}
|
|
1171
|
+
else {
|
|
1172
|
+
latestXlsxBase64 = undefined;
|
|
1173
|
+
}
|
|
1174
|
+
}
|
|
1175
|
+
const persisted = await this.persistLoadedArtifactMutation({
|
|
1176
|
+
provider: params.provider,
|
|
1177
|
+
contextUser: params.contextUser,
|
|
1178
|
+
state,
|
|
1179
|
+
previousContentStr,
|
|
1180
|
+
finalContentStr,
|
|
1181
|
+
workingXlsxBytes,
|
|
1182
|
+
latestXlsxBase64,
|
|
1183
|
+
lastToolName,
|
|
1184
|
+
lastToolInput,
|
|
1185
|
+
lastLocation,
|
|
1186
|
+
comments: params.agentName
|
|
1187
|
+
? `Edited by ${params.agentName} via '${lastToolName}'`
|
|
1188
|
+
: `Updated via '${lastToolName}'`,
|
|
1189
|
+
configurationPatch: latestConfigurationPatch,
|
|
1190
|
+
agentRunId: params.agentRunId,
|
|
1191
|
+
agentName: params.agentName,
|
|
1192
|
+
});
|
|
1193
|
+
if (!persisted.success) {
|
|
1194
|
+
await this.rollbackAppliedCommentOps(params.provider, params.contextUser, appliedComments);
|
|
1195
|
+
return {
|
|
1196
|
+
success: false,
|
|
1197
|
+
artifactId: state.artifactId,
|
|
1198
|
+
errorMessage: persisted.errorMessage,
|
|
1199
|
+
};
|
|
1200
|
+
}
|
|
1201
|
+
return {
|
|
1202
|
+
success: true,
|
|
1203
|
+
artifactId: state.artifactId,
|
|
1204
|
+
versionId: persisted.versionId,
|
|
1205
|
+
versionNumber: persisted.versionNumber,
|
|
1206
|
+
name: state.name,
|
|
1207
|
+
typeName: state.typeName,
|
|
1208
|
+
driverClass: state.driverClass,
|
|
1209
|
+
results: stepResults,
|
|
1210
|
+
...(warnings.length > 0 ? { warnings } : {}),
|
|
1211
|
+
};
|
|
1212
|
+
}
|
|
1213
|
+
catch (err) {
|
|
1214
|
+
return {
|
|
1215
|
+
success: false,
|
|
1216
|
+
artifactId: state.artifactId,
|
|
1217
|
+
errorMessage: `MutateGovernedArtifact error: ${err instanceof Error ? err.message : String(err)}`,
|
|
1218
|
+
};
|
|
1219
|
+
}
|
|
1220
|
+
finally {
|
|
1221
|
+
if (workingEmitted) {
|
|
1222
|
+
await this.EmitAgentPresence({
|
|
1223
|
+
artifactId: state.artifactId,
|
|
1224
|
+
phase: 'exit',
|
|
1225
|
+
contextUser: params.contextUser,
|
|
1226
|
+
agentRunId: params.agentRunId,
|
|
1227
|
+
agentName: params.agentName,
|
|
1228
|
+
});
|
|
1229
|
+
}
|
|
1230
|
+
}
|
|
1231
|
+
}
|
|
1232
|
+
async rollbackAppliedCommentOps(provider, contextUser, appliedComments) {
|
|
1233
|
+
for (let i = appliedComments.length - 1; i >= 0; i--) {
|
|
1234
|
+
const entry = appliedComments[i];
|
|
1235
|
+
try {
|
|
1236
|
+
if (entry.commentId && IsValidUUID(entry.commentId)) {
|
|
1237
|
+
const detail = await provider.GetEntityObject('MJ: Conversation Details', contextUser);
|
|
1238
|
+
if (detail && (await detail.Load(entry.commentId))) {
|
|
1239
|
+
await detail.Delete();
|
|
1240
|
+
}
|
|
1241
|
+
}
|
|
1242
|
+
if (entry.kind === 'thread' && entry.threadId && IsValidUUID(entry.threadId)) {
|
|
1243
|
+
const conv = await provider.GetEntityObject('MJ: Conversations', contextUser);
|
|
1244
|
+
if (conv && (await conv.Load(entry.threadId))) {
|
|
1245
|
+
await conv.Delete();
|
|
1246
|
+
}
|
|
1247
|
+
}
|
|
1248
|
+
}
|
|
1249
|
+
catch (rollbackErr) {
|
|
1250
|
+
LogError(`GovernedArtifactService: comment rollback error: ${rollbackErr instanceof Error ? rollbackErr.message : String(rollbackErr)}`);
|
|
1251
|
+
}
|
|
1252
|
+
}
|
|
1253
|
+
}
|
|
1254
|
+
async executeToolOperations(input) {
|
|
1255
|
+
let workingContent = input.initialContent;
|
|
1256
|
+
let latestXlsxBase64;
|
|
1257
|
+
let lastLocation;
|
|
1258
|
+
let lastToolName = input.ops[0]?.tool ?? '';
|
|
1259
|
+
let lastToolInput = this.sanitizeToolInput(input.ops[input.ops.length - 1]?.input);
|
|
1260
|
+
let latestConfigurationPatch;
|
|
1261
|
+
const stepResults = [];
|
|
1262
|
+
const appliedComments = [];
|
|
1263
|
+
for (const op of input.ops) {
|
|
1264
|
+
const toolName = (op.tool ?? '').trim();
|
|
1265
|
+
if (!toolName) {
|
|
1266
|
+
await this.rollbackAppliedCommentOps(input.toolContext.provider, input.toolContext.contextUser, appliedComments);
|
|
1267
|
+
return { success: false, errorMessage: 'Each operation requires a non-empty tool name.' };
|
|
1268
|
+
}
|
|
1269
|
+
const toolInput = this.sanitizeToolInput(op.input);
|
|
1270
|
+
lastToolName = toolName;
|
|
1271
|
+
lastToolInput = toolInput;
|
|
1272
|
+
lastLocation = ExtractAgentTargetLocation(toolName, toolInput, workingContent, input.artifactTypeName);
|
|
1273
|
+
if (input.emitPresenceArtifactId && input.toolContext.contextUser) {
|
|
1274
|
+
await this.EmitAgentPresence({
|
|
1275
|
+
artifactId: input.emitPresenceArtifactId,
|
|
1276
|
+
phase: 'working',
|
|
1277
|
+
contextUser: input.toolContext.contextUser,
|
|
1278
|
+
agentRunId: input.toolContext.agentRunId,
|
|
1279
|
+
agentName: input.toolContext.agentName,
|
|
1280
|
+
toolName,
|
|
1281
|
+
actionSummary: FormatAgentActionSummary(toolName, toolInput, lastLocation),
|
|
1282
|
+
location: lastLocation,
|
|
1283
|
+
});
|
|
1284
|
+
input.onWorkingEmitted?.();
|
|
1285
|
+
}
|
|
1286
|
+
const res = await input.lib.InvokeTool(toolName, toolInput, workingContent, input.toolContext);
|
|
1287
|
+
if (!res.success) {
|
|
1288
|
+
if (input.toolContext.provider && input.toolContext.contextUser) {
|
|
1289
|
+
await this.rollbackAppliedCommentOps(input.toolContext.provider, input.toolContext.contextUser, appliedComments);
|
|
1290
|
+
}
|
|
1291
|
+
return {
|
|
1292
|
+
success: false,
|
|
1293
|
+
errorMessage: res.errorMessage || `Tool '${toolName}' failed.`,
|
|
1294
|
+
};
|
|
1295
|
+
}
|
|
1296
|
+
const rawData = res.data !== null && typeof res.data === 'object' && !Array.isArray(res.data)
|
|
1297
|
+
? res.data
|
|
1298
|
+
: {};
|
|
1299
|
+
if (toolName === 'add_comment' && typeof rawData.threadId === 'string') {
|
|
1300
|
+
appliedComments.push({
|
|
1301
|
+
kind: 'thread',
|
|
1302
|
+
threadId: rawData.threadId,
|
|
1303
|
+
commentId: typeof rawData.commentId === 'string' ? rawData.commentId : undefined,
|
|
1304
|
+
});
|
|
1305
|
+
}
|
|
1306
|
+
else if (toolName === 'reply_comment' && typeof rawData.commentId === 'string') {
|
|
1307
|
+
appliedComments.push({
|
|
1308
|
+
kind: 'reply',
|
|
1309
|
+
commentId: rawData.commentId,
|
|
1310
|
+
});
|
|
1311
|
+
}
|
|
1312
|
+
if (typeof rawData.updatedContent === 'string') {
|
|
1313
|
+
workingContent = rawData.updatedContent;
|
|
1314
|
+
if (typeof rawData.xlsxBase64 === 'string') {
|
|
1315
|
+
latestXlsxBase64 = rawData.xlsxBase64;
|
|
1316
|
+
}
|
|
1317
|
+
}
|
|
1318
|
+
if (rawData.configurationPatch !== null &&
|
|
1319
|
+
typeof rawData.configurationPatch === 'object' &&
|
|
1320
|
+
!Array.isArray(rawData.configurationPatch)) {
|
|
1321
|
+
latestConfigurationPatch = {
|
|
1322
|
+
...(latestConfigurationPatch ?? {}),
|
|
1323
|
+
...rawData.configurationPatch,
|
|
1324
|
+
};
|
|
1325
|
+
}
|
|
1326
|
+
lastLocation =
|
|
1327
|
+
ExtractAgentTargetLocation(toolName, toolInput, workingContent, input.artifactTypeName, rawData) ?? lastLocation;
|
|
1328
|
+
const sanitized = {};
|
|
1329
|
+
for (const [k, v] of Object.entries(rawData)) {
|
|
1330
|
+
if (k === 'updatedContent' || k === 'xlsxBase64')
|
|
1331
|
+
continue;
|
|
1332
|
+
sanitized[k] = v;
|
|
1333
|
+
}
|
|
1334
|
+
stepResults.push({ tool: toolName, data: sanitized });
|
|
1335
|
+
}
|
|
1336
|
+
return {
|
|
1337
|
+
success: true,
|
|
1338
|
+
workingContent,
|
|
1339
|
+
latestXlsxBase64,
|
|
1340
|
+
lastLocation,
|
|
1341
|
+
lastToolName,
|
|
1342
|
+
lastToolInput,
|
|
1343
|
+
latestConfigurationPatch,
|
|
1344
|
+
stepResults,
|
|
1345
|
+
appliedComments,
|
|
1346
|
+
};
|
|
1347
|
+
}
|
|
1348
|
+
async persistLoadedArtifactMutation(input) {
|
|
1349
|
+
const { state } = input;
|
|
1350
|
+
let finalContentStr = input.finalContentStr;
|
|
1351
|
+
let workingXlsxBytes = input.workingXlsxBytes;
|
|
1352
|
+
let latestXlsxBase64 = input.latestXlsxBase64;
|
|
1353
|
+
const liveHook = GetArtifactLiveMutationHook();
|
|
1354
|
+
let hookOutcome = undefined;
|
|
1355
|
+
if (liveHook) {
|
|
1356
|
+
const hookResult = await liveHook({
|
|
1357
|
+
artifactId: state.artifactId,
|
|
1358
|
+
alphaId: 'A',
|
|
1359
|
+
versionId: state.versionId,
|
|
1360
|
+
versionNumber: state.versionNumber + 1,
|
|
1361
|
+
previousContent: input.previousContentStr,
|
|
1362
|
+
updatedContent: finalContentStr,
|
|
1363
|
+
xlsxBase64: latestXlsxBase64,
|
|
1364
|
+
configurationPatch: input.configurationPatch,
|
|
1365
|
+
tool: input.lastToolName,
|
|
1366
|
+
contextUser: input.contextUser,
|
|
1367
|
+
agentRunId: input.agentRunId,
|
|
1368
|
+
agentName: input.agentName,
|
|
1369
|
+
deferCommit: true,
|
|
1370
|
+
});
|
|
1371
|
+
if (hookResult && typeof hookResult === 'object') {
|
|
1372
|
+
hookOutcome = hookResult;
|
|
1373
|
+
if (typeof hookResult.mergedContent === 'string' && hookResult.mergedContent !== finalContentStr) {
|
|
1374
|
+
finalContentStr = hookResult.mergedContent;
|
|
1375
|
+
if (workingXlsxBytes || state.contentMode === 'File') {
|
|
1376
|
+
const rematerialized = await this.materializeXlsxForContent(finalContentStr, workingXlsxBytes);
|
|
1377
|
+
if (rematerialized.xlsxBytes) {
|
|
1378
|
+
workingXlsxBytes = rematerialized.xlsxBytes;
|
|
1379
|
+
latestXlsxBase64 = rematerialized.xlsxBase64;
|
|
1380
|
+
}
|
|
1381
|
+
else {
|
|
1382
|
+
latestXlsxBase64 = undefined;
|
|
1383
|
+
}
|
|
1384
|
+
}
|
|
1385
|
+
}
|
|
1386
|
+
}
|
|
1387
|
+
}
|
|
1388
|
+
// Re-check latest DB version number before persisting to catch out-of-band concurrent edits
|
|
1389
|
+
const rv = RunView.FromMetadataProvider(input.provider);
|
|
1390
|
+
const verCheck = await rv.RunView({
|
|
1391
|
+
EntityName: 'MJ: Artifact Versions',
|
|
1392
|
+
ExtraFilter: `ArtifactID='${EscapeSQLString(state.artifactId)}'`,
|
|
1393
|
+
OrderBy: 'VersionNumber DESC',
|
|
1394
|
+
Fields: ['ID', 'VersionNumber'],
|
|
1395
|
+
MaxRows: 1,
|
|
1396
|
+
SkipTotalRowCount: true,
|
|
1397
|
+
ResultType: 'simple',
|
|
1398
|
+
}, input.contextUser);
|
|
1399
|
+
if (verCheck.Success && verCheck.Results?.length) {
|
|
1400
|
+
const currentDbVersion = verCheck.Results[0].VersionNumber ?? 1;
|
|
1401
|
+
if (currentDbVersion > state.dbVersionNumber) {
|
|
1402
|
+
return {
|
|
1403
|
+
success: false,
|
|
1404
|
+
errorMessage: `Concurrent modification detected on artifact '${state.artifactId}': expected version ${state.dbVersionNumber}, found version ${currentDbVersion}. Please re-inspect and retry.`,
|
|
1405
|
+
};
|
|
1406
|
+
}
|
|
1407
|
+
}
|
|
1408
|
+
let uploadedFileId = null;
|
|
1409
|
+
let xlsxSizeBytes = null;
|
|
1410
|
+
if (state.contentMode === 'File') {
|
|
1411
|
+
if (!latestXlsxBase64) {
|
|
1412
|
+
return {
|
|
1413
|
+
success: false,
|
|
1414
|
+
errorMessage: 'Failed to materialize updated .xlsx bytes for File-mode artifact.',
|
|
1415
|
+
};
|
|
1416
|
+
}
|
|
1417
|
+
const upload = await this.uploadXlsxBuffer(input, state.name, latestXlsxBase64);
|
|
1418
|
+
uploadedFileId = upload.fileId;
|
|
1419
|
+
xlsxSizeBytes = upload.sizeBytes;
|
|
1420
|
+
if (!uploadedFileId) {
|
|
1421
|
+
return {
|
|
1422
|
+
success: false,
|
|
1423
|
+
errorMessage: 'Failed to upload updated .xlsx binary to FileStorageEngine; refusing to downgrade File-mode artifact.',
|
|
1424
|
+
};
|
|
1425
|
+
}
|
|
1426
|
+
}
|
|
1427
|
+
const nextVersionNumber = Math.max(state.versionNumber, state.dbVersionNumber) + 1;
|
|
1428
|
+
const versionEntity = await input.provider.GetEntityObject('MJ: Artifact Versions', input.contextUser);
|
|
1429
|
+
versionEntity.NewRecord();
|
|
1430
|
+
versionEntity.ArtifactID = state.artifactId;
|
|
1431
|
+
versionEntity.VersionNumber = nextVersionNumber;
|
|
1432
|
+
versionEntity.Name = state.name;
|
|
1433
|
+
versionEntity.UserID = input.contextUser.ID;
|
|
1434
|
+
versionEntity.Comments = input.comments;
|
|
1435
|
+
this.applyVersionPayload(versionEntity, state, finalContentStr, input.lastToolName, { agentRunId: input.agentRunId, agentName: input.agentName }, uploadedFileId, xlsxSizeBytes, input.configurationPatch);
|
|
1436
|
+
if (!(await versionEntity.Save())) {
|
|
1437
|
+
await this.DeleteUnreferencedArtifactFile(input.provider, input.contextUser, uploadedFileId);
|
|
1438
|
+
return {
|
|
1439
|
+
success: false,
|
|
1440
|
+
errorMessage: versionEntity.LatestResult?.CompleteMessage || 'Failed to save new MJ: Artifact Versions record.',
|
|
1441
|
+
};
|
|
1442
|
+
}
|
|
1443
|
+
if (hookOutcome?.commit) {
|
|
1444
|
+
let commitRes;
|
|
1445
|
+
try {
|
|
1446
|
+
commitRes = await hookOutcome.commit({
|
|
1447
|
+
versionId: versionEntity.ID,
|
|
1448
|
+
versionNumber: nextVersionNumber,
|
|
1449
|
+
});
|
|
1450
|
+
}
|
|
1451
|
+
catch (commitErr) {
|
|
1452
|
+
const savedVersionId = versionEntity.ID;
|
|
1453
|
+
await this.safeDeleteVersionEntity(versionEntity);
|
|
1454
|
+
await this.DeleteUnreferencedArtifactFile(input.provider, input.contextUser, uploadedFileId);
|
|
1455
|
+
await this.safeRollbackHook(hookOutcome.rollback, savedVersionId);
|
|
1456
|
+
return {
|
|
1457
|
+
success: false,
|
|
1458
|
+
errorMessage: `Live room commit failed for artifact '${state.artifactId}': ${commitErr instanceof Error ? commitErr.message : String(commitErr)}`,
|
|
1459
|
+
};
|
|
1460
|
+
}
|
|
1461
|
+
if (commitRes && typeof commitRes === 'object' && commitRes.applied === false) {
|
|
1462
|
+
const savedVersionId = versionEntity.ID;
|
|
1463
|
+
await this.safeDeleteVersionEntity(versionEntity);
|
|
1464
|
+
await this.DeleteUnreferencedArtifactFile(input.provider, input.contextUser, uploadedFileId);
|
|
1465
|
+
await this.safeRollbackHook(commitRes.rollback ?? hookOutcome.rollback, savedVersionId);
|
|
1466
|
+
return {
|
|
1467
|
+
success: false,
|
|
1468
|
+
errorMessage: `Live room commit rejected mutation for artifact '${state.artifactId}' (applied=false).`,
|
|
1469
|
+
};
|
|
1470
|
+
}
|
|
1471
|
+
if (commitRes &&
|
|
1472
|
+
typeof commitRes === 'object' &&
|
|
1473
|
+
typeof commitRes.mergedContent === 'string' &&
|
|
1474
|
+
commitRes.mergedContent !== finalContentStr) {
|
|
1475
|
+
finalContentStr = commitRes.mergedContent;
|
|
1476
|
+
let updatedFileId = uploadedFileId;
|
|
1477
|
+
let updatedSizeBytes = xlsxSizeBytes;
|
|
1478
|
+
if (state.contentMode === 'File') {
|
|
1479
|
+
const rematerialized = await this.materializeXlsxForContent(finalContentStr, workingXlsxBytes);
|
|
1480
|
+
if (!rematerialized.xlsxBase64) {
|
|
1481
|
+
const savedVersionId = versionEntity.ID;
|
|
1482
|
+
await this.safeDeleteVersionEntity(versionEntity);
|
|
1483
|
+
await this.DeleteUnreferencedArtifactFile(input.provider, input.contextUser, uploadedFileId);
|
|
1484
|
+
await this.safeRollbackHook(commitRes.rollback ?? hookOutcome.rollback, savedVersionId);
|
|
1485
|
+
return {
|
|
1486
|
+
success: false,
|
|
1487
|
+
errorMessage: 'Failed to rematerialize merged .xlsx binary after live room commit.',
|
|
1488
|
+
};
|
|
1489
|
+
}
|
|
1490
|
+
workingXlsxBytes = rematerialized.xlsxBytes;
|
|
1491
|
+
latestXlsxBase64 = rematerialized.xlsxBase64;
|
|
1492
|
+
const reupload = await this.uploadXlsxBuffer(input, state.name, rematerialized.xlsxBase64);
|
|
1493
|
+
if (!reupload.fileId) {
|
|
1494
|
+
const savedVersionId = versionEntity.ID;
|
|
1495
|
+
await this.safeDeleteVersionEntity(versionEntity);
|
|
1496
|
+
await this.DeleteUnreferencedArtifactFile(input.provider, input.contextUser, uploadedFileId);
|
|
1497
|
+
await this.safeRollbackHook(commitRes.rollback ?? hookOutcome.rollback, savedVersionId);
|
|
1498
|
+
return {
|
|
1499
|
+
success: false,
|
|
1500
|
+
errorMessage: 'Live room merged content after save, but re-uploading merged .xlsx binary failed.',
|
|
1501
|
+
};
|
|
1502
|
+
}
|
|
1503
|
+
updatedFileId = reupload.fileId;
|
|
1504
|
+
updatedSizeBytes = reupload.sizeBytes;
|
|
1505
|
+
}
|
|
1506
|
+
this.applyVersionPayload(versionEntity, state, finalContentStr, input.lastToolName, { agentRunId: input.agentRunId, agentName: input.agentName }, updatedFileId, updatedSizeBytes, input.configurationPatch);
|
|
1507
|
+
if (!(await versionEntity.Save())) {
|
|
1508
|
+
const errMsg = versionEntity.LatestResult?.CompleteMessage ||
|
|
1509
|
+
'Failed to re-save version record with post-commit merged content.';
|
|
1510
|
+
const savedVersionId = versionEntity.ID;
|
|
1511
|
+
await this.safeDeleteVersionEntity(versionEntity);
|
|
1512
|
+
if (updatedFileId && updatedFileId !== uploadedFileId) {
|
|
1513
|
+
await this.DeleteUnreferencedArtifactFile(input.provider, input.contextUser, updatedFileId);
|
|
1514
|
+
}
|
|
1515
|
+
await this.DeleteUnreferencedArtifactFile(input.provider, input.contextUser, uploadedFileId);
|
|
1516
|
+
await this.safeRollbackHook(commitRes.rollback ?? hookOutcome.rollback, savedVersionId);
|
|
1517
|
+
return {
|
|
1518
|
+
success: false,
|
|
1519
|
+
errorMessage: errMsg,
|
|
1520
|
+
};
|
|
1521
|
+
}
|
|
1522
|
+
if (uploadedFileId && updatedFileId && uploadedFileId !== updatedFileId) {
|
|
1523
|
+
await this.DeleteUnreferencedArtifactFile(input.provider, input.contextUser, uploadedFileId);
|
|
1524
|
+
}
|
|
1525
|
+
}
|
|
1526
|
+
}
|
|
1527
|
+
try {
|
|
1528
|
+
MJGlobal.Instance.RaiseEvent({
|
|
1529
|
+
component: this,
|
|
1530
|
+
event: MJEventType.ComponentEvent,
|
|
1531
|
+
eventCode: ARTIFACT_LIVE_MUTATION_EVENT_CODE,
|
|
1532
|
+
args: {
|
|
1533
|
+
ArtifactID: state.artifactId,
|
|
1534
|
+
NewContent: finalContentStr,
|
|
1535
|
+
PreviousContent: input.previousContentStr,
|
|
1536
|
+
ToolName: input.lastToolName,
|
|
1537
|
+
User: input.contextUser,
|
|
1538
|
+
SaveVersion: false,
|
|
1539
|
+
AlreadyAppliedToRoom: Boolean(liveHook),
|
|
1540
|
+
},
|
|
1541
|
+
});
|
|
1542
|
+
}
|
|
1543
|
+
catch {
|
|
1544
|
+
// Never fail mutation if UI subscriber throws
|
|
1545
|
+
}
|
|
1546
|
+
this.RecordTouchedArtifact(input.agentRunId, {
|
|
1547
|
+
ArtifactID: state.artifactId,
|
|
1548
|
+
ArtifactVersionID: versionEntity.ID,
|
|
1549
|
+
VersionNumber: nextVersionNumber,
|
|
1550
|
+
Name: state.name,
|
|
1551
|
+
ArtifactTypeName: state.typeName,
|
|
1552
|
+
DriverClass: state.driverClass,
|
|
1553
|
+
Operation: 'mutated',
|
|
1554
|
+
});
|
|
1555
|
+
await this.EmitAgentPresence({
|
|
1556
|
+
artifactId: state.artifactId,
|
|
1557
|
+
phase: 'settled',
|
|
1558
|
+
contextUser: input.contextUser,
|
|
1559
|
+
agentRunId: input.agentRunId,
|
|
1560
|
+
agentName: input.agentName,
|
|
1561
|
+
toolName: input.lastToolName,
|
|
1562
|
+
actionSummary: FormatAgentActionSummary(input.lastToolName, input.lastToolInput, input.lastLocation),
|
|
1563
|
+
location: input.lastLocation,
|
|
1564
|
+
});
|
|
1565
|
+
return {
|
|
1566
|
+
success: true,
|
|
1567
|
+
versionId: versionEntity.ID,
|
|
1568
|
+
versionNumber: nextVersionNumber,
|
|
1569
|
+
};
|
|
1570
|
+
}
|
|
1571
|
+
/**
|
|
1572
|
+
* Refreshes a governed artifact's live blocks/formulas (`LiveTables`, `=MJ.*`, slide/doc blocks) under
|
|
1573
|
+
* the per-artifact lock, reconciling live Yjs collaboration rooms and preserving `.xlsx` `File`-mode binaries.
|
|
1574
|
+
* Shared by both `RefreshAndSnapshotArtifactAction` (`CoreActions`) and `ArtifactToolManager` workspace tools.
|
|
1575
|
+
*/
|
|
1576
|
+
async RefreshAndSnapshotArtifact(params) {
|
|
1577
|
+
const trimmedId = (params.artifactId ?? '').trim();
|
|
1578
|
+
if (!IsValidUUID(trimmedId)) {
|
|
1579
|
+
return {
|
|
1580
|
+
success: false,
|
|
1581
|
+
resultCode: 'ARTIFACT_NOT_FOUND',
|
|
1582
|
+
message: `Invalid artifactId '${params.artifactId}'.`,
|
|
1583
|
+
changed: false,
|
|
1584
|
+
artifactId: trimmedId,
|
|
1585
|
+
errorMessage: `Invalid artifactId '${params.artifactId}'.`,
|
|
1586
|
+
};
|
|
1587
|
+
}
|
|
1588
|
+
return this.WithArtifactLock(trimmedId, () => this.refreshAndSnapshotArtifactLocked(params, trimmedId));
|
|
1589
|
+
}
|
|
1590
|
+
async refreshAndSnapshotArtifactLocked(params, artifactId) {
|
|
1591
|
+
const loaded = await this.LoadReadableArtifactState(params.provider, params.contextUser, artifactId, {
|
|
1592
|
+
failOnMissingFileContent: true,
|
|
1593
|
+
});
|
|
1594
|
+
if (!loaded.state) {
|
|
1595
|
+
const errMsg = loaded.errorMessage || `Artifact '${artifactId}' could not be loaded.`;
|
|
1596
|
+
const lower = errMsg.toLowerCase();
|
|
1597
|
+
const code = lower.includes('not found')
|
|
1598
|
+
? 'ARTIFACT_NOT_FOUND'
|
|
1599
|
+
: lower.includes('version')
|
|
1600
|
+
? 'VERSION_NOT_FOUND'
|
|
1601
|
+
: 'PERMISSION_DENIED';
|
|
1602
|
+
return {
|
|
1603
|
+
success: false,
|
|
1604
|
+
resultCode: code,
|
|
1605
|
+
message: errMsg,
|
|
1606
|
+
changed: false,
|
|
1607
|
+
artifactId,
|
|
1608
|
+
errorMessage: errMsg,
|
|
1609
|
+
};
|
|
1610
|
+
}
|
|
1611
|
+
const state = loaded.state;
|
|
1612
|
+
if (!state.permissions.CanEdit) {
|
|
1613
|
+
const deniedMsg = `Permission denied: user lacks Edit access to artifact '${state.artifactId}'.`;
|
|
1614
|
+
return {
|
|
1615
|
+
success: false,
|
|
1616
|
+
resultCode: 'PERMISSION_DENIED',
|
|
1617
|
+
message: deniedMsg,
|
|
1618
|
+
changed: false,
|
|
1619
|
+
artifactId: state.artifactId,
|
|
1620
|
+
errorMessage: deniedMsg,
|
|
1621
|
+
};
|
|
1622
|
+
}
|
|
1623
|
+
if (!state.versionId) {
|
|
1624
|
+
const noVerMsg = `No artifact versions exist for artifact '${state.artifactId}'.`;
|
|
1625
|
+
return {
|
|
1626
|
+
success: false,
|
|
1627
|
+
resultCode: 'VERSION_NOT_FOUND',
|
|
1628
|
+
message: noVerMsg,
|
|
1629
|
+
changed: false,
|
|
1630
|
+
artifactId: state.artifactId,
|
|
1631
|
+
errorMessage: noVerMsg,
|
|
1632
|
+
};
|
|
1633
|
+
}
|
|
1634
|
+
const freezeBlocks = Boolean(params.freezeRefreshedBlocks);
|
|
1635
|
+
const forceRefreshFrozen = Boolean(params.forceRefreshFrozen);
|
|
1636
|
+
const forceSaveIfUnchanged = Boolean(params.forceSaveIfUnchanged);
|
|
1637
|
+
const driverClass = state.driverClass ?? '';
|
|
1638
|
+
const rawContent = Buffer.isBuffer(state.content) ? '' : String(state.content ?? '');
|
|
1639
|
+
const prevConfig = ParseArtifactVersionConfiguration(state.configuration) ?? {};
|
|
1640
|
+
const domain = ResolvePresenceDomain(state.typeName);
|
|
1641
|
+
let workingEmitted = false;
|
|
1642
|
+
try {
|
|
1643
|
+
await this.EmitAgentPresence({
|
|
1644
|
+
artifactId: state.artifactId,
|
|
1645
|
+
phase: 'working',
|
|
1646
|
+
contextUser: params.contextUser,
|
|
1647
|
+
agentRunId: params.agentRunId,
|
|
1648
|
+
agentName: params.agentName,
|
|
1649
|
+
toolName: 'refresh_and_snapshot_artifact',
|
|
1650
|
+
actionSummary: freezeBlocks
|
|
1651
|
+
? `Refreshing & freezing "${state.name}"`
|
|
1652
|
+
: `Refreshing live data in "${state.name}"`,
|
|
1653
|
+
location: { Domain: domain },
|
|
1654
|
+
});
|
|
1655
|
+
workingEmitted = true;
|
|
1656
|
+
const refreshResult = await this.computeRefreshedArtifactPayload({
|
|
1657
|
+
artifactId: state.artifactId,
|
|
1658
|
+
rawContent,
|
|
1659
|
+
rawConfiguration: state.configuration ?? null,
|
|
1660
|
+
driverClass,
|
|
1661
|
+
title: state.name,
|
|
1662
|
+
freezeBlocks,
|
|
1663
|
+
forceRefreshFrozen,
|
|
1664
|
+
contextUser: params.contextUser,
|
|
1665
|
+
provider: params.provider,
|
|
1666
|
+
});
|
|
1667
|
+
if (refreshResult.updatedContent !== rawContent) {
|
|
1668
|
+
const isArtifactOwner = state.permissions.Source === 'Owner' ||
|
|
1669
|
+
Boolean(state.ownerUserId && UUIDsEqual(state.ownerUserId, params.contextUser.ID));
|
|
1670
|
+
const lockCheck = ValidateArtifactContentMutationAgainstLocks(rawContent, refreshResult.updatedContent, params.contextUser.ID, isArtifactOwner);
|
|
1671
|
+
if (!lockCheck.Allowed) {
|
|
1672
|
+
const deniedMsg = lockCheck.Reason ?? 'Write rejected: refreshed content modifies a locked region.';
|
|
1673
|
+
return {
|
|
1674
|
+
success: false,
|
|
1675
|
+
resultCode: 'PERMISSION_DENIED',
|
|
1676
|
+
message: deniedMsg,
|
|
1677
|
+
changed: false,
|
|
1678
|
+
artifactId: state.artifactId,
|
|
1679
|
+
errorMessage: deniedMsg,
|
|
1680
|
+
};
|
|
1681
|
+
}
|
|
1682
|
+
}
|
|
1683
|
+
const prevDigestHash = typeof prevConfig['livingReportDigest'] === 'string'
|
|
1684
|
+
? prevConfig['livingReportDigest']
|
|
1685
|
+
: this.computeBaselineDigestForComparison(rawContent, driverClass, state.configuration ?? null, state.name);
|
|
1686
|
+
const changed = refreshResult.digestHash !== prevDigestHash;
|
|
1687
|
+
if (!changed && !forceSaveIfUnchanged) {
|
|
1688
|
+
return {
|
|
1689
|
+
success: true,
|
|
1690
|
+
resultCode: 'NO_CHANGES',
|
|
1691
|
+
message: `No changes detected for '${state.name}' (v${state.versionNumber}).`,
|
|
1692
|
+
changed: false,
|
|
1693
|
+
artifactId: state.artifactId,
|
|
1694
|
+
versionId: state.versionId,
|
|
1695
|
+
previousVersionId: state.versionId,
|
|
1696
|
+
newVersionId: state.versionId,
|
|
1697
|
+
previousVersionNumber: state.versionNumber,
|
|
1698
|
+
versionNumber: state.versionNumber,
|
|
1699
|
+
newVersionNumber: state.versionNumber,
|
|
1700
|
+
artifactName: state.name,
|
|
1701
|
+
artifactTypeName: state.typeName,
|
|
1702
|
+
driverClass,
|
|
1703
|
+
diffSummary: 'No changes detected.',
|
|
1704
|
+
signedFrozenBlocksCount: refreshResult.signedFrozenBlocksCount,
|
|
1705
|
+
highlightLines: refreshResult.highlightLines,
|
|
1706
|
+
};
|
|
1707
|
+
}
|
|
1708
|
+
const nextVersionNumber = Math.max(state.versionNumber, state.dbVersionNumber) + 1;
|
|
1709
|
+
const prevLines = this.extractPreviousHighlightLines(prevConfig);
|
|
1710
|
+
const diffSummary = this.computeRefreshDiffSummary(state.name, state.versionNumber, nextVersionNumber, prevLines, refreshResult.highlightLines);
|
|
1711
|
+
let workingXlsxBytes = state.originalXlsxBytes;
|
|
1712
|
+
let latestXlsxBase64;
|
|
1713
|
+
if (workingXlsxBytes || state.contentMode === 'File') {
|
|
1714
|
+
const materialized = await this.materializeXlsxForContent(refreshResult.updatedContent, workingXlsxBytes);
|
|
1715
|
+
if (materialized.xlsxBytes) {
|
|
1716
|
+
workingXlsxBytes = materialized.xlsxBytes;
|
|
1717
|
+
latestXlsxBase64 = materialized.xlsxBase64;
|
|
1718
|
+
}
|
|
1719
|
+
}
|
|
1720
|
+
const configurationPatch = {
|
|
1721
|
+
livingReportDigest: refreshResult.digestHash,
|
|
1722
|
+
livingReportHighlightLines: refreshResult.highlightLines,
|
|
1723
|
+
livingReportRefreshedAt: new Date().toISOString(),
|
|
1724
|
+
};
|
|
1725
|
+
const comments = (params.versionComments ?? '').trim() ||
|
|
1726
|
+
`Scheduled refresh from v${state.versionNumber}: ${diffSummary}`;
|
|
1727
|
+
const persistRes = await this.persistLoadedArtifactMutation({
|
|
1728
|
+
provider: params.provider,
|
|
1729
|
+
contextUser: params.contextUser,
|
|
1730
|
+
state,
|
|
1731
|
+
previousContentStr: rawContent,
|
|
1732
|
+
finalContentStr: refreshResult.updatedContent,
|
|
1733
|
+
workingXlsxBytes,
|
|
1734
|
+
latestXlsxBase64,
|
|
1735
|
+
lastToolName: 'refresh_and_snapshot_artifact',
|
|
1736
|
+
lastToolInput: {
|
|
1737
|
+
freezeRefreshedBlocks: freezeBlocks,
|
|
1738
|
+
forceRefreshFrozen,
|
|
1739
|
+
forceSaveIfUnchanged,
|
|
1740
|
+
},
|
|
1741
|
+
lastLocation: { Domain: domain },
|
|
1742
|
+
comments,
|
|
1743
|
+
configurationPatch,
|
|
1744
|
+
agentRunId: params.agentRunId,
|
|
1745
|
+
agentName: params.agentName,
|
|
1746
|
+
});
|
|
1747
|
+
if (!persistRes.success || !persistRes.versionId) {
|
|
1748
|
+
const failMsg = persistRes.errorMessage || `Failed to save refreshed artifact version v${nextVersionNumber}.`;
|
|
1749
|
+
return {
|
|
1750
|
+
success: false,
|
|
1751
|
+
resultCode: 'FAILED',
|
|
1752
|
+
message: failMsg,
|
|
1753
|
+
changed,
|
|
1754
|
+
artifactId: state.artifactId,
|
|
1755
|
+
previousVersionId: state.versionId,
|
|
1756
|
+
previousVersionNumber: state.versionNumber,
|
|
1757
|
+
artifactName: state.name,
|
|
1758
|
+
artifactTypeName: state.typeName,
|
|
1759
|
+
driverClass,
|
|
1760
|
+
errorMessage: failMsg,
|
|
1761
|
+
};
|
|
1762
|
+
}
|
|
1763
|
+
return {
|
|
1764
|
+
success: true,
|
|
1765
|
+
resultCode: 'SUCCESS',
|
|
1766
|
+
message: `Refreshed '${state.name}' to v${persistRes.versionNumber}: ${diffSummary}`,
|
|
1767
|
+
changed,
|
|
1768
|
+
artifactId: state.artifactId,
|
|
1769
|
+
versionId: persistRes.versionId,
|
|
1770
|
+
previousVersionId: state.versionId,
|
|
1771
|
+
newVersionId: persistRes.versionId,
|
|
1772
|
+
previousVersionNumber: state.versionNumber,
|
|
1773
|
+
versionNumber: persistRes.versionNumber,
|
|
1774
|
+
newVersionNumber: persistRes.versionNumber,
|
|
1775
|
+
artifactName: state.name,
|
|
1776
|
+
artifactTypeName: state.typeName,
|
|
1777
|
+
driverClass,
|
|
1778
|
+
diffSummary,
|
|
1779
|
+
signedFrozenBlocksCount: refreshResult.signedFrozenBlocksCount,
|
|
1780
|
+
highlightLines: refreshResult.highlightLines,
|
|
1781
|
+
};
|
|
1782
|
+
}
|
|
1783
|
+
catch (err) {
|
|
1784
|
+
const msg = `RefreshAndSnapshotArtifact error: ${err instanceof Error ? err.message : String(err)}`;
|
|
1785
|
+
return {
|
|
1786
|
+
success: false,
|
|
1787
|
+
resultCode: 'FAILED',
|
|
1788
|
+
message: msg,
|
|
1789
|
+
changed: false,
|
|
1790
|
+
artifactId: state.artifactId,
|
|
1791
|
+
errorMessage: msg,
|
|
1792
|
+
};
|
|
1793
|
+
}
|
|
1794
|
+
finally {
|
|
1795
|
+
if (workingEmitted) {
|
|
1796
|
+
await this.EmitAgentPresence({
|
|
1797
|
+
artifactId: state.artifactId,
|
|
1798
|
+
phase: 'exit',
|
|
1799
|
+
contextUser: params.contextUser,
|
|
1800
|
+
agentRunId: params.agentRunId,
|
|
1801
|
+
agentName: params.agentName,
|
|
1802
|
+
});
|
|
1803
|
+
}
|
|
1804
|
+
}
|
|
1805
|
+
}
|
|
1806
|
+
/**
|
|
1807
|
+
* Refreshes an in-memory artifact payload (Spreadsheet, SlideDeck, or Markdown Document),
|
|
1808
|
+
* optionally freezes blocks/tables, and returns the updated payload, configuration, and diff digest.
|
|
1809
|
+
*/
|
|
1810
|
+
async RefreshArtifactPayloadInMemory(input) {
|
|
1811
|
+
const driverClass = input.driverClass ?? '';
|
|
1812
|
+
const title = input.title ?? input.artifactTypeName ?? 'Artifact';
|
|
1813
|
+
const freezeBlocks = input.freezeRefreshedBlocks === true;
|
|
1814
|
+
const forceRefreshFrozen = input.forceRefreshFrozen === true;
|
|
1815
|
+
const prevConfig = ParseArtifactVersionConfiguration(input.configuration ?? null) ?? {};
|
|
1816
|
+
const prevDigestHash = typeof prevConfig['livingReportDigest'] === 'string'
|
|
1817
|
+
? prevConfig['livingReportDigest']
|
|
1818
|
+
: this.computeBaselineDigestForComparison(input.content, driverClass, input.configuration ?? null, title);
|
|
1819
|
+
const refreshed = await this.computeRefreshedArtifactPayload({
|
|
1820
|
+
rawContent: input.content,
|
|
1821
|
+
rawConfiguration: input.configuration ?? null,
|
|
1822
|
+
driverClass,
|
|
1823
|
+
title,
|
|
1824
|
+
freezeBlocks,
|
|
1825
|
+
forceRefreshFrozen,
|
|
1826
|
+
contextUser: input.contextUser,
|
|
1827
|
+
provider: input.provider,
|
|
1828
|
+
});
|
|
1829
|
+
const changed = refreshed.digestHash !== prevDigestHash || refreshed.signedFrozenBlocksCount > 0;
|
|
1830
|
+
const prevLines = this.extractPreviousHighlightLines(prevConfig);
|
|
1831
|
+
const diffSummary = changed
|
|
1832
|
+
? this.computeRefreshDiffSummary(title, 1, 2, prevLines, refreshed.highlightLines)
|
|
1833
|
+
: `All live blocks matched prior snapshot; no changes.`;
|
|
1834
|
+
const mergedCfg = JSON.stringify({
|
|
1835
|
+
...prevConfig,
|
|
1836
|
+
livingReportDigest: refreshed.digestHash,
|
|
1837
|
+
livingReportHighlightLines: refreshed.highlightLines,
|
|
1838
|
+
livingReportRefreshedAt: new Date().toISOString(),
|
|
1839
|
+
});
|
|
1840
|
+
const updatedConfiguration = BuildArtifactVersionConfigurationWithPreview(mergedCfg, refreshed.updatedContent, driverClass || undefined, title) ?? '{}';
|
|
1841
|
+
return {
|
|
1842
|
+
changed,
|
|
1843
|
+
updatedContent: refreshed.updatedContent,
|
|
1844
|
+
updatedConfiguration,
|
|
1845
|
+
diffSummary,
|
|
1846
|
+
signedFrozenBlocksCount: refreshed.signedFrozenBlocksCount,
|
|
1847
|
+
highlightLines: refreshed.highlightLines,
|
|
1848
|
+
};
|
|
1849
|
+
}
|
|
1850
|
+
computeFullPayloadDigestHash(payload) {
|
|
1851
|
+
return createHash('sha256').update(payload, 'utf8').digest('hex');
|
|
1852
|
+
}
|
|
1853
|
+
canonicalizeWorkbookForDigest(wb) {
|
|
1854
|
+
const serialized = SpreadsheetEngine.Instance.SerializeWorkbook(wb, { preserveTimestamps: true });
|
|
1855
|
+
try {
|
|
1856
|
+
const parsed = JSON.parse(serialized);
|
|
1857
|
+
if (parsed && typeof parsed === 'object') {
|
|
1858
|
+
parsed.UpdatedAt = '';
|
|
1859
|
+
if (Array.isArray(parsed.Worksheets)) {
|
|
1860
|
+
for (const ws of parsed.Worksheets) {
|
|
1861
|
+
if (ws && typeof ws === 'object') {
|
|
1862
|
+
ws.UpdatedAt = '';
|
|
1863
|
+
if (Array.isArray(ws.LiveTables)) {
|
|
1864
|
+
for (const tbl of ws.LiveTables) {
|
|
1865
|
+
if (tbl && typeof tbl === 'object') {
|
|
1866
|
+
tbl.LastRefreshedAt = '';
|
|
1867
|
+
}
|
|
1868
|
+
}
|
|
1869
|
+
}
|
|
1870
|
+
}
|
|
1871
|
+
}
|
|
1872
|
+
}
|
|
1873
|
+
return JSON.stringify(parsed);
|
|
1874
|
+
}
|
|
1875
|
+
}
|
|
1876
|
+
catch {
|
|
1877
|
+
// Fall back to preserveTimestamps serialization
|
|
1878
|
+
}
|
|
1879
|
+
return serialized;
|
|
1880
|
+
}
|
|
1881
|
+
buildSpreadsheetCellDigestEntries(wb) {
|
|
1882
|
+
const fullCellEntries = [];
|
|
1883
|
+
for (const ws of wb.Worksheets) {
|
|
1884
|
+
const sortedCells = Object.values(ws.Cells).sort((a, b) => a.Address.localeCompare(b.Address));
|
|
1885
|
+
for (const c of sortedCells) {
|
|
1886
|
+
fullCellEntries.push(`${ws.Name}!${c.Address}=${String(c.ComputedValue ?? c.RawValue ?? '')}`);
|
|
1887
|
+
}
|
|
1888
|
+
}
|
|
1889
|
+
return fullCellEntries;
|
|
1890
|
+
}
|
|
1891
|
+
canonicalizeDeckForDigest(deck) {
|
|
1892
|
+
const serialized = SlideDeckEngine.Instance.SerializeDeckSpec(deck);
|
|
1893
|
+
try {
|
|
1894
|
+
const parsed = JSON.parse(serialized);
|
|
1895
|
+
if (parsed && typeof parsed === 'object') {
|
|
1896
|
+
parsed.UpdatedAt = '';
|
|
1897
|
+
if (Array.isArray(parsed.Slides)) {
|
|
1898
|
+
for (const slide of parsed.Slides) {
|
|
1899
|
+
if (slide && typeof slide === 'object') {
|
|
1900
|
+
slide.UpdatedAt = '';
|
|
1901
|
+
}
|
|
1902
|
+
}
|
|
1903
|
+
}
|
|
1904
|
+
return JSON.stringify(parsed);
|
|
1905
|
+
}
|
|
1906
|
+
}
|
|
1907
|
+
catch {
|
|
1908
|
+
// Fall back to serialized deck JSON
|
|
1909
|
+
}
|
|
1910
|
+
return serialized;
|
|
1911
|
+
}
|
|
1912
|
+
buildDeckDigestParts(deck, liveResults) {
|
|
1913
|
+
const fullDeckDigestParts = [];
|
|
1914
|
+
const highlightLines = [];
|
|
1915
|
+
for (const s of deck.Slides) {
|
|
1916
|
+
const regionSummaries = s.Regions.map((r) => r.MarkdownContent ?? '');
|
|
1917
|
+
fullDeckDigestParts.push(`Slide[${s.SlideID}|${s.Title}]: ${regionSummaries.join(' | ')}`);
|
|
1918
|
+
highlightLines.push(`Slide[${s.Title}]: ${regionSummaries.map((m) => m.slice(0, 80)).join(' | ')}`);
|
|
1919
|
+
}
|
|
1920
|
+
if (liveResults) {
|
|
1921
|
+
for (const [blockId, res] of Object.entries(liveResults).sort(([a], [b]) => a.localeCompare(b))) {
|
|
1922
|
+
// fls-guard: hashed internally for digest calculation only; never emitted to highlightLines or callers (`B7`).
|
|
1923
|
+
const rowsJson = JSON.stringify(res.Rows);
|
|
1924
|
+
fullDeckDigestParts.push(`Block[${blockId}]: rows=${res.TotalRowCount}, all=${rowsJson}`);
|
|
1925
|
+
}
|
|
1926
|
+
}
|
|
1927
|
+
return { fullDeckDigestParts, highlightLines };
|
|
1928
|
+
}
|
|
1929
|
+
computeBaselineDigestForComparison(rawContent, driverClass, rawConfiguration, title) {
|
|
1930
|
+
const isSheet = driverClass === 'SpreadsheetArtifactViewerPlugin' ||
|
|
1931
|
+
(rawContent.trim().startsWith('{') && rawContent.includes('"Worksheets"'));
|
|
1932
|
+
if (isSheet) {
|
|
1933
|
+
try {
|
|
1934
|
+
const wb = SpreadsheetEngine.Instance.ParseWorkbook(rawContent, rawConfiguration, { SkipEvaluate: true });
|
|
1935
|
+
const fullCellEntries = this.buildSpreadsheetCellDigestEntries(wb);
|
|
1936
|
+
return this.computeFullPayloadDigestHash(JSON.stringify({ updatedContent: this.canonicalizeWorkbookForDigest(wb), fullCellEntries }));
|
|
1937
|
+
}
|
|
1938
|
+
catch {
|
|
1939
|
+
return this.computeFullPayloadDigestHash(rawContent);
|
|
1940
|
+
}
|
|
1941
|
+
}
|
|
1942
|
+
const isDeck = driverClass === 'SlideDeckArtifactViewerPlugin' ||
|
|
1943
|
+
(rawContent.trim().startsWith('{') && rawContent.includes('"Slides"'));
|
|
1944
|
+
if (isDeck) {
|
|
1945
|
+
try {
|
|
1946
|
+
const deck = SlideDeckEngine.Instance.ParseDeckSpec(rawContent, title);
|
|
1947
|
+
const { fullDeckDigestParts } = this.buildDeckDigestParts(deck);
|
|
1948
|
+
return this.computeFullPayloadDigestHash(JSON.stringify({ updatedContent: this.canonicalizeDeckForDigest(deck), fullDeckDigestParts }));
|
|
1949
|
+
}
|
|
1950
|
+
catch {
|
|
1951
|
+
return this.computeFullPayloadDigestHash(rawContent);
|
|
1952
|
+
}
|
|
1953
|
+
}
|
|
1954
|
+
try {
|
|
1955
|
+
const segments = DocumentLiveBlockEngine.Instance.ParseMarkdownDirectives(rawContent);
|
|
1956
|
+
const fullDigestParts = [];
|
|
1957
|
+
for (const seg of segments) {
|
|
1958
|
+
if (seg.Type === 'markdown') {
|
|
1959
|
+
fullDigestParts.push(seg.RawText);
|
|
1960
|
+
}
|
|
1961
|
+
else if (seg.BlockSpec) {
|
|
1962
|
+
const snap = seg.BlockSpec.FrozenSnapshot;
|
|
1963
|
+
if (seg.BlockSpec.Mode === 'Frozen' && snap) {
|
|
1964
|
+
// fls-guard: hashed internally for digest calculation only; never returned to caller
|
|
1965
|
+
const snapRowsJson = JSON.stringify(snap.Rows);
|
|
1966
|
+
fullDigestParts.push(`FrozenBlock[${seg.BlockSpec.BlockID}]: rows=${snap.TotalRowCount}, all=${snapRowsJson}`);
|
|
1967
|
+
}
|
|
1968
|
+
else {
|
|
1969
|
+
fullDigestParts.push(seg.RawText);
|
|
1970
|
+
}
|
|
1971
|
+
}
|
|
1972
|
+
}
|
|
1973
|
+
return this.computeFullPayloadDigestHash(JSON.stringify({ updatedContent: rawContent, fullDigestParts }));
|
|
1974
|
+
}
|
|
1975
|
+
catch {
|
|
1976
|
+
return this.computeFullPayloadDigestHash(rawContent);
|
|
1977
|
+
}
|
|
1978
|
+
}
|
|
1979
|
+
async computeRefreshedArtifactPayload(input) {
|
|
1980
|
+
const isSheet = input.driverClass === 'SpreadsheetArtifactViewerPlugin' ||
|
|
1981
|
+
(input.rawContent.trim().startsWith('{') && input.rawContent.includes('"Worksheets"'));
|
|
1982
|
+
if (isSheet) {
|
|
1983
|
+
const engine = SpreadsheetEngine.Instance;
|
|
1984
|
+
const wb = await engine.ParseWorkbookIsolated(input.rawContent, input.rawConfiguration, { SkipEvaluate: true });
|
|
1985
|
+
const tableResults = await engine.RefreshLiveTables(wb, input.contextUser, input.provider, {
|
|
1986
|
+
ForceRefreshFrozen: input.freezeBlocks || input.forceRefreshFrozen,
|
|
1987
|
+
});
|
|
1988
|
+
await engine.EvaluateMjCustomFunctions(wb, input.contextUser, input.provider, {
|
|
1989
|
+
BypassCache: true,
|
|
1990
|
+
});
|
|
1991
|
+
await engine.EvaluateWorkbookIsolated(wb);
|
|
1992
|
+
let signedFrozenBlocksCount = 0;
|
|
1993
|
+
if (input.freezeBlocks) {
|
|
1994
|
+
for (const ws of wb.Worksheets) {
|
|
1995
|
+
for (const tbl of ws.LiveTables) {
|
|
1996
|
+
const tblRes = tableResults[tbl.TableID];
|
|
1997
|
+
if (tblRes && tblRes.Success && !tblRes.AccessDenied) {
|
|
1998
|
+
engine.FreezeLiveTable(wb, ws.Name, tbl.TableID, tblRes, input.contextUser, true, undefined, input.artifactId, false);
|
|
1999
|
+
signedFrozenBlocksCount++;
|
|
2000
|
+
}
|
|
2001
|
+
}
|
|
2002
|
+
}
|
|
2003
|
+
if (signedFrozenBlocksCount > 0) {
|
|
2004
|
+
await engine.EvaluateWorkbookIsolated(wb);
|
|
2005
|
+
}
|
|
2006
|
+
}
|
|
2007
|
+
// fls-guard: fullCellEntries hashed for digest ONLY; highlightLines use sanitized workbook without viewer-scoped live/AI data (`B7b`).
|
|
2008
|
+
const fullCellEntries = this.buildSpreadsheetCellDigestEntries(wb);
|
|
2009
|
+
const sanitizedWb = engine.CloneWorkbookWithoutViewerScopedData(wb);
|
|
2010
|
+
const highlightLines = [];
|
|
2011
|
+
for (const ws of sanitizedWb.Worksheets) {
|
|
2012
|
+
highlightLines.push(`Sheet[${ws.Name}]: liveTables=${ws.LiveTables.length}`);
|
|
2013
|
+
const liveCellCoords = new Set();
|
|
2014
|
+
for (const tbl of ws.LiveTables) {
|
|
2015
|
+
const anchor = ParseRangeAddress(tbl.AnchorCell || 'A1', 10_000, 512);
|
|
2016
|
+
if (!anchor)
|
|
2017
|
+
continue;
|
|
2018
|
+
const rowCount = (tbl.LastRowCount ?? 0) + (tbl.IncludeHeaders !== false ? 1 : 0);
|
|
2019
|
+
const colCount = Math.max(tbl.LastColumnCount ?? 0, 1);
|
|
2020
|
+
for (let r = anchor.startRow; r < anchor.startRow + rowCount; r++) {
|
|
2021
|
+
for (let c = anchor.startCol; c < anchor.startCol + colCount; c++) {
|
|
2022
|
+
liveCellCoords.add(`${r}:${c}`);
|
|
2023
|
+
}
|
|
2024
|
+
}
|
|
2025
|
+
}
|
|
2026
|
+
const sortedCells = Object.values(ws.Cells).sort((a, b) => a.Address.localeCompare(b.Address));
|
|
2027
|
+
for (const cell of sortedCells) {
|
|
2028
|
+
if (highlightLines.length >= 80)
|
|
2029
|
+
break;
|
|
2030
|
+
if (cell.Formula && /^\s*=\s*MJ\./i.test(cell.Formula))
|
|
2031
|
+
continue;
|
|
2032
|
+
const pos = ParseRangeAddress(cell.Address, 10_000, 512);
|
|
2033
|
+
if (pos && liveCellCoords.has(`${pos.startRow}:${pos.startCol}`))
|
|
2034
|
+
continue;
|
|
2035
|
+
highlightLines.push(`${ws.Name}!${cell.Address}=${String(cell.RawValue ?? '')}`);
|
|
2036
|
+
}
|
|
2037
|
+
}
|
|
2038
|
+
const updatedContent = engine.SerializeWorkbook(wb, { preserveTimestamps: true });
|
|
2039
|
+
const canonicalContent = this.canonicalizeWorkbookForDigest(wb);
|
|
2040
|
+
return {
|
|
2041
|
+
updatedContent,
|
|
2042
|
+
digestHash: this.computeFullPayloadDigestHash(JSON.stringify({ updatedContent: canonicalContent, fullCellEntries })),
|
|
2043
|
+
highlightLines: highlightLines.slice(0, 80),
|
|
2044
|
+
signedFrozenBlocksCount,
|
|
2045
|
+
};
|
|
2046
|
+
}
|
|
2047
|
+
const isDeck = input.driverClass === 'SlideDeckArtifactViewerPlugin' ||
|
|
2048
|
+
(input.rawContent.trim().startsWith('{') && input.rawContent.includes('"Slides"'));
|
|
2049
|
+
if (isDeck) {
|
|
2050
|
+
const slideEngine = SlideDeckEngine.Instance;
|
|
2051
|
+
let deck = slideEngine.ParseDeckSpec(input.rawContent, input.title);
|
|
2052
|
+
const liveResults = await slideEngine.ExecuteDeckLiveBlocks(deck, input.provider, input.contextUser);
|
|
2053
|
+
let signedFrozenBlocksCount = 0;
|
|
2054
|
+
if (input.freezeBlocks) {
|
|
2055
|
+
const resultsMap = new Map(Object.entries(liveResults));
|
|
2056
|
+
const secret = DocumentLiveBlockEngine.Instance.ResolveSigningSecret() ?? undefined;
|
|
2057
|
+
deck = slideEngine.FreezeDeckLiveBlocksForPresentation(deck, resultsMap, input.contextUser, {
|
|
2058
|
+
SigningSecret: secret,
|
|
2059
|
+
ArtifactID: input.artifactId,
|
|
2060
|
+
});
|
|
2061
|
+
signedFrozenBlocksCount = resultsMap.size;
|
|
2062
|
+
}
|
|
2063
|
+
const { fullDeckDigestParts, highlightLines } = this.buildDeckDigestParts(deck, liveResults);
|
|
2064
|
+
const updatedContent = slideEngine.SerializeDeckSpec(deck);
|
|
2065
|
+
const canonicalDeckContent = this.canonicalizeDeckForDigest(deck);
|
|
2066
|
+
return {
|
|
2067
|
+
updatedContent,
|
|
2068
|
+
digestHash: this.computeFullPayloadDigestHash(JSON.stringify({ updatedContent: canonicalDeckContent, fullDeckDigestParts })),
|
|
2069
|
+
highlightLines: highlightLines.slice(0, 80),
|
|
2070
|
+
signedFrozenBlocksCount,
|
|
2071
|
+
};
|
|
2072
|
+
}
|
|
2073
|
+
// Markdown Document with :::mj-block directives
|
|
2074
|
+
const docEngine = DocumentLiveBlockEngine.Instance;
|
|
2075
|
+
const segments = docEngine.ParseMarkdownDirectives(input.rawContent);
|
|
2076
|
+
const rebuiltParts = [];
|
|
2077
|
+
const highlightLines = [];
|
|
2078
|
+
const fullDigestParts = [];
|
|
2079
|
+
let signedFrozenBlocksCount = 0;
|
|
2080
|
+
for (const seg of segments) {
|
|
2081
|
+
if (seg.Type === 'markdown') {
|
|
2082
|
+
rebuiltParts.push(seg.RawText);
|
|
2083
|
+
fullDigestParts.push(seg.RawText);
|
|
2084
|
+
const textSample = seg.RawText.split('\n')
|
|
2085
|
+
.map((l) => l.trim())
|
|
2086
|
+
.filter(Boolean)
|
|
2087
|
+
.slice(0, 10);
|
|
2088
|
+
highlightLines.push(...textSample);
|
|
2089
|
+
continue;
|
|
2090
|
+
}
|
|
2091
|
+
if (seg.BlockSpec) {
|
|
2092
|
+
const isFrozen = seg.BlockSpec.Mode === 'Frozen';
|
|
2093
|
+
if (isFrozen && !input.freezeBlocks && !input.forceRefreshFrozen && seg.BlockSpec.FrozenSnapshot) {
|
|
2094
|
+
const snap = seg.BlockSpec.FrozenSnapshot;
|
|
2095
|
+
// fls-guard: hashed internally for digest calculation only; never emitted to highlightLines or callers (`B7`).
|
|
2096
|
+
const snapRowsJson = JSON.stringify(snap.Rows);
|
|
2097
|
+
fullDigestParts.push(`FrozenBlock[${seg.BlockSpec.BlockID}]: rows=${snap.TotalRowCount}, all=${snapRowsJson}`);
|
|
2098
|
+
highlightLines.push(`Block[${seg.BlockSpec.Title || seg.BlockSpec.BlockID}]: mode=${seg.BlockSpec.Mode}`);
|
|
2099
|
+
rebuiltParts.push(seg.RawText);
|
|
2100
|
+
continue;
|
|
2101
|
+
}
|
|
2102
|
+
const res = await docEngine.ExecuteBlock(seg.BlockSpec, input.contextUser, input.provider);
|
|
2103
|
+
// fls-guard: hashed internally for digest calculation only; never emitted to highlightLines or callers (`B7`).
|
|
2104
|
+
const resRowsJson = JSON.stringify(res.Rows);
|
|
2105
|
+
fullDigestParts.push(`Block[${seg.BlockSpec.BlockID}]: rows=${res.TotalRowCount}, all=${resRowsJson}`);
|
|
2106
|
+
highlightLines.push(`Block[${seg.BlockSpec.Title || seg.BlockSpec.BlockID}]: mode=${seg.BlockSpec.Mode}`);
|
|
2107
|
+
if (input.freezeBlocks) {
|
|
2108
|
+
const frozen = await docEngine.FreezeBlock(seg.BlockSpec, input.contextUser, true, input.provider, undefined, input.artifactId);
|
|
2109
|
+
if (frozen.Success && frozen.UpdatedSpec) {
|
|
2110
|
+
signedFrozenBlocksCount++;
|
|
2111
|
+
rebuiltParts.push(docEngine.SerializeBlockToMarkdownDirective(frozen.UpdatedSpec));
|
|
2112
|
+
continue;
|
|
2113
|
+
}
|
|
2114
|
+
}
|
|
2115
|
+
}
|
|
2116
|
+
rebuiltParts.push(seg.RawText);
|
|
2117
|
+
}
|
|
2118
|
+
const updatedContent = input.freezeBlocks ? rebuiltParts.join('\n') : input.rawContent;
|
|
2119
|
+
return {
|
|
2120
|
+
updatedContent,
|
|
2121
|
+
digestHash: this.computeFullPayloadDigestHash(JSON.stringify({ updatedContent, fullDigestParts })),
|
|
2122
|
+
highlightLines: highlightLines.slice(0, 80),
|
|
2123
|
+
signedFrozenBlocksCount,
|
|
2124
|
+
};
|
|
2125
|
+
}
|
|
2126
|
+
extractPreviousHighlightLines(prevConfig) {
|
|
2127
|
+
const stored = prevConfig['livingReportHighlightLines'];
|
|
2128
|
+
if (Array.isArray(stored)) {
|
|
2129
|
+
return stored.filter((v) => typeof v === 'string');
|
|
2130
|
+
}
|
|
2131
|
+
const snap = prevConfig.previewSnapshot;
|
|
2132
|
+
if (snap && snap.Kind === 'doc') {
|
|
2133
|
+
return [snap.Heading, snap.Excerpt].filter(Boolean);
|
|
2134
|
+
}
|
|
2135
|
+
return [];
|
|
2136
|
+
}
|
|
2137
|
+
computeRefreshDiffSummary(artifactName, prevVersionNumber, nextVersionNumber, prevLines, nextLines) {
|
|
2138
|
+
const prevSet = new Set(prevLines);
|
|
2139
|
+
const added = nextLines.filter((l) => !prevSet.has(l));
|
|
2140
|
+
const nextSet = new Set(nextLines);
|
|
2141
|
+
const removed = prevLines.filter((l) => !nextSet.has(l));
|
|
2142
|
+
if (added.length === 0 && removed.length === 0) {
|
|
2143
|
+
return `Saved '${artifactName}' v${nextVersionNumber} (from v${prevVersionNumber}).`;
|
|
2144
|
+
}
|
|
2145
|
+
const highlights = added.slice(0, 3).map((l) => `- ${l}`).join('\n');
|
|
2146
|
+
return `Updated '${artifactName}' from v${prevVersionNumber} to v${nextVersionNumber} (${added.length} added/changed, ${removed.length} removed)${highlights ? `:\n${highlights}` : '.'}`;
|
|
2147
|
+
}
|
|
2148
|
+
/**
|
|
2149
|
+
* Lists readable governed artifacts in a collection or owned/shared with the current user.
|
|
2150
|
+
*/
|
|
2151
|
+
async ListWorkspaceArtifacts(params) {
|
|
2152
|
+
const collectionId = (params.collectionId ?? '').trim();
|
|
2153
|
+
const typeFilter = (params.typeFilter ?? '').trim().toLowerCase();
|
|
2154
|
+
const normalizedTypeFilter = typeFilter ? this.NormalizeArtifactTypeName(params.typeFilter).toLowerCase() : '';
|
|
2155
|
+
const search = (params.search ?? '').trim().toLowerCase();
|
|
2156
|
+
const maxResults = Math.min(Math.max(params.maxResults ?? 25, 1), 100);
|
|
2157
|
+
const offset = Math.max(params.offset ?? 0, 0);
|
|
2158
|
+
try {
|
|
2159
|
+
await ArtifactMetadataEngine.Instance.Config(false, params.contextUser, params.provider);
|
|
2160
|
+
}
|
|
2161
|
+
catch {
|
|
2162
|
+
// Proceed even if metadata engine warmup falls back to raw fields
|
|
2163
|
+
}
|
|
2164
|
+
const rv = RunView.FromMetadataProvider(params.provider);
|
|
2165
|
+
const sqlFilters = [];
|
|
2166
|
+
const MAX_DIRECT_IN_IDS = 2500;
|
|
2167
|
+
const ID_IN_CHUNK_SIZE = 500;
|
|
2168
|
+
const appendChunkedIdInFilter = (ids) => {
|
|
2169
|
+
if (ids.length === 0 || ids.length > MAX_DIRECT_IN_IDS) {
|
|
2170
|
+
return false;
|
|
2171
|
+
}
|
|
2172
|
+
const chunks = [];
|
|
2173
|
+
for (let i = 0; i < ids.length; i += ID_IN_CHUNK_SIZE) {
|
|
2174
|
+
const slice = ids.slice(i, i + ID_IN_CHUNK_SIZE);
|
|
2175
|
+
chunks.push(`ID IN (${slice.map((id) => `'${EscapeSQLString(id)}'`).join(',')})`);
|
|
2176
|
+
}
|
|
2177
|
+
sqlFilters.push(chunks.length === 1 ? chunks[0] : `(${chunks.join(' OR ')})`);
|
|
2178
|
+
return true;
|
|
2179
|
+
};
|
|
2180
|
+
let readableIdsInMemoryFilter = null;
|
|
2181
|
+
try {
|
|
2182
|
+
if (collectionId) {
|
|
2183
|
+
const colCheck = await this.CheckCollectionPermission(params.provider, params.contextUser, collectionId, 'read');
|
|
2184
|
+
if (!colCheck.allowed) {
|
|
2185
|
+
return { success: false, artifacts: [], errorMessage: colCheck.reason };
|
|
2186
|
+
}
|
|
2187
|
+
const colArtRes = await rv.RunView({
|
|
2188
|
+
EntityName: 'MJ: Collection Artifacts',
|
|
2189
|
+
ExtraFilter: `CollectionID='${EscapeSQLString(collectionId)}'`,
|
|
2190
|
+
Fields: ['ArtifactVersionID'],
|
|
2191
|
+
IgnoreMaxRows: true,
|
|
2192
|
+
SkipTotalRowCount: true,
|
|
2193
|
+
ResultType: 'simple',
|
|
2194
|
+
}, params.contextUser);
|
|
2195
|
+
if (!colArtRes.Success) {
|
|
2196
|
+
const errMsg = colArtRes.ErrorMessage || `Failed querying collection '${collectionId}' artifacts.`;
|
|
2197
|
+
LogError(`GovernedArtifactService.ListWorkspaceArtifacts: ${errMsg}`);
|
|
2198
|
+
return { success: false, artifacts: [], errorMessage: errMsg };
|
|
2199
|
+
}
|
|
2200
|
+
const versionIds = Array.from(new Set((colArtRes.Results ?? [])
|
|
2201
|
+
.map((r) => (r.ArtifactVersionID ?? '').trim())
|
|
2202
|
+
.filter((id) => IsValidUUID(id))));
|
|
2203
|
+
if (versionIds.length === 0) {
|
|
2204
|
+
return { success: true, artifacts: [] };
|
|
2205
|
+
}
|
|
2206
|
+
const colArtifactIdSet = new Set();
|
|
2207
|
+
const colArtifactIds = [];
|
|
2208
|
+
for (let i = 0; i < versionIds.length; i += ID_IN_CHUNK_SIZE) {
|
|
2209
|
+
const verSlice = versionIds.slice(i, i + ID_IN_CHUNK_SIZE);
|
|
2210
|
+
const verInList = verSlice.map((id) => `'${EscapeSQLString(id)}'`).join(',');
|
|
2211
|
+
const verLookup = await rv.RunView({
|
|
2212
|
+
EntityName: 'MJ: Artifact Versions',
|
|
2213
|
+
ExtraFilter: `ID IN (${verInList})`,
|
|
2214
|
+
Fields: ['ArtifactID'],
|
|
2215
|
+
IgnoreMaxRows: true,
|
|
2216
|
+
SkipTotalRowCount: true,
|
|
2217
|
+
ResultType: 'simple',
|
|
2218
|
+
}, params.contextUser);
|
|
2219
|
+
if (!verLookup.Success) {
|
|
2220
|
+
const errMsg = verLookup.ErrorMessage || `Failed querying version headers for collection '${collectionId}'.`;
|
|
2221
|
+
LogError(`GovernedArtifactService.ListWorkspaceArtifacts: ${errMsg}`);
|
|
2222
|
+
return { success: false, artifacts: [], errorMessage: errMsg };
|
|
2223
|
+
}
|
|
2224
|
+
for (const row of verLookup.Results ?? []) {
|
|
2225
|
+
const aid = (row.ArtifactID ?? '').trim();
|
|
2226
|
+
if (IsValidUUID(aid)) {
|
|
2227
|
+
const norm = NormalizeUUID(aid);
|
|
2228
|
+
if (!colArtifactIdSet.has(norm)) {
|
|
2229
|
+
colArtifactIdSet.add(norm);
|
|
2230
|
+
colArtifactIds.push(aid);
|
|
2231
|
+
}
|
|
2232
|
+
}
|
|
2233
|
+
}
|
|
2234
|
+
}
|
|
2235
|
+
if (colArtifactIds.length === 0) {
|
|
2236
|
+
return { success: true, artifacts: [] };
|
|
2237
|
+
}
|
|
2238
|
+
if (!appendChunkedIdInFilter(colArtifactIds)) {
|
|
2239
|
+
readableIdsInMemoryFilter = colArtifactIdSet;
|
|
2240
|
+
}
|
|
2241
|
+
}
|
|
2242
|
+
else {
|
|
2243
|
+
const readableIds = await ArtifactPermissionEngine.Instance.TryBuildReadableArtifactIdSet(params.provider, params.contextUser);
|
|
2244
|
+
if (!readableIds) {
|
|
2245
|
+
const errMsg = `Failed resolving readable workspace artifacts for user '${params.contextUser.ID}'.`;
|
|
2246
|
+
LogError(`GovernedArtifactService.ListWorkspaceArtifacts: ${errMsg}`);
|
|
2247
|
+
return { success: false, artifacts: [], errorMessage: errMsg };
|
|
2248
|
+
}
|
|
2249
|
+
if (readableIds.size === 0) {
|
|
2250
|
+
return { success: true, artifacts: [] };
|
|
2251
|
+
}
|
|
2252
|
+
if (!appendChunkedIdInFilter(Array.from(readableIds))) {
|
|
2253
|
+
// Above MAX_DIRECT_IN_IDS, rely on ArtifactPreRunViewHook SQL EXISTS scoping + in-memory check (`S-g`).
|
|
2254
|
+
readableIdsInMemoryFilter = readableIds;
|
|
2255
|
+
}
|
|
2256
|
+
}
|
|
2257
|
+
if (search) {
|
|
2258
|
+
sqlFilters.push(`Name LIKE '%${EscapeSQLString(this.escapeSqlLike(search))}%'`);
|
|
2259
|
+
}
|
|
2260
|
+
if (typeFilter) {
|
|
2261
|
+
const canonicalName = this.NormalizeArtifactTypeName(params.typeFilter);
|
|
2262
|
+
const types = ArtifactMetadataEngine.Instance.ArtifactTypes ?? [];
|
|
2263
|
+
const matchedTypeNames = types
|
|
2264
|
+
.filter((t) => t.Name.toLowerCase().includes(typeFilter) ||
|
|
2265
|
+
t.Name.toLowerCase() === normalizedTypeFilter)
|
|
2266
|
+
.map((t) => t.Name);
|
|
2267
|
+
if (matchedTypeNames.length > 0) {
|
|
2268
|
+
sqlFilters.push(`Type IN (${Array.from(new Set(matchedTypeNames))
|
|
2269
|
+
.map((n) => `'${EscapeSQLString(n)}'`)
|
|
2270
|
+
.join(',')})`);
|
|
2271
|
+
}
|
|
2272
|
+
else {
|
|
2273
|
+
const escapedLike = EscapeSQLString(this.escapeSqlLike(typeFilter));
|
|
2274
|
+
if (canonicalName.toLowerCase() !== typeFilter) {
|
|
2275
|
+
sqlFilters.push(`(Type LIKE '%${escapedLike}%' OR Type='${EscapeSQLString(canonicalName)}')`);
|
|
2276
|
+
}
|
|
2277
|
+
else {
|
|
2278
|
+
sqlFilters.push(`Type LIKE '%${escapedLike}%'`);
|
|
2279
|
+
}
|
|
2280
|
+
}
|
|
2281
|
+
}
|
|
2282
|
+
const fetchLimit = Math.min(Math.max((offset + maxResults) * 2, maxResults), 500);
|
|
2283
|
+
const allArtResults = [];
|
|
2284
|
+
if (collectionId && readableIdsInMemoryFilter && readableIdsInMemoryFilter.size > MAX_DIRECT_IN_IDS) {
|
|
2285
|
+
// Collection exceeds single-query 2,500-ID cap (`N8`): query by 2,500-ID batches so items aren't silently truncated.
|
|
2286
|
+
const colIds = Array.from(readableIdsInMemoryFilter);
|
|
2287
|
+
const baseFilter = sqlFilters.length > 0 ? sqlFilters.join(' AND ') : '';
|
|
2288
|
+
for (let i = 0; i < colIds.length; i += MAX_DIRECT_IN_IDS) {
|
|
2289
|
+
const batch = colIds.slice(i, i + MAX_DIRECT_IN_IDS);
|
|
2290
|
+
const batchOrChunks = [];
|
|
2291
|
+
for (let j = 0; j < batch.length; j += ID_IN_CHUNK_SIZE) {
|
|
2292
|
+
const slice = batch.slice(j, j + ID_IN_CHUNK_SIZE);
|
|
2293
|
+
batchOrChunks.push(`ID IN (${slice.map((id) => `'${EscapeSQLString(id)}'`).join(',')})`);
|
|
2294
|
+
}
|
|
2295
|
+
const batchIdClause = batchOrChunks.length === 1 ? batchOrChunks[0] : `(${batchOrChunks.join(' OR ')})`;
|
|
2296
|
+
const batchFilter = baseFilter ? `(${baseFilter}) AND ${batchIdClause}` : batchIdClause;
|
|
2297
|
+
const batchRes = await rv.RunView({
|
|
2298
|
+
EntityName: 'MJ: Artifacts',
|
|
2299
|
+
ExtraFilter: batchFilter,
|
|
2300
|
+
OrderBy: '__mj_UpdatedAt DESC',
|
|
2301
|
+
Fields: ['ID', 'Name', 'Description', 'Type', 'TypeID', 'UserID', '__mj_UpdatedAt'],
|
|
2302
|
+
IgnoreMaxRows: true,
|
|
2303
|
+
SkipTotalRowCount: true,
|
|
2304
|
+
ResultType: 'simple',
|
|
2305
|
+
}, params.contextUser);
|
|
2306
|
+
if (!batchRes.Success) {
|
|
2307
|
+
const errMsg = batchRes.ErrorMessage || 'Failed querying workspace artifacts batch.';
|
|
2308
|
+
LogError(`GovernedArtifactService.ListWorkspaceArtifacts: ${errMsg}`);
|
|
2309
|
+
return { success: false, artifacts: [], errorMessage: errMsg };
|
|
2310
|
+
}
|
|
2311
|
+
if (batchRes.Results) {
|
|
2312
|
+
allArtResults.push(...batchRes.Results);
|
|
2313
|
+
}
|
|
2314
|
+
}
|
|
2315
|
+
allArtResults.sort((a, b) => {
|
|
2316
|
+
const ta = a.__mj_UpdatedAt ? new Date(a.__mj_UpdatedAt).getTime() : 0;
|
|
2317
|
+
const tb = b.__mj_UpdatedAt ? new Date(b.__mj_UpdatedAt).getTime() : 0;
|
|
2318
|
+
return tb - ta;
|
|
2319
|
+
});
|
|
2320
|
+
}
|
|
2321
|
+
else {
|
|
2322
|
+
const artRes = await rv.RunView({
|
|
2323
|
+
EntityName: 'MJ: Artifacts',
|
|
2324
|
+
ExtraFilter: sqlFilters.join(' AND '),
|
|
2325
|
+
OrderBy: '__mj_UpdatedAt DESC',
|
|
2326
|
+
Fields: ['ID', 'Name', 'Description', 'Type', 'TypeID', 'UserID'],
|
|
2327
|
+
MaxRows: fetchLimit,
|
|
2328
|
+
SkipTotalRowCount: true,
|
|
2329
|
+
ResultType: 'simple',
|
|
2330
|
+
}, params.contextUser);
|
|
2331
|
+
if (!artRes.Success) {
|
|
2332
|
+
const errMsg = artRes.ErrorMessage || 'Failed querying workspace artifacts.';
|
|
2333
|
+
LogError(`GovernedArtifactService.ListWorkspaceArtifacts: ${errMsg}`);
|
|
2334
|
+
return { success: false, artifacts: [], errorMessage: errMsg };
|
|
2335
|
+
}
|
|
2336
|
+
if (artRes.Results) {
|
|
2337
|
+
allArtResults.push(...artRes.Results);
|
|
2338
|
+
}
|
|
2339
|
+
}
|
|
2340
|
+
const candidateArts = [];
|
|
2341
|
+
const seen = new Set();
|
|
2342
|
+
for (const row of allArtResults) {
|
|
2343
|
+
const id = (row.ID ?? '').trim();
|
|
2344
|
+
const norm = NormalizeUUID(id);
|
|
2345
|
+
if (readableIdsInMemoryFilter && !readableIdsInMemoryFilter.has(norm)) {
|
|
2346
|
+
continue;
|
|
2347
|
+
}
|
|
2348
|
+
if (id && !seen.has(norm)) {
|
|
2349
|
+
seen.add(norm);
|
|
2350
|
+
candidateArts.push(row);
|
|
2351
|
+
}
|
|
2352
|
+
}
|
|
2353
|
+
if (candidateArts.length === 0) {
|
|
2354
|
+
return { success: true, artifacts: [] };
|
|
2355
|
+
}
|
|
2356
|
+
// S6-3: Filter & paginate matching readable artifacts first so we only fetch the latest version
|
|
2357
|
+
// (never historical Content blobs) for the paginated result page, logging any failed chunks.
|
|
2358
|
+
const pageEntries = [];
|
|
2359
|
+
let matchedCount = 0;
|
|
2360
|
+
for (const art of candidateArts) {
|
|
2361
|
+
if (pageEntries.length >= maxResults)
|
|
2362
|
+
break;
|
|
2363
|
+
const artName = (art.Name ?? 'Untitled Artifact').trim();
|
|
2364
|
+
const typeEntity = art.Type
|
|
2365
|
+
? ArtifactMetadataEngine.Instance.FindArtifactType(art.Type)
|
|
2366
|
+
: undefined;
|
|
2367
|
+
const typeName = (art.Type ?? typeEntity?.Name ?? 'Document').trim();
|
|
2368
|
+
const stTypeLower = typeName.toLowerCase();
|
|
2369
|
+
if (typeFilter && !stTypeLower.includes(typeFilter) && stTypeLower !== normalizedTypeFilter)
|
|
2370
|
+
continue;
|
|
2371
|
+
if (search && !artName.toLowerCase().includes(search))
|
|
2372
|
+
continue;
|
|
2373
|
+
const perms = await ArtifactPermissionEngine.Instance.ResolvePermissions(params.provider, art.ID, params.contextUser);
|
|
2374
|
+
if (!perms.CanRead)
|
|
2375
|
+
continue;
|
|
2376
|
+
matchedCount++;
|
|
2377
|
+
if (matchedCount <= offset)
|
|
2378
|
+
continue;
|
|
2379
|
+
pageEntries.push({
|
|
2380
|
+
art,
|
|
2381
|
+
artName,
|
|
2382
|
+
typeName,
|
|
2383
|
+
typeEntity: typeEntity ?? undefined,
|
|
2384
|
+
canEdit: perms.CanEdit,
|
|
2385
|
+
});
|
|
2386
|
+
}
|
|
2387
|
+
if (pageEntries.length === 0) {
|
|
2388
|
+
return { success: true, artifacts: [] };
|
|
2389
|
+
}
|
|
2390
|
+
// 1. Fetch lightweight version headers (no Content/Configuration blobs) to find each artifact's latest Version ID
|
|
2391
|
+
const latestMetaByArtId = new Map();
|
|
2392
|
+
const VER_CHUNK_SIZE = 500;
|
|
2393
|
+
for (let i = 0; i < pageEntries.length; i += VER_CHUNK_SIZE) {
|
|
2394
|
+
const chunkIn = pageEntries
|
|
2395
|
+
.slice(i, i + VER_CHUNK_SIZE)
|
|
2396
|
+
.map((e) => `'${EscapeSQLString(e.art.ID)}'`)
|
|
2397
|
+
.join(',');
|
|
2398
|
+
const metaRes = await rv.RunView({
|
|
2399
|
+
EntityName: 'MJ: Artifact Versions',
|
|
2400
|
+
ExtraFilter: `ArtifactID IN (${chunkIn})`,
|
|
2401
|
+
OrderBy: 'VersionNumber DESC',
|
|
2402
|
+
Fields: ['ID', 'ArtifactID', 'VersionNumber'],
|
|
2403
|
+
IgnoreMaxRows: true,
|
|
2404
|
+
SkipTotalRowCount: true,
|
|
2405
|
+
ResultType: 'simple',
|
|
2406
|
+
}, params.contextUser);
|
|
2407
|
+
if (!metaRes.Success) {
|
|
2408
|
+
LogError(`GovernedArtifactService.ListWorkspaceArtifacts: failed to load version headers for chunk: ${metaRes.ErrorMessage || 'unknown error'}`);
|
|
2409
|
+
continue;
|
|
2410
|
+
}
|
|
2411
|
+
for (const row of metaRes.Results ?? []) {
|
|
2412
|
+
const normArt = NormalizeUUID(row.ArtifactID);
|
|
2413
|
+
const verNum = row.VersionNumber ?? 0;
|
|
2414
|
+
const existing = latestMetaByArtId.get(normArt);
|
|
2415
|
+
if (!existing || verNum > existing.VersionNumber) {
|
|
2416
|
+
latestMetaByArtId.set(normArt, { ID: row.ID, VersionNumber: verNum });
|
|
2417
|
+
}
|
|
2418
|
+
}
|
|
2419
|
+
}
|
|
2420
|
+
// 2. Fetch full Content/Configuration ONLY for those latest version IDs
|
|
2421
|
+
const latestVersionByArtId = new Map();
|
|
2422
|
+
const latestVersionIds = Array.from(latestMetaByArtId.values()).map((m) => m.ID);
|
|
2423
|
+
for (let i = 0; i < latestVersionIds.length; i += VER_CHUNK_SIZE) {
|
|
2424
|
+
const idIn = latestVersionIds
|
|
2425
|
+
.slice(i, i + VER_CHUNK_SIZE)
|
|
2426
|
+
.map((id) => `'${EscapeSQLString(id)}'`)
|
|
2427
|
+
.join(',');
|
|
2428
|
+
const batchVerRes = await rv.RunView({
|
|
2429
|
+
EntityName: 'MJ: Artifact Versions',
|
|
2430
|
+
ExtraFilter: `ID IN (${idIn})`,
|
|
2431
|
+
Fields: ['ID', 'ArtifactID', 'VersionNumber', 'Name', 'ContentMode', 'Content', 'Configuration', 'MimeType'],
|
|
2432
|
+
MaxRows: latestVersionIds.length,
|
|
2433
|
+
SkipTotalRowCount: true,
|
|
2434
|
+
ResultType: 'simple',
|
|
2435
|
+
}, params.contextUser);
|
|
2436
|
+
if (!batchVerRes.Success) {
|
|
2437
|
+
LogError(`GovernedArtifactService.ListWorkspaceArtifacts: failed to load latest version content for chunk: ${batchVerRes.ErrorMessage || 'unknown error'}`);
|
|
2438
|
+
continue;
|
|
2439
|
+
}
|
|
2440
|
+
for (const v of batchVerRes.Results ?? []) {
|
|
2441
|
+
latestVersionByArtId.set(NormalizeUUID(v.ArtifactID), v);
|
|
2442
|
+
}
|
|
2443
|
+
}
|
|
2444
|
+
const items = [];
|
|
2445
|
+
const liveReader = GetArtifactLiveContentReaderHook();
|
|
2446
|
+
for (const entry of pageEntries) {
|
|
2447
|
+
const { art, artName, typeName, typeEntity, canEdit } = entry;
|
|
2448
|
+
const ver = latestVersionByArtId.get(NormalizeUUID(art.ID));
|
|
2449
|
+
let contentStr = ver?.Content ?? null;
|
|
2450
|
+
if (ver?.ContentMode === 'File' && ver?.Configuration) {
|
|
2451
|
+
contentStr = ver.Configuration;
|
|
2452
|
+
}
|
|
2453
|
+
if (liveReader) {
|
|
2454
|
+
try {
|
|
2455
|
+
const liveSnap = await liveReader(art.ID, params.contextUser);
|
|
2456
|
+
if (liveSnap && typeof liveSnap.Content === 'string') {
|
|
2457
|
+
contentStr = liveSnap.Content;
|
|
2458
|
+
}
|
|
2459
|
+
}
|
|
2460
|
+
catch {
|
|
2461
|
+
// Non-fatal fallback to DB snapshot
|
|
2462
|
+
}
|
|
2463
|
+
}
|
|
2464
|
+
const displayName = (ver?.Name ?? artName).trim();
|
|
2465
|
+
const digest = ArtifactSynthesisEngine.Instance.ExtractSourceDigest({
|
|
2466
|
+
ArtifactID: art.ID,
|
|
2467
|
+
Name: displayName,
|
|
2468
|
+
ArtifactType: typeName,
|
|
2469
|
+
VersionNumber: ver?.VersionNumber ?? 1,
|
|
2470
|
+
ContentMode: ver?.ContentMode === 'File' ? 'File' : 'Text',
|
|
2471
|
+
Content: contentStr,
|
|
2472
|
+
Configuration: ver?.Configuration ?? null,
|
|
2473
|
+
Description: art.Description ?? null,
|
|
2474
|
+
MimeType: ver?.MimeType ?? typeEntity?.ContentType ?? null,
|
|
2475
|
+
}, 1200);
|
|
2476
|
+
items.push({
|
|
2477
|
+
artifactId: art.ID,
|
|
2478
|
+
versionId: ver?.ID,
|
|
2479
|
+
versionNumber: ver?.VersionNumber ?? undefined,
|
|
2480
|
+
name: displayName,
|
|
2481
|
+
typeName,
|
|
2482
|
+
typeEntity: typeEntity ?? undefined,
|
|
2483
|
+
driverClass: typeEntity?.DriverClass ?? undefined,
|
|
2484
|
+
canEdit,
|
|
2485
|
+
sections: digest.Sections,
|
|
2486
|
+
embeddedCharts: digest.EmbeddedCharts,
|
|
2487
|
+
summaryPreview: digest.SummaryText.slice(0, 400),
|
|
2488
|
+
});
|
|
2489
|
+
}
|
|
2490
|
+
return { success: true, artifacts: items };
|
|
2491
|
+
}
|
|
2492
|
+
catch (err) {
|
|
2493
|
+
const errMsg = err instanceof Error ? err.message : String(err);
|
|
2494
|
+
LogError(`GovernedArtifactService.ListWorkspaceArtifacts error: ${errMsg}`);
|
|
2495
|
+
return { success: false, artifacts: [], errorMessage: errMsg };
|
|
2496
|
+
}
|
|
2497
|
+
}
|
|
2498
|
+
resolveLibraryChain(typeName) {
|
|
2499
|
+
const engine = ArtifactMetadataEngine.Instance;
|
|
2500
|
+
if (!engine.ArtifactTypes?.length)
|
|
2501
|
+
return [];
|
|
2502
|
+
const typesById = IndexByUUID(engine.ArtifactTypes);
|
|
2503
|
+
const chain = [];
|
|
2504
|
+
const visited = new Set();
|
|
2505
|
+
let current = engine.FindArtifactType(typeName);
|
|
2506
|
+
while (current && !visited.has(current.ID)) {
|
|
2507
|
+
visited.add(current.ID);
|
|
2508
|
+
const className = current.ToolLibraryClass;
|
|
2509
|
+
if (className) {
|
|
2510
|
+
const lib = MJGlobal.Instance.ClassFactory.CreateInstance(BaseArtifactToolLibrary, className);
|
|
2511
|
+
if (lib)
|
|
2512
|
+
chain.push(lib);
|
|
2513
|
+
}
|
|
2514
|
+
current = current.ParentID ? typesById.Get(current.ParentID) : undefined;
|
|
2515
|
+
}
|
|
2516
|
+
return chain;
|
|
2517
|
+
}
|
|
2518
|
+
resolveLeafLibrary(typeName, toolLibraryClass) {
|
|
2519
|
+
if (toolLibraryClass) {
|
|
2520
|
+
const instance = MJGlobal.Instance.ClassFactory.CreateInstance(BaseArtifactToolLibrary, toolLibraryClass);
|
|
2521
|
+
if (instance)
|
|
2522
|
+
return instance;
|
|
2523
|
+
}
|
|
2524
|
+
const lower = (typeName ?? '').toLowerCase();
|
|
2525
|
+
// Order specific extensions & domain types ahead of generic substrings ('data', 'document')
|
|
2526
|
+
if (lower.includes('search')) {
|
|
2527
|
+
return new SearchResultSetToolLibrary();
|
|
2528
|
+
}
|
|
2529
|
+
if (lower.includes('csv')) {
|
|
2530
|
+
return new CSVToolLibrary();
|
|
2531
|
+
}
|
|
2532
|
+
if (lower.includes('pdf')) {
|
|
2533
|
+
const lib = MJGlobal.Instance.ClassFactory.CreateInstance(BaseArtifactToolLibrary, 'PDFToolLibrary');
|
|
2534
|
+
return lib ?? new PDFToolLibrary();
|
|
2535
|
+
}
|
|
2536
|
+
if (lower.includes('word') || lower.includes('docx')) {
|
|
2537
|
+
const lib = MJGlobal.Instance.ClassFactory.CreateInstance(BaseArtifactToolLibrary, 'DocxToolLibrary');
|
|
2538
|
+
return lib ?? new DocxToolLibrary();
|
|
2539
|
+
}
|
|
2540
|
+
if (lower.includes('excel') || lower.includes('xlsx') || lower.includes('spreadsheet') || lower.includes('sheet')) {
|
|
2541
|
+
const sheetLib = MJGlobal.Instance.ClassFactory.CreateInstance(BaseArtifactToolLibrary, 'SpreadsheetToolLibrary');
|
|
2542
|
+
return sheetLib ?? new SpreadsheetToolLibrary();
|
|
2543
|
+
}
|
|
2544
|
+
if (lower.includes('presentation') || lower.includes('slide') || lower.includes('deck')) {
|
|
2545
|
+
const slideLib = MJGlobal.Instance.ClassFactory.CreateInstance(BaseArtifactToolLibrary, 'SlideDeckToolLibrary');
|
|
2546
|
+
return slideLib ?? new SlideDeckToolLibrary();
|
|
2547
|
+
}
|
|
2548
|
+
if (lower.includes('whiteboard')) {
|
|
2549
|
+
const wbLib = MJGlobal.Instance.ClassFactory.CreateInstance(BaseArtifactToolLibrary, 'WhiteboardToolLibrary');
|
|
2550
|
+
return wbLib ?? new WhiteboardToolLibrary();
|
|
2551
|
+
}
|
|
2552
|
+
if (lower.includes('markdown')) {
|
|
2553
|
+
const docLib = MJGlobal.Instance.ClassFactory.CreateInstance(BaseArtifactToolLibrary, 'DocumentToolLibrary');
|
|
2554
|
+
return docLib ?? new DocumentToolLibrary();
|
|
2555
|
+
}
|
|
2556
|
+
if (lower.includes('json')) {
|
|
2557
|
+
return new JSONToolLibrary();
|
|
2558
|
+
}
|
|
2559
|
+
if (lower.includes('data') || lower.includes('snapshot')) {
|
|
2560
|
+
return new DataSnapshotToolLibrary();
|
|
2561
|
+
}
|
|
2562
|
+
if (lower.includes('document')) {
|
|
2563
|
+
const docLib = MJGlobal.Instance.ClassFactory.CreateInstance(BaseArtifactToolLibrary, 'DocumentToolLibrary');
|
|
2564
|
+
return docLib ?? new DocumentToolLibrary();
|
|
2565
|
+
}
|
|
2566
|
+
return new TextToolLibrary();
|
|
2567
|
+
}
|
|
2568
|
+
}
|
|
2569
|
+
//# sourceMappingURL=GovernedArtifactService.js.map
|