@memberjunction/ai-agents 6.2.0-edge.4 → 6.2.0-edge.6
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 +154 -7
- package/dist/AgentDataPreloader.d.ts +4 -2
- package/dist/AgentDataPreloader.d.ts.map +1 -1
- package/dist/AgentDataPreloader.js +21 -12
- package/dist/AgentDataPreloader.js.map +1 -1
- package/dist/AgentRunner.d.ts +61 -6
- package/dist/AgentRunner.d.ts.map +1 -1
- package/dist/AgentRunner.js +313 -68
- package/dist/AgentRunner.js.map +1 -1
- package/dist/AgentWakeTriggerService.d.ts +183 -0
- package/dist/AgentWakeTriggerService.d.ts.map +1 -0
- package/dist/AgentWakeTriggerService.js +478 -0
- package/dist/AgentWakeTriggerService.js.map +1 -0
- package/dist/ArtifactToolManager.d.ts +12 -3
- package/dist/ArtifactToolManager.d.ts.map +1 -1
- package/dist/ArtifactToolManager.js +77 -6
- package/dist/ArtifactToolManager.js.map +1 -1
- package/dist/ClientToolRequestManager.d.ts +11 -1
- package/dist/ClientToolRequestManager.d.ts.map +1 -1
- package/dist/ClientToolRequestManager.js +19 -6
- package/dist/ClientToolRequestManager.js.map +1 -1
- package/dist/ConversationToolManager.d.ts +1 -1
- package/dist/ConversationToolManager.d.ts.map +1 -1
- package/dist/ConversationToolManager.js +10 -4
- package/dist/ConversationToolManager.js.map +1 -1
- package/dist/MJAIAgentRequestEntityServer.d.ts.map +1 -1
- package/dist/MJAIAgentRequestEntityServer.js +20 -0
- package/dist/MJAIAgentRequestEntityServer.js.map +1 -1
- package/dist/PayloadChangeAnalyzer.d.ts.map +1 -1
- package/dist/PayloadChangeAnalyzer.js +53 -30
- package/dist/PayloadChangeAnalyzer.js.map +1 -1
- package/dist/PayloadManager.d.ts +35 -2
- package/dist/PayloadManager.d.ts.map +1 -1
- package/dist/PayloadManager.js +250 -149
- package/dist/PayloadManager.js.map +1 -1
- package/dist/ScratchpadManager.d.ts +18 -0
- package/dist/ScratchpadManager.d.ts.map +1 -1
- package/dist/ScratchpadManager.js +61 -0
- package/dist/ScratchpadManager.js.map +1 -1
- package/dist/agent-audience.d.ts +38 -0
- package/dist/agent-audience.d.ts.map +1 -0
- package/dist/agent-audience.js +99 -0
- package/dist/agent-audience.js.map +1 -0
- package/dist/agent-context-injector.d.ts +38 -6
- package/dist/agent-context-injector.d.ts.map +1 -1
- package/dist/agent-context-injector.js +72 -20
- package/dist/agent-context-injector.js.map +1 -1
- package/dist/agent-memory-context-builder.d.ts +7 -2
- package/dist/agent-memory-context-builder.d.ts.map +1 -1
- package/dist/agent-memory-context-builder.js +14 -5
- package/dist/agent-memory-context-builder.js.map +1 -1
- package/dist/agent-pre-execution-rag.d.ts +101 -9
- package/dist/agent-pre-execution-rag.d.ts.map +1 -1
- package/dist/agent-pre-execution-rag.js +227 -29
- package/dist/agent-pre-execution-rag.js.map +1 -1
- package/dist/agent-run-watchdog.d.ts +23 -8
- package/dist/agent-run-watchdog.d.ts.map +1 -1
- package/dist/agent-run-watchdog.js +141 -76
- package/dist/agent-run-watchdog.js.map +1 -1
- package/dist/agent-types/flow-agent-type.d.ts +15 -0
- package/dist/agent-types/flow-agent-type.d.ts.map +1 -1
- package/dist/agent-types/flow-agent-type.js +129 -13
- package/dist/agent-types/flow-agent-type.js.map +1 -1
- package/dist/agent-types/loop-agent-prompt-params.d.ts +6 -2
- package/dist/agent-types/loop-agent-prompt-params.d.ts.map +1 -1
- package/dist/agent-types/loop-agent-prompt-params.js.map +1 -1
- package/dist/agent-types/loop-agent-response-type.d.ts +8 -2
- package/dist/agent-types/loop-agent-response-type.d.ts.map +1 -1
- package/dist/agent-types/loop-agent-response-type.js.map +1 -1
- package/dist/agent-types/loop-agent-type.d.ts +85 -7
- package/dist/agent-types/loop-agent-type.d.ts.map +1 -1
- package/dist/agent-types/loop-agent-type.js +290 -66
- package/dist/agent-types/loop-agent-type.js.map +1 -1
- package/dist/base-agent.d.ts +809 -38
- package/dist/base-agent.d.ts.map +1 -1
- package/dist/base-agent.js +3308 -609
- package/dist/base-agent.js.map +1 -1
- package/dist/bound-action-params.d.ts +57 -0
- package/dist/bound-action-params.d.ts.map +1 -0
- package/dist/bound-action-params.js +91 -0
- package/dist/bound-action-params.js.map +1 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +9 -0
- package/dist/index.js.map +1 -1
- package/dist/memory-cleanup-agent.d.ts.map +1 -1
- package/dist/memory-cleanup-agent.js +3 -0
- package/dist/memory-cleanup-agent.js.map +1 -1
- package/dist/memory-manager-agent.d.ts.map +1 -1
- package/dist/memory-manager-agent.js +52 -35
- package/dist/memory-manager-agent.js.map +1 -1
- package/dist/native-tools/action-param-schema.d.ts +57 -0
- package/dist/native-tools/action-param-schema.d.ts.map +1 -0
- package/dist/native-tools/action-param-schema.js +238 -0
- package/dist/native-tools/action-param-schema.js.map +1 -0
- package/dist/native-tools/action-tool-builder.d.ts +5 -4
- package/dist/native-tools/action-tool-builder.d.ts.map +1 -1
- package/dist/native-tools/action-tool-builder.js +29 -71
- package/dist/native-tools/action-tool-builder.js.map +1 -1
- package/dist/native-tools/agent-tools.d.ts +64 -0
- package/dist/native-tools/agent-tools.d.ts.map +1 -0
- package/dist/native-tools/agent-tools.js +23 -0
- package/dist/native-tools/agent-tools.js.map +1 -0
- package/dist/native-tools/control-tools.d.ts +26 -4
- package/dist/native-tools/control-tools.d.ts.map +1 -1
- package/dist/native-tools/control-tools.js +114 -42
- package/dist/native-tools/control-tools.js.map +1 -1
- package/dist/native-tools/framework-tools.d.ts +47 -0
- package/dist/native-tools/framework-tools.d.ts.map +1 -0
- package/dist/native-tools/framework-tools.js +187 -0
- package/dist/native-tools/framework-tools.js.map +1 -0
- package/dist/native-tools/json-argument.d.ts +41 -0
- package/dist/native-tools/json-argument.d.ts.map +1 -0
- package/dist/native-tools/json-argument.js +79 -0
- package/dist/native-tools/json-argument.js.map +1 -0
- package/dist/native-tools/native-control-config.d.ts +93 -0
- package/dist/native-tools/native-control-config.d.ts.map +1 -0
- package/dist/native-tools/native-control-config.js +104 -0
- package/dist/native-tools/native-control-config.js.map +1 -0
- package/dist/native-tools/tool-result-turns.d.ts +41 -8
- package/dist/native-tools/tool-result-turns.d.ts.map +1 -1
- package/dist/native-tools/tool-result-turns.js +76 -2
- package/dist/native-tools/tool-result-turns.js.map +1 -1
- package/dist/native-tools/turn-mode.d.ts +8 -0
- package/dist/native-tools/turn-mode.d.ts.map +1 -0
- package/dist/native-tools/turn-mode.js +14 -0
- package/dist/native-tools/turn-mode.js.map +1 -0
- package/dist/query-builder-agent.d.ts +33 -5
- package/dist/query-builder-agent.d.ts.map +1 -1
- package/dist/query-builder-agent.js +137 -30
- package/dist/query-builder-agent.js.map +1 -1
- package/dist/realtime/bridge-room-transcript-sink.js +1 -0
- package/dist/realtime/bridge-room-transcript-sink.js.map +1 -1
- package/dist/realtime/bridge-session-transcript-sink.js +1 -0
- package/dist/realtime/bridge-session-transcript-sink.js.map +1 -1
- package/dist/realtime/realtime-client-session-service.d.ts +5 -4
- package/dist/realtime/realtime-client-session-service.d.ts.map +1 -1
- package/dist/realtime/realtime-client-session-service.js +42 -30
- package/dist/realtime/realtime-client-session-service.js.map +1 -1
- package/dist/realtime/realtime-coagent-config.d.ts +8 -1
- package/dist/realtime/realtime-coagent-config.d.ts.map +1 -1
- package/dist/realtime/realtime-coagent-config.js +17 -1
- package/dist/realtime/realtime-coagent-config.js.map +1 -1
- package/dist/realtime/realtime-recording-ledger.d.ts +150 -0
- package/dist/realtime/realtime-recording-ledger.d.ts.map +1 -0
- package/dist/realtime/realtime-recording-ledger.js +206 -0
- package/dist/realtime/realtime-recording-ledger.js.map +1 -0
- package/dist/realtime/realtime-recording-opus-assembly.d.ts +211 -0
- package/dist/realtime/realtime-recording-opus-assembly.d.ts.map +1 -0
- package/dist/realtime/realtime-recording-opus-assembly.js +706 -0
- package/dist/realtime/realtime-recording-opus-assembly.js.map +1 -0
- package/dist/realtime/realtime-recording-store.d.ts +44 -6
- package/dist/realtime/realtime-recording-store.d.ts.map +1 -1
- package/dist/realtime/realtime-recording-store.js +105 -51
- package/dist/realtime/realtime-recording-store.js.map +1 -1
- package/dist/realtime/realtime-turn-moderator.d.ts +2 -1
- package/dist/realtime/realtime-turn-moderator.d.ts.map +1 -1
- package/dist/realtime/realtime-turn-moderator.js +7 -1
- package/dist/realtime/realtime-turn-moderator.js.map +1 -1
- package/dist/volatile-child-prompt.js +3 -3
- package/package.json +21 -19
package/dist/AgentRunner.js
CHANGED
|
@@ -11,12 +11,13 @@
|
|
|
11
11
|
*/
|
|
12
12
|
import { createHash } from 'crypto';
|
|
13
13
|
import { LogError, LogStatusEx, IsVerboseLoggingEnabled, LogStatus, Metadata, RunView, RunQuery, ProviderType } from '@memberjunction/core';
|
|
14
|
-
import { MJGlobal, UUIDsEqual, IsValidUUID, EscapeSQLString } from '@memberjunction/global';
|
|
14
|
+
import { MJGlobal, UUIDsEqual, IsValidUUID, EscapeSQLString, IndexByUUID } from '@memberjunction/global';
|
|
15
15
|
import { AIEngine } from '@memberjunction/aiengine';
|
|
16
|
-
import { ResolvePromptRunUserID } from '@memberjunction/ai-core-plus';
|
|
16
|
+
import { ResolvePromptRunUserID, WithAgentRunDataTrustApplied } from '@memberjunction/ai-core-plus';
|
|
17
17
|
import { PlanArtifactTarget, IsKnownArtifactBehavior } from './artifact-target-plan.js';
|
|
18
18
|
import { BaseAgent } from './base-agent.js';
|
|
19
19
|
import { MJEnvironmentEntityExtended, ArtifactMetadataEngine, ConversationEngine, ExtractBase64FromDataUrl, DecideInlineStorage } from '@memberjunction/core-entities';
|
|
20
|
+
import { ActionEngineServer } from '@memberjunction/actions';
|
|
20
21
|
import { FileStorageEngine } from '@memberjunction/storage';
|
|
21
22
|
/**
|
|
22
23
|
* Choose the artifact a run should be represented by.
|
|
@@ -86,6 +87,8 @@ export class AgentRunner {
|
|
|
86
87
|
}
|
|
87
88
|
/** Fallback artifact type for agent payloads when the agent declares no DefaultArtifactTypeID. */
|
|
88
89
|
static { this.JSON_ARTIFACT_TYPE_ID = 'ae674c7e-ea0d-49ea-89e4-0649f5eb20d4'; }
|
|
90
|
+
/** Artifact type for structured research report payloads containing `{ report: { html } }`. */
|
|
91
|
+
static { this.RESEARCH_CONTENT_ARTIFACT_TYPE_ID = 'a7b8c9d0-e1f2-3a4b-5c6d-7e8f9a0b1c2d'; }
|
|
89
92
|
/**
|
|
90
93
|
* Max length of `MJ: Artifacts.Name` (`nvarchar(255)`).
|
|
91
94
|
*
|
|
@@ -138,12 +141,34 @@ export class AgentRunner {
|
|
|
138
141
|
if (!agentInstance) {
|
|
139
142
|
throw new Error(`Failed to create agent instance for driver class: ${driverClass}`);
|
|
140
143
|
}
|
|
144
|
+
// Ensure caller params carries the shared AgentTreeBudget reference before any shallow
|
|
145
|
+
// clone occurs in hydrateConversationArtifacts or Execute.
|
|
146
|
+
if (!params.treeBudget) {
|
|
147
|
+
params.treeBudget = {
|
|
148
|
+
maxTreeSteps: params.maxTreeSteps,
|
|
149
|
+
maxTreeTokens: params.maxTreeTokens,
|
|
150
|
+
maxTreeCost: params.maxTreeCost,
|
|
151
|
+
maxTreeDurationMs: params.maxTreeDurationMs,
|
|
152
|
+
totalSteps: 0,
|
|
153
|
+
totalTokens: 0,
|
|
154
|
+
totalCost: 0,
|
|
155
|
+
startedAtMs: Date.now()
|
|
156
|
+
};
|
|
157
|
+
}
|
|
141
158
|
// A conversation-linked run must see the conversation's artifacts no matter which
|
|
142
159
|
// entry point the caller used. See hydrateConversationArtifacts for why.
|
|
143
160
|
const runParams = await this.hydrateConversationArtifacts(params);
|
|
161
|
+
runParams.treeBudget = params.treeBudget;
|
|
144
162
|
// Execute the agent and return the result directly, threading the isolated provider.
|
|
145
163
|
// Favor provider already in params (caller-supplied) over the instance-level provider.
|
|
146
|
-
|
|
164
|
+
try {
|
|
165
|
+
return await agentInstance.Execute({ ...runParams, provider: runParams.provider || this._provider });
|
|
166
|
+
}
|
|
167
|
+
finally {
|
|
168
|
+
if (agentInstance.TreeBudget) {
|
|
169
|
+
params.treeBudget = agentInstance.TreeBudget;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
147
172
|
}
|
|
148
173
|
catch (error) {
|
|
149
174
|
const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
|
|
@@ -153,6 +178,46 @@ export class AgentRunner {
|
|
|
153
178
|
throw error;
|
|
154
179
|
}
|
|
155
180
|
}
|
|
181
|
+
/**
|
|
182
|
+
* Creates the reply row for an agent's turn on the server: `Role` `AI`, In-Progress, '⏳ Starting...', marked with
|
|
183
|
+
* `MarkServerAuthoredReply()` so the conversation detail gate accepts it. Only the server writes replies, so this is
|
|
184
|
+
* the one place a reply row starts; pass the returned instance to {@link RunAgentInConversation} as
|
|
185
|
+
* `agentResponseDetail` and the run writes its progress and result into it.
|
|
186
|
+
*
|
|
187
|
+
* @param args.conversationId The conversation the reply belongs to.
|
|
188
|
+
* @param args.branchId The fork it sits on, the same as the message it answers; null or omitted is Main.
|
|
189
|
+
* @param args.agentId The agent the reply is from; null for a status line no agent wrote (a workflow's).
|
|
190
|
+
* @param args.contextUser Whom the row is written as: the person the reply is for. They must own the conversation
|
|
191
|
+
* or hold an `Edit` grant on it.
|
|
192
|
+
* @param args.parentId The message the reply answers, when known.
|
|
193
|
+
* @param args.testRunId A test run to link the row to.
|
|
194
|
+
* @param args.provider The provider to write through; defaults to this runner's.
|
|
195
|
+
* @param args.message The row's text, for a server-composed status line; defaults to '⏳ Starting...'.
|
|
196
|
+
* @param args.status The row's status; defaults to In-Progress (a reply a run will fill).
|
|
197
|
+
* @returns The saved row. Throws with the gate's reason when the save is refused.
|
|
198
|
+
*/
|
|
199
|
+
async CreateAgentReplyDetail(args) {
|
|
200
|
+
const md = args.provider || this._provider;
|
|
201
|
+
const reply = await md.GetEntityObject('MJ: Conversation Details', args.contextUser);
|
|
202
|
+
reply.MarkServerAuthoredReply();
|
|
203
|
+
reply.ConversationID = args.conversationId;
|
|
204
|
+
reply.BranchID = args.branchId ?? null;
|
|
205
|
+
reply.Message = args.message ?? '⏳ Starting...';
|
|
206
|
+
reply.Role = 'AI';
|
|
207
|
+
reply.Status = args.status ?? 'In-Progress';
|
|
208
|
+
reply.HiddenToUser = false;
|
|
209
|
+
reply.AgentID = args.agentId;
|
|
210
|
+
if (args.parentId) {
|
|
211
|
+
reply.ParentID = args.parentId;
|
|
212
|
+
}
|
|
213
|
+
if (args.testRunId) {
|
|
214
|
+
reply.TestRunID = args.testRunId; // test execution traceability
|
|
215
|
+
}
|
|
216
|
+
if (!(await reply.Save())) {
|
|
217
|
+
throw new Error(`Failed to create agent response conversation detail: ${AgentRunner.saveFailureReason(reply)}`);
|
|
218
|
+
}
|
|
219
|
+
return reply;
|
|
220
|
+
}
|
|
156
221
|
/**
|
|
157
222
|
* Runs an AI agent within a conversation context, handling conversation and artifact management.
|
|
158
223
|
*
|
|
@@ -187,13 +252,26 @@ export class AgentRunner {
|
|
|
187
252
|
if (!contextUser) {
|
|
188
253
|
throw new Error('contextUser is required for RunAgentInConversation');
|
|
189
254
|
}
|
|
255
|
+
const conversationWriter = options.ConversationWriter ?? contextUser;
|
|
190
256
|
let agentResponseDetail;
|
|
191
257
|
try {
|
|
192
258
|
let conversationId;
|
|
193
259
|
let userMessageDetailId;
|
|
194
260
|
let agentResponseDetailId;
|
|
195
|
-
|
|
196
|
-
|
|
261
|
+
if (options.agentResponseDetail) {
|
|
262
|
+
// The server created the reply row for this run (RunAIAgentFromConversationDetail): write into it.
|
|
263
|
+
agentResponseDetail = options.agentResponseDetail;
|
|
264
|
+
agentResponseDetailId = agentResponseDetail.ID;
|
|
265
|
+
conversationId = options.conversationId || agentResponseDetail.ConversationID;
|
|
266
|
+
userMessageDetailId = agentResponseDetail.ParentID || agentResponseDetailId;
|
|
267
|
+
}
|
|
268
|
+
else if (options.conversationDetailId) {
|
|
269
|
+
// A caller-supplied detail ID (the legacy RunAIAgent(conversationDetailId=...) shape). The row was not
|
|
270
|
+
// created for this run, so it is loaded unmarked (no MarkServerAuthoredReply), and the conversation
|
|
271
|
+
// detail gate's reply rule refuses the final save (step 5 changes Message and Status) for every user,
|
|
272
|
+
// the system user included. So a caller-supplied detail ID cannot receive the final reply: the run
|
|
273
|
+
// fails at step 5. Only the server-created reply path (options.agentResponseDetail, or the branch
|
|
274
|
+
// below that creates the reply via CreateAgentReplyDetail) completes.
|
|
197
275
|
agentResponseDetailId = options.conversationDetailId;
|
|
198
276
|
// LATENCY OPTIMIZATION (Opt #2): When conversationId is pre-resolved by the caller
|
|
199
277
|
// (e.g., the resolver already loaded the ConversationDetail to build history), we
|
|
@@ -212,7 +290,7 @@ export class AgentRunner {
|
|
|
212
290
|
else {
|
|
213
291
|
// Fallback for callers that don't provide conversationId (backward compatibility).
|
|
214
292
|
// This path still works but incurs the extra DB round-trip to extract conversationId.
|
|
215
|
-
const tempDetail = await md.GetEntityObject('MJ: Conversation Details',
|
|
293
|
+
const tempDetail = await md.GetEntityObject('MJ: Conversation Details', conversationWriter);
|
|
216
294
|
if (await tempDetail.Load(agentResponseDetailId)) {
|
|
217
295
|
conversationId = tempDetail.ConversationID;
|
|
218
296
|
LogStatus(`Using existing conversation ${conversationId} and agent response detail ${agentResponseDetailId}`);
|
|
@@ -223,7 +301,7 @@ export class AgentRunner {
|
|
|
223
301
|
}
|
|
224
302
|
// Load the entity object for progress updates and final status Save at step 5.
|
|
225
303
|
// This is needed regardless of whether conversationId was pre-resolved.
|
|
226
|
-
agentResponseDetail = await md.GetEntityObject('MJ: Conversation Details',
|
|
304
|
+
agentResponseDetail = await md.GetEntityObject('MJ: Conversation Details', conversationWriter);
|
|
227
305
|
if (!await agentResponseDetail.Load(agentResponseDetailId)) {
|
|
228
306
|
throw new Error(`Failed to load conversation detail entity for status updates: ${agentResponseDetailId}`);
|
|
229
307
|
}
|
|
@@ -238,7 +316,7 @@ export class AgentRunner {
|
|
|
238
316
|
conversationId = options.conversationId || '';
|
|
239
317
|
if (!conversationId) {
|
|
240
318
|
LogStatus('Creating new conversation');
|
|
241
|
-
const conversation = await md.GetEntityObject('MJ: Conversations',
|
|
319
|
+
const conversation = await md.GetEntityObject('MJ: Conversations', conversationWriter);
|
|
242
320
|
// Smart conversation naming:
|
|
243
321
|
// 1. Use provided name if given
|
|
244
322
|
// 2. Otherwise, use AI prompt to generate a good name from user message
|
|
@@ -258,7 +336,7 @@ export class AgentRunner {
|
|
|
258
336
|
}
|
|
259
337
|
conversation.Name = conversationName;
|
|
260
338
|
conversation.Description = conversationDescription || ''; // Set description too (like UI does)
|
|
261
|
-
conversation.UserID = params.userId ||
|
|
339
|
+
conversation.UserID = params.userId || conversationWriter.ID;
|
|
262
340
|
conversation.Status = 'Available';
|
|
263
341
|
conversation.DataContextID = null; // Can be set by caller if needed
|
|
264
342
|
// Link to test run if provided (for test execution traceability)
|
|
@@ -273,11 +351,11 @@ export class AgentRunner {
|
|
|
273
351
|
}
|
|
274
352
|
// Step 2: Create conversation detail for user message
|
|
275
353
|
LogStatus('Creating conversation detail for user message');
|
|
276
|
-
const userMessageDetail = await md.GetEntityObject('MJ: Conversation Details',
|
|
354
|
+
const userMessageDetail = await md.GetEntityObject('MJ: Conversation Details', conversationWriter);
|
|
277
355
|
userMessageDetail.ConversationID = conversationId;
|
|
278
356
|
userMessageDetail.Message = options.userMessage;
|
|
279
357
|
userMessageDetail.Role = 'User';
|
|
280
|
-
userMessageDetail.UserID =
|
|
358
|
+
userMessageDetail.UserID = conversationWriter.ID;
|
|
281
359
|
userMessageDetail.HiddenToUser = false;
|
|
282
360
|
userMessageDetail.BranchID = params.ConversationBranchID ?? null;
|
|
283
361
|
// Link to test run if provided (for test execution traceability)
|
|
@@ -289,23 +367,16 @@ export class AgentRunner {
|
|
|
289
367
|
}
|
|
290
368
|
userMessageDetailId = userMessageDetail.ID;
|
|
291
369
|
LogStatus(`Created user message detail ${userMessageDetailId}`);
|
|
292
|
-
// Step 3: Create conversation detail for agent response
|
|
370
|
+
// Step 3: Create conversation detail for agent response
|
|
293
371
|
LogStatus('Creating conversation detail for agent response');
|
|
294
|
-
agentResponseDetail = await
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
// Link to test run if provided (for test execution traceability)
|
|
303
|
-
if (options.testRunId) {
|
|
304
|
-
agentResponseDetail.TestRunID = options.testRunId;
|
|
305
|
-
}
|
|
306
|
-
if (!(await agentResponseDetail.Save())) {
|
|
307
|
-
throw new Error(`Failed to create agent response conversation detail: ${AgentRunner.saveFailureReason(agentResponseDetail)}`);
|
|
308
|
-
}
|
|
372
|
+
agentResponseDetail = await this.CreateAgentReplyDetail({
|
|
373
|
+
conversationId,
|
|
374
|
+
branchId: params.ConversationBranchID ?? null,
|
|
375
|
+
agentId: params.agent.ID,
|
|
376
|
+
contextUser: conversationWriter,
|
|
377
|
+
testRunId: options.testRunId,
|
|
378
|
+
provider: md
|
|
379
|
+
});
|
|
309
380
|
agentResponseDetailId = agentResponseDetail.ID;
|
|
310
381
|
LogStatus(`Created agent response detail ${agentResponseDetailId}`);
|
|
311
382
|
}
|
|
@@ -314,6 +385,13 @@ export class AgentRunner {
|
|
|
314
385
|
// Flag to prevent late progress callbacks from overwriting final status
|
|
315
386
|
// Progress callbacks fire async and may complete AFTER agent returns
|
|
316
387
|
let agentExecutionCompleted = false;
|
|
388
|
+
// Progress saves run one at a time on this chain, and the final update awaits it.
|
|
389
|
+
// EnsureSaveComplete() alone is not enough: it resolves on the entity's 'save' event,
|
|
390
|
+
// which BaseEntity raises before the save finishes committing, so a progress save
|
|
391
|
+
// can still be in flight when the final update calls Save(). BaseEntity.Save() hands
|
|
392
|
+
// a concurrent caller the in-flight save's promise, so the final status was dropped
|
|
393
|
+
// and the detail stayed 'In-Progress' with the last progress message.
|
|
394
|
+
let progressSaves = Promise.resolve();
|
|
317
395
|
// Wrap progress callback to update agent response detail
|
|
318
396
|
const originalOnProgress = params.onProgress;
|
|
319
397
|
const wrappedOnProgress = agentResponseDetail
|
|
@@ -329,11 +407,21 @@ export class AgentRunner {
|
|
|
329
407
|
}
|
|
330
408
|
// Update the agent response detail with progress message
|
|
331
409
|
if (agentResponseDetail && progress.message) {
|
|
332
|
-
|
|
333
|
-
const
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
410
|
+
const detail = agentResponseDetail;
|
|
411
|
+
const message = progress.message;
|
|
412
|
+
progressSaves = progressSaves.then(async () => {
|
|
413
|
+
try {
|
|
414
|
+
detail.Message = message;
|
|
415
|
+
if (!(await detail.Save())) {
|
|
416
|
+
LogError(`Failed to save agent response detail progress update: ${AgentRunner.saveFailureReason(detail)}`);
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
catch (error) {
|
|
420
|
+
// A failed progress save must not break the chain the final update awaits
|
|
421
|
+
LogError(`Failed to save agent response detail progress update: ${error}`, undefined, error);
|
|
422
|
+
}
|
|
423
|
+
});
|
|
424
|
+
await progressSaves;
|
|
337
425
|
}
|
|
338
426
|
// Call original callback if provided
|
|
339
427
|
if (originalOnProgress) {
|
|
@@ -397,8 +485,9 @@ export class AgentRunner {
|
|
|
397
485
|
// Step 5: Update agent response detail with final result.
|
|
398
486
|
const updateDetail = async () => {
|
|
399
487
|
if (agentResponseDetail && agentResponseDetailId) {
|
|
400
|
-
// Wait for
|
|
401
|
-
//
|
|
488
|
+
// Wait for every queued progress save (none can be added: the flag is set),
|
|
489
|
+
// then for any other save still in flight on this entity
|
|
490
|
+
await progressSaves;
|
|
402
491
|
await agentResponseDetail.EnsureSaveComplete();
|
|
403
492
|
LogStatus('Updating agent response detail with final result');
|
|
404
493
|
// Reload to get any updates from agent execution
|
|
@@ -421,7 +510,11 @@ export class AgentRunner {
|
|
|
421
510
|
}
|
|
422
511
|
const saved = await agentResponseDetail.Save();
|
|
423
512
|
if (!saved) {
|
|
424
|
-
|
|
513
|
+
const reason = AgentRunner.saveFailureReason(agentResponseDetail);
|
|
514
|
+
LogError(`Failed to save agent response detail ${agentResponseDetailId} with final status: ${reason}`);
|
|
515
|
+
// The reply never reached the conversation, so the caller must not report success: a chat
|
|
516
|
+
// client waiting for this row to complete would otherwise wait forever.
|
|
517
|
+
throw new Error(`The agent's reply could not be saved: ${reason}`);
|
|
425
518
|
}
|
|
426
519
|
LogStatus(`Updated agent response detail ${agentResponseDetailId} with final status: ${agentResponseDetail.Status}`);
|
|
427
520
|
}
|
|
@@ -506,7 +599,46 @@ export class AgentRunner {
|
|
|
506
599
|
// no report." Sequential execution removes the interleave; all writes still complete
|
|
507
600
|
// before we return, so the resolver's 'complete' event still guarantees the client sees
|
|
508
601
|
// every write.
|
|
509
|
-
|
|
602
|
+
//
|
|
603
|
+
// A failed reply save (step 5) into the reply row created for this run does NOT skip steps 6-7. AgentRunner is the only writer of
|
|
604
|
+
// AIAgentRunMedia and nothing retries, so skipping them would leave the run Completed with no
|
|
605
|
+
// artifact linked and its media bytes lost. Instead the step-5 error is held, steps 6, 6b and 7
|
|
606
|
+
// each run (one's rejection must not skip the next, and ProcessAgentArtifacts can reject outside
|
|
607
|
+
// its own try/catch), and the step-5 error is thrown last, so the run still fails with its reason.
|
|
608
|
+
let replySaveError;
|
|
609
|
+
try {
|
|
610
|
+
await updateDetail();
|
|
611
|
+
}
|
|
612
|
+
catch (error) {
|
|
613
|
+
replySaveError = error instanceof Error ? error : new Error(String(error));
|
|
614
|
+
}
|
|
615
|
+
if (replySaveError) {
|
|
616
|
+
const runDespiteFailedReply = async (stepName, step) => {
|
|
617
|
+
try {
|
|
618
|
+
await step();
|
|
619
|
+
}
|
|
620
|
+
catch (stepError) {
|
|
621
|
+
const stepMessage = stepError instanceof Error ? stepError.message : String(stepError);
|
|
622
|
+
LogError(`${stepName} failed for agent run ${agentResult.agentRun?.ID} (reply detail ${agentResponseDetailId}) after its reply could not be saved: ${stepMessage}`, undefined, stepError);
|
|
623
|
+
}
|
|
624
|
+
};
|
|
625
|
+
if (options.conversationDetailId && !options.agentResponseDetail) {
|
|
626
|
+
// A caller-supplied row (not created for this run) that the gate refused: link nothing to it, since
|
|
627
|
+
// that would write into a conversation the gate kept this run out of, as the run user. The media
|
|
628
|
+
// bytes belong to the run (AIAgentRunMedia), so only those are kept.
|
|
629
|
+
await runDespiteFailedReply('Step 7 (media audit)', async () => {
|
|
630
|
+
if (agentResult.mediaOutputs?.length) {
|
|
631
|
+
await this.SaveAgentRunMedia(agentResult.agentRun.ID, agentResult.mediaOutputs, contextUser, md);
|
|
632
|
+
}
|
|
633
|
+
});
|
|
634
|
+
}
|
|
635
|
+
else {
|
|
636
|
+
await runDespiteFailedReply('Step 6 (payload artifacts)', processArtifacts);
|
|
637
|
+
await runDespiteFailedReply('Step 6b (file artifacts)', processFileArtifacts);
|
|
638
|
+
await runDespiteFailedReply('Step 7 (media)', saveMedia);
|
|
639
|
+
}
|
|
640
|
+
throw replySaveError;
|
|
641
|
+
}
|
|
510
642
|
const payloadArtifact = await processArtifacts();
|
|
511
643
|
const fileArtifacts = await processFileArtifacts();
|
|
512
644
|
await saveMedia();
|
|
@@ -806,8 +938,34 @@ export class AgentRunner {
|
|
|
806
938
|
}
|
|
807
939
|
// Check agent's ArtifactCreationMode
|
|
808
940
|
await AIEngine.Instance.Config(false, contextUser);
|
|
809
|
-
const
|
|
810
|
-
|
|
941
|
+
const agentsById = IndexByUUID(AIEngine.Instance.Agents);
|
|
942
|
+
let agent = agentsById.Get(agentRun.AgentID);
|
|
943
|
+
let creationMode = agent?.ArtifactCreationMode;
|
|
944
|
+
// When an orchestrator with ArtifactCreationMode='Never' or 'System Only' (or no
|
|
945
|
+
// DefaultArtifactTypeID, such as Sage) delegates a folded single-node task graph (or
|
|
946
|
+
// sub-agent step) to a specialist agent (such as Query Builder or Research Agent) that
|
|
947
|
+
// DOES produce user-visible artifacts, resolve the artifact creation mode and
|
|
948
|
+
// DefaultArtifactTypeID from the last completed Sub-Agent step's specialist agent so
|
|
949
|
+
// the specialist's deliverable artifact is persisted with the specialist's
|
|
950
|
+
// DefaultArtifactTypeID and visibility.
|
|
951
|
+
if ((creationMode === 'Never' || creationMode === 'System Only' || !agent?.DefaultArtifactTypeID) && agentRun?.Steps?.length) {
|
|
952
|
+
for (let i = agentRun.Steps.length - 1; i >= 0; i--) {
|
|
953
|
+
const step = agentRun.Steps[i];
|
|
954
|
+
if (step.StepType === 'Sub-Agent' && step.Success) {
|
|
955
|
+
const subAgentId = step.TargetID || step.SubAgentRun?.AgentID;
|
|
956
|
+
const delegatedAgent = subAgentId
|
|
957
|
+
? agentsById.Get(subAgentId)
|
|
958
|
+
: undefined;
|
|
959
|
+
if (delegatedAgent &&
|
|
960
|
+
delegatedAgent.ArtifactCreationMode !== 'Never' &&
|
|
961
|
+
(delegatedAgent.DefaultArtifactTypeID != null || delegatedAgent.ArtifactCreationMode === 'Always')) {
|
|
962
|
+
agent = delegatedAgent;
|
|
963
|
+
creationMode = delegatedAgent.ArtifactCreationMode;
|
|
964
|
+
break;
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
}
|
|
968
|
+
}
|
|
811
969
|
if (creationMode === 'Never') {
|
|
812
970
|
LogStatus(`Skipping artifact creation - agent "${agent?.Name}" has ArtifactCreationMode='Never'`);
|
|
813
971
|
return undefined;
|
|
@@ -886,7 +1044,7 @@ export class AgentRunner {
|
|
|
886
1044
|
LogStatus(`Creating version ${newVersionNumber} of existing artifact ${artifactId}`);
|
|
887
1045
|
}
|
|
888
1046
|
else {
|
|
889
|
-
const artifact = await this.createArtifactHeader(md, contextUser, agent, creationMode, directive);
|
|
1047
|
+
const artifact = await this.createArtifactHeader(md, contextUser, agent, creationMode, directive, payload);
|
|
890
1048
|
artifactId = artifact.ID;
|
|
891
1049
|
newVersionNumber = 1;
|
|
892
1050
|
isNewArtifact = true;
|
|
@@ -914,19 +1072,54 @@ export class AgentRunner {
|
|
|
914
1072
|
version.VersionNumber = newVersionNumber;
|
|
915
1073
|
version.Content = serializedContent;
|
|
916
1074
|
version.UserID = contextUser.ID;
|
|
1075
|
+
const directiveName = AgentRunner.safeDirectiveText(directive?.name, AgentRunner.ARTIFACT_NAME_MAX_LENGTH);
|
|
1076
|
+
const directiveDescription = AgentRunner.safeDirectiveText(directive?.description);
|
|
1077
|
+
const payloadRecord = (typeof payload === 'object' && payload !== null && !Array.isArray(payload))
|
|
1078
|
+
? payload
|
|
1079
|
+
: undefined;
|
|
1080
|
+
const reportRecord = (typeof payloadRecord?.report === 'object' && payloadRecord.report !== null && !Array.isArray(payloadRecord.report))
|
|
1081
|
+
? payloadRecord.report
|
|
1082
|
+
: undefined;
|
|
1083
|
+
const synthesisRecord = (typeof payloadRecord?.synthesis === 'object' && payloadRecord.synthesis !== null && !Array.isArray(payloadRecord.synthesis))
|
|
1084
|
+
? payloadRecord.synthesis
|
|
1085
|
+
: undefined;
|
|
1086
|
+
const payloadName = AgentRunner.safeDirectiveText(payloadRecord?.title ?? payloadRecord?.name ?? payloadRecord?.savedQueryName ?? reportRecord?.name, AgentRunner.ARTIFACT_NAME_MAX_LENGTH);
|
|
1087
|
+
const payloadDescription = AgentRunner.safeDirectiveText(payloadRecord?.description ?? payloadRecord?.interpretation ?? reportRecord?.description ?? synthesisRecord?.executiveSummary);
|
|
1088
|
+
if (directiveName || payloadName) {
|
|
1089
|
+
version.Name = directiveName || payloadName || null;
|
|
1090
|
+
}
|
|
1091
|
+
if (directiveDescription || payloadDescription) {
|
|
1092
|
+
version.Description = directiveDescription || payloadDescription || null;
|
|
1093
|
+
}
|
|
917
1094
|
if (!(await version.Save())) {
|
|
918
1095
|
throw new Error('Failed to save artifact version');
|
|
919
1096
|
}
|
|
920
1097
|
LogStatus(`Created artifact version ${newVersionNumber} (${version.ID})`);
|
|
921
|
-
// First version of a new artifact: adopt the extracted Name attribute
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
1098
|
+
// First version of a new artifact: adopt the extracted Name/Description attribute (or payload title/description)
|
|
1099
|
+
// unless the agent explicitly named/described it via artifactDirective.
|
|
1100
|
+
if (isNewArtifact && newVersionNumber === 1 && (!directiveName || !directiveDescription)) {
|
|
1101
|
+
const attrs = version.Attributes;
|
|
1102
|
+
const nameAttr = attrs?.find((attr) => attr.StandardProperty === 'name' || attr.Name?.toLowerCase() === 'name');
|
|
1103
|
+
const descAttr = attrs?.find((attr) => attr.StandardProperty === 'description' || attr.Name?.toLowerCase() === 'description');
|
|
1104
|
+
const cleanAttr = (val, maxLen) => {
|
|
1105
|
+
const trimmed = val?.trim();
|
|
1106
|
+
if (!trimmed || trimmed.toLowerCase() === 'null') {
|
|
1107
|
+
return undefined;
|
|
1108
|
+
}
|
|
1109
|
+
const unquoted = trimmed.replace(/^["']|["']$/g, '').trim();
|
|
1110
|
+
return AgentRunner.safeDirectiveText(unquoted, maxLen);
|
|
1111
|
+
};
|
|
1112
|
+
const resolvedName = !directiveName ? (cleanAttr(nameAttr?.Value, AgentRunner.ARTIFACT_NAME_MAX_LENGTH) || payloadName) : undefined;
|
|
1113
|
+
const resolvedDescription = !directiveDescription ? (cleanAttr(descAttr?.Value) || payloadDescription) : undefined;
|
|
1114
|
+
if (resolvedName || resolvedDescription) {
|
|
927
1115
|
const artifact = await md.GetEntityObject('MJ: Artifacts', contextUser);
|
|
928
1116
|
if (await artifact.Load(artifactId)) {
|
|
929
|
-
|
|
1117
|
+
if (resolvedName) {
|
|
1118
|
+
artifact.Name = resolvedName;
|
|
1119
|
+
}
|
|
1120
|
+
if (resolvedDescription) {
|
|
1121
|
+
artifact.Description = resolvedDescription;
|
|
1122
|
+
}
|
|
930
1123
|
if (await artifact.Save()) {
|
|
931
1124
|
LogStatus(`Updated artifact name to: ${artifact.Name}`);
|
|
932
1125
|
}
|
|
@@ -1140,7 +1333,7 @@ export class AgentRunner {
|
|
|
1140
1333
|
* Creates the artifact header row. Name and description come from the agent's directive when
|
|
1141
1334
|
* it supplied them (e.g. Skip's artifactRequest); otherwise the historical placeholder.
|
|
1142
1335
|
*/
|
|
1143
|
-
async createArtifactHeader(md, contextUser, agent, creationMode, directive) {
|
|
1336
|
+
async createArtifactHeader(md, contextUser, agent, creationMode, directive, payload) {
|
|
1144
1337
|
const artifact = await md.GetEntityObject('MJ: Artifacts', contextUser);
|
|
1145
1338
|
const agentName = agent?.Name || 'Agent';
|
|
1146
1339
|
// Both fields are model output: coerced, trimmed, and (for Name) clamped to its column so a
|
|
@@ -1150,8 +1343,17 @@ export class AgentRunner {
|
|
|
1150
1343
|
// Description is nvarchar(MAX), so there is no length to clamp to — only the type to check.
|
|
1151
1344
|
artifact.Description = AgentRunner.safeDirectiveText(directive?.description)
|
|
1152
1345
|
|| `Payload returned by ${agentName}`;
|
|
1153
|
-
// Use agent's DefaultArtifactTypeID if available
|
|
1154
|
-
|
|
1346
|
+
// Use agent's DefaultArtifactTypeID if available; otherwise infer Research Content when
|
|
1347
|
+
// the payload carries a non-empty report.html string (e.g., Research Report Writer).
|
|
1348
|
+
const payloadObj = (typeof payload === 'object' && payload !== null && !Array.isArray(payload))
|
|
1349
|
+
? payload
|
|
1350
|
+
: undefined;
|
|
1351
|
+
const reportObj = (typeof payloadObj?.report === 'object' && payloadObj.report !== null && !Array.isArray(payloadObj.report))
|
|
1352
|
+
? payloadObj.report
|
|
1353
|
+
: undefined;
|
|
1354
|
+
const hasReportHtml = typeof reportObj?.html === 'string' && reportObj.html.trim().length > 0;
|
|
1355
|
+
artifact.TypeID = agent?.DefaultArtifactTypeID
|
|
1356
|
+
|| (hasReportHtml ? AgentRunner.RESEARCH_CONTENT_ARTIFACT_TYPE_ID : AgentRunner.JSON_ARTIFACT_TYPE_ID);
|
|
1155
1357
|
artifact.UserID = contextUser.ID;
|
|
1156
1358
|
artifact.EnvironmentID = contextUser.EnvironmentID || MJEnvironmentEntityExtended.DefaultEnvironmentID;
|
|
1157
1359
|
// Set visibility based on agent's ArtifactCreationMode
|
|
@@ -1698,8 +1900,10 @@ export class AgentRunner {
|
|
|
1698
1900
|
if (!contextUser?.ReturningVisitorContext) {
|
|
1699
1901
|
return;
|
|
1700
1902
|
}
|
|
1701
|
-
// Gate 2: need a conversation to read from, and an explicit caller scope always wins
|
|
1702
|
-
|
|
1903
|
+
// Gate 2: need a conversation to read from, and an explicit caller scope always wins — a data scope only when
|
|
1904
|
+
// the run will honour it (TrustReservedRunData; BaseAgent.Execute drops it otherwise).
|
|
1905
|
+
const runData = WithAgentRunDataTrustApplied(params).Params.data;
|
|
1906
|
+
if (!conversationId || params.PrimaryScopeRecordID || runData?.PrimaryScopeRecordID) {
|
|
1703
1907
|
return;
|
|
1704
1908
|
}
|
|
1705
1909
|
const convo = await md.GetEntityObject('MJ: Conversations', contextUser);
|
|
@@ -1839,7 +2043,7 @@ export class AgentRunner {
|
|
|
1839
2043
|
const typeName = row.TypeName || 'Text';
|
|
1840
2044
|
let content = '';
|
|
1841
2045
|
if (row.ContentMode === 'File' && row.FileID) {
|
|
1842
|
-
const downloaded = await this.
|
|
2046
|
+
const downloaded = await this.DownloadArtifactFileContent(row.FileID, contextUser);
|
|
1843
2047
|
if (downloaded) {
|
|
1844
2048
|
content = downloaded;
|
|
1845
2049
|
}
|
|
@@ -1865,10 +2069,18 @@ export class AgentRunner {
|
|
|
1865
2069
|
content = await this.hydrateSqlBackedContent(content, contextUser);
|
|
1866
2070
|
}
|
|
1867
2071
|
if (content) {
|
|
2072
|
+
const rawDescription = row.VersionDescription || row.ArtifactDescription;
|
|
2073
|
+
const cleanDescription = rawDescription && !rawDescription.startsWith('Payload returned by ')
|
|
2074
|
+
? rawDescription
|
|
2075
|
+
: undefined;
|
|
1868
2076
|
inputArtifacts.push({
|
|
1869
2077
|
name: artifactName,
|
|
1870
2078
|
typeName,
|
|
1871
2079
|
content,
|
|
2080
|
+
...(row.ArtifactID ? { artifactId: row.ArtifactID } : {}),
|
|
2081
|
+
...(row.VersionID ? { versionId: row.VersionID } : {}),
|
|
2082
|
+
...(row.VersionNumber != null ? { versionNumber: row.VersionNumber } : {}),
|
|
2083
|
+
...(cleanDescription ? { description: cleanDescription } : {}),
|
|
1872
2084
|
mimeType: row.MimeType ?? undefined,
|
|
1873
2085
|
...(row.ToolLibraryClass ? { toolLibraryClass: row.ToolLibraryClass } : {}),
|
|
1874
2086
|
deliveryMode: row.DefaultDeliveryMode ?? 'ToolsOnly',
|
|
@@ -1904,9 +2116,10 @@ export class AgentRunner {
|
|
|
1904
2116
|
* `ArtifactToolManager`. No-op for binary content, non-JSON content, or
|
|
1905
2117
|
* content that already has rows populated.
|
|
1906
2118
|
*
|
|
1907
|
-
* Security:
|
|
1908
|
-
*
|
|
1909
|
-
*
|
|
2119
|
+
* Security: the stored SQL runs as ad-hoc SQL for `contextUser`, so the provider
|
|
2120
|
+
* allows only a single read statement over entity views that user may read in
|
|
2121
|
+
* full (no row-level filter, no denied field). It runs on the host's read-only
|
|
2122
|
+
* database login when one is configured, and on the default provider otherwise.
|
|
1910
2123
|
*/
|
|
1911
2124
|
async hydrateSqlBackedContent(content, contextUser) {
|
|
1912
2125
|
let parsed;
|
|
@@ -1916,8 +2129,11 @@ export class AgentRunner {
|
|
|
1916
2129
|
catch {
|
|
1917
2130
|
return content;
|
|
1918
2131
|
}
|
|
2132
|
+
if (!this.hasUnhydratedSql(parsed)) {
|
|
2133
|
+
return content;
|
|
2134
|
+
}
|
|
1919
2135
|
let changed = false;
|
|
1920
|
-
const rq =
|
|
2136
|
+
const rq = await this.adhocSqlRunner();
|
|
1921
2137
|
const rootMeta = parsed?.metadata;
|
|
1922
2138
|
const rootRows = parsed?.rows;
|
|
1923
2139
|
if (rootMeta?.sql && (!rootRows || rootRows.length === 0)) {
|
|
@@ -1954,6 +2170,32 @@ export class AgentRunner {
|
|
|
1954
2170
|
}
|
|
1955
2171
|
return changed ? JSON.stringify(parsed) : content;
|
|
1956
2172
|
}
|
|
2173
|
+
/** True when the parsed artifact carries stored SQL whose rows are missing. */
|
|
2174
|
+
hasUnhydratedSql(parsed) {
|
|
2175
|
+
const rootMeta = parsed?.metadata;
|
|
2176
|
+
const rootRows = parsed?.rows;
|
|
2177
|
+
if (rootMeta?.sql && (!rootRows || rootRows.length === 0)) {
|
|
2178
|
+
return true;
|
|
2179
|
+
}
|
|
2180
|
+
const tables = parsed?.tables;
|
|
2181
|
+
return Array.isArray(tables) && tables.some(t => !!t?.metadata?.sql && (!t.rows || t.rows.length === 0));
|
|
2182
|
+
}
|
|
2183
|
+
/**
|
|
2184
|
+
* A RunQuery on the host's read-only database login when one is registered with the action
|
|
2185
|
+
* engine, otherwise on the default provider.
|
|
2186
|
+
*/
|
|
2187
|
+
async adhocSqlRunner() {
|
|
2188
|
+
try {
|
|
2189
|
+
const readOnly = await ActionEngineServer.Instance.GetReadOnlyProvider();
|
|
2190
|
+
if (readOnly) {
|
|
2191
|
+
return new RunQuery(readOnly);
|
|
2192
|
+
}
|
|
2193
|
+
}
|
|
2194
|
+
catch (error) {
|
|
2195
|
+
LogError(`[AgentRunner] Could not open the read-only provider; using the default provider: ${error instanceof Error ? error.message : String(error)}`);
|
|
2196
|
+
}
|
|
2197
|
+
return new RunQuery();
|
|
2198
|
+
}
|
|
1957
2199
|
/**
|
|
1958
2200
|
* Infer an artifact type name from a MIME type so ArtifactToolManager
|
|
1959
2201
|
* can resolve the correct tool library.
|
|
@@ -1973,20 +2215,25 @@ export class AgentRunner {
|
|
|
1973
2215
|
}
|
|
1974
2216
|
/**
|
|
1975
2217
|
* Downloads binary content for a file-backed artifact from MJStorage.
|
|
1976
|
-
*
|
|
1977
|
-
*
|
|
2218
|
+
* Reads the `MJ: Files` row as the user, then resolves it through
|
|
2219
|
+
* `FileStorageEngine.ResolveFileObject`, which applies the storage-account gate and the
|
|
2220
|
+
* tracked-file rule before any driver call — the same path every other file-ID route uses.
|
|
1978
2221
|
*
|
|
1979
2222
|
* @param fileId - The MJ: Files entity ID referenced by ArtifactVersion.FileID
|
|
1980
2223
|
* @param contextUser - User context for storage driver authentication
|
|
1981
2224
|
* @returns Buffer of file content, or null if download fails
|
|
1982
2225
|
*/
|
|
1983
|
-
async
|
|
2226
|
+
async DownloadArtifactFileContent(fileId, contextUser) {
|
|
2227
|
+
if (!IsValidUUID(fileId)) {
|
|
2228
|
+
LogError(`[AgentRunner] Refusing to read artifact file content: '${fileId}' is not a file ID`);
|
|
2229
|
+
return null;
|
|
2230
|
+
}
|
|
1984
2231
|
try {
|
|
1985
2232
|
await FileStorageEngine.Instance.Config(false, contextUser);
|
|
1986
|
-
const rv =
|
|
2233
|
+
const rv = RunView.FromMetadataProvider(this._provider);
|
|
1987
2234
|
const fileResult = await rv.RunView({
|
|
1988
2235
|
EntityName: 'MJ: Files',
|
|
1989
|
-
ExtraFilter: `ID = '${fileId}'`,
|
|
2236
|
+
ExtraFilter: `ID = '${EscapeSQLString(fileId.trim())}'`,
|
|
1990
2237
|
Fields: ['ID', 'Name', 'ContentType', 'ProviderID', 'ProviderKey'],
|
|
1991
2238
|
ResultType: 'simple',
|
|
1992
2239
|
}, contextUser);
|
|
@@ -1994,15 +2241,13 @@ export class AgentRunner {
|
|
|
1994
2241
|
LogError(`[AgentRunner] File not found in MJ: Files for FileID: ${fileId}`);
|
|
1995
2242
|
return null;
|
|
1996
2243
|
}
|
|
1997
|
-
|
|
1998
|
-
const
|
|
1999
|
-
if (
|
|
2000
|
-
LogError(`[AgentRunner] No FileStorageAccount found for ProviderID: ${
|
|
2244
|
+
// Account gate and tracked-file rule first; a refusal throws and is logged below.
|
|
2245
|
+
const resolved = await FileStorageEngine.Instance.ResolveFileObject(fileResult.Results[0], contextUser, 'Read', this._provider);
|
|
2246
|
+
if (!resolved) {
|
|
2247
|
+
LogError(`[AgentRunner] No FileStorageAccount found for ProviderID: ${fileResult.Results[0].ProviderID}`);
|
|
2001
2248
|
return null;
|
|
2002
2249
|
}
|
|
2003
|
-
const
|
|
2004
|
-
const objectName = file.ProviderKey ?? file.Name;
|
|
2005
|
-
const content = await driver.GetObject({ fullPath: objectName });
|
|
2250
|
+
const content = await resolved.Driver.GetObject({ fullPath: resolved.ObjectKey });
|
|
2006
2251
|
// GetObject returns string or Buffer depending on provider
|
|
2007
2252
|
if (Buffer.isBuffer(content)) {
|
|
2008
2253
|
return content;
|