@memberjunction/ai-prompts 6.2.0-edge.3 → 6.2.0-edge.5

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.
Files changed (51) hide show
  1. package/README.md +54 -2
  2. package/dist/AIModelRunner.d.ts +4 -0
  3. package/dist/AIModelRunner.d.ts.map +1 -1
  4. package/dist/AIModelRunner.js +7 -1
  5. package/dist/AIModelRunner.js.map +1 -1
  6. package/dist/AIPromptRunner.d.ts +51 -6
  7. package/dist/AIPromptRunner.d.ts.map +1 -1
  8. package/dist/AIPromptRunner.js +285 -125
  9. package/dist/AIPromptRunner.js.map +1 -1
  10. package/dist/AIPromptTimeoutError.d.ts +7 -1
  11. package/dist/AIPromptTimeoutError.d.ts.map +1 -1
  12. package/dist/AIPromptTimeoutError.js +5 -0
  13. package/dist/AIPromptTimeoutError.js.map +1 -1
  14. package/dist/BaseModelRunner.d.ts +106 -13
  15. package/dist/BaseModelRunner.d.ts.map +1 -1
  16. package/dist/BaseModelRunner.js +379 -74
  17. package/dist/BaseModelRunner.js.map +1 -1
  18. package/dist/PromptRunDataCapture.d.ts +54 -0
  19. package/dist/PromptRunDataCapture.d.ts.map +1 -0
  20. package/dist/PromptRunDataCapture.js +181 -0
  21. package/dist/PromptRunDataCapture.js.map +1 -0
  22. package/dist/audio/AISpeechToTextRunner.d.ts +2 -1
  23. package/dist/audio/AISpeechToTextRunner.d.ts.map +1 -1
  24. package/dist/audio/AISpeechToTextRunner.js +5 -3
  25. package/dist/audio/AISpeechToTextRunner.js.map +1 -1
  26. package/dist/audio/AITextToSpeechRunner.js +1 -1
  27. package/dist/audio/AITextToSpeechRunner.js.map +1 -1
  28. package/dist/decision/AIDecisionRunner.d.ts.map +1 -1
  29. package/dist/decision/AIDecisionRunner.js +8 -3
  30. package/dist/decision/AIDecisionRunner.js.map +1 -1
  31. package/dist/embedding/AIEmbeddingRunner.d.ts +24 -1
  32. package/dist/embedding/AIEmbeddingRunner.d.ts.map +1 -1
  33. package/dist/embedding/AIEmbeddingRunner.js +80 -21
  34. package/dist/embedding/AIEmbeddingRunner.js.map +1 -1
  35. package/dist/embedding/embedding-runner.types.d.ts +14 -0
  36. package/dist/embedding/embedding-runner.types.d.ts.map +1 -1
  37. package/dist/image/AIImageGenerationRunner.d.ts +31 -5
  38. package/dist/image/AIImageGenerationRunner.d.ts.map +1 -1
  39. package/dist/image/AIImageGenerationRunner.js +75 -13
  40. package/dist/image/AIImageGenerationRunner.js.map +1 -1
  41. package/dist/image/image-runner.types.d.ts +14 -0
  42. package/dist/image/image-runner.types.d.ts.map +1 -1
  43. package/dist/media/BaseMediaRunner.d.ts +20 -18
  44. package/dist/media/BaseMediaRunner.d.ts.map +1 -1
  45. package/dist/media/BaseMediaRunner.js +35 -51
  46. package/dist/media/BaseMediaRunner.js.map +1 -1
  47. package/dist/media/media-runner.types.d.ts +9 -6
  48. package/dist/media/media-runner.types.d.ts.map +1 -1
  49. package/dist/video/AIVideoRunner.js +1 -1
  50. package/dist/video/AIVideoRunner.js.map +1 -1
  51. package/package.json +13 -12
@@ -1,9 +1,9 @@
1
- import { BaseLLM, ChatParams, ChatMessageRole, ErrorAnalyzer, ResolveFileInputStrategy, EncodeToolTurnsAsText, CredentialScopeAllows } from '@memberjunction/ai';
1
+ import { BaseLLM, ChatParams, ChatMessageRole, ErrorAnalyzer, ResolveFileInputStrategy, EncodeToolTurnsAsText, CredentialScopeAllows, ResolveEffectiveModelConfiguration } from '@memberjunction/ai';
2
2
  import { BaseModelRunner, } from './BaseModelRunner.js';
3
3
  import { GetToolCallingDecision, GetToolCallingMode, RecordToolCallingDecision, RecordToolCallingMode, ResolveNativeToolCalling, ResolveToolChoiceForRequest } from './nativeToolCallingGate.js';
4
4
  import { AIModelRunner } from './AIModelRunner.js';
5
5
  import { AIModelSelectionInfo, PickPromptExecutionScope } from '@memberjunction/ai-core-plus';
6
- import { LogStatus, IsVerboseLoggingEnabled, Metadata } from '@memberjunction/core';
6
+ import { LogError, LogStatus, IsVerboseLoggingEnabled, Metadata } from '@memberjunction/core';
7
7
  import { CleanJSON, RepairJSONEscaping, MJGlobal, JSONValidator, ValidationResult, ValidationErrorInfo, ValidationErrorType, UUIDsEqual, NormalizeUUID } from '@memberjunction/global';
8
8
  import { TemplateEngineServer } from '@memberjunction/templates';
9
9
  import { ExecutionPlanner } from './ExecutionPlanner.js';
@@ -12,7 +12,8 @@ import { ParseManifestEntryMime, TrimSpacesAndTabs } from './linearTextScan.js';
12
12
  import { AIEngine } from '@memberjunction/aiengine';
13
13
  import { AIEngineBase } from '@memberjunction/ai-engine-base';
14
14
  import { SystemPlaceholderManager } from '@memberjunction/ai-core-plus';
