@memberjunction/ai-agents 6.2.2 → 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 +29 -6
- package/dist/AgentContextAssembler.d.ts +127 -0
- package/dist/AgentContextAssembler.d.ts.map +1 -0
- package/dist/AgentContextAssembler.js +482 -0
- package/dist/AgentContextAssembler.js.map +1 -0
- package/dist/AgentDataPreloader.d.ts +14 -3
- package/dist/AgentDataPreloader.d.ts.map +1 -1
- package/dist/AgentDataPreloader.js +147 -22
- 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/AgentFeedbackCoordinator.d.ts +169 -0
- package/dist/AgentFeedbackCoordinator.d.ts.map +1 -0
- package/dist/AgentFeedbackCoordinator.js +593 -0
- package/dist/AgentFeedbackCoordinator.js.map +1 -0
- 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/AgentStepDispatcher.d.ts +211 -0
- package/dist/AgentStepDispatcher.d.ts.map +1 -0
- package/dist/AgentStepDispatcher.js +729 -0
- package/dist/AgentStepDispatcher.js.map +1 -0
- package/dist/AgentTreeBudgetTracker.d.ts +163 -0
- package/dist/AgentTreeBudgetTracker.d.ts.map +1 -0
- package/dist/AgentTreeBudgetTracker.js +415 -0
- package/dist/AgentTreeBudgetTracker.js.map +1 -0
- package/dist/AgentWakeTriggerService.d.ts +41 -1
- package/dist/AgentWakeTriggerService.d.ts.map +1 -1
- package/dist/AgentWakeTriggerService.js +154 -8
- package/dist/AgentWakeTriggerService.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/MJAIAgentRequestEntityServer.d.ts +32 -1
- package/dist/MJAIAgentRequestEntityServer.d.ts.map +1 -1
- package/dist/MJAIAgentRequestEntityServer.js +105 -3
- package/dist/MJAIAgentRequestEntityServer.js.map +1 -1
- package/dist/SkillMarkdownConverter.d.ts +1 -1
- package/dist/SkillMarkdownConverter.d.ts.map +1 -1
- package/dist/SkillMarkdownConverter.js +8 -6
- 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 +5 -0
- package/dist/agent-pre-execution-rag.d.ts.map +1 -1
- package/dist/agent-pre-execution-rag.js +10 -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-prompt-params.d.ts +18 -0
- package/dist/agent-types/loop-agent-prompt-params.d.ts.map +1 -1
- package/dist/agent-types/loop-agent-prompt-params.js +2 -0
- package/dist/agent-types/loop-agent-prompt-params.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 +151 -137
- package/dist/base-agent.d.ts.map +1 -1
- package/dist/base-agent.js +727 -1550
- package/dist/base-agent.js.map +1 -1
- package/dist/catalog-narrowing.d.ts +112 -5
- package/dist/catalog-narrowing.d.ts.map +1 -1
- package/dist/catalog-narrowing.js +181 -6
- package/dist/catalog-narrowing.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 +17 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +17 -3
- 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/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/pipeline/operators.d.ts.map +1 -1
- package/dist/pipeline/operators.js +1 -1
- package/dist/pipeline/operators.js.map +1 -1
- package/dist/pipeline/pipeline-executor.d.ts +29 -1
- package/dist/pipeline/pipeline-executor.d.ts.map +1 -1
- package/dist/pipeline/pipeline-executor.js +159 -2
- package/dist/pipeline/pipeline-executor.js.map +1 -1
- package/dist/pipeline/pipeline.types.d.ts +19 -1
- package/dist/pipeline/pipeline.types.d.ts.map +1 -1
- package/dist/pipeline/template.d.ts +16 -0
- package/dist/pipeline/template.d.ts.map +1 -1
- package/dist/pipeline/template.js +55 -6
- 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/bridge-room-transcript-sink.d.ts.map +1 -1
- package/dist/realtime/bridge-room-transcript-sink.js +28 -1
- package/dist/realtime/bridge-room-transcript-sink.js.map +1 -1
- package/dist/realtime/media-channel-server.js +1 -1
- package/dist/realtime/media-channel-server.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 +209 -19
- package/dist/realtime/realtime-client-session-service.d.ts.map +1 -1
- package/dist/realtime/realtime-client-session-service.js +670 -41
- package/dist/realtime/realtime-client-session-service.js.map +1 -1
- package/dist/realtime/realtime-coagent-config.d.ts +26 -9
- package/dist/realtime/realtime-coagent-config.d.ts.map +1 -1
- package/dist/realtime/realtime-coagent-config.js +47 -60
- package/dist/realtime/realtime-coagent-config.js.map +1 -1
- package/dist/realtime/realtime-delegation-narrator.js +1 -1
- package/dist/realtime/realtime-delegation-narrator.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-session-runner.d.ts +2 -0
- package/dist/realtime/realtime-session-runner.d.ts.map +1 -1
- package/dist/realtime/realtime-session-runner.js +24 -3
- package/dist/realtime/realtime-session-runner.js.map +1 -1
- 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,1846 @@
|
|
|
1
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
2
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
3
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
4
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
|
+
};
|
|
7
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
8
|
+
import { RegisterClass } from '@memberjunction/global';
|
|
9
|
+
import { BaseArtifactToolLibrary, ResolveEmbeddedArtifactId, ResolveEmbeddedVersionId } from '@memberjunction/ai-core-plus';
|
|
10
|
+
import { CompileSafeUserRegex, DocumentLiveBlockEngine, IsSafeUserRegex } from '@memberjunction/core-entities';
|
|
11
|
+
import { EnsureNodeVmSafeRegexExecutorRegistered, ExecuteSafeRegexBatchWithRecovery } from './node-vm-safe-regex.js';
|
|
12
|
+
import { ExecuteStructuredLineGrep } from './grepHelper.js';
|
|
13
|
+
import { ExecuteArtifactCommentTool, ExecuteListSuggestionsTool, ExecuteProposeSuggestionTool, ExecuteReviewSuggestionTool, GetSharedCommentAndSuggestionToolDefinitions, ParseSuggestionAnchor, ValidateEmbeddedArtifactAccess } from './artifact-comment-suggestion-helper.js';
|
|
14
|
+
const TOOL_REGEX_BUDGET_MS = 150;
|
|
15
|
+
const BATCH_REGEX_MAX_MS = 40;
|
|
16
|
+
const MAX_BATCH_ITEMS = 512;
|
|
17
|
+
const MAX_BATCH_CHARS = 262_144;
|
|
18
|
+
const MAX_REGEX_INPUT_BYTES = 65_536;
|
|
19
|
+
const MAX_SAFE_UTF16_UNITS_FOR_64KB = 21_845;
|
|
20
|
+
const MAX_REPORTED_UNSEARCHABLE_BLOCKS = 25;
|
|
21
|
+
function exceedsRegexInputBytes(text) {
|
|
22
|
+
if (text.length <= MAX_SAFE_UTF16_UNITS_FOR_64KB) {
|
|
23
|
+
return false;
|
|
24
|
+
}
|
|
25
|
+
return Buffer.byteLength(text, 'utf8') > MAX_REGEX_INPUT_BYTES;
|
|
26
|
+
}
|
|
27
|
+
const VALID_DISPLAY_MODES = new Set([
|
|
28
|
+
'grid',
|
|
29
|
+
'cards',
|
|
30
|
+
'summary',
|
|
31
|
+
'table',
|
|
32
|
+
'chart',
|
|
33
|
+
'kpi'
|
|
34
|
+
]);
|
|
35
|
+
const VALID_CHART_TYPES = new Set([
|
|
36
|
+
'bar',
|
|
37
|
+
'line',
|
|
38
|
+
'pie',
|
|
39
|
+
'area'
|
|
40
|
+
]);
|
|
41
|
+
function toDisplayMode(value) {
|
|
42
|
+
if (typeof value !== 'string') {
|
|
43
|
+
return undefined;
|
|
44
|
+
}
|
|
45
|
+
const normalized = value.trim().toLowerCase();
|
|
46
|
+
return VALID_DISPLAY_MODES.has(normalized) ? normalized : undefined;
|
|
47
|
+
}
|
|
48
|
+
function toChartType(value) {
|
|
49
|
+
if (typeof value !== 'string') {
|
|
50
|
+
return undefined;
|
|
51
|
+
}
|
|
52
|
+
const normalized = value.trim().toLowerCase();
|
|
53
|
+
return VALID_CHART_TYPES.has(normalized) ? normalized : undefined;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Server-side and agent tool library for `Markdown Document` artifacts (`MJ Docs`, § 3.6 & § 4).
|
|
57
|
+
*
|
|
58
|
+
* Provides structured document inspection (`get_outline`, `get_section`, `get_blocks`, `search_blocks`,
|
|
59
|
+
* `grep`, `get_lines`) as well as revision-checked block mutations (`insert_block_after`, `replace_block`,
|
|
60
|
+
* `delete_block`, `move_block`, `duplicate_block`, `upsert_table`, `insert_live_block`, `embed_artifact_block`).
|
|
61
|
+
*/
|
|
62
|
+
let DocumentToolLibrary = class DocumentToolLibrary extends BaseArtifactToolLibrary {
|
|
63
|
+
constructor() {
|
|
64
|
+
super(...arguments);
|
|
65
|
+
/**
|
|
66
|
+
* Wall-clock budget, in milliseconds, for one regex `search_blocks` or `grep` call.
|
|
67
|
+
* Defaults to {@link TOOL_REGEX_BUDGET_MS}; tests that assert a complete search raise it so
|
|
68
|
+
* a loaded CI runner does not turn a timing margin into a failure.
|
|
69
|
+
*/
|
|
70
|
+
this.RegexBudgetMs = TOOL_REGEX_BUDGET_MS;
|
|
71
|
+
}
|
|
72
|
+
getSubclassToolList() {
|
|
73
|
+
return [
|
|
74
|
+
{
|
|
75
|
+
name: 'get_outline',
|
|
76
|
+
description: 'Returns the hierarchical heading outline of the Markdown document along with line ranges, word counts, and any embedded MJ live/artifact blocks.',
|
|
77
|
+
inputSchema: {
|
|
78
|
+
type: 'object',
|
|
79
|
+
properties: {},
|
|
80
|
+
required: []
|
|
81
|
+
}
|
|
82
|
+
},
|
|
83
|
+
{
|
|
84
|
+
name: 'get_section',
|
|
85
|
+
description: 'Returns the Markdown content of a specific section identified by heading title (case-insensitive substring) or heading blockId.',
|
|
86
|
+
inputSchema: {
|
|
87
|
+
type: 'object',
|
|
88
|
+
properties: {
|
|
89
|
+
heading: { type: 'string', description: 'Heading title or substring to match.' },
|
|
90
|
+
blockId: { type: 'string', description: 'Optional exact blockId of the heading.' }
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
},
|
|
94
|
+
{
|
|
95
|
+
name: 'get_blocks',
|
|
96
|
+
description: 'Parses the document into logical blocks (headings, paragraphs, tables, code fences, callouts, lists, and :::mj-block directives) with blockId and revisionHash.',
|
|
97
|
+
inputSchema: {
|
|
98
|
+
type: 'object',
|
|
99
|
+
properties: {
|
|
100
|
+
kind: {
|
|
101
|
+
type: 'string',
|
|
102
|
+
description: 'Optional filter by block kind (heading, paragraph, table, code, callout, list, mj-block).'
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
},
|
|
107
|
+
{
|
|
108
|
+
name: 'search_blocks',
|
|
109
|
+
description: 'Searches logical blocks in the document by case-insensitive literal substring (default false for use_regex) or by regular expression when use_regex is true.',
|
|
110
|
+
inputSchema: {
|
|
111
|
+
type: 'object',
|
|
112
|
+
properties: {
|
|
113
|
+
query: {
|
|
114
|
+
type: 'string',
|
|
115
|
+
description: 'Plain-text literal substring (default) or case-insensitive regex pattern (when use_regex is true) to find.'
|
|
116
|
+
},
|
|
117
|
+
use_regex: {
|
|
118
|
+
type: 'boolean',
|
|
119
|
+
description: 'Optional (default false): set true to evaluate query as a regular expression; defaults to false for literal substring matching with no 64 KB cap.'
|
|
120
|
+
},
|
|
121
|
+
useRegex: {
|
|
122
|
+
type: 'boolean',
|
|
123
|
+
description: 'Alias for use_regex (default false).'
|
|
124
|
+
}
|
|
125
|
+
},
|
|
126
|
+
required: ['query']
|
|
127
|
+
}
|
|
128
|
+
},
|
|
129
|
+
{
|
|
130
|
+
name: 'grep',
|
|
131
|
+
description: 'Search lines in the document by case-insensitive literal substring (default false for use_regex) or by regular expression when use_regex is true. Returns a stable result object with matching lines and line numbers.',
|
|
132
|
+
inputSchema: {
|
|
133
|
+
type: 'object',
|
|
134
|
+
properties: {
|
|
135
|
+
pattern: {
|
|
136
|
+
type: 'string',
|
|
137
|
+
description: 'Literal text substring (default) or regex pattern (when use_regex/useRegex is true) to search for.'
|
|
138
|
+
},
|
|
139
|
+
flags: { type: 'string', description: 'Optional regex flags when use_regex is true (e.g., "i" for case-insensitive).' },
|
|
140
|
+
case_sensitive: {
|
|
141
|
+
type: 'boolean',
|
|
142
|
+
description: 'Case-sensitive matching. Defaults to false (case-insensitive) for literal search; when use_regex is true, defaults to regex flags (case-sensitive unless flags includes "i", and explicit case_sensitive overrides flags).'
|
|
143
|
+
},
|
|
144
|
+
caseSensitive: {
|
|
145
|
+
type: 'boolean',
|
|
146
|
+
description: 'Alias for case_sensitive (default false).'
|
|
147
|
+
},
|
|
148
|
+
use_regex: {
|
|
149
|
+
type: 'boolean',
|
|
150
|
+
description: 'Optional (default false): set true to evaluate pattern as a regular expression instead of a literal substring.'
|
|
151
|
+
},
|
|
152
|
+
useRegex: {
|
|
153
|
+
type: 'boolean',
|
|
154
|
+
description: 'Alias for use_regex (default false): set true to evaluate pattern as a regular expression instead of a literal substring.'
|
|
155
|
+
}
|
|
156
|
+
},
|
|
157
|
+
required: ['pattern']
|
|
158
|
+
}
|
|
159
|
+
},
|
|
160
|
+
{
|
|
161
|
+
name: 'get_lines',
|
|
162
|
+
description: 'Return lines from `start` (0-based) for `count` lines.',
|
|
163
|
+
inputSchema: {
|
|
164
|
+
type: 'object',
|
|
165
|
+
properties: {
|
|
166
|
+
start: { type: 'number', description: 'Start line number (0-based).' },
|
|
167
|
+
count: { type: 'number', description: 'Number of lines to return.' }
|
|
168
|
+
},
|
|
169
|
+
required: ['start', 'count']
|
|
170
|
+
}
|
|
171
|
+
},
|
|
172
|
+
{
|
|
173
|
+
name: 'insert_block_after',
|
|
174
|
+
description: 'Inserts a new Markdown block after `afterBlockId` (or at the end of the document if `afterBlockId` is omitted). Returns `updatedContent` and the new `revisionHash`.',
|
|
175
|
+
inputSchema: {
|
|
176
|
+
type: 'object',
|
|
177
|
+
properties: {
|
|
178
|
+
afterBlockId: {
|
|
179
|
+
type: 'string',
|
|
180
|
+
description: 'Block ID after which to insert. Use "START" to insert at the top.'
|
|
181
|
+
},
|
|
182
|
+
markdown: { type: 'string', description: 'Markdown content of the new block.' },
|
|
183
|
+
newBlockId: { type: 'string', description: 'Optional explicit block ID to stamp on the block.' },
|
|
184
|
+
expectedRevisionHash: {
|
|
185
|
+
type: 'string',
|
|
186
|
+
description: 'Optional SHA-256 revision hash for optimistic concurrency checking.'
|
|
187
|
+
}
|
|
188
|
+
},
|
|
189
|
+
required: ['markdown']
|
|
190
|
+
}
|
|
191
|
+
},
|
|
192
|
+
{
|
|
193
|
+
name: 'replace_block',
|
|
194
|
+
description: 'Replaces the Markdown content of the block identified by `blockId`. Supports optimistic concurrency via `expectedRevisionHash`.',
|
|
195
|
+
inputSchema: {
|
|
196
|
+
type: 'object',
|
|
197
|
+
properties: {
|
|
198
|
+
blockId: { type: 'string', description: 'Target blockId to replace.' },
|
|
199
|
+
markdown: { type: 'string', description: 'Replacement Markdown content.' },
|
|
200
|
+
expectedRevisionHash: {
|
|
201
|
+
type: 'string',
|
|
202
|
+
description: 'Optional SHA-256 revision hash of the document prior to edit.'
|
|
203
|
+
}
|
|
204
|
+
},
|
|
205
|
+
required: ['blockId', 'markdown']
|
|
206
|
+
}
|
|
207
|
+
},
|
|
208
|
+
{
|
|
209
|
+
name: 'delete_block',
|
|
210
|
+
description: 'Deletes the block identified by `blockId` from the document.',
|
|
211
|
+
inputSchema: {
|
|
212
|
+
type: 'object',
|
|
213
|
+
properties: {
|
|
214
|
+
blockId: { type: 'string', description: 'Target blockId to delete.' },
|
|
215
|
+
expectedRevisionHash: {
|
|
216
|
+
type: 'string',
|
|
217
|
+
description: 'Optional SHA-256 revision hash of the document prior to edit.'
|
|
218
|
+
}
|
|
219
|
+
},
|
|
220
|
+
required: ['blockId']
|
|
221
|
+
}
|
|
222
|
+
},
|
|
223
|
+
{
|
|
224
|
+
name: 'upsert_table',
|
|
225
|
+
description: 'Creates or replaces a GitHub-Flavored Markdown table with `headers` and `rows` at `blockId` or after `afterBlockId`.',
|
|
226
|
+
inputSchema: {
|
|
227
|
+
type: 'object',
|
|
228
|
+
properties: {
|
|
229
|
+
headers: {
|
|
230
|
+
type: 'array',
|
|
231
|
+
items: { type: 'string' },
|
|
232
|
+
description: 'Column header labels.'
|
|
233
|
+
},
|
|
234
|
+
rows: {
|
|
235
|
+
type: 'array',
|
|
236
|
+
items: { type: 'array', items: { type: 'string' } },
|
|
237
|
+
description: '2D array of row cells.'
|
|
238
|
+
},
|
|
239
|
+
blockId: { type: 'string', description: 'Existing table blockId to replace.' },
|
|
240
|
+
afterBlockId: { type: 'string', description: 'BlockId after which to insert a new table.' },
|
|
241
|
+
alignments: {
|
|
242
|
+
type: 'array',
|
|
243
|
+
items: { type: 'string', enum: ['left', 'center', 'right'] },
|
|
244
|
+
description: 'Optional column alignments ("left", "center", or "right") matching headers.'
|
|
245
|
+
},
|
|
246
|
+
expectedRevisionHash: {
|
|
247
|
+
type: 'string',
|
|
248
|
+
description: 'Optional SHA-256 revision hash of the document prior to edit.'
|
|
249
|
+
}
|
|
250
|
+
},
|
|
251
|
+
required: ['headers', 'rows']
|
|
252
|
+
}
|
|
253
|
+
},
|
|
254
|
+
{
|
|
255
|
+
name: 'insert_live_block',
|
|
256
|
+
description: 'Inserts a live MJ block (`EntityView`, `SavedQuery`, `DashboardPart`, or `InteractiveComponent`) serialized as a `:::mj-block` directive.',
|
|
257
|
+
inputSchema: {
|
|
258
|
+
type: 'object',
|
|
259
|
+
properties: {
|
|
260
|
+
blockId: { type: 'string', description: 'Unique ID for the block.' },
|
|
261
|
+
kind: {
|
|
262
|
+
type: 'string',
|
|
263
|
+
enum: ['EntityView', 'SavedQuery', 'DashboardPart', 'InteractiveComponent'],
|
|
264
|
+
description: 'Kind of MJ live block.'
|
|
265
|
+
},
|
|
266
|
+
title: { type: 'string', description: 'Display title for the block.' },
|
|
267
|
+
entityName: { type: 'string', description: 'Entity name when kind is EntityView.' },
|
|
268
|
+
viewId: { type: 'string', description: 'Saved UserView ID when kind is EntityView.' },
|
|
269
|
+
viewName: { type: 'string', description: 'Saved UserView Name when kind is EntityView.' },
|
|
270
|
+
extraFilter: { type: 'string', description: 'Optional ExtraFilter when kind is EntityView.' },
|
|
271
|
+
fields: {
|
|
272
|
+
type: 'array',
|
|
273
|
+
items: { type: 'string' },
|
|
274
|
+
description: 'Field names to display when kind is EntityView.'
|
|
275
|
+
},
|
|
276
|
+
maxRows: { type: 'number', description: 'Maximum rows to fetch in live mode.' },
|
|
277
|
+
displayMode: {
|
|
278
|
+
type: 'string',
|
|
279
|
+
enum: ['grid', 'cards', 'summary', 'table', 'chart', 'kpi'],
|
|
280
|
+
description: 'Presentation mode for EntityView or SavedQuery blocks.'
|
|
281
|
+
},
|
|
282
|
+
chartType: {
|
|
283
|
+
type: 'string',
|
|
284
|
+
enum: ['bar', 'line', 'pie', 'area'],
|
|
285
|
+
description: 'Chart visualization type when displayMode is "chart".'
|
|
286
|
+
},
|
|
287
|
+
categoryField: {
|
|
288
|
+
type: 'string',
|
|
289
|
+
description: 'Category field name when displayMode is "chart".'
|
|
290
|
+
},
|
|
291
|
+
valueFields: {
|
|
292
|
+
type: 'array',
|
|
293
|
+
items: { type: 'string' },
|
|
294
|
+
description: 'Numeric value field names when displayMode is "chart".'
|
|
295
|
+
},
|
|
296
|
+
queryId: { type: 'string', description: 'Saved Query ID when kind is SavedQuery.' },
|
|
297
|
+
queryName: { type: 'string', description: 'Saved Query Name when kind is SavedQuery.' },
|
|
298
|
+
parameters: {
|
|
299
|
+
type: 'object',
|
|
300
|
+
description: 'Query parameters when kind is SavedQuery.'
|
|
301
|
+
},
|
|
302
|
+
dashboardId: { type: 'string', description: 'Dashboard ID when kind is DashboardPart.' },
|
|
303
|
+
componentId: { type: 'string', description: 'Component ID when kind is InteractiveComponent.' },
|
|
304
|
+
afterBlockId: { type: 'string', description: 'Optional blockId after which to insert.' },
|
|
305
|
+
expectedRevisionHash: {
|
|
306
|
+
type: 'string',
|
|
307
|
+
description: 'Optional SHA-256 revision hash of the document prior to edit.'
|
|
308
|
+
}
|
|
309
|
+
},
|
|
310
|
+
required: ['kind']
|
|
311
|
+
}
|
|
312
|
+
},
|
|
313
|
+
{
|
|
314
|
+
name: 'embed_artifact_block',
|
|
315
|
+
description: 'Embeds an OLE Artifact block (`Kind = "Artifact"`, e.g. a Whiteboard, Presentation, or Spreadsheet) into the document as a `:::mj-block` directive.',
|
|
316
|
+
inputSchema: {
|
|
317
|
+
type: 'object',
|
|
318
|
+
properties: {
|
|
319
|
+
blockId: { type: 'string', description: 'Optional unique block ID.' },
|
|
320
|
+
artifactId: {
|
|
321
|
+
type: 'string',
|
|
322
|
+
description: 'Target MJ: Artifacts UUID (or session short-ID like "B", "D", which is automatically resolved to its UUID).'
|
|
323
|
+
},
|
|
324
|
+
artifactType: {
|
|
325
|
+
type: 'string',
|
|
326
|
+
description: 'Artifact type name (e.g., "Whiteboard", "Presentation", "Excel Spreadsheet").'
|
|
327
|
+
},
|
|
328
|
+
title: { type: 'string', description: 'Optional caption/title for the embedded artifact.' },
|
|
329
|
+
embedMode: {
|
|
330
|
+
type: 'string',
|
|
331
|
+
enum: ['Inline', 'Link'],
|
|
332
|
+
description: '"Inline" for delegated child artifacts or "Link" for standalone artifacts.'
|
|
333
|
+
},
|
|
334
|
+
versionId: {
|
|
335
|
+
type: 'string',
|
|
336
|
+
description: 'Optional pinned MJ: Artifact Versions UUID (or session short ID such as "E"; omit to track latest version).'
|
|
337
|
+
},
|
|
338
|
+
sheetId: {
|
|
339
|
+
type: 'string',
|
|
340
|
+
description: 'Optional worksheet ID when embedding a Spreadsheet range or chart.'
|
|
341
|
+
},
|
|
342
|
+
sheetName: {
|
|
343
|
+
type: 'string',
|
|
344
|
+
description: 'Optional worksheet name when embedding a Spreadsheet range or chart.'
|
|
345
|
+
},
|
|
346
|
+
range: {
|
|
347
|
+
type: 'string',
|
|
348
|
+
description: 'Optional A1 cell range (e.g. "A1:D10") when embedding a Spreadsheet range.'
|
|
349
|
+
},
|
|
350
|
+
chartId: {
|
|
351
|
+
type: 'string',
|
|
352
|
+
description: 'Optional chart ID when embedding a chart from a Spreadsheet artifact.'
|
|
353
|
+
},
|
|
354
|
+
displayMode: {
|
|
355
|
+
type: 'string',
|
|
356
|
+
enum: ['grid', 'cards', 'summary', 'table', 'chart', 'kpi'],
|
|
357
|
+
description: 'Optional presentation layout mode for embedded range/chart previews.'
|
|
358
|
+
},
|
|
359
|
+
afterBlockId: { type: 'string', description: 'Optional blockId after which to insert.' },
|
|
360
|
+
replaceBlockId: {
|
|
361
|
+
type: 'string',
|
|
362
|
+
description: 'Optional existing blockId to replace instead of inserting a new block.'
|
|
363
|
+
},
|
|
364
|
+
expectedRevisionHash: {
|
|
365
|
+
type: 'string',
|
|
366
|
+
description: 'Optional SHA-256 revision hash of the document prior to edit.'
|
|
367
|
+
}
|
|
368
|
+
},
|
|
369
|
+
required: ['artifactId']
|
|
370
|
+
}
|
|
371
|
+
},
|
|
372
|
+
{
|
|
373
|
+
name: 'move_block',
|
|
374
|
+
description: 'Moves an existing block (`blockId`) to a new position after `afterBlockId` (or `"START"` / end of document).',
|
|
375
|
+
inputSchema: {
|
|
376
|
+
type: 'object',
|
|
377
|
+
properties: {
|
|
378
|
+
blockId: { type: 'string', description: 'Target blockId to move.' },
|
|
379
|
+
afterBlockId: {
|
|
380
|
+
type: 'string',
|
|
381
|
+
description: 'Block ID after which to move the block, "START" for top, or omit for end.'
|
|
382
|
+
},
|
|
383
|
+
expectedRevisionHash: {
|
|
384
|
+
type: 'string',
|
|
385
|
+
description: 'Optional SHA-256 revision hash of the document prior to edit.'
|
|
386
|
+
}
|
|
387
|
+
},
|
|
388
|
+
required: ['blockId']
|
|
389
|
+
}
|
|
390
|
+
},
|
|
391
|
+
{
|
|
392
|
+
name: 'duplicate_block',
|
|
393
|
+
description: 'Duplicates an existing block (`blockId`) with a fresh unique block ID and inserts the copy.',
|
|
394
|
+
inputSchema: {
|
|
395
|
+
type: 'object',
|
|
396
|
+
properties: {
|
|
397
|
+
blockId: { type: 'string', description: 'Source blockId to duplicate.' },
|
|
398
|
+
afterBlockId: {
|
|
399
|
+
type: 'string',
|
|
400
|
+
description: 'Optional blockId after which to insert the copy (defaults to right after the source block, or "START").'
|
|
401
|
+
},
|
|
402
|
+
newBlockId: { type: 'string', description: 'Optional explicit block ID for the duplicated block.' },
|
|
403
|
+
expectedRevisionHash: {
|
|
404
|
+
type: 'string',
|
|
405
|
+
description: 'Optional SHA-256 revision hash of the document prior to edit.'
|
|
406
|
+
}
|
|
407
|
+
},
|
|
408
|
+
required: ['blockId']
|
|
409
|
+
}
|
|
410
|
+
},
|
|
411
|
+
{
|
|
412
|
+
name: 'mutate_markdown_table',
|
|
413
|
+
description: 'Performs structured row or column mutations on an existing Markdown table block.',
|
|
414
|
+
inputSchema: {
|
|
415
|
+
type: 'object',
|
|
416
|
+
properties: {
|
|
417
|
+
blockId: { type: 'string', description: 'Target table blockId.' },
|
|
418
|
+
operation: {
|
|
419
|
+
type: 'string',
|
|
420
|
+
enum: ['add_row', 'update_row', 'delete_row', 'add_column', 'rename_column'],
|
|
421
|
+
description: 'Table mutation operation.'
|
|
422
|
+
},
|
|
423
|
+
rowIndex: { type: 'number', description: '0-based data row index for update_row / delete_row.' },
|
|
424
|
+
row: {
|
|
425
|
+
type: 'array',
|
|
426
|
+
items: { type: 'string' },
|
|
427
|
+
description: 'Cell values array (in column order) for add_row / update_row.'
|
|
428
|
+
},
|
|
429
|
+
columnName: { type: 'string', description: 'Column header name for add_column / rename_column.' },
|
|
430
|
+
newColumnName: { type: 'string', description: 'Replacement column header name for rename_column.' },
|
|
431
|
+
defaultValue: { type: 'string', description: 'Default cell value when adding a column.' },
|
|
432
|
+
expectedRevisionHash: { type: 'string', description: 'Optional SHA-256 revision hash of the document prior to edit.' }
|
|
433
|
+
},
|
|
434
|
+
required: ['blockId', 'operation']
|
|
435
|
+
}
|
|
436
|
+
},
|
|
437
|
+
{
|
|
438
|
+
name: 'upsert_frontmatter',
|
|
439
|
+
description: 'Creates or updates YAML frontmatter fields at the top of the Markdown document.',
|
|
440
|
+
inputSchema: {
|
|
441
|
+
type: 'object',
|
|
442
|
+
properties: {
|
|
443
|
+
fields: { type: 'object', description: 'Key/value pairs to set in YAML frontmatter.' },
|
|
444
|
+
removeKeys: {
|
|
445
|
+
type: 'array',
|
|
446
|
+
items: { type: 'string' },
|
|
447
|
+
description: 'Optional frontmatter keys to remove.'
|
|
448
|
+
},
|
|
449
|
+
expectedRevisionHash: { type: 'string', description: 'Optional SHA-256 revision hash of the document prior to edit.' }
|
|
450
|
+
},
|
|
451
|
+
required: ['fields']
|
|
452
|
+
}
|
|
453
|
+
},
|
|
454
|
+
{
|
|
455
|
+
name: 'set_lock',
|
|
456
|
+
description: 'Locks a Markdown heading section via `<!-- mj-lock: owner-only -->`.',
|
|
457
|
+
inputSchema: {
|
|
458
|
+
type: 'object',
|
|
459
|
+
properties: {
|
|
460
|
+
headingLineNumber: { type: 'number', description: '1-based line number of the Markdown heading to lock.' },
|
|
461
|
+
heading: { type: 'string', description: 'Optional heading text if headingLineNumber is omitted.' },
|
|
462
|
+
blockId: { type: 'string', description: 'Optional heading blockId if headingLineNumber is omitted.' },
|
|
463
|
+
expectedRevisionHash: { type: 'string', description: 'Optional SHA-256 revision hash of the document prior to edit.' }
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
},
|
|
467
|
+
{
|
|
468
|
+
name: 'release_lock',
|
|
469
|
+
description: 'Removes a `<!-- mj-lock -->` guard from a Markdown heading section if the actor is authorized.',
|
|
470
|
+
inputSchema: {
|
|
471
|
+
type: 'object',
|
|
472
|
+
properties: {
|
|
473
|
+
headingLineNumber: { type: 'number', description: '1-based line number of the locked Markdown heading.' },
|
|
474
|
+
heading: { type: 'string', description: 'Optional heading text if headingLineNumber is omitted.' },
|
|
475
|
+
blockId: { type: 'string', description: 'Optional heading blockId if headingLineNumber is omitted.' },
|
|
476
|
+
expectedRevisionHash: { type: 'string', description: 'Optional SHA-256 revision hash of the document prior to edit.' }
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
},
|
|
480
|
+
...GetSharedCommentAndSuggestionToolDefinitions('document')
|
|
481
|
+
];
|
|
482
|
+
}
|
|
483
|
+
async invokeSubclassTool(toolName, input, artifactContent, context) {
|
|
484
|
+
const contentStr = typeof artifactContent === 'string' ? artifactContent : artifactContent.toString('utf-8');
|
|
485
|
+
const result = await this.dispatchSubclassTool(toolName, contentStr, input, context);
|
|
486
|
+
if (result.success && result.data && typeof result.data === 'object') {
|
|
487
|
+
const updatedContent = result.data.updatedContent;
|
|
488
|
+
if (typeof updatedContent === 'string' && updatedContent !== contentStr) {
|
|
489
|
+
const actorUserId = context?.actorUserId ?? context?.contextUser?.ID;
|
|
490
|
+
const ownerUserId = context?.ownerUserId;
|
|
491
|
+
const isEditor = Boolean(context?.isEditor);
|
|
492
|
+
const lockCheck = DocumentLiveBlockEngine.Instance.ValidateDocumentEditAgainstLocks(contentStr, updatedContent, actorUserId, ownerUserId, isEditor);
|
|
493
|
+
if (!lockCheck.Allowed) {
|
|
494
|
+
return {
|
|
495
|
+
success: false,
|
|
496
|
+
data: null,
|
|
497
|
+
errorMessage: lockCheck.ViolationReason ||
|
|
498
|
+
'Cannot modify a locked region (<!-- mj-lock: owner-only -->).'
|
|
499
|
+
};
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
return result;
|
|
504
|
+
}
|
|
505
|
+
async dispatchSubclassTool(toolName, contentStr, input, context) {
|
|
506
|
+
switch (toolName) {
|
|
507
|
+
case 'get_outline':
|
|
508
|
+
return this.handleGetOutline(contentStr);
|
|
509
|
+
case 'get_section':
|
|
510
|
+
return this.handleGetSection(contentStr, input);
|
|
511
|
+
case 'get_blocks':
|
|
512
|
+
return this.handleGetBlocks(contentStr, input);
|
|
513
|
+
case 'search_blocks':
|
|
514
|
+
return this.handleSearchBlocks(contentStr, input);
|
|
515
|
+
case 'grep':
|
|
516
|
+
return this.handleGrep(contentStr, input);
|
|
517
|
+
case 'get_lines':
|
|
518
|
+
return this.handleGetLines(contentStr, input);
|
|
519
|
+
case 'insert_block_after':
|
|
520
|
+
return this.handleInsertBlockAfter(contentStr, input, context);
|
|
521
|
+
case 'replace_block':
|
|
522
|
+
return this.handleReplaceBlock(contentStr, input, context);
|
|
523
|
+
case 'delete_block':
|
|
524
|
+
return this.handleDeleteBlock(contentStr, input);
|
|
525
|
+
case 'upsert_table':
|
|
526
|
+
return this.handleUpsertTable(contentStr, input, context);
|
|
527
|
+
case 'insert_live_block':
|
|
528
|
+
return this.handleInsertLiveBlock(contentStr, input, context);
|
|
529
|
+
case 'embed_artifact_block':
|
|
530
|
+
return this.handleEmbedArtifactBlock(contentStr, input, context);
|
|
531
|
+
case 'move_block':
|
|
532
|
+
return this.handleMoveBlock(contentStr, input);
|
|
533
|
+
case 'duplicate_block':
|
|
534
|
+
return this.handleDuplicateBlock(contentStr, input);
|
|
535
|
+
case 'mutate_markdown_table':
|
|
536
|
+
return this.handleMutateMarkdownTable(contentStr, input, context);
|
|
537
|
+
case 'upsert_frontmatter':
|
|
538
|
+
return this.handleUpsertFrontmatter(contentStr, input);
|
|
539
|
+
case 'set_lock':
|
|
540
|
+
return this.handleToggleLock(contentStr, input, true, context);
|
|
541
|
+
case 'release_lock':
|
|
542
|
+
return this.handleToggleLock(contentStr, input, false, context);
|
|
543
|
+
case 'list_comments':
|
|
544
|
+
case 'add_comment':
|
|
545
|
+
case 'reply_comment':
|
|
546
|
+
case 'resolve_comment':
|
|
547
|
+
return ExecuteArtifactCommentTool({
|
|
548
|
+
toolName,
|
|
549
|
+
input,
|
|
550
|
+
context,
|
|
551
|
+
domain: 'document'
|
|
552
|
+
});
|
|
553
|
+
case 'list_suggestions':
|
|
554
|
+
return ExecuteListSuggestionsTool({
|
|
555
|
+
domain: 'document',
|
|
556
|
+
artifactContent: contentStr,
|
|
557
|
+
input,
|
|
558
|
+
context
|
|
559
|
+
});
|
|
560
|
+
case 'propose_suggestion':
|
|
561
|
+
return this.handleProposeSuggestion(contentStr, input, context);
|
|
562
|
+
case 'review_suggestion':
|
|
563
|
+
return this.handleReviewSuggestion(contentStr, input, context);
|
|
564
|
+
default:
|
|
565
|
+
return { success: false, data: null, errorMessage: `Unknown tool: "${toolName}"` };
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
/**
|
|
569
|
+
* Computes a deterministic SHA-256 revision hash for optimistic concurrency checking.
|
|
570
|
+
*/
|
|
571
|
+
ComputeRevisionHash(content) {
|
|
572
|
+
return createHash('sha256').update(content ?? '', 'utf8').digest('hex');
|
|
573
|
+
}
|
|
574
|
+
/**
|
|
575
|
+
* Parses a Markdown document into logical blocks (`heading`, `paragraph`, `table`, `code`,
|
|
576
|
+
* `callout`, `list`, `mj-block`) with deterministic IDs.
|
|
577
|
+
*/
|
|
578
|
+
ParseLogicalBlocks(markdown) {
|
|
579
|
+
const segments = DocumentLiveBlockEngine.Instance.ParseMarkdownDirectives(markdown ?? '');
|
|
580
|
+
const blocks = [];
|
|
581
|
+
let autoCounter = 1;
|
|
582
|
+
for (const seg of segments) {
|
|
583
|
+
if (seg.Type === 'mj-block' && seg.BlockSpec) {
|
|
584
|
+
blocks.push({
|
|
585
|
+
blockId: seg.BlockSpec.BlockID || `blk-${autoCounter++}`,
|
|
586
|
+
kind: 'mj-block',
|
|
587
|
+
startLine: seg.StartLine,
|
|
588
|
+
endLine: seg.EndLine,
|
|
589
|
+
rawMarkdown: seg.RawText,
|
|
590
|
+
mjBlockSpec: seg.BlockSpec
|
|
591
|
+
});
|
|
592
|
+
continue;
|
|
593
|
+
}
|
|
594
|
+
// Parse prose segment into paragraphs, headings, code fences, tables, lists, callouts
|
|
595
|
+
const lines = seg.RawText.split(/\r?\n/);
|
|
596
|
+
let i = 0;
|
|
597
|
+
let pendingBlockId = null;
|
|
598
|
+
while (i < lines.length) {
|
|
599
|
+
const line = lines[i];
|
|
600
|
+
const trimmed = line.trim();
|
|
601
|
+
if (!trimmed) {
|
|
602
|
+
i++;
|
|
603
|
+
continue;
|
|
604
|
+
}
|
|
605
|
+
// Check for explicit block ID comment: <!-- mj-block-id: blk-xyz -->
|
|
606
|
+
const commentMatch = /^<!--\s*mj-block-id:\s*([A-Za-z0-9_-]+)\s*-->$/.exec(trimmed);
|
|
607
|
+
if (commentMatch) {
|
|
608
|
+
pendingBlockId = commentMatch[1];
|
|
609
|
+
i++;
|
|
610
|
+
continue;
|
|
611
|
+
}
|
|
612
|
+
const blockStartOffset = i;
|
|
613
|
+
const assignId = () => {
|
|
614
|
+
if (pendingBlockId) {
|
|
615
|
+
const id = pendingBlockId;
|
|
616
|
+
pendingBlockId = null;
|
|
617
|
+
return { blockId: id, hasExplicitId: true };
|
|
618
|
+
}
|
|
619
|
+
return { blockId: `blk-${autoCounter++}`, hasExplicitId: false };
|
|
620
|
+
};
|
|
621
|
+
// 1. Heading (# .. ######)
|
|
622
|
+
const headingMatch = /^(#{1,6})\s+(.+)$/.exec(trimmed);
|
|
623
|
+
if (headingMatch) {
|
|
624
|
+
const lineNum = seg.StartLine + i;
|
|
625
|
+
const assigned = assignId();
|
|
626
|
+
blocks.push({
|
|
627
|
+
blockId: assigned.blockId,
|
|
628
|
+
hasExplicitId: assigned.hasExplicitId,
|
|
629
|
+
kind: 'heading',
|
|
630
|
+
headingLevel: headingMatch[1].length,
|
|
631
|
+
headingText: headingMatch[2].trim(),
|
|
632
|
+
startLine: lineNum,
|
|
633
|
+
endLine: lineNum,
|
|
634
|
+
rawMarkdown: line
|
|
635
|
+
});
|
|
636
|
+
i++;
|
|
637
|
+
continue;
|
|
638
|
+
}
|
|
639
|
+
// 2. Code fence (``` or ~~~)
|
|
640
|
+
if (trimmed.startsWith('```') || trimmed.startsWith('~~~')) {
|
|
641
|
+
const fence = trimmed.slice(0, 3);
|
|
642
|
+
const codeLines = [line];
|
|
643
|
+
i++;
|
|
644
|
+
while (i < lines.length && !lines[i].trim().startsWith(fence)) {
|
|
645
|
+
codeLines.push(lines[i]);
|
|
646
|
+
i++;
|
|
647
|
+
}
|
|
648
|
+
if (i < lines.length) {
|
|
649
|
+
codeLines.push(lines[i]);
|
|
650
|
+
i++;
|
|
651
|
+
}
|
|
652
|
+
const assigned = assignId();
|
|
653
|
+
blocks.push({
|
|
654
|
+
blockId: assigned.blockId,
|
|
655
|
+
hasExplicitId: assigned.hasExplicitId,
|
|
656
|
+
kind: 'code',
|
|
657
|
+
startLine: seg.StartLine + blockStartOffset,
|
|
658
|
+
endLine: seg.StartLine + i - 1,
|
|
659
|
+
rawMarkdown: codeLines.join('\n')
|
|
660
|
+
});
|
|
661
|
+
continue;
|
|
662
|
+
}
|
|
663
|
+
// 3. Table (starts with |)
|
|
664
|
+
if (trimmed.startsWith('|')) {
|
|
665
|
+
const tableLines = [];
|
|
666
|
+
while (i < lines.length && lines[i].trim().startsWith('|')) {
|
|
667
|
+
tableLines.push(lines[i]);
|
|
668
|
+
i++;
|
|
669
|
+
}
|
|
670
|
+
const assigned = assignId();
|
|
671
|
+
blocks.push({
|
|
672
|
+
blockId: assigned.blockId,
|
|
673
|
+
hasExplicitId: assigned.hasExplicitId,
|
|
674
|
+
kind: 'table',
|
|
675
|
+
startLine: seg.StartLine + blockStartOffset,
|
|
676
|
+
endLine: seg.StartLine + i - 1,
|
|
677
|
+
rawMarkdown: tableLines.join('\n')
|
|
678
|
+
});
|
|
679
|
+
continue;
|
|
680
|
+
}
|
|
681
|
+
// 4. Callout / blockquote (starts with >)
|
|
682
|
+
if (trimmed.startsWith('>')) {
|
|
683
|
+
const quoteLines = [];
|
|
684
|
+
while (i < lines.length && lines[i].trim().startsWith('>')) {
|
|
685
|
+
quoteLines.push(lines[i]);
|
|
686
|
+
i++;
|
|
687
|
+
}
|
|
688
|
+
const assigned = assignId();
|
|
689
|
+
blocks.push({
|
|
690
|
+
blockId: assigned.blockId,
|
|
691
|
+
hasExplicitId: assigned.hasExplicitId,
|
|
692
|
+
kind: 'callout',
|
|
693
|
+
startLine: seg.StartLine + blockStartOffset,
|
|
694
|
+
endLine: seg.StartLine + i - 1,
|
|
695
|
+
rawMarkdown: quoteLines.join('\n')
|
|
696
|
+
});
|
|
697
|
+
continue;
|
|
698
|
+
}
|
|
699
|
+
// 5. Bullet / numbered / task list
|
|
700
|
+
if (/^([-*+]|\d+\.)\s+/.test(trimmed)) {
|
|
701
|
+
const listLines = [];
|
|
702
|
+
while (i < lines.length &&
|
|
703
|
+
lines[i].trim().length > 0 &&
|
|
704
|
+
(/^([-*+]|\d+\.)\s+/.test(lines[i].trim()) || /^\s{2,}/.test(lines[i]))) {
|
|
705
|
+
listLines.push(lines[i]);
|
|
706
|
+
i++;
|
|
707
|
+
}
|
|
708
|
+
const assigned = assignId();
|
|
709
|
+
blocks.push({
|
|
710
|
+
blockId: assigned.blockId,
|
|
711
|
+
hasExplicitId: assigned.hasExplicitId,
|
|
712
|
+
kind: 'list',
|
|
713
|
+
startLine: seg.StartLine + blockStartOffset,
|
|
714
|
+
endLine: seg.StartLine + i - 1,
|
|
715
|
+
rawMarkdown: listLines.join('\n')
|
|
716
|
+
});
|
|
717
|
+
continue;
|
|
718
|
+
}
|
|
719
|
+
// 6. Standard paragraph
|
|
720
|
+
const paraLines = [];
|
|
721
|
+
while (i < lines.length &&
|
|
722
|
+
lines[i].trim().length > 0 &&
|
|
723
|
+
!/^(#{1,6}\s+|```|~~~|\||>|([-*+]|\d+\.)\s+|<!--\s*mj-(?:block-id|suggestion):)/.test(lines[i].trim())) {
|
|
724
|
+
paraLines.push(lines[i]);
|
|
725
|
+
i++;
|
|
726
|
+
}
|
|
727
|
+
const assigned = assignId();
|
|
728
|
+
blocks.push({
|
|
729
|
+
blockId: assigned.blockId,
|
|
730
|
+
hasExplicitId: assigned.hasExplicitId,
|
|
731
|
+
kind: 'paragraph',
|
|
732
|
+
startLine: seg.StartLine + blockStartOffset,
|
|
733
|
+
endLine: seg.StartLine + i - 1,
|
|
734
|
+
rawMarkdown: paraLines.join('\n')
|
|
735
|
+
});
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
return blocks;
|
|
739
|
+
}
|
|
740
|
+
handleGetOutline(content) {
|
|
741
|
+
const blocks = this.ParseLogicalBlocks(content);
|
|
742
|
+
const headings = blocks.filter((b) => b.kind === 'heading');
|
|
743
|
+
const outline = [];
|
|
744
|
+
for (let idx = 0; idx < headings.length; idx++) {
|
|
745
|
+
const h = headings[idx];
|
|
746
|
+
const nextH = headings.slice(idx + 1).find((candidate) => (candidate.headingLevel ?? 6) <= (h.headingLevel ?? 1));
|
|
747
|
+
const sectionEndLine = nextH ? nextH.startLine - 1 : blocks[blocks.length - 1]?.endLine ?? h.endLine;
|
|
748
|
+
const sectionBlocks = blocks.filter((b) => b.startLine >= h.startLine && b.endLine <= sectionEndLine);
|
|
749
|
+
const words = sectionBlocks
|
|
750
|
+
.map((b) => b.rawMarkdown)
|
|
751
|
+
.join(' ')
|
|
752
|
+
.trim()
|
|
753
|
+
.split(/\s+/)
|
|
754
|
+
.filter(Boolean).length;
|
|
755
|
+
const embeddedBlocks = sectionBlocks
|
|
756
|
+
.filter((b) => b.kind === 'mj-block' && b.mjBlockSpec)
|
|
757
|
+
.map((b) => ({
|
|
758
|
+
blockId: b.mjBlockSpec.BlockID,
|
|
759
|
+
kind: b.mjBlockSpec.Kind,
|
|
760
|
+
mode: b.mjBlockSpec.Mode,
|
|
761
|
+
title: b.mjBlockSpec.Title
|
|
762
|
+
}));
|
|
763
|
+
outline.push({
|
|
764
|
+
blockId: h.blockId,
|
|
765
|
+
level: h.headingLevel ?? 1,
|
|
766
|
+
title: h.headingText ?? '',
|
|
767
|
+
startLine: h.startLine,
|
|
768
|
+
endLine: sectionEndLine,
|
|
769
|
+
wordCount: words,
|
|
770
|
+
embeddedBlocks
|
|
771
|
+
});
|
|
772
|
+
}
|
|
773
|
+
return {
|
|
774
|
+
success: true,
|
|
775
|
+
data: {
|
|
776
|
+
revisionHash: this.ComputeRevisionHash(content),
|
|
777
|
+
totalBlocks: blocks.length,
|
|
778
|
+
outline
|
|
779
|
+
}
|
|
780
|
+
};
|
|
781
|
+
}
|
|
782
|
+
handleGetSection(content, input) {
|
|
783
|
+
const blocks = this.ParseLogicalBlocks(content);
|
|
784
|
+
const targetBlockId = typeof input.blockId === 'string' ? input.blockId.trim() : '';
|
|
785
|
+
const headingQuery = typeof input.heading === 'string' ? input.heading.trim().toLowerCase() : '';
|
|
786
|
+
const headingIdx = blocks.findIndex((b) => b.kind === 'heading' &&
|
|
787
|
+
((targetBlockId && b.blockId === targetBlockId) ||
|
|
788
|
+
(headingQuery && (b.headingText ?? '').toLowerCase().includes(headingQuery))));
|
|
789
|
+
if (headingIdx < 0) {
|
|
790
|
+
return {
|
|
791
|
+
success: false,
|
|
792
|
+
data: null,
|
|
793
|
+
errorMessage: `Section heading '${targetBlockId || headingQuery}' not found.`
|
|
794
|
+
};
|
|
795
|
+
}
|
|
796
|
+
const startHeading = blocks[headingIdx];
|
|
797
|
+
const startLevel = startHeading.headingLevel ?? 1;
|
|
798
|
+
const sectionBlocks = [startHeading];
|
|
799
|
+
for (let i = headingIdx + 1; i < blocks.length; i++) {
|
|
800
|
+
const b = blocks[i];
|
|
801
|
+
if (b.kind === 'heading' && (b.headingLevel ?? 6) <= startLevel) {
|
|
802
|
+
break;
|
|
803
|
+
}
|
|
804
|
+
sectionBlocks.push(b);
|
|
805
|
+
}
|
|
806
|
+
return {
|
|
807
|
+
success: true,
|
|
808
|
+
data: {
|
|
809
|
+
headingBlockId: startHeading.blockId,
|
|
810
|
+
title: startHeading.headingText,
|
|
811
|
+
level: startLevel,
|
|
812
|
+
markdown: sectionBlocks.map((b) => b.rawMarkdown).join('\n\n'),
|
|
813
|
+
blocks: sectionBlocks
|
|
814
|
+
}
|
|
815
|
+
};
|
|
816
|
+
}
|
|
817
|
+
handleGetBlocks(content, input) {
|
|
818
|
+
const kindFilter = typeof input.kind === 'string' ? input.kind.trim().toLowerCase() : '';
|
|
819
|
+
const allBlocks = this.ParseLogicalBlocks(content);
|
|
820
|
+
const filtered = kindFilter ? allBlocks.filter((b) => b.kind.toLowerCase() === kindFilter) : allBlocks;
|
|
821
|
+
return {
|
|
822
|
+
success: true,
|
|
823
|
+
data: {
|
|
824
|
+
revisionHash: this.ComputeRevisionHash(content),
|
|
825
|
+
blocks: filtered
|
|
826
|
+
}
|
|
827
|
+
};
|
|
828
|
+
}
|
|
829
|
+
handleSearchBlocks(content, input) {
|
|
830
|
+
EnsureNodeVmSafeRegexExecutorRegistered();
|
|
831
|
+
const query = String(input.query ?? '').trim();
|
|
832
|
+
if (!query) {
|
|
833
|
+
return { success: false, data: null, errorMessage: 'search_blocks requires a non-empty query.' };
|
|
834
|
+
}
|
|
835
|
+
const explicitRegex = input.use_regex === true || input.useRegex === true;
|
|
836
|
+
const blocks = this.ParseLogicalBlocks(content);
|
|
837
|
+
if (!explicitRegex) {
|
|
838
|
+
const needle = query.toLowerCase();
|
|
839
|
+
const literalMatches = blocks.filter((b) => b.rawMarkdown.toLowerCase().includes(needle));
|
|
840
|
+
return {
|
|
841
|
+
success: true,
|
|
842
|
+
data: {
|
|
843
|
+
revisionHash: this.ComputeRevisionHash(content),
|
|
844
|
+
matchCount: literalMatches.length,
|
|
845
|
+
matches: literalMatches,
|
|
846
|
+
partial: false,
|
|
847
|
+
timedOut: false,
|
|
848
|
+
unsearchableCount: 0,
|
|
849
|
+
unsearchableBlocks: [],
|
|
850
|
+
warnings: []
|
|
851
|
+
}
|
|
852
|
+
};
|
|
853
|
+
}
|
|
854
|
+
if (query.length > 256) {
|
|
855
|
+
return {
|
|
856
|
+
success: false,
|
|
857
|
+
data: null,
|
|
858
|
+
errorMessage: 'Unsafe or overly complex regular expression rejected'
|
|
859
|
+
};
|
|
860
|
+
}
|
|
861
|
+
try {
|
|
862
|
+
new RegExp(query, 'i');
|
|
863
|
+
}
|
|
864
|
+
catch (err) {
|
|
865
|
+
return {
|
|
866
|
+
success: false,
|
|
867
|
+
data: null,
|
|
868
|
+
errorMessage: `Invalid regular expression: ${err instanceof Error ? err.message : String(err)}`
|
|
869
|
+
};
|
|
870
|
+
}
|
|
871
|
+
const activeRegex = CompileSafeUserRegex(query, 'i');
|
|
872
|
+
if (!activeRegex || !IsSafeUserRegex(query, 'i')) {
|
|
873
|
+
return {
|
|
874
|
+
success: false,
|
|
875
|
+
data: null,
|
|
876
|
+
errorMessage: 'Unsafe or overly complex regular expression rejected'
|
|
877
|
+
};
|
|
878
|
+
}
|
|
879
|
+
const matches = [];
|
|
880
|
+
const unsearchableBlocks = [];
|
|
881
|
+
let tooLongCount = 0;
|
|
882
|
+
let timeoutCount = 0;
|
|
883
|
+
let budgetExpired = false;
|
|
884
|
+
const budgetMs = this.RegexBudgetMs;
|
|
885
|
+
const regexDeadline = performance.now() + budgetMs;
|
|
886
|
+
const recordUnsearchableBlock = (block, reason) => {
|
|
887
|
+
if (reason === 'exceeds_64kb_regex_limit') {
|
|
888
|
+
tooLongCount++;
|
|
889
|
+
}
|
|
890
|
+
else {
|
|
891
|
+
timeoutCount++;
|
|
892
|
+
}
|
|
893
|
+
if (unsearchableBlocks.length < MAX_REPORTED_UNSEARCHABLE_BLOCKS) {
|
|
894
|
+
unsearchableBlocks.push({
|
|
895
|
+
blockId: block.blockId,
|
|
896
|
+
startLine: block.startLine,
|
|
897
|
+
endLine: block.endLine,
|
|
898
|
+
reason
|
|
899
|
+
});
|
|
900
|
+
}
|
|
901
|
+
};
|
|
902
|
+
let pendingBlocks = [];
|
|
903
|
+
let pendingTexts = [];
|
|
904
|
+
let pendingChars = 0;
|
|
905
|
+
const flushBlockBatch = () => {
|
|
906
|
+
if (pendingBlocks.length === 0)
|
|
907
|
+
return;
|
|
908
|
+
if (budgetExpired) {
|
|
909
|
+
for (const b of pendingBlocks) {
|
|
910
|
+
recordUnsearchableBlock(b, 'regex_timeout');
|
|
911
|
+
}
|
|
912
|
+
pendingBlocks = [];
|
|
913
|
+
pendingTexts = [];
|
|
914
|
+
pendingChars = 0;
|
|
915
|
+
return;
|
|
916
|
+
}
|
|
917
|
+
const recRes = ExecuteSafeRegexBatchWithRecovery(activeRegex, pendingTexts, regexDeadline, BATCH_REGEX_MAX_MS, MAX_REGEX_INPUT_BYTES);
|
|
918
|
+
if (recRes.BudgetExpired) {
|
|
919
|
+
budgetExpired = true;
|
|
920
|
+
}
|
|
921
|
+
for (let k = 0; k < pendingBlocks.length; k++) {
|
|
922
|
+
if (recRes.Matches[k]) {
|
|
923
|
+
matches.push(pendingBlocks[k]);
|
|
924
|
+
}
|
|
925
|
+
else if (recRes.TimedOut[k] || recRes.BudgetSkipped[k]) {
|
|
926
|
+
recordUnsearchableBlock(pendingBlocks[k], 'regex_timeout');
|
|
927
|
+
}
|
|
928
|
+
else if (recRes.InputTooLong[k]) {
|
|
929
|
+
recordUnsearchableBlock(pendingBlocks[k], 'exceeds_64kb_regex_limit');
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
pendingBlocks = [];
|
|
933
|
+
pendingTexts = [];
|
|
934
|
+
pendingChars = 0;
|
|
935
|
+
};
|
|
936
|
+
for (const block of blocks) {
|
|
937
|
+
if (exceedsRegexInputBytes(block.rawMarkdown)) {
|
|
938
|
+
flushBlockBatch();
|
|
939
|
+
recordUnsearchableBlock(block, 'exceeds_64kb_regex_limit');
|
|
940
|
+
continue;
|
|
941
|
+
}
|
|
942
|
+
if (budgetExpired) {
|
|
943
|
+
recordUnsearchableBlock(block, 'regex_timeout');
|
|
944
|
+
continue;
|
|
945
|
+
}
|
|
946
|
+
pendingBlocks.push(block);
|
|
947
|
+
pendingTexts.push(block.rawMarkdown);
|
|
948
|
+
pendingChars += block.rawMarkdown.length;
|
|
949
|
+
if (pendingBlocks.length >= MAX_BATCH_ITEMS || pendingChars >= MAX_BATCH_CHARS) {
|
|
950
|
+
flushBlockBatch();
|
|
951
|
+
}
|
|
952
|
+
}
|
|
953
|
+
flushBlockBatch();
|
|
954
|
+
const unsearchableCount = tooLongCount + timeoutCount;
|
|
955
|
+
const warnings = [];
|
|
956
|
+
if (tooLongCount > 0) {
|
|
957
|
+
warnings.push(`${tooLongCount} block(s) exceeded the 64 KB regex limit and were not searched. Retry with use_regex: false for plain-text search across arbitrarily large blocks.`);
|
|
958
|
+
}
|
|
959
|
+
if (timeoutCount > 0) {
|
|
960
|
+
warnings.push(`${timeoutCount} block(s) were skipped because regex evaluation reached the ${budgetMs}ms tool time budget. Simplify the pattern or retry with use_regex: false for plain-text search.`);
|
|
961
|
+
}
|
|
962
|
+
if (unsearchableCount > unsearchableBlocks.length) {
|
|
963
|
+
warnings.push(`Showing first ${unsearchableBlocks.length} of ${unsearchableCount} unsearchable block(s) in unsearchableBlocks.`);
|
|
964
|
+
}
|
|
965
|
+
return {
|
|
966
|
+
success: true,
|
|
967
|
+
data: {
|
|
968
|
+
revisionHash: this.ComputeRevisionHash(content),
|
|
969
|
+
matchCount: matches.length,
|
|
970
|
+
matches,
|
|
971
|
+
partial: unsearchableCount > 0,
|
|
972
|
+
timedOut: timeoutCount > 0,
|
|
973
|
+
unsearchableCount,
|
|
974
|
+
unsearchableBlocks,
|
|
975
|
+
warnings
|
|
976
|
+
}
|
|
977
|
+
};
|
|
978
|
+
}
|
|
979
|
+
handleGrep(content, input) {
|
|
980
|
+
return ExecuteStructuredLineGrep(content, input, this.RegexBudgetMs);
|
|
981
|
+
}
|
|
982
|
+
handleGetLines(content, input) {
|
|
983
|
+
const start = Number(input.start ?? 0);
|
|
984
|
+
const count = Number(input.count ?? 20);
|
|
985
|
+
const lines = content.split('\n');
|
|
986
|
+
const sliced = lines.slice(start, start + count);
|
|
987
|
+
return {
|
|
988
|
+
success: true,
|
|
989
|
+
data: sliced.map((text, idx) => ({ lineNumber: start + idx, text }))
|
|
990
|
+
};
|
|
991
|
+
}
|
|
992
|
+
checkRevision(content, expectedRevisionHash) {
|
|
993
|
+
if (typeof expectedRevisionHash !== 'string' || !expectedRevisionHash.trim()) {
|
|
994
|
+
return null;
|
|
995
|
+
}
|
|
996
|
+
const current = this.ComputeRevisionHash(content);
|
|
997
|
+
if (current !== expectedRevisionHash.trim()) {
|
|
998
|
+
return `Revision conflict: expected revisionHash '${expectedRevisionHash.trim()}', but current document revisionHash is '${current}'. Reload blocks and retry.`;
|
|
999
|
+
}
|
|
1000
|
+
return null;
|
|
1001
|
+
}
|
|
1002
|
+
serializeLogicalBlocks(blocks) {
|
|
1003
|
+
return blocks
|
|
1004
|
+
.map((b) => {
|
|
1005
|
+
let body = b.rawMarkdown;
|
|
1006
|
+
if (b.kind !== 'mj-block' &&
|
|
1007
|
+
b.hasExplicitId &&
|
|
1008
|
+
!/^\s*<!--\s*mj-block-id:/i.test(body)) {
|
|
1009
|
+
body = `<!-- mj-block-id: ${b.blockId} -->\n${body}`;
|
|
1010
|
+
}
|
|
1011
|
+
return body;
|
|
1012
|
+
})
|
|
1013
|
+
.join('\n\n');
|
|
1014
|
+
}
|
|
1015
|
+
async normalizeArtifactBlocksInMarkdown(markdown, context) {
|
|
1016
|
+
const parsedSegs = DocumentLiveBlockEngine.Instance.ParseMarkdownDirectives(markdown);
|
|
1017
|
+
let updated = markdown;
|
|
1018
|
+
for (const seg of parsedSegs) {
|
|
1019
|
+
if (seg.Type !== 'mj-block' || !seg.BlockSpec || seg.BlockSpec.Kind !== 'Artifact') {
|
|
1020
|
+
continue;
|
|
1021
|
+
}
|
|
1022
|
+
const rawArtifactId = String(seg.BlockSpec.ArtifactID ?? '').trim();
|
|
1023
|
+
if (!rawArtifactId) {
|
|
1024
|
+
return { ok: false, errorMessage: 'Embedded Artifact block requires a valid ArtifactID.' };
|
|
1025
|
+
}
|
|
1026
|
+
const resolved = ResolveEmbeddedArtifactId(rawArtifactId, context);
|
|
1027
|
+
if (!resolved.ok) {
|
|
1028
|
+
return { ok: false, errorMessage: resolved.errorMessage };
|
|
1029
|
+
}
|
|
1030
|
+
const rawVersionId = typeof seg.BlockSpec.VersionID === 'string' ? seg.BlockSpec.VersionID.trim() : '';
|
|
1031
|
+
let resolvedVersionId = seg.BlockSpec.VersionID;
|
|
1032
|
+
if (rawVersionId) {
|
|
1033
|
+
const verResult = ResolveEmbeddedVersionId(rawVersionId, context);
|
|
1034
|
+
if (!verResult.ok) {
|
|
1035
|
+
return { ok: false, errorMessage: verResult.errorMessage };
|
|
1036
|
+
}
|
|
1037
|
+
resolvedVersionId = verResult.versionId;
|
|
1038
|
+
}
|
|
1039
|
+
const accessCheck = await ValidateEmbeddedArtifactAccess({
|
|
1040
|
+
targetArtifactId: resolved.artifactId,
|
|
1041
|
+
targetVersionId: resolvedVersionId,
|
|
1042
|
+
context
|
|
1043
|
+
});
|
|
1044
|
+
if (!accessCheck.Ok) {
|
|
1045
|
+
return { ok: false, errorMessage: accessCheck.ErrorMessage };
|
|
1046
|
+
}
|
|
1047
|
+
if (resolved.artifactId !== seg.BlockSpec.ArtifactID || resolvedVersionId !== seg.BlockSpec.VersionID) {
|
|
1048
|
+
const normalizedDirective = DocumentLiveBlockEngine.Instance.SerializeBlockToMarkdownDirective({
|
|
1049
|
+
...seg.BlockSpec,
|
|
1050
|
+
ArtifactID: resolved.artifactId,
|
|
1051
|
+
VersionID: resolvedVersionId
|
|
1052
|
+
});
|
|
1053
|
+
updated = updated.replace(seg.RawText, () => normalizedDirective);
|
|
1054
|
+
}
|
|
1055
|
+
}
|
|
1056
|
+
return { ok: true, markdown: updated };
|
|
1057
|
+
}
|
|
1058
|
+
async handleInsertBlockAfter(content, input, context) {
|
|
1059
|
+
const conflict = this.checkRevision(content, input.expectedRevisionHash);
|
|
1060
|
+
if (conflict) {
|
|
1061
|
+
return { success: false, data: null, errorMessage: conflict };
|
|
1062
|
+
}
|
|
1063
|
+
const rawNewMarkdown = String(input.markdown ?? '').trim();
|
|
1064
|
+
if (!rawNewMarkdown) {
|
|
1065
|
+
return { success: false, data: null, errorMessage: 'insert_block_after requires non-empty markdown.' };
|
|
1066
|
+
}
|
|
1067
|
+
const normalized = await this.normalizeArtifactBlocksInMarkdown(rawNewMarkdown, context);
|
|
1068
|
+
if (!normalized.ok) {
|
|
1069
|
+
return { success: false, data: null, errorMessage: normalized.errorMessage };
|
|
1070
|
+
}
|
|
1071
|
+
const newMarkdown = normalized.markdown;
|
|
1072
|
+
const blocks = this.ParseLogicalBlocks(content);
|
|
1073
|
+
const existingIds = new Set(blocks.map((b) => b.blockId));
|
|
1074
|
+
const isMjBlockDirective = newMarkdown.startsWith(':::mj-block');
|
|
1075
|
+
const leadingCommentMatch = /^<!--\s*mj-block-id:\s*([A-Za-z0-9_-]+)\s*-->\s*\r?\n([\s\S]*)$/.exec(newMarkdown);
|
|
1076
|
+
const explicitId = typeof input.newBlockId === 'string' && input.newBlockId.trim()
|
|
1077
|
+
? input.newBlockId.trim()
|
|
1078
|
+
: leadingCommentMatch?.[1] ?? null;
|
|
1079
|
+
let mintedBlockId;
|
|
1080
|
+
let cleanBody = leadingCommentMatch ? leadingCommentMatch[2].trim() : newMarkdown;
|
|
1081
|
+
if (isMjBlockDirective) {
|
|
1082
|
+
const parsedSegs = DocumentLiveBlockEngine.Instance.ParseMarkdownDirectives(newMarkdown);
|
|
1083
|
+
mintedBlockId = parsedSegs[0]?.BlockSpec?.BlockID ?? explicitId ?? `mj-${randomUUID().slice(0, 8)}`;
|
|
1084
|
+
}
|
|
1085
|
+
else if (explicitId && !existingIds.has(explicitId)) {
|
|
1086
|
+
mintedBlockId = explicitId;
|
|
1087
|
+
}
|
|
1088
|
+
else {
|
|
1089
|
+
let candidate = `blk-${randomUUID().slice(0, 8)}`;
|
|
1090
|
+
while (existingIds.has(candidate)) {
|
|
1091
|
+
candidate = `blk-${randomUUID().slice(0, 8)}`;
|
|
1092
|
+
}
|
|
1093
|
+
mintedBlockId = candidate;
|
|
1094
|
+
}
|
|
1095
|
+
const stampedMarkdown = isMjBlockDirective
|
|
1096
|
+
? cleanBody
|
|
1097
|
+
: `<!-- mj-block-id: ${mintedBlockId} -->\n${cleanBody}`;
|
|
1098
|
+
const afterBlockId = typeof input.afterBlockId === 'string' ? input.afterBlockId.trim() : '';
|
|
1099
|
+
let updatedContent;
|
|
1100
|
+
if (!afterBlockId) {
|
|
1101
|
+
updatedContent = content.trim() ? `${content.trimEnd()}\n\n${stampedMarkdown}` : stampedMarkdown;
|
|
1102
|
+
}
|
|
1103
|
+
else if (afterBlockId.toUpperCase() === 'START') {
|
|
1104
|
+
updatedContent = content.trim() ? `${stampedMarkdown}\n\n${content.trimStart()}` : stampedMarkdown;
|
|
1105
|
+
}
|
|
1106
|
+
else {
|
|
1107
|
+
const idx = blocks.findIndex((b) => b.blockId === afterBlockId);
|
|
1108
|
+
if (idx < 0) {
|
|
1109
|
+
return {
|
|
1110
|
+
success: false,
|
|
1111
|
+
data: null,
|
|
1112
|
+
errorMessage: `Target afterBlockId '${afterBlockId}' was not found.`
|
|
1113
|
+
};
|
|
1114
|
+
}
|
|
1115
|
+
const newBlockEntry = {
|
|
1116
|
+
blockId: mintedBlockId,
|
|
1117
|
+
hasExplicitId: !isMjBlockDirective,
|
|
1118
|
+
kind: isMjBlockDirective ? 'mj-block' : 'paragraph',
|
|
1119
|
+
startLine: 0,
|
|
1120
|
+
endLine: 0,
|
|
1121
|
+
rawMarkdown: cleanBody
|
|
1122
|
+
};
|
|
1123
|
+
blocks.splice(idx + 1, 0, newBlockEntry);
|
|
1124
|
+
updatedContent = this.serializeLogicalBlocks(blocks);
|
|
1125
|
+
}
|
|
1126
|
+
return {
|
|
1127
|
+
success: true,
|
|
1128
|
+
data: {
|
|
1129
|
+
blockId: mintedBlockId,
|
|
1130
|
+
updatedContent,
|
|
1131
|
+
revisionHash: this.ComputeRevisionHash(updatedContent)
|
|
1132
|
+
}
|
|
1133
|
+
};
|
|
1134
|
+
}
|
|
1135
|
+
async handleReplaceBlock(content, input, context) {
|
|
1136
|
+
const conflict = this.checkRevision(content, input.expectedRevisionHash);
|
|
1137
|
+
if (conflict) {
|
|
1138
|
+
return { success: false, data: null, errorMessage: conflict };
|
|
1139
|
+
}
|
|
1140
|
+
const blockId = String(input.blockId ?? '').trim();
|
|
1141
|
+
const rawInputMarkdown = String(input.markdown ?? '').trim();
|
|
1142
|
+
if (!blockId) {
|
|
1143
|
+
return { success: false, data: null, errorMessage: 'replace_block requires blockId.' };
|
|
1144
|
+
}
|
|
1145
|
+
const normalized = await this.normalizeArtifactBlocksInMarkdown(rawInputMarkdown, context);
|
|
1146
|
+
if (!normalized.ok) {
|
|
1147
|
+
return { success: false, data: null, errorMessage: normalized.errorMessage };
|
|
1148
|
+
}
|
|
1149
|
+
const rawReplacement = normalized.markdown;
|
|
1150
|
+
const blocks = this.ParseLogicalBlocks(content);
|
|
1151
|
+
const idx = blocks.findIndex((b) => b.blockId === blockId);
|
|
1152
|
+
if (idx < 0) {
|
|
1153
|
+
return { success: false, data: null, errorMessage: `Block '${blockId}' was not found.` };
|
|
1154
|
+
}
|
|
1155
|
+
const leadingComment = /^<!--\s*mj-block-id:\s*([A-Za-z0-9_-]+)\s*-->\s*\r?\n([\s\S]*)$/.exec(rawReplacement);
|
|
1156
|
+
const cleanedReplacement = leadingComment ? leadingComment[2].trim() : rawReplacement;
|
|
1157
|
+
const isMjBlock = cleanedReplacement.startsWith(':::mj-block');
|
|
1158
|
+
const preserveExplicitId = !isMjBlock && Boolean(blocks[idx].hasExplicitId || leadingComment);
|
|
1159
|
+
blocks[idx] = {
|
|
1160
|
+
...blocks[idx],
|
|
1161
|
+
kind: isMjBlock ? 'mj-block' : blocks[idx].kind,
|
|
1162
|
+
hasExplicitId: preserveExplicitId,
|
|
1163
|
+
rawMarkdown: cleanedReplacement
|
|
1164
|
+
};
|
|
1165
|
+
const updatedContent = this.serializeLogicalBlocks(blocks);
|
|
1166
|
+
return {
|
|
1167
|
+
success: true,
|
|
1168
|
+
data: {
|
|
1169
|
+
blockId,
|
|
1170
|
+
updatedContent,
|
|
1171
|
+
revisionHash: this.ComputeRevisionHash(updatedContent)
|
|
1172
|
+
}
|
|
1173
|
+
};
|
|
1174
|
+
}
|
|
1175
|
+
handleDeleteBlock(content, input) {
|
|
1176
|
+
const conflict = this.checkRevision(content, input.expectedRevisionHash);
|
|
1177
|
+
if (conflict) {
|
|
1178
|
+
return { success: false, data: null, errorMessage: conflict };
|
|
1179
|
+
}
|
|
1180
|
+
const blockId = String(input.blockId ?? '').trim();
|
|
1181
|
+
const blocks = this.ParseLogicalBlocks(content);
|
|
1182
|
+
const idx = blocks.findIndex((b) => b.blockId === blockId);
|
|
1183
|
+
if (idx < 0) {
|
|
1184
|
+
return { success: false, data: null, errorMessage: `Block '${blockId}' was not found.` };
|
|
1185
|
+
}
|
|
1186
|
+
blocks.splice(idx, 1);
|
|
1187
|
+
const updatedContent = this.serializeLogicalBlocks(blocks);
|
|
1188
|
+
return {
|
|
1189
|
+
success: true,
|
|
1190
|
+
data: {
|
|
1191
|
+
deletedBlockId: blockId,
|
|
1192
|
+
updatedContent,
|
|
1193
|
+
revisionHash: this.ComputeRevisionHash(updatedContent)
|
|
1194
|
+
}
|
|
1195
|
+
};
|
|
1196
|
+
}
|
|
1197
|
+
async handleUpsertTable(content, input, context) {
|
|
1198
|
+
const headers = Array.isArray(input.headers) ? input.headers.map((h) => String(h ?? '')) : [];
|
|
1199
|
+
const rows = Array.isArray(input.rows)
|
|
1200
|
+
? input.rows.map((r) => (Array.isArray(r) ? r.map((c) => String(c ?? '')) : []))
|
|
1201
|
+
: [];
|
|
1202
|
+
const alignments = Array.isArray(input.alignments)
|
|
1203
|
+
? input.alignments.map((a) => (typeof a === 'string' ? a.trim().toLowerCase() : ''))
|
|
1204
|
+
: [];
|
|
1205
|
+
if (headers.length === 0) {
|
|
1206
|
+
return { success: false, data: null, errorMessage: 'upsert_table requires at least one column header.' };
|
|
1207
|
+
}
|
|
1208
|
+
const escapeTableCell = (cellText) => cellText
|
|
1209
|
+
.replace(/\\/g, '\\\\')
|
|
1210
|
+
.replace(/\|/g, '\\|')
|
|
1211
|
+
.replace(/\r?\n/g, ' ');
|
|
1212
|
+
const dividerFor = (colIdx) => {
|
|
1213
|
+
const align = alignments[colIdx];
|
|
1214
|
+
if (align === 'center')
|
|
1215
|
+
return ':---:';
|
|
1216
|
+
if (align === 'right')
|
|
1217
|
+
return '---:';
|
|
1218
|
+
if (align === 'left')
|
|
1219
|
+
return ':---';
|
|
1220
|
+
return '---';
|
|
1221
|
+
};
|
|
1222
|
+
const escapedHeaders = headers.map((h) => escapeTableCell(h));
|
|
1223
|
+
const headerLine = `| ${escapedHeaders.join(' | ')} |`;
|
|
1224
|
+
const dividerLine = `| ${headers.map((_, colIdx) => dividerFor(colIdx)).join(' | ')} |`;
|
|
1225
|
+
const rowLines = rows.map((row) => {
|
|
1226
|
+
const padded = headers.map((_, colIdx) => escapeTableCell(row[colIdx] ?? ''));
|
|
1227
|
+
return `| ${padded.join(' | ')} |`;
|
|
1228
|
+
});
|
|
1229
|
+
const tableMarkdown = [headerLine, dividerLine, ...rowLines].join('\n');
|
|
1230
|
+
if (typeof input.blockId === 'string' && input.blockId.trim()) {
|
|
1231
|
+
return this.handleReplaceBlock(content, {
|
|
1232
|
+
blockId: input.blockId,
|
|
1233
|
+
markdown: tableMarkdown,
|
|
1234
|
+
expectedRevisionHash: input.expectedRevisionHash
|
|
1235
|
+
}, context);
|
|
1236
|
+
}
|
|
1237
|
+
return this.handleInsertBlockAfter(content, {
|
|
1238
|
+
afterBlockId: input.afterBlockId,
|
|
1239
|
+
markdown: tableMarkdown,
|
|
1240
|
+
expectedRevisionHash: input.expectedRevisionHash
|
|
1241
|
+
}, context);
|
|
1242
|
+
}
|
|
1243
|
+
async handleInsertLiveBlock(content, input, context) {
|
|
1244
|
+
const kind = String(input.kind ?? '');
|
|
1245
|
+
const blockId = typeof input.blockId === 'string' && input.blockId.trim()
|
|
1246
|
+
? input.blockId.trim()
|
|
1247
|
+
: `mj-block-${Date.now()}`;
|
|
1248
|
+
const explicitFields = Array.isArray(input.fields) ? input.fields.map(String) : undefined;
|
|
1249
|
+
const categoryField = typeof input.categoryField === 'string' && input.categoryField.trim()
|
|
1250
|
+
? input.categoryField.trim()
|
|
1251
|
+
: undefined;
|
|
1252
|
+
const valueFields = Array.isArray(input.valueFields)
|
|
1253
|
+
? input.valueFields.map((v) => String(v ?? '').trim()).filter(Boolean)
|
|
1254
|
+
: undefined;
|
|
1255
|
+
const mergedFields = explicitFields && explicitFields.length > 0
|
|
1256
|
+
? explicitFields
|
|
1257
|
+
: categoryField || (valueFields && valueFields.length > 0)
|
|
1258
|
+
? Array.from(new Set([...(categoryField ? [categoryField] : []), ...(valueFields ?? [])]))
|
|
1259
|
+
: undefined;
|
|
1260
|
+
const parameters = input.parameters && typeof input.parameters === 'object' && !Array.isArray(input.parameters)
|
|
1261
|
+
? input.parameters
|
|
1262
|
+
: undefined;
|
|
1263
|
+
const spec = {
|
|
1264
|
+
BlockID: blockId,
|
|
1265
|
+
Kind: kind,
|
|
1266
|
+
Mode: 'Live',
|
|
1267
|
+
Title: typeof input.title === 'string' ? input.title : undefined,
|
|
1268
|
+
EntityName: typeof input.entityName === 'string' ? input.entityName : undefined,
|
|
1269
|
+
ViewID: typeof input.viewId === 'string' ? input.viewId : undefined,
|
|
1270
|
+
ViewName: typeof input.viewName === 'string' && input.viewName.trim() ? input.viewName.trim() : undefined,
|
|
1271
|
+
ExtraFilter: typeof input.extraFilter === 'string' ? input.extraFilter : undefined,
|
|
1272
|
+
Fields: mergedFields,
|
|
1273
|
+
MaxRows: typeof input.maxRows === 'number' && Number.isFinite(input.maxRows) && input.maxRows > 0
|
|
1274
|
+
? Math.floor(input.maxRows)
|
|
1275
|
+
: undefined,
|
|
1276
|
+
DisplayMode: toDisplayMode(input.displayMode),
|
|
1277
|
+
ChartType: toChartType(input.chartType),
|
|
1278
|
+
CategoryField: categoryField,
|
|
1279
|
+
ValueFields: valueFields && valueFields.length > 0 ? valueFields : undefined,
|
|
1280
|
+
QueryID: typeof input.queryId === 'string' ? input.queryId : undefined,
|
|
1281
|
+
QueryName: typeof input.queryName === 'string' ? input.queryName : undefined,
|
|
1282
|
+
Parameters: parameters,
|
|
1283
|
+
DashboardID: typeof input.dashboardId === 'string' ? input.dashboardId : undefined,
|
|
1284
|
+
ComponentID: typeof input.componentId === 'string' ? input.componentId : undefined
|
|
1285
|
+
};
|
|
1286
|
+
const directive = DocumentLiveBlockEngine.Instance.SerializeBlockToMarkdownDirective(spec);
|
|
1287
|
+
const insertResult = await this.handleInsertBlockAfter(content, {
|
|
1288
|
+
afterBlockId: input.afterBlockId,
|
|
1289
|
+
markdown: directive,
|
|
1290
|
+
expectedRevisionHash: input.expectedRevisionHash
|
|
1291
|
+
}, context);
|
|
1292
|
+
if (!insertResult.success || !context?.contextUser || !context?.provider) {
|
|
1293
|
+
return insertResult;
|
|
1294
|
+
}
|
|
1295
|
+
try {
|
|
1296
|
+
const execRes = await DocumentLiveBlockEngine.Instance.ExecuteBlock(spec, context.contextUser, context.provider);
|
|
1297
|
+
if (execRes.AccessDenied || !execRes.Success) {
|
|
1298
|
+
return {
|
|
1299
|
+
success: false,
|
|
1300
|
+
data: null,
|
|
1301
|
+
errorMessage: execRes.ErrorMessage ||
|
|
1302
|
+
`Access denied or execution failed for live block '${spec.BlockID}'.`
|
|
1303
|
+
};
|
|
1304
|
+
}
|
|
1305
|
+
const dataObj = insertResult.data && typeof insertResult.data === 'object' && !Array.isArray(insertResult.data)
|
|
1306
|
+
? insertResult.data
|
|
1307
|
+
: {};
|
|
1308
|
+
return {
|
|
1309
|
+
...insertResult,
|
|
1310
|
+
data: {
|
|
1311
|
+
...dataObj,
|
|
1312
|
+
liveValidation: {
|
|
1313
|
+
blockId: spec.BlockID,
|
|
1314
|
+
valid: true,
|
|
1315
|
+
rowCount: execRes.Rows.length,
|
|
1316
|
+
columns: execRes.Columns.map((c) => c.DisplayName || c.Name),
|
|
1317
|
+
validationError: execRes.ErrorMessage ?? null
|
|
1318
|
+
}
|
|
1319
|
+
}
|
|
1320
|
+
};
|
|
1321
|
+
}
|
|
1322
|
+
catch (err) {
|
|
1323
|
+
return {
|
|
1324
|
+
success: false,
|
|
1325
|
+
data: null,
|
|
1326
|
+
errorMessage: err instanceof Error ? err.message : String(err)
|
|
1327
|
+
};
|
|
1328
|
+
}
|
|
1329
|
+
}
|
|
1330
|
+
async handleEmbedArtifactBlock(content, input, context) {
|
|
1331
|
+
const rawArtifactId = String(input.artifactId ?? '').trim();
|
|
1332
|
+
if (!rawArtifactId) {
|
|
1333
|
+
return { success: false, data: null, errorMessage: 'embed_artifact_block requires artifactId.' };
|
|
1334
|
+
}
|
|
1335
|
+
const resolved = ResolveEmbeddedArtifactId(rawArtifactId, context);
|
|
1336
|
+
if (!resolved.ok) {
|
|
1337
|
+
return { success: false, data: null, errorMessage: resolved.errorMessage };
|
|
1338
|
+
}
|
|
1339
|
+
const artifactId = resolved.artifactId;
|
|
1340
|
+
let resolvedVersionId = null;
|
|
1341
|
+
if (typeof input.versionId === 'string' && input.versionId.trim()) {
|
|
1342
|
+
const verResult = ResolveEmbeddedVersionId(input.versionId, context);
|
|
1343
|
+
if (!verResult.ok) {
|
|
1344
|
+
return { success: false, data: null, errorMessage: verResult.errorMessage };
|
|
1345
|
+
}
|
|
1346
|
+
resolvedVersionId = verResult.versionId;
|
|
1347
|
+
}
|
|
1348
|
+
const access = await ValidateEmbeddedArtifactAccess({
|
|
1349
|
+
targetArtifactId: artifactId,
|
|
1350
|
+
targetVersionId: resolvedVersionId,
|
|
1351
|
+
context
|
|
1352
|
+
});
|
|
1353
|
+
if (!access.Ok) {
|
|
1354
|
+
return { success: false, data: null, errorMessage: access.ErrorMessage || `Cannot embed artifact '${artifactId}'.` };
|
|
1355
|
+
}
|
|
1356
|
+
const replaceBlockId = typeof input.replaceBlockId === 'string' && input.replaceBlockId.trim()
|
|
1357
|
+
? input.replaceBlockId.trim()
|
|
1358
|
+
: undefined;
|
|
1359
|
+
const blockId = typeof input.blockId === 'string' && input.blockId.trim()
|
|
1360
|
+
? input.blockId.trim()
|
|
1361
|
+
: replaceBlockId ?? `mj-artifact-${Date.now()}`;
|
|
1362
|
+
const embedMode = input.embedMode === 'Link' ? 'Link' : 'Inline';
|
|
1363
|
+
const rawSheetId = typeof input.sheetId === 'string' && input.sheetId.trim() ? input.sheetId.trim() : undefined;
|
|
1364
|
+
const rawSheetName = typeof input.sheetName === 'string' && input.sheetName.trim() ? input.sheetName.trim() : undefined;
|
|
1365
|
+
const spec = {
|
|
1366
|
+
BlockID: blockId,
|
|
1367
|
+
Kind: 'Artifact',
|
|
1368
|
+
Mode: 'Live',
|
|
1369
|
+
Title: typeof input.title === 'string' ? input.title : undefined,
|
|
1370
|
+
ArtifactID: artifactId,
|
|
1371
|
+
ArtifactType: typeof input.artifactType === 'string'
|
|
1372
|
+
? input.artifactType
|
|
1373
|
+
: access.ArtifactTypeName ?? 'Whiteboard',
|
|
1374
|
+
EmbedMode: embedMode,
|
|
1375
|
+
VersionID: resolvedVersionId,
|
|
1376
|
+
SheetID: rawSheetId ?? rawSheetName,
|
|
1377
|
+
SheetRange: typeof input.range === 'string' && input.range.trim() ? input.range.trim() : undefined,
|
|
1378
|
+
SheetChartID: typeof input.chartId === 'string' && input.chartId.trim() ? input.chartId.trim() : undefined,
|
|
1379
|
+
DisplayMode: toDisplayMode(input.displayMode)
|
|
1380
|
+
};
|
|
1381
|
+
const directive = DocumentLiveBlockEngine.Instance.SerializeBlockToMarkdownDirective(spec);
|
|
1382
|
+
if (replaceBlockId) {
|
|
1383
|
+
return this.handleReplaceBlock(content, {
|
|
1384
|
+
blockId: replaceBlockId,
|
|
1385
|
+
markdown: directive,
|
|
1386
|
+
expectedRevisionHash: input.expectedRevisionHash
|
|
1387
|
+
}, context);
|
|
1388
|
+
}
|
|
1389
|
+
return this.handleInsertBlockAfter(content, {
|
|
1390
|
+
afterBlockId: input.afterBlockId,
|
|
1391
|
+
markdown: directive,
|
|
1392
|
+
expectedRevisionHash: input.expectedRevisionHash
|
|
1393
|
+
}, context);
|
|
1394
|
+
}
|
|
1395
|
+
handleMoveBlock(content, input) {
|
|
1396
|
+
const conflict = this.checkRevision(content, input.expectedRevisionHash);
|
|
1397
|
+
if (conflict) {
|
|
1398
|
+
return { success: false, data: null, errorMessage: conflict };
|
|
1399
|
+
}
|
|
1400
|
+
const blockId = String(input.blockId ?? '').trim();
|
|
1401
|
+
if (!blockId) {
|
|
1402
|
+
return { success: false, data: null, errorMessage: 'move_block requires blockId.' };
|
|
1403
|
+
}
|
|
1404
|
+
const afterBlockId = typeof input.afterBlockId === 'string' ? input.afterBlockId.trim() : '';
|
|
1405
|
+
if (afterBlockId && afterBlockId === blockId) {
|
|
1406
|
+
return { success: false, data: null, errorMessage: 'move_block cannot move a block relative to itself.' };
|
|
1407
|
+
}
|
|
1408
|
+
const blocks = this.ParseLogicalBlocks(content);
|
|
1409
|
+
const srcIdx = blocks.findIndex((b) => b.blockId === blockId);
|
|
1410
|
+
if (srcIdx < 0) {
|
|
1411
|
+
return { success: false, data: null, errorMessage: `Block '${blockId}' was not found.` };
|
|
1412
|
+
}
|
|
1413
|
+
let insertMode = 'end';
|
|
1414
|
+
if (afterBlockId.toUpperCase() === 'START') {
|
|
1415
|
+
insertMode = 'start';
|
|
1416
|
+
}
|
|
1417
|
+
else if (afterBlockId) {
|
|
1418
|
+
if (!blocks.some((b) => b.blockId === afterBlockId)) {
|
|
1419
|
+
return { success: false, data: null, errorMessage: `Target afterBlockId '${afterBlockId}' was not found.` };
|
|
1420
|
+
}
|
|
1421
|
+
insertMode = 'after';
|
|
1422
|
+
}
|
|
1423
|
+
const [movedBlock] = blocks.splice(srcIdx, 1);
|
|
1424
|
+
if (insertMode === 'start') {
|
|
1425
|
+
blocks.unshift(movedBlock);
|
|
1426
|
+
}
|
|
1427
|
+
else if (insertMode === 'end') {
|
|
1428
|
+
blocks.push(movedBlock);
|
|
1429
|
+
}
|
|
1430
|
+
else {
|
|
1431
|
+
const targetIdx = blocks.findIndex((b) => b.blockId === afterBlockId);
|
|
1432
|
+
blocks.splice(targetIdx + 1, 0, movedBlock);
|
|
1433
|
+
}
|
|
1434
|
+
const updatedContent = this.serializeLogicalBlocks(blocks);
|
|
1435
|
+
return {
|
|
1436
|
+
success: true,
|
|
1437
|
+
data: {
|
|
1438
|
+
blockId,
|
|
1439
|
+
movedAfterBlockId: afterBlockId || 'END',
|
|
1440
|
+
updatedContent,
|
|
1441
|
+
revisionHash: this.ComputeRevisionHash(updatedContent)
|
|
1442
|
+
}
|
|
1443
|
+
};
|
|
1444
|
+
}
|
|
1445
|
+
handleDuplicateBlock(content, input) {
|
|
1446
|
+
const conflict = this.checkRevision(content, input.expectedRevisionHash);
|
|
1447
|
+
if (conflict) {
|
|
1448
|
+
return { success: false, data: null, errorMessage: conflict };
|
|
1449
|
+
}
|
|
1450
|
+
const sourceBlockId = String(input.blockId ?? '').trim();
|
|
1451
|
+
if (!sourceBlockId) {
|
|
1452
|
+
return { success: false, data: null, errorMessage: 'duplicate_block requires blockId.' };
|
|
1453
|
+
}
|
|
1454
|
+
const blocks = this.ParseLogicalBlocks(content);
|
|
1455
|
+
const srcIdx = blocks.findIndex((b) => b.blockId === sourceBlockId);
|
|
1456
|
+
if (srcIdx < 0) {
|
|
1457
|
+
return { success: false, data: null, errorMessage: `Block '${sourceBlockId}' was not found.` };
|
|
1458
|
+
}
|
|
1459
|
+
const sourceBlock = blocks[srcIdx];
|
|
1460
|
+
const existingIds = new Set(blocks.map((b) => b.blockId));
|
|
1461
|
+
const requestedNewId = typeof input.newBlockId === 'string' ? input.newBlockId.trim() : '';
|
|
1462
|
+
let mintedId;
|
|
1463
|
+
if (requestedNewId && !existingIds.has(requestedNewId)) {
|
|
1464
|
+
mintedId = requestedNewId;
|
|
1465
|
+
}
|
|
1466
|
+
else {
|
|
1467
|
+
const prefix = sourceBlock.kind === 'mj-block' ? 'mj' : 'blk';
|
|
1468
|
+
let candidate = `${prefix}-${randomUUID().slice(0, 8)}`;
|
|
1469
|
+
while (existingIds.has(candidate)) {
|
|
1470
|
+
candidate = `${prefix}-${randomUUID().slice(0, 8)}`;
|
|
1471
|
+
}
|
|
1472
|
+
mintedId = candidate;
|
|
1473
|
+
}
|
|
1474
|
+
let clonedRawMarkdown = sourceBlock.rawMarkdown;
|
|
1475
|
+
let clonedSpec = sourceBlock.mjBlockSpec ? { ...sourceBlock.mjBlockSpec, BlockID: mintedId } : undefined;
|
|
1476
|
+
if (sourceBlock.kind === 'mj-block' && clonedSpec) {
|
|
1477
|
+
clonedRawMarkdown = DocumentLiveBlockEngine.Instance.SerializeBlockToMarkdownDirective(clonedSpec);
|
|
1478
|
+
}
|
|
1479
|
+
const duplicatedBlock = {
|
|
1480
|
+
blockId: mintedId,
|
|
1481
|
+
hasExplicitId: sourceBlock.kind !== 'mj-block',
|
|
1482
|
+
kind: sourceBlock.kind,
|
|
1483
|
+
headingLevel: sourceBlock.headingLevel,
|
|
1484
|
+
headingText: sourceBlock.headingText,
|
|
1485
|
+
startLine: 0,
|
|
1486
|
+
endLine: 0,
|
|
1487
|
+
rawMarkdown: clonedRawMarkdown,
|
|
1488
|
+
mjBlockSpec: clonedSpec
|
|
1489
|
+
};
|
|
1490
|
+
const afterBlockId = typeof input.afterBlockId === 'string' ? input.afterBlockId.trim() : '';
|
|
1491
|
+
if (afterBlockId.toUpperCase() === 'START') {
|
|
1492
|
+
blocks.unshift(duplicatedBlock);
|
|
1493
|
+
}
|
|
1494
|
+
else if (afterBlockId) {
|
|
1495
|
+
const targetIdx = blocks.findIndex((b) => b.blockId === afterBlockId);
|
|
1496
|
+
if (targetIdx < 0) {
|
|
1497
|
+
return { success: false, data: null, errorMessage: `Target afterBlockId '${afterBlockId}' was not found.` };
|
|
1498
|
+
}
|
|
1499
|
+
blocks.splice(targetIdx + 1, 0, duplicatedBlock);
|
|
1500
|
+
}
|
|
1501
|
+
else {
|
|
1502
|
+
blocks.splice(srcIdx + 1, 0, duplicatedBlock);
|
|
1503
|
+
}
|
|
1504
|
+
const updatedContent = this.serializeLogicalBlocks(blocks);
|
|
1505
|
+
return {
|
|
1506
|
+
success: true,
|
|
1507
|
+
data: {
|
|
1508
|
+
sourceBlockId,
|
|
1509
|
+
blockId: mintedId,
|
|
1510
|
+
updatedContent,
|
|
1511
|
+
revisionHash: this.ComputeRevisionHash(updatedContent)
|
|
1512
|
+
}
|
|
1513
|
+
};
|
|
1514
|
+
}
|
|
1515
|
+
async handleMutateMarkdownTable(content, input, context) {
|
|
1516
|
+
const conflict = this.checkRevision(content, input.expectedRevisionHash);
|
|
1517
|
+
if (conflict) {
|
|
1518
|
+
return { success: false, data: null, errorMessage: conflict };
|
|
1519
|
+
}
|
|
1520
|
+
const blockId = typeof input.blockId === 'string' ? input.blockId.trim() : '';
|
|
1521
|
+
const operation = typeof input.operation === 'string' ? input.operation.trim() : '';
|
|
1522
|
+
if (!blockId || !operation) {
|
|
1523
|
+
return { success: false, data: null, errorMessage: 'mutate_markdown_table requires blockId and operation.' };
|
|
1524
|
+
}
|
|
1525
|
+
const blocks = this.ParseLogicalBlocks(content);
|
|
1526
|
+
const target = blocks.find((b) => b.blockId === blockId);
|
|
1527
|
+
if (!target || target.kind !== 'table') {
|
|
1528
|
+
return { success: false, data: null, errorMessage: `Markdown table block '${blockId}' was not found.` };
|
|
1529
|
+
}
|
|
1530
|
+
const tableLines = target.rawMarkdown
|
|
1531
|
+
.split(/\r?\n/)
|
|
1532
|
+
.map((l) => l.trim())
|
|
1533
|
+
.filter((l) => l.startsWith('|'));
|
|
1534
|
+
if (tableLines.length < 2) {
|
|
1535
|
+
return { success: false, data: null, errorMessage: `Block '${blockId}' is not a valid pipe-delimited Markdown table.` };
|
|
1536
|
+
}
|
|
1537
|
+
const parseCells = (line) => {
|
|
1538
|
+
const stripped = line.replace(/^\|/, '').replace(/\|$/, '');
|
|
1539
|
+
return stripped.split('|').map((c) => c.trim());
|
|
1540
|
+
};
|
|
1541
|
+
const headers = parseCells(tableLines[0]);
|
|
1542
|
+
const dividers = parseCells(tableLines[1]);
|
|
1543
|
+
const rows = tableLines.slice(2).map((line) => parseCells(line));
|
|
1544
|
+
const escapeCell = (val) => val.replace(/\\/g, '\\\\').replace(/\|/g, '\\|').replace(/\r?\n/g, ' ').trim();
|
|
1545
|
+
switch (operation) {
|
|
1546
|
+
case 'add_row': {
|
|
1547
|
+
const rowVals = Array.isArray(input.row) ? input.row.map((v) => String(v ?? '')) : [];
|
|
1548
|
+
rows.push(headers.map((_, idx) => rowVals[idx] ?? ''));
|
|
1549
|
+
break;
|
|
1550
|
+
}
|
|
1551
|
+
case 'update_row': {
|
|
1552
|
+
const rowIdx = typeof input.rowIndex === 'number' ? Math.trunc(input.rowIndex) : -1;
|
|
1553
|
+
if (rowIdx < 0 || rowIdx >= rows.length) {
|
|
1554
|
+
return { success: false, data: null, errorMessage: `Row index ${rowIdx} is out of bounds.` };
|
|
1555
|
+
}
|
|
1556
|
+
const rowVals = Array.isArray(input.row) ? input.row.map((v) => String(v ?? '')) : [];
|
|
1557
|
+
rows[rowIdx] = headers.map((_, idx) => (idx < rowVals.length ? rowVals[idx] : rows[rowIdx][idx] ?? ''));
|
|
1558
|
+
break;
|
|
1559
|
+
}
|
|
1560
|
+
case 'delete_row': {
|
|
1561
|
+
const rowIdx = typeof input.rowIndex === 'number' ? Math.trunc(input.rowIndex) : -1;
|
|
1562
|
+
if (rowIdx < 0 || rowIdx >= rows.length) {
|
|
1563
|
+
return { success: false, data: null, errorMessage: `Row index ${rowIdx} is out of bounds.` };
|
|
1564
|
+
}
|
|
1565
|
+
rows.splice(rowIdx, 1);
|
|
1566
|
+
break;
|
|
1567
|
+
}
|
|
1568
|
+
case 'add_column': {
|
|
1569
|
+
const colName = typeof input.columnName === 'string' ? input.columnName.trim() : '';
|
|
1570
|
+
if (!colName) {
|
|
1571
|
+
return { success: false, data: null, errorMessage: 'add_column requires columnName.' };
|
|
1572
|
+
}
|
|
1573
|
+
const defVal = typeof input.defaultValue === 'string' ? input.defaultValue : '';
|
|
1574
|
+
headers.push(colName);
|
|
1575
|
+
dividers.push('---');
|
|
1576
|
+
for (const r of rows) {
|
|
1577
|
+
r.push(defVal);
|
|
1578
|
+
}
|
|
1579
|
+
break;
|
|
1580
|
+
}
|
|
1581
|
+
case 'rename_column': {
|
|
1582
|
+
const colName = typeof input.columnName === 'string' ? input.columnName.trim() : '';
|
|
1583
|
+
const nextName = typeof input.newColumnName === 'string' ? input.newColumnName.trim() : '';
|
|
1584
|
+
const colIdx = headers.findIndex((h) => h.toLowerCase() === colName.toLowerCase());
|
|
1585
|
+
if (colIdx < 0 || !nextName) {
|
|
1586
|
+
return { success: false, data: null, errorMessage: `Column '${colName}' not found or newColumnName missing.` };
|
|
1587
|
+
}
|
|
1588
|
+
headers[colIdx] = nextName;
|
|
1589
|
+
break;
|
|
1590
|
+
}
|
|
1591
|
+
default:
|
|
1592
|
+
return { success: false, data: null, errorMessage: `Unsupported table operation '${operation}'.` };
|
|
1593
|
+
}
|
|
1594
|
+
const nextTableMd = [
|
|
1595
|
+
`| ${headers.map(escapeCell).join(' | ')} |`,
|
|
1596
|
+
`| ${headers.map((_, idx) => dividers[idx] || '---').join(' | ')} |`,
|
|
1597
|
+
...rows.map((r) => `| ${headers.map((_, idx) => escapeCell(r[idx] ?? '')).join(' | ')} |`)
|
|
1598
|
+
].join('\n');
|
|
1599
|
+
return this.handleReplaceBlock(content, {
|
|
1600
|
+
blockId,
|
|
1601
|
+
markdown: nextTableMd,
|
|
1602
|
+
expectedRevisionHash: input.expectedRevisionHash
|
|
1603
|
+
}, context);
|
|
1604
|
+
}
|
|
1605
|
+
handleUpsertFrontmatter(content, input) {
|
|
1606
|
+
const conflict = this.checkRevision(content, input.expectedRevisionHash);
|
|
1607
|
+
if (conflict) {
|
|
1608
|
+
return { success: false, data: null, errorMessage: conflict };
|
|
1609
|
+
}
|
|
1610
|
+
const rawFields = input.fields && typeof input.fields === 'object' && !Array.isArray(input.fields)
|
|
1611
|
+
? input.fields
|
|
1612
|
+
: null;
|
|
1613
|
+
if (!rawFields) {
|
|
1614
|
+
return { success: false, data: null, errorMessage: 'upsert_frontmatter requires a fields object.' };
|
|
1615
|
+
}
|
|
1616
|
+
const fmMatch = content.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/);
|
|
1617
|
+
const existingMap = new Map();
|
|
1618
|
+
let body = content;
|
|
1619
|
+
if (fmMatch) {
|
|
1620
|
+
body = content.slice(fmMatch[0].length);
|
|
1621
|
+
for (const line of fmMatch[1].split(/\r?\n/)) {
|
|
1622
|
+
const colonIdx = line.indexOf(':');
|
|
1623
|
+
if (colonIdx > 0) {
|
|
1624
|
+
existingMap.set(line.slice(0, colonIdx).trim(), line.slice(colonIdx + 1).trim());
|
|
1625
|
+
}
|
|
1626
|
+
}
|
|
1627
|
+
}
|
|
1628
|
+
const removeKeys = Array.isArray(input.removeKeys)
|
|
1629
|
+
? input.removeKeys.filter((k) => typeof k === 'string')
|
|
1630
|
+
: [];
|
|
1631
|
+
for (const k of removeKeys) {
|
|
1632
|
+
existingMap.delete(k.trim());
|
|
1633
|
+
}
|
|
1634
|
+
for (const [k, v] of Object.entries(rawFields)) {
|
|
1635
|
+
if (!k.trim() || v === undefined)
|
|
1636
|
+
continue;
|
|
1637
|
+
const serialized = typeof v === 'string'
|
|
1638
|
+
? JSON.stringify(v)
|
|
1639
|
+
: typeof v === 'number' || typeof v === 'boolean' || v === null
|
|
1640
|
+
? String(v)
|
|
1641
|
+
: JSON.stringify(v);
|
|
1642
|
+
existingMap.set(k.trim(), serialized);
|
|
1643
|
+
}
|
|
1644
|
+
const fmLines = Array.from(existingMap.entries()).map(([k, v]) => `${k}: ${v}`);
|
|
1645
|
+
const updatedContent = fmLines.length > 0 ? `---\n${fmLines.join('\n')}\n---\n${body}` : body;
|
|
1646
|
+
return {
|
|
1647
|
+
success: true,
|
|
1648
|
+
data: {
|
|
1649
|
+
updatedContent,
|
|
1650
|
+
frontmatterKeys: Array.from(existingMap.keys()),
|
|
1651
|
+
revisionHash: this.ComputeRevisionHash(updatedContent)
|
|
1652
|
+
}
|
|
1653
|
+
};
|
|
1654
|
+
}
|
|
1655
|
+
handleToggleLock(content, input, locked, context) {
|
|
1656
|
+
const conflict = this.checkRevision(content, input.expectedRevisionHash);
|
|
1657
|
+
if (conflict) {
|
|
1658
|
+
return { success: false, data: null, errorMessage: conflict };
|
|
1659
|
+
}
|
|
1660
|
+
let lineNum = typeof input.headingLineNumber === 'number' && Number.isFinite(input.headingLineNumber)
|
|
1661
|
+
? Math.trunc(input.headingLineNumber)
|
|
1662
|
+
: 0;
|
|
1663
|
+
const blocks = this.ParseLogicalBlocks(content);
|
|
1664
|
+
if (lineNum <= 0 && typeof input.blockId === 'string' && input.blockId.trim()) {
|
|
1665
|
+
const match = blocks.find((b) => b.blockId === input.blockId.toString().trim() && b.kind === 'heading');
|
|
1666
|
+
if (match) {
|
|
1667
|
+
lineNum = match.startLine;
|
|
1668
|
+
}
|
|
1669
|
+
}
|
|
1670
|
+
if (lineNum <= 0 && typeof input.heading === 'string' && input.heading.trim()) {
|
|
1671
|
+
const target = input.heading.trim().toLowerCase();
|
|
1672
|
+
const match = blocks.find((b) => b.kind === 'heading' && (b.headingText ?? '').trim().toLowerCase() === target);
|
|
1673
|
+
if (match) {
|
|
1674
|
+
lineNum = match.startLine;
|
|
1675
|
+
}
|
|
1676
|
+
}
|
|
1677
|
+
if (lineNum <= 0) {
|
|
1678
|
+
return {
|
|
1679
|
+
success: false,
|
|
1680
|
+
data: null,
|
|
1681
|
+
errorMessage: 'set_lock / release_lock requires headingLineNumber, heading, or a heading blockId.'
|
|
1682
|
+
};
|
|
1683
|
+
}
|
|
1684
|
+
const actorUserId = context?.actorUserId ?? context?.contextUser?.ID ?? 'system';
|
|
1685
|
+
const ownerUserId = context?.ownerUserId;
|
|
1686
|
+
const isEditor = Boolean(context?.isEditor);
|
|
1687
|
+
try {
|
|
1688
|
+
const updatedContent = DocumentLiveBlockEngine.Instance.ToggleHeadingLockInMarkdown(content, lineNum, locked, actorUserId, ownerUserId, isEditor);
|
|
1689
|
+
return {
|
|
1690
|
+
success: true,
|
|
1691
|
+
data: {
|
|
1692
|
+
locked,
|
|
1693
|
+
headingLineNumber: lineNum,
|
|
1694
|
+
updatedContent,
|
|
1695
|
+
revisionHash: this.ComputeRevisionHash(updatedContent)
|
|
1696
|
+
}
|
|
1697
|
+
};
|
|
1698
|
+
}
|
|
1699
|
+
catch (err) {
|
|
1700
|
+
return {
|
|
1701
|
+
success: false,
|
|
1702
|
+
data: null,
|
|
1703
|
+
errorMessage: err instanceof Error ? err.message : String(err)
|
|
1704
|
+
};
|
|
1705
|
+
}
|
|
1706
|
+
}
|
|
1707
|
+
resolveDocumentSuggestionAnchor(content, anchor, originalSlice) {
|
|
1708
|
+
const blocks = this.ParseLogicalBlocks(content);
|
|
1709
|
+
if (anchor.BlockId) {
|
|
1710
|
+
const block = blocks.find((b) => b.blockId === anchor.BlockId);
|
|
1711
|
+
if (!block) {
|
|
1712
|
+
return { ok: false, errorMessage: `Target block '${anchor.BlockId}' was not found.` };
|
|
1713
|
+
}
|
|
1714
|
+
if (originalSlice && !block.rawMarkdown.includes(originalSlice)) {
|
|
1715
|
+
return {
|
|
1716
|
+
ok: false,
|
|
1717
|
+
errorMessage: `originalSlice was not found inside block '${anchor.BlockId}'.`
|
|
1718
|
+
};
|
|
1719
|
+
}
|
|
1720
|
+
return {
|
|
1721
|
+
ok: true,
|
|
1722
|
+
resolvedAnchor: {
|
|
1723
|
+
...anchor,
|
|
1724
|
+
BlockId: block.blockId,
|
|
1725
|
+
...(block.headingText && !anchor.Heading ? { Heading: block.headingText } : {})
|
|
1726
|
+
}
|
|
1727
|
+
};
|
|
1728
|
+
}
|
|
1729
|
+
if (originalSlice && !content.includes(originalSlice)) {
|
|
1730
|
+
return { ok: false, errorMessage: 'originalSlice was not found in the document.' };
|
|
1731
|
+
}
|
|
1732
|
+
const needle = originalSlice || (typeof anchor.Quote === 'string' ? anchor.Quote : '');
|
|
1733
|
+
let searchBlocks = blocks;
|
|
1734
|
+
let matchedHeadingBlock;
|
|
1735
|
+
if (anchor.Heading) {
|
|
1736
|
+
const targetHeading = anchor.Heading.trim().toLowerCase();
|
|
1737
|
+
const headingIdx = blocks.findIndex((b) => b.kind === 'heading' &&
|
|
1738
|
+
((b.headingText ?? '').trim().toLowerCase() === targetHeading ||
|
|
1739
|
+
(b.headingText ?? '').trim().toLowerCase().includes(targetHeading)));
|
|
1740
|
+
if (headingIdx >= 0) {
|
|
1741
|
+
matchedHeadingBlock = blocks[headingIdx];
|
|
1742
|
+
const baseLevel = matchedHeadingBlock.headingLevel ?? 1;
|
|
1743
|
+
let endIdx = blocks.length;
|
|
1744
|
+
for (let i = headingIdx + 1; i < blocks.length; i++) {
|
|
1745
|
+
const candidate = blocks[i];
|
|
1746
|
+
if (candidate.kind === 'heading' && (candidate.headingLevel ?? 6) <= baseLevel) {
|
|
1747
|
+
endIdx = i;
|
|
1748
|
+
break;
|
|
1749
|
+
}
|
|
1750
|
+
}
|
|
1751
|
+
searchBlocks = blocks.slice(headingIdx, endIdx);
|
|
1752
|
+
}
|
|
1753
|
+
}
|
|
1754
|
+
const matchedBlock = needle
|
|
1755
|
+
? searchBlocks.find((b) => b.rawMarkdown.includes(needle)) ??
|
|
1756
|
+
(searchBlocks !== blocks ? blocks.find((b) => b.rawMarkdown.includes(needle)) : undefined)
|
|
1757
|
+
: matchedHeadingBlock;
|
|
1758
|
+
if (matchedBlock) {
|
|
1759
|
+
return {
|
|
1760
|
+
ok: true,
|
|
1761
|
+
resolvedAnchor: {
|
|
1762
|
+
...anchor,
|
|
1763
|
+
BlockId: matchedBlock.blockId,
|
|
1764
|
+
...(matchedBlock.headingText && !anchor.Heading
|
|
1765
|
+
? { Heading: matchedBlock.headingText }
|
|
1766
|
+
: matchedHeadingBlock?.headingText && !anchor.Heading
|
|
1767
|
+
? { Heading: matchedHeadingBlock.headingText }
|
|
1768
|
+
: {})
|
|
1769
|
+
}
|
|
1770
|
+
};
|
|
1771
|
+
}
|
|
1772
|
+
return { ok: true };
|
|
1773
|
+
}
|
|
1774
|
+
async handleProposeSuggestion(content, input, context) {
|
|
1775
|
+
return ExecuteProposeSuggestionTool({
|
|
1776
|
+
domain: 'document',
|
|
1777
|
+
artifactContent: content,
|
|
1778
|
+
input,
|
|
1779
|
+
context,
|
|
1780
|
+
validateTarget: (anchor, originalSlice) => this.resolveDocumentSuggestionAnchor(content, anchor, originalSlice)
|
|
1781
|
+
});
|
|
1782
|
+
}
|
|
1783
|
+
async handleReviewSuggestion(content, input, context) {
|
|
1784
|
+
return ExecuteReviewSuggestionTool({
|
|
1785
|
+
domain: 'document',
|
|
1786
|
+
artifactContent: content,
|
|
1787
|
+
input,
|
|
1788
|
+
context,
|
|
1789
|
+
applyAcceptedSuggestion: async (suggestion) => {
|
|
1790
|
+
let updatedContent = content;
|
|
1791
|
+
const targetAnchor = ParseSuggestionAnchor(suggestion.Anchor, 'document');
|
|
1792
|
+
if (targetAnchor.BlockId) {
|
|
1793
|
+
const blocks = this.ParseLogicalBlocks(content);
|
|
1794
|
+
const idx = blocks.findIndex((b) => b.blockId === targetAnchor.BlockId);
|
|
1795
|
+
if (idx < 0) {
|
|
1796
|
+
return { ok: false, errorMessage: `Target block '${targetAnchor.BlockId}' was not found.` };
|
|
1797
|
+
}
|
|
1798
|
+
const block = blocks[idx];
|
|
1799
|
+
if (suggestion.OriginalSlice && !block.rawMarkdown.includes(suggestion.OriginalSlice)) {
|
|
1800
|
+
return {
|
|
1801
|
+
ok: false,
|
|
1802
|
+
errorMessage: `originalSlice is stale and no longer matches block '${targetAnchor.BlockId}'.`
|
|
1803
|
+
};
|
|
1804
|
+
}
|
|
1805
|
+
const nextRaw = suggestion.OriginalSlice
|
|
1806
|
+
? block.rawMarkdown.replace(suggestion.OriginalSlice, () => suggestion.ProposedReplacement)
|
|
1807
|
+
: suggestion.ProposedReplacement;
|
|
1808
|
+
blocks[idx] = { ...block, rawMarkdown: nextRaw };
|
|
1809
|
+
updatedContent = this.serializeLogicalBlocks(blocks);
|
|
1810
|
+
}
|
|
1811
|
+
else {
|
|
1812
|
+
if (!suggestion.OriginalSlice || !content.includes(suggestion.OriginalSlice)) {
|
|
1813
|
+
return {
|
|
1814
|
+
ok: false,
|
|
1815
|
+
errorMessage: 'originalSlice is stale or empty and cannot be unambiguously applied.'
|
|
1816
|
+
};
|
|
1817
|
+
}
|
|
1818
|
+
updatedContent = content.replace(suggestion.OriginalSlice, () => suggestion.ProposedReplacement);
|
|
1819
|
+
}
|
|
1820
|
+
const normalized = await this.normalizeArtifactBlocksInMarkdown(updatedContent, context);
|
|
1821
|
+
if (!normalized.ok) {
|
|
1822
|
+
return { ok: false, errorMessage: normalized.errorMessage };
|
|
1823
|
+
}
|
|
1824
|
+
updatedContent = normalized.markdown;
|
|
1825
|
+
const lockCheck = DocumentLiveBlockEngine.Instance.ValidateDocumentEditAgainstLocks(content, updatedContent, context?.actorUserId ?? context?.contextUser?.ID, context?.ownerUserId, Boolean(context?.isEditor));
|
|
1826
|
+
if (!lockCheck.Allowed) {
|
|
1827
|
+
return {
|
|
1828
|
+
ok: false,
|
|
1829
|
+
errorMessage: lockCheck.ViolationReason ||
|
|
1830
|
+
'Cannot apply suggestion to a locked Markdown section.'
|
|
1831
|
+
};
|
|
1832
|
+
}
|
|
1833
|
+
return {
|
|
1834
|
+
ok: true,
|
|
1835
|
+
updatedContent,
|
|
1836
|
+
revisionHash: this.ComputeRevisionHash(updatedContent)
|
|
1837
|
+
};
|
|
1838
|
+
}
|
|
1839
|
+
});
|
|
1840
|
+
}
|
|
1841
|
+
};
|
|
1842
|
+
DocumentToolLibrary = __decorate([
|
|
1843
|
+
RegisterClass(BaseArtifactToolLibrary, 'DocumentToolLibrary')
|
|
1844
|
+
], DocumentToolLibrary);
|
|
1845
|
+
export { DocumentToolLibrary };
|
|
1846
|
+
//# sourceMappingURL=DocumentToolLibrary.js.map
|