15
- import { ResolvePromptRunUserID } from '@memberjunction/ai-core-plus';
15
+ import { ResolvePromptRunUserID, } from '@memberjunction/ai-core-plus';
16
+ import { BuildCaptureFailedPromptRunMessages, BuildStoredPromptRunMessages, ReadServerTemplateDataCaptureDefault, ResolveTemplateDataCaptureMode, } from './PromptRunDataCapture.js';
16
17
  // json5 is a CJS module: under this package's ESM output its import namespace has no
17
18
  // `parse` — only the default export does. `import * as JSON5` made JSON5.parse
18
19
  // undefined at runtime ("JSON5.parse is not a function"), silently disabling the
@@ -33,6 +34,10 @@ function mimeFromBlockType(type) {
33
34
  }
34
35
  }
35
36
  export class AIPromptRunner extends BaseModelRunner {
37
+ /** The render options a prompt asks for: a raw render when `templateAutoescape` is false, else the engine's default. */
38
+ static RenderOptions(params) {
39
+ return params.templateAutoescape === false ? { autoescape: false } : undefined;
40
+ }
36
41
  /**
37
42
  * The model type this runner requires. Returns 'LLM' for AIPromptRunner.
38
43
  */
@@ -60,7 +65,9 @@ export class AIPromptRunner extends BaseModelRunner {
60
65
  static { this.NOT_EVALUATED_REASON = 'Not evaluated (a higher-priority candidate was already selected; set AIPromptParams.forceFullModelEvaluation to probe all)'; }
61
66
  constructor() {
62
67
  super();
63
- this._metadata = this._provider ?? new Metadata();
68
+ this._metadata =
69
+ this._provider ??
70
+ (typeof Metadata === 'function' ? new Metadata() : {}); // global-provider-ok: the same no-provider fallback as `provider ?? new Metadata()`; the typeof guard keeps core mocks without Metadata working
64
71
  this._templateEngine = TemplateEngineServer.Instance;
65
72
  this._executionPlanner = new ExecutionPlanner();
66
73
  this._jsonValidator = new JSONValidator();
@@ -268,14 +275,19 @@ export class AIPromptRunner extends BaseModelRunner {
268
275
  return result;
269
276
  }
270
277
  catch (error) {
271
- this.logError(error, {
272
- prompt: params.prompt,
273
- metadata: {
274
- executionPhase: 'main-execution',
275
- hasChildPrompts: !!params.childPrompts?.length
276
- },
277
- maxErrorLength: params.maxErrorLength
278
- });
278
+ if (this.isCancellation(error, params)) {
279
+ this.logStatus(`⏹️ Prompt "${params.prompt?.Name}" was cancelled: ${error.message}`, false, params);
280
+ }
281
+ else {
282
+ this.logError(error, {
283
+ prompt: params.prompt,
284
+ metadata: {
285
+ executionPhase: 'main-execution',
286
+ hasChildPrompts: !!params.childPrompts?.length
287
+ },
288
+ maxErrorLength: params.maxErrorLength
289
+ });
290
+ }
279
291
  const endTime = new Date();
280
292
  const executionTimeMS = endTime.getTime() - startTime.getTime();
281
293
  // Update prompt run with error if it was created
@@ -294,7 +306,7 @@ export class AIPromptRunner extends BaseModelRunner {
294
306
  promptRun.Status = 'Failed';
295
307
  promptRun.ErrorDetails = error.message;
296
308
  }
297
- const saveResult = await promptRun.Save();
309
+ const saveResult = await promptRun.Save({ SaveReturnMode: 'datestamps_only' });
298
310
  if (!saveResult) {
299
311
  this.logError(`Failed to save error to AIPromptRun: ${promptRun.LatestResult?.CompleteMessage || 'Unknown error'}`, {
300
312
  category: 'PromptRunSave',
@@ -406,8 +418,10 @@ export class AIPromptRunner extends BaseModelRunner {
406
418
  // Validation failed (Warn or Strict mode)
407
419
  errorMessage = `Validation failed: ${parsedResult.validationResult.Errors?.map(e => e.Message).join('; ')}`;
408
420
  }
421
+ const cancelled = !chatResult.success && this.IsCallerCancellation(chatResult.errorInfo);
409
422
  return {
410
423
  success: chatResult.success,
424
+ ...(cancelled ? { status: 'Cancelled', cancelled: true, cancellationReason: 'user_requested' } : {}),
411
425
  rawResult: chatResult.data?.choices?.[0]?.message?.content,
412
426
  result: parsedResult?.result ? parsedResult.result : parsedResult,
413
427
  errorMessage, // Include error message for proper error propagation
@@ -535,18 +549,21 @@ export class AIPromptRunner extends BaseModelRunner {
535
549
  selectedResult = aiSelectedResult;
536
550
  }
537
551
  }
538
- // Update parent with selected arm's model and vendor
539
- consolidatedPromptRun.ModelID = selectedResult.task.model.ID;
540
- if (selectedResult.task.vendorId) {
541
- consolidatedPromptRun.VendorID = selectedResult.task.vendorId;
542
- }
543
- else if (selectedResult.task.promptModel?.VendorID) {
544
- consolidatedPromptRun.VendorID = selectedResult.task.promptModel.VendorID;
552
+ // Update parent with selected arm's model and vendor (also re-applied inside applyConsolidatedFields
553
+ // so an in-flight INSERT reload on consolidatedPromptRun can never revert them).
554
+ const selectedModelId = selectedResult.task.model.ID;
555
+ const selectedVendorId = selectedResult.task.vendorId ?? selectedResult.task.promptModel?.VendorID;
556
+ consolidatedPromptRun.ModelID = selectedModelId;
557
+ if (selectedVendorId) {
558
+ consolidatedPromptRun.VendorID = selectedVendorId;
545
559
  }
546
- // Ensure selectedResult child is marked WasSelectedResult = true
560
+ // Ensure selectedResult child is marked WasSelectedResult = true via the fire-and-forget prompt run queue
547
561
  if (selectedResult.promptRun) {
548
- selectedResult.promptRun.WasSelectedResult = true;
549
- await selectedResult.promptRun.Save();
562
+ const selectedRun = selectedResult.promptRun;
563
+ selectedRun.WasSelectedResult = true;
564
+ this._promptRunQueue.Update(selectedRun, () => {
565
+ selectedRun.WasSelectedResult = true;
566
+ });
550
567
  }
551
568
  // Calculate total tokens and costs from all parallel executions
552
569
  let totalPromptTokens = 0;
@@ -570,67 +587,67 @@ export class AIPromptRunner extends BaseModelRunner {
570
587
  }
571
588
  }
572
589
  }
573
- // Update with parallel execution metadata
590
+ // Update with parallel execution metadata (applied immediately in memory and re-applied inside the
591
+ // queued Update callback so an in-flight INSERT reload can never clobber the consolidated fields).
574
592
  const endTime = new Date();
575
- consolidatedPromptRun.CompletedAt = endTime;
576
- consolidatedPromptRun.ExecutionTimeMS = parallelResult.totalExecutionTimeMS;
577
- consolidatedPromptRun.Result = selectedResult.rawResult || '';
578
- consolidatedPromptRun.TokensUsed = parallelResult.totalTokensUsed;
579
- // Layer 4 instrumentation, same as the single-model path. This path reaches the same
580
- // `executeModel` and therefore declares tools, so leaving the column NULL here would tell the
581
- // agent loop a NativeImplicit turn was not implicit — every control-flow call would then be
582
- // rejected as an undeclared tool and the loop would retry on tools it declared itself.
583
- consolidatedPromptRun.ToolCallingMode = GetToolCallingMode(selectedResult.modelResult) ?? null;
584
- // Extract token and cost info from selected result
585
- const selectedResultUsage = selectedResult.modelResult?.data?.usage;
586
- if (selectedResultUsage) {
587
- consolidatedPromptRun.TokensPrompt = selectedResultUsage.promptTokens;
588
- consolidatedPromptRun.TokensCompletion = selectedResultUsage.completionTokens;
589
- // Persist the selected result's cache token counts so (a) they are recorded and (b) any
590
- // downstream cost recompute (MJAIPromptRunEntityServer, when no provider cost is present)
591
- // prices the full input including cached tokens rather than dropping them.
592
- consolidatedPromptRun.TokensCacheRead = selectedResultUsage.cacheReadTokens ?? 0;
593
- consolidatedPromptRun.TokensCacheWrite = selectedResultUsage.cacheWriteTokens ?? 0;
594
- // NOTE (§5.1): On the parent, do NOT assign Cost from the selected arm. Leave Cost = null.
595
- // TotalCost is maintained by server-side TriggerParentCostRollup.
596
- if (selectedResultUsage.costCurrency !== undefined) {
597
- consolidatedPromptRun.CostCurrency = selectedResultUsage.costCurrency;
598
- }
599
- }
600
- // Add parallel execution metadata to Messages field
601
- const parallelMetadata = {
593
+ const storedMessagesJSON = this.buildStoredMessagesJSON(prompt, params, params.conversationMessages || [], {
602
594
  parallelizationMode: prompt.ParallelizationMode,
603
595
  totalTasks: executionTasks.length,
604
596
  successfulTasks: parallelResult.successCount,
605
597
  failedTasks: parallelResult.failureCount,
606
598
  selectedTaskId: selectedResult.task.taskId,
607
599
  executionGroups: Array.from(parallelResult.groupResults.keys()),
600
+ });
601
+ const selectedToolCallingMode = GetToolCallingMode(selectedResult.modelResult) ?? null;
602
+ const selectedResultUsage = selectedResult.modelResult?.data?.usage;
603
+ const consolidatedStatus = parallelResult.successCount > 0 ? 'Completed' : 'Failed';
604
+ const applyConsolidatedFields = () => {
605
+ consolidatedPromptRun.ModelID = selectedModelId;
606
+ if (selectedVendorId) {
607
+ consolidatedPromptRun.VendorID = selectedVendorId;
608
+ }
609
+ consolidatedPromptRun.CompletedAt = endTime;
610
+ consolidatedPromptRun.ExecutionTimeMS = parallelResult.totalExecutionTimeMS;
611
+ consolidatedPromptRun.Result = selectedResult.rawResult || '';
612
+ consolidatedPromptRun.TokensUsed = parallelResult.totalTokensUsed;
613
+ // Layer 4 instrumentation, same as the single-model path. This path reaches the same
614
+ // `executeModel` and therefore declares tools, so leaving the column NULL here would tell the
615
+ // agent loop a NativeImplicit turn was not implicit — every control-flow call would then be
616
+ // rejected as an undeclared tool and the loop would retry on tools it declared itself.
617
+ consolidatedPromptRun.ToolCallingMode = selectedToolCallingMode;
618
+ // Extract token and cost info from selected result
619
+ if (selectedResultUsage) {
620
+ consolidatedPromptRun.TokensPrompt = selectedResultUsage.promptTokens;
621
+ consolidatedPromptRun.TokensCompletion = selectedResultUsage.completionTokens;
622
+ // Persist the selected result's cache token counts so (a) they are recorded and (b) any
623
+ // downstream cost recompute (MJAIPromptRunEntityServer, when no provider cost is present)
624
+ // prices the full input including cached tokens rather than dropping them.
625
+ consolidatedPromptRun.TokensCacheRead = selectedResultUsage.cacheReadTokens ?? 0;
626
+ consolidatedPromptRun.TokensCacheWrite = selectedResultUsage.cacheWriteTokens ?? 0;
627
+ // NOTE (§5.1): On the parent, do NOT assign Cost from the selected arm. Leave Cost = null.
628
+ // TotalCost is maintained by server-side TriggerParentCostRollup.
629
+ if (selectedResultUsage.costCurrency !== undefined) {
630
+ consolidatedPromptRun.CostCurrency = selectedResultUsage.costCurrency;
631
+ }
632
+ }
633
+ // Store the parallel execution summary in the Messages field, with the messages and the allowed template inputs
634
+ consolidatedPromptRun.Messages = storedMessagesJSON;
635
+ // For parallel execution, set rollup fields to match totals
636
+ consolidatedPromptRun.TokensPromptRollup = totalPromptTokens;
637
+ consolidatedPromptRun.TokensCompletionRollup = totalCompletionTokens;
638
+ consolidatedPromptRun.TokensUsedRollup = totalPromptTokens + totalCompletionTokens;
639
+ consolidatedPromptRun.TokensCacheReadRollup = totalCacheReadTokens;
640
+ consolidatedPromptRun.TokensCacheWriteRollup = totalCacheWriteTokens;
641
+ if (hasCost) {
642
+ consolidatedPromptRun.DescendantCost = totalCost;
643
+ consolidatedPromptRun.TotalCost = totalCost;
644
+ }
645
+ // Set Status and WasSelectedResult for parallel execution
646
+ consolidatedPromptRun.Status = consolidatedStatus;
647
+ consolidatedPromptRun.WasSelectedResult = false; // WasSelectedResult stays on the selected child, not the parent
608
648
  };
609
- if (params.data || params.templateData || parallelMetadata) {
610
- consolidatedPromptRun.Messages = JSON.stringify({
611
- data: params.data,
612
- templateData: params.templateData,
613
- parallelExecution: parallelMetadata,
614
- messages: params.conversationMessages || [],
615
- });
616
- }
617
- // For parallel execution, set rollup fields to match totals
618
- consolidatedPromptRun.TokensPromptRollup = totalPromptTokens;
619
- consolidatedPromptRun.TokensCompletionRollup = totalCompletionTokens;
620
- consolidatedPromptRun.TokensUsedRollup = totalPromptTokens + totalCompletionTokens;
621
- consolidatedPromptRun.TokensCacheReadRollup = totalCacheReadTokens;
622
- consolidatedPromptRun.TokensCacheWriteRollup = totalCacheWriteTokens;
623
- if (hasCost) {
624
- consolidatedPromptRun.DescendantCost = totalCost;
625
- consolidatedPromptRun.TotalCost = totalCost;
626
- }
627
- // Set Status and WasSelectedResult for parallel execution
628
- consolidatedPromptRun.Status = parallelResult.successCount > 0 ? 'Completed' : 'Failed';
629
- consolidatedPromptRun.WasSelectedResult = false; // WasSelectedResult stays on the selected child, not the parent
630
- // Persist the consolidated run fire-and-forget; the finalize UPDATE chains after its INSERT via
631
- // the save queue. These fields are set after all the awaited parallel work, so the INSERT has long
632
- // landed — a plain Update (no post-INSERT callback) is race-safe here.
633
- this._promptRunQueue.Update(consolidatedPromptRun);
649
+ applyConsolidatedFields();
650
+ this._promptRunQueue.Update(consolidatedPromptRun, () => applyConsolidatedFields());
634
651
  // Create additional results from all other successful results (excluding the best one)
635
652
  const additionalResults = [];
636
653
  // Sort successful results by ranking (if available) or keep original order
@@ -711,7 +728,9 @@ export class AIPromptRunner extends BaseModelRunner {
711
728
  async loadTemplate(templateId, _contextUser) {
712
729
  try {
713
730
  // Use the template engine to find the template
714
- const template = this._templateEngine.Templates.find((t) => UUIDsEqual(t.ID, templateId));
731
+ const template = typeof this._templateEngine.FindTemplateByID === 'function'
732
+ ? this._templateEngine.FindTemplateByID(templateId)
733
+ : this._templateEngine.Templates.find((t) => UUIDsEqual(t.ID, templateId));
715
734
  return template || null;
716
735
  }
717
736
  catch (error) {
@@ -965,8 +984,8 @@ export class AIPromptRunner extends BaseModelRunner {
965
984
  //this.logStatus(` 📝 ${placeholder} -> ${truncatedTemplate}`, true, params);
966
985
  }
967
986
  // Render the template with the full params context
968
- // We already have system placeholders resolved, so we'll render directly
969
- const renderedPrompt = await this._templateEngine.RenderTemplate(template, template.GetHighestPriorityContent(), mergedData);
987
+ // We already have system placeholders resolved, so we'll render directly.
988
+ const renderedPrompt = await this._templateEngine.RenderTemplate(template, template.GetHighestPriorityContent(), mergedData, undefined, undefined, AIPromptRunner.RenderOptions(params));
970
989
  if (!renderedPrompt.Success) {
971
990
  throw new Error(`Failed to render template for prompt ${prompt.Name}: ${renderedPrompt.Message}`);
972
991
  }
@@ -1312,7 +1331,7 @@ export class AIPromptRunner extends BaseModelRunner {
1312
1331
  // almost always what the author meant. If real param validation is
1313
1332
  // needed (e.g., catching typos at template-author time), it should
1314
1333
  // live in the authoring tools, not in the runtime render path.
1315
- return await this._templateEngine.RenderTemplate(template, templateContent, mergedData, true, false);
1334
+ return await this._templateEngine.RenderTemplate(template, templateContent, mergedData, true, false, AIPromptRunner.RenderOptions(params));
1316
1335
  }
1317
1336
  catch (error) {
1318
1337
  this.logError(error, {
@@ -1376,7 +1395,7 @@ export class AIPromptRunner extends BaseModelRunner {
1376
1395
  errorMessage: lastError?.message || 'Unknown error',
1377
1396
  exception: lastError,
1378
1397
  errorInfo: errorInfo,
1379
- statusText: `Failover failed after ${failoverAttempts.length} attempts`,
1398
+ statusText: this.IsCallerCancellation(errorInfo) ? 'Cancelled' : `Failover failed after ${failoverAttempts.length} attempts`,
1380
1399
  timeElapsed: endTime.getTime() - startTime.getTime(),
1381
1400
  data: null
1382
1401
  };
@@ -1417,7 +1436,7 @@ export class AIPromptRunner extends BaseModelRunner {
1417
1436
  try {
1418
1437
  return ResolveNativeToolCalling({
1419
1438
  catalogConfiguration: this.catalogConfigurationFor(model, vendorId),
1420
- promptConfiguration: prompt.PromptConfigurationObject,
1439
+ promptConfiguration: this.ResolveEffectivePromptConfiguration(prompt, params),
1421
1440
  promptModelConfiguration,
1422
1441
  // Action tools and control-flow tools are counted separately: under the hybrid the control
1423
1442
  // tools are stripped, so on their own they must not open the gate (spec §5).
@@ -1431,6 +1450,24 @@ export class AIPromptRunner extends BaseModelRunner {
1431
1450
  return { useNativeTools: false, mode: 'Envelope', controlFlow: 'envelope', toolResults: false };
1432
1451
  }
1433
1452
  }
1453
+ /**
1454
+ * The prompt layer of the native tool-calling cascade, with a hierarchical run's child prompt
1455
+ * merged over its parent.
1456
+ *
1457
+ * An agent runs its agent type's system prompt as `prompt` and its own prompt as the first
1458
+ * child, so the parent's bag alone describes the agent TYPE, not the agent. Native tool calling
1459
+ * is a property of the agent's own prompt, so the child's bag sits between the parent and the
1460
+ * selected `AIPromptModel` row: parent → child → row. The merge is per key, so an explicit value
1461
+ * in the child (including `false`) overrides the parent, and an absent key inherits.
1462
+ *
1463
+ * @param prompt The prompt being run (the parent on a hierarchical run)
1464
+ * @param params The caller's params — supplies the child prompts, if any
1465
+ * @returns The merged prompt configuration, or null when neither layer sets one
1466
+ */
1467
+ ResolveEffectivePromptConfiguration(prompt, params) {
1468
+ const childPrompt = params.childPrompts?.[0]?.childPrompt?.prompt;
1469
+ return ResolveEffectiveModelConfiguration(prompt.PromptConfigurationObject ?? null, childPrompt?.PromptConfigurationObject ?? null);
1470
+ }
1434
1471
  /**
1435
1472
  * Returns the template data with `_NATIVE_TOOL_CALLING` and `_NATIVE_CONTROL_FLOW` set.
1436
1473
  *
@@ -1496,6 +1533,13 @@ export class AIPromptRunner extends BaseModelRunner {
1496
1533
  // decision travels so the agent loop can read `toolResults` off the result later.
1497
1534
  RecordToolCallingDecision(chatParams, decision);
1498
1535
  }
1536
+ /**
1537
+ * Whether an error ended a prompt run because the caller cancelled it: the caller's token is aborted,
1538
+ * or the error is classified as a cancellation.
1539
+ */
1540
+ isCancellation(error, params) {
1541
+ return params.cancellationToken?.aborted === true || this.IsCallerCancellation(ErrorAnalyzer.analyzeError(error));
1542
+ }
1499
1543
  /**
1500
1544
  * Whether a failed result failed for a TOOLS-specific reason, and so is worth one retry with the
1501
1545
  * declarations stripped.
@@ -1512,7 +1556,7 @@ export class AIPromptRunner extends BaseModelRunner {
1512
1556
  return false;
1513
1557
  }
1514
1558
  // A cancellation is the caller's decision, never a tool problem.
1515
- if (result.errorInfo?.canFailover === false && result.errorInfo?.providerErrorCode === 'request_cancelled') {
1559
+ if (this.IsCallerCancellation(result.errorInfo)) {
1516
1560
  return false;
1517
1561
  }
1518
1562
  return this.isToolSpecificFailureText(`${result.errorMessage ?? ''} ${result.statusText ?? ''}`);
@@ -1769,6 +1813,10 @@ export class AIPromptRunner extends BaseModelRunner {
1769
1813
  }
1770
1814
  catch (error) {
1771
1815
  const errorInfo = ErrorAnalyzer.analyzeError(error, driverClass);
1816
+ // A caller cancellation is not a model failure. Whoever handles it logs it once, at info level.
1817
+ if (this.IsCallerCancellation(errorInfo)) {
1818
+ throw error;
1819
+ }
1772
1820
  this.logError(error, {
1773
1821
  category: 'ModelExecution',
1774
1822
  model: model,
@@ -1791,9 +1839,9 @@ export class AIPromptRunner extends BaseModelRunner {
1791
1839
  * as a rejected promise the caller's failover/retry logic can act on.
1792
1840
  *
1793
1841
  * A timeout rejects with a typed {@link AIPromptTimeoutError} (classified by ErrorAnalyzer as a
1794
- * retriable NetworkError); a caller cancellation rejects with the same
1795
- * `'Chat completion was cancelled'` error the previous implementation produced, so cancellation
1796
- * semantics are unchanged.
1842
+ * retriable NetworkError); a caller cancellation rejects with a `'Chat completion was cancelled'`
1843
+ * error classified as a cancellation (see {@link BaseModelRunner.BuildCancellationError}), so
1844
+ * failover stops instead of trying the next candidate.
1797
1845
  *
1798
1846
  * NOTE: `Promise.race` ignores the losing `ChatCompletion()` promise's eventual result, but the
1799
1847
  * underlying request IS torn down — the composed signal is on `ChatParams.cancellationToken`, and
@@ -1807,29 +1855,37 @@ export class AIPromptRunner extends BaseModelRunner {
1807
1855
  // Neither a caller token nor a prompt timeout — execute unbounded (legacy behavior).
1808
1856
  return await llm.ChatCompletion(chatParams);
1809
1857
  }
1810
- return await Promise.race([
1811
- llm.ChatCompletion(chatParams),
1812
- new Promise((_, reject) => {
1813
- const fail = () => reject(this.buildAbortError(signal, bound));
1814
- if (signal.aborted) {
1815
- fail();
1816
- }
1817
- else {
1818
- signal.addEventListener('abort', fail, { once: true });
1819
- }
1820
- }),
1821
- ]);
1858
+ let fail;
1859
+ const aborted = new Promise((_, reject) => {
1860
+ fail = () => reject(this.buildAbortError(signal, bound));
1861
+ if (signal.aborted) {
1862
+ fail();
1863
+ }
1864
+ else {
1865
+ signal.addEventListener('abort', fail, { once: true });
1866
+ }
1867
+ });
1868
+ try {
1869
+ return await Promise.race([llm.ChatCompletion(chatParams), aborted]);
1870
+ }
1871
+ finally {
1872
+ // With no prompt timeout the signal is the caller's own token, which outlives this call: a
1873
+ // listener left on it would pile up across every prompt the caller runs.
1874
+ if (fail) {
1875
+ signal.removeEventListener('abort', fail);
1876
+ }
1877
+ }
1822
1878
  }
1823
1879
  /**
1824
1880
  * Builds the rejection error for an aborted model call — a typed {@link AIPromptTimeoutError} when
1825
- * the prompt's TimeoutMS fired, otherwise the legacy cancellation error.
1881
+ * the prompt's TimeoutMS fired, otherwise a caller cancellation that is not eligible for failover.
1826
1882
  */
1827
1883
  buildAbortError(signal, bound) {
1828
1884
  if (bound.TimedOut()) {
1829
1885
  const reason = signal.reason;
1830
1886
  return reason instanceof AIPromptTimeoutError ? reason : new Error('Chat completion timed out');
1831
1887
  }
1832
- return new Error('Chat completion was cancelled');
1888
+ return this.BuildCancellationError();
1833
1889
  }
1834
1890
  /**
1835
1891
  * Walks every message in chatParams and rewrites media content blocks
@@ -1843,17 +1899,22 @@ export class AIPromptRunner extends BaseModelRunner {
1843
1899
  * No-op when the driver's GetFileCapabilities() returns non-null AND the
1844
1900
  * block's MIME matches the supported list. The driver baseclass returns
1845
1901
  * null by default; only providers that declare vision/file support override
1846
- * it (currently: OpenAI). For everyone else, every media block falls back
1902
+ * it (currently Anthropic, OpenAI and Gemini; drivers built on the OpenAI
1903
+ * driver inherit its list). For everyone else, every media block falls back
1847
1904
  * to text — exactly what you want when running a text-only model.
1905
+ *
1906
+ * A changed message is replaced by a new object in chatParams.messages; the
1907
+ * caller's message objects stay as they were.
1848
1908
  */
1849
1909
  stripUnsupportedMediaBlocks(llm, chatParams, model, verbose, params) {
1850
1910
  const caps = llm.GetFileCapabilities();
1851
1911
  const modelName = model?.Name ?? '<unknown model>';
1852
1912
  let stripped = 0;
1853
- for (const msg of chatParams.messages) {
1913
+ chatParams.messages = chatParams.messages.map((msg) => {
1854
1914
  // Path 1: replace unsupported media content BLOCKS in array-content messages.
1855
1915
  if (Array.isArray(msg.content)) {
1856
- msg.content = msg.content.map((block) => {
1916
+ const blocks = msg.content;
1917
+ const content = blocks.map((block) => {
1857
1918
  const blockType = block.type;
1858
1919
  if (blockType !== 'image_url' && blockType !== 'audio_url' && blockType !== 'video_url' && blockType !== 'file_url') {
1859
1920
  return block;
@@ -1870,7 +1931,7 @@ export class AIPromptRunner extends BaseModelRunner {
1870
1931
  `Tell the user the active model cannot process ${blockMime.split('/')[0]} content rather than guessing what the file contains.]`,
1871
1932
  };
1872
1933
  });
1873
- continue;
1934
+ return content.some((b, i) => b !== blocks[i]) ? { ...msg, content } : msg;
1874
1935
  }
1875
1936
  // Path 2: artifacts that went through the tool-dispatch path appear in
1876
1937
  // the artifact manifest section of the rendered system prompt. The model
@@ -1880,12 +1941,14 @@ export class AIPromptRunner extends BaseModelRunner {
1880
1941
  // examples and pretends. Annotate the manifest inline so the model
1881
1942
  // knows it can't actually view the artifact.
1882
1943
  if (typeof msg.content === 'string' && msg.role === ChatMessageRole.system) {
1883
- const before = msg.content;
1884
- msg.content = this.annotateManifestForUnsupportedMedia(before, caps, modelName);
1885
- if (msg.content !== before)
1944
+ const annotated = this.annotateManifestForUnsupportedMedia(msg.content, caps, modelName);
1945
+ if (annotated !== msg.content) {
1886
1946
  stripped++;
1947
+ return { ...msg, content: annotated };
1948
+ }
1887
1949
  }
1888
- }
1950
+ return msg;
1951
+ });
1889
1952
  if (stripped > 0) {
1890
1953
  this.logStatus(`[ModalityCheck] Annotated ${stripped} unsupported media artifact reference(s) for model "${modelName}". Driver capabilities: ${caps ? caps.SupportedMimeTypes.join(', ') : 'none (driver declares no file support)'}.`, verbose, params);
1891
1954
  }
@@ -1989,16 +2052,16 @@ export class AIPromptRunner extends BaseModelRunner {
1989
2052
  }
1990
2053
  if (fileBlocks.length === 0 && textFallbackBlocks.length === 0)
1991
2054
  return;
1992
- // Find the last user message and convert its content to content blocks
2055
+ // Find the last user message and put the file blocks ahead of its content, keeping any blocks it already has.
2056
+ // A block the message already carries is not added again, so injecting the same files twice adds them once.
1993
2057
  for (let i = chatParams.messages.length - 1; i >= 0; i--) {
1994
2058
  const msg = chatParams.messages[i];
1995
2059
  if (msg.role === 'user') {
1996
- const textContent = typeof msg.content === 'string' ? msg.content : '';
1997
- msg.content = [
1998
- ...fileBlocks,
1999
- ...textFallbackBlocks,
2000
- { type: 'text', content: textContent },
2001
- ];
2060
+ const existing = typeof msg.content === 'string'
2061
+ ? [{ type: 'text', content: msg.content }]
2062
+ : [...msg.content];
2063
+ const isNew = (block) => !existing.some((e) => e.type === block.type && e.content === block.content);
2064
+ msg.content = [...fileBlocks.filter(isNew), ...textFallbackBlocks.filter(isNew), ...existing];
2002
2065
  break;
2003
2066
  }
2004
2067
  }
@@ -2310,6 +2373,10 @@ export class AIPromptRunner extends BaseModelRunner {
2310
2373
  }
2311
2374
  }
2312
2375
  catch (error) {
2376
+ // A cancellation ends the retries; the caller logs it and records the run as cancelled.
2377
+ if (this.isCancellation(error, params)) {
2378
+ throw error;
2379
+ }
2313
2380
  lastError = error;
2314
2381
  this.logError(error, {
2315
2382
  category: 'ExecutionRetry',
@@ -2485,6 +2552,16 @@ export class AIPromptRunner extends BaseModelRunner {
2485
2552
  * for "is this an envelope or plain prose?" under implicit control flow. Never throws.
2486
2553
  */
2487
2554
  parsesAsJSON(text) {
2555
+ const trimmed = text.trimStart();
2556
+ if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
2557
+ try {
2558
+ JSON.parse(text);
2559
+ return true;
2560
+ }
2561
+ catch {
2562
+ // Fall through to CleanJSON extraction
2563
+ }
2564
+ }
2488
2565
  try {
2489
2566
  JSON.parse(CleanJSON(text) ?? text);
2490
2567
  return true;
@@ -2703,8 +2780,20 @@ export class AIPromptRunner extends BaseModelRunner {
2703
2780
  async parseObjectOutput(rawOutput, prompt, skipValidation, cleanValidationSyntax, validationErrors, currentPromptRun, params) {
2704
2781
  let parsedResult;
2705
2782
  try {
2706
- // First attempt: Use CleanJSON to handle common JSON issues
2707
- parsedResult = JSON.parse(CleanJSON(rawOutput));
2783
+ // Fast path: when rawOutput already begins with '{' or '[', try native JSON.parse
2784
+ // directly before running CleanJSON's multi-pass regex extraction.
2785
+ const trimmed = rawOutput.trimStart();
2786
+ if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
2787
+ try {
2788
+ parsedResult = JSON.parse(rawOutput);
2789
+ }
2790
+ catch {
2791
+ parsedResult = JSON.parse(CleanJSON(rawOutput));
2792
+ }
2793
+ }
2794
+ else {
2795
+ parsedResult = JSON.parse(CleanJSON(rawOutput));
2796
+ }
2708
2797
  }
2709
2798
  catch (jsonError) {
2710
2799
  // If attemptJSONRepair is enabled and we're dealing with object output
@@ -2723,8 +2812,7 @@ export class AIPromptRunner extends BaseModelRunner {
2723
2812
  }
2724
2813
  // Clean validation syntax if needed
2725
2814
  if (parsedResult && (cleanValidationSyntax || (!skipValidation && prompt.OutputExample))) {
2726
- const validator = new JSONValidator();
2727
- parsedResult = validator.cleanValidationSyntax(parsedResult);
2815
+ parsedResult = this._jsonValidator.cleanValidationSyntax(parsedResult);
2728
2816
  }
2729
2817
  return parsedResult;
2730
2818
  }
@@ -3072,7 +3160,8 @@ export class AIPromptRunner extends BaseModelRunner {
3072
3160
  if (params.additionalParameters?.stopSequences !== undefined && params.additionalParameters.stopSequences.length > 0) {
3073
3161
  promptRun.StopSequences = JSON.stringify(params.additionalParameters.stopSequences);
3074
3162
  }
3075
- // Store the input data/context as JSON in Messages field.
3163
+ // Store the messages the model received in the Messages field, plus the template inputs
3164
+ // (data, templateData) that the run's template-data capture mode allows.
3076
3165
  // Also capture callers that supply conversationMessages directly (e.g. templateMessageRole='none',
3077
3166
  // no rendered system prompt) — otherwise their assembled prompt would never be persisted.
3078
3167
  if (params.data || params.templateData || systemPromptText || (params.conversationMessages?.length ?? 0) > 0) {
@@ -3097,11 +3186,7 @@ export class AIPromptRunner extends BaseModelRunner {
3097
3186
  // Always include any caller-supplied conversation messages (previously only recorded when a
3098
3187
  // template system prompt was present, which dropped them for the pure-conversationMessages path).
3099
3188
  messages.push(...(params.conversationMessages || []));
3100
- promptRun.Messages = JSON.stringify({
3101
- data: params.data,
3102
- templateData: params.templateData,
3103
- messages: messages || [],
3104
- });
3189
+ promptRun.Messages = this.buildStoredMessagesJSON(prompt, params, messages);
3105
3190
  }
3106
3191
  // Populate new retry tracking columns with initial values
3107
3192
  promptRun.ValidationBehavior = params.validationBehavior || prompt.ValidationBehavior || 'Warn';
@@ -3112,6 +3197,75 @@ export class AIPromptRunner extends BaseModelRunner {
3112
3197
  promptRun.SuccessfulValidationCount = 0;
3113
3198
  promptRun.FinalValidationPassed = false; // Will be updated after execution
3114
3199
  }
3200
+ /** The server default template-data capture mode (`aiPromptRuns.templateDataCapture` in mj.config). */
3201
+ GetServerTemplateDataCaptureDefault() {
3202
+ if (AIPromptRunner.serverTemplateDataCaptureDefault === undefined) {
3203
+ AIPromptRunner.serverTemplateDataCaptureDefault = ReadServerTemplateDataCaptureDefault();
3204
+ }
3205
+ return AIPromptRunner.serverTemplateDataCaptureDefault;
3206
+ }
3207
+ /**
3208
+ * Serializes what this run stores in `AIPromptRun.Messages`, applying the template-data capture mode.
3209
+ * A capture error never fails the run: it is logged, and the run stores `None` with a fixed note and no template data.
3210
+ */
3211
+ buildStoredMessagesJSON(prompt, params, messages, parallelExecution) {
3212
+ try {
3213
+ const mode = ResolveTemplateDataCaptureMode(params.TemplateDataCapture, this.promptTemplateDataCaptureSettings(prompt, params), this.GetServerTemplateDataCaptureDefault());
3214
+ return JSON.stringify(BuildStoredPromptRunMessages({
3215
+ Mode: mode,
3216
+ Data: params.data,
3217
+ TemplateData: params.templateData,
3218
+ Messages: messages,
3219
+ GetReferencedVariables: () => this.collectReferencedVariables(prompt, params),
3220
+ ParallelExecution: parallelExecution,
3221
+ }));
3222
+ }
3223
+ catch (error) {
3224
+ LogError(`Template data capture failed for prompt "${prompt.Name}"; the run stores no template data`, null, error);
3225
+ return JSON.stringify(BuildCaptureFailedPromptRunMessages(messages, parallelExecution));
3226
+ }
3227
+ }
3228
+ /** The child prompts rendered in a run, depth first: each child prompt, then its own child prompts. */
3229
+ childPromptsDepthFirst(children) {
3230
+ const prompts = [];
3231
+ for (const child of children ?? []) {
3232
+ prompts.push(child.childPrompt.prompt, ...this.childPromptsDepthFirst(child.childPrompt.childPrompts));
3233
+ }
3234
+ return prompts;
3235
+ }
3236
+ /**
3237
+ * `TemplateDataCapture` of each prompt in the run, most specific first: the child prompts depth first, then the
3238
+ * main prompt. For a Loop or Harness agent, the agent's own prompt is a child prompt of the agent-type system prompt.
3239
+ */
3240
+ promptTemplateDataCaptureSettings(prompt, params) {
3241
+ return [...this.childPromptsDepthFirst(params.childPrompts).map((child) => child.TemplateDataCapture), prompt.TemplateDataCapture];
3242
+ }
3243
+ /** Variables read by the prompt's template and by every child prompt template rendered in the same run. */
3244
+ collectReferencedVariables(prompt, params) {
3245
+ const names = new Set();
3246
+ const problems = [];
3247
+ const addPromptTemplate = (templateId, promptName) => {
3248
+ if (!templateId)
3249
+ return;
3250
+ const template = typeof this._templateEngine.FindTemplateByID === 'function'
3251
+ ? this._templateEngine.FindTemplateByID(templateId)
3252
+ : this._templateEngine.Templates.find((t) => UUIDsEqual(t.ID, templateId));
3253
+ const text = template?.GetHighestPriorityContent()?.TemplateText;
3254
+ if (!text) {
3255
+ problems.push(`the template of prompt "${promptName}" was not found`);
3256
+ return;
3257
+ }
3258
+ const result = this._templateEngine.GetReferencedVariables(text);
3259
+ result.Names.forEach((name) => names.add(name));
3260
+ if (!result.Complete)
3261
+ problems.push(`prompt "${promptName}": ${result.Reason ?? 'incomplete analysis'}`);
3262
+ };
3263
+ addPromptTemplate(prompt.TemplateID, prompt.Name);
3264
+ for (const child of this.childPromptsDepthFirst(params.childPrompts)) {
3265
+ addPromptTemplate(child.TemplateID, child.Name);
3266
+ }
3267
+ return problems.length === 0 ? { Names: names, Complete: true } : { Names: names, Complete: false, Reason: problems.join('; ') };
3268
+ }
3115
3269
  /**
3116
3270
  * Updates the AIPromptRun entity with execution results
3117
3271
  */
@@ -3288,6 +3442,12 @@ export class AIPromptRunner extends BaseModelRunner {
3288
3442
  }
3289
3443
  }
3290
3444
  // Success and Status were set by FinalizeRunRecord from the outcome updatePromptRun passed it.
3445
+ // A call the caller cancelled is recorded as cancelled, not as a failed model call.
3446
+ if (!modelResult.success && this.IsCallerCancellation(modelResult.errorInfo)) {
3447
+ promptRun.Status = 'Cancelled';
3448
+ promptRun.Cancelled = true;
3449
+ promptRun.CancellationReason = 'user_requested';
3450
+ }
3291
3451
  // Set ErrorDetails if failed
3292
3452
  if (!promptRun.Success) {
3293
3453
  if (!modelResult.success && modelResult.errorMessage) {