@memberjunction/ai-prompts 6.2.0-edge.5 → 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.
@@ -2,12 +2,14 @@ import { BaseLLM, ChatParams, ChatMessageRole, ErrorAnalyzer, ResolveFileInputSt
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
+ import { RecordSentPrefixFingerprint, ReplayedReasoningPrefixFingerprint, WithoutReplayedReasoning } from './replayedReasoningPrefix.js';
5
6
  import { AIModelSelectionInfo, PickPromptExecutionScope } from '@memberjunction/ai-core-plus';
6
7
  import { LogError, LogStatus, IsVerboseLoggingEnabled, Metadata } from '@memberjunction/core';
7
8
  import { CleanJSON, RepairJSONEscaping, MJGlobal, JSONValidator, ValidationResult, ValidationErrorInfo, ValidationErrorType, UUIDsEqual, NormalizeUUID } from '@memberjunction/global';
8
9
  import { TemplateEngineServer } from '@memberjunction/templates';
9
10
  import { ExecutionPlanner } from './ExecutionPlanner.js';
10
11
  import { AIPromptTimeoutError } from './AIPromptTimeoutError.js';
12
+ import { BuildNoModelFoundMessage, NOT_EVALUATED_REASON } from './no-model-found-message.js';
11
13
  import { ParseManifestEntryMime, TrimSpacesAndTabs } from './linearTextScan.js';
12
14
  import { AIEngine } from '@memberjunction/aiengine';
13
15
  import { AIEngineBase } from '@memberjunction/ai-engine-base';
@@ -34,9 +36,11 @@ function mimeFromBlockType(type) {
34
36
  }
35
37
  }
36
38
  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. */
39
+ /** The render options a prompt asks for: the prompt caller as the render user, and a raw render when `templateAutoescape` is false. */
38
40
  static RenderOptions(params) {
39
- return params.templateAutoescape === false ? { autoescape: false } : undefined;
41
+ return params.templateAutoescape === false
42
+ ? { autoescape: false, ContextUser: params.contextUser }
43
+ : { ContextUser: params.contextUser };
40
44
  }
41
45
  /**
42
46
  * The model type this runner requires. Returns 'LLM' for AIPromptRunner.
@@ -48,6 +52,14 @@ export class AIPromptRunner extends BaseModelRunner {
48
52
  get DefaultLogCategory() {
49
53
  return 'AIPromptRunner';
50
54
  }
55
+ /**
56
+ * Per request: renders its template again with other template data (see `rerenderForNativeDecision`).
57
+ * Shared across runner instances, because the parallel coordinator runs each task on its own
58
+ * runner with a copy of the params (see {@link ShareNativeRerender}).
59
+ */
60
+ static { this._nativeRerenderers = new WeakMap(); }
61
+ /** Per result: the prompt run's `Messages`, when the attempt sent a prompt rendered again for its own path. */
62
+ static { this._rerenderedMessages = new WeakMap(); }
51
63
  /**
52
64
  * Process-wide cache of parsed `OutputExample` JSON, keyed by the raw example string.
53
65
  * A prompt's OutputExample is a static string reused across every run and every validation
@@ -62,7 +74,7 @@ export class AIPromptRunner extends BaseModelRunner {
62
74
  * that were intentionally NOT credential-checked because a higher-priority candidate had
63
75
  * already been selected. See the DECISION note in {@link selectModelWithAPIKeyTracked}.
64
76
  */
65
- static { this.NOT_EVALUATED_REASON = 'Not evaluated (a higher-priority candidate was already selected; set AIPromptParams.forceFullModelEvaluation to probe all)'; }
77
+ static { this.NOT_EVALUATED_REASON = NOT_EVALUATED_REASON; }
66
78
  constructor() {
67
79
  super();
68
80
  this._metadata =
@@ -188,9 +200,8 @@ export class AIPromptRunner extends BaseModelRunner {
188
200
  // (plan §8.4), and that is only safe if the flag is the gate's real answer rather than the
189
201
  // caller's intent — a prompt that suppressed its catalog while the model received no tools
190
202
  // would leave the agent unable to act at all.
191
- // Caveat: failover re-resolves the gate per attempt, so a failover onto a model without
192
- // the capability keeps the already-rendered native wording. The request still degrades
193
- // correctly (no tools are sent); the prompt is merely quieter than it should be.
203
+ // Failover re-resolves the gate per attempt; an attempt whose decision differs from this one
204
+ // renders the template again for its own path (see `rerenderForNativeDecision`).
194
205
  //
195
206
  // This must resolve from the SAME inputs the request-time call uses (see
196
207
  // `applyNativeToolCalling`), or the template can render for the opposite path: the vendor
@@ -214,6 +225,15 @@ export class AIPromptRunner extends BaseModelRunner {
214
225
  : await this.renderChildPromptTemplates(params.childPrompts, params, params.cancellationToken);
215
226
  // Render the parent prompt with child templates embedded
216
227
  renderedPromptText = await this.renderPromptWithChildTemplates(prompt, params, childTemplateRenderingResult.renderedTemplates);
228
+ // Child templates read the native flags too, so a re-render renders them again — unless the
229
+ // caller supplied them already rendered, in which case they are all there is.
230
+ const preRendered = params.PreRenderedChildTemplates;
231
+ this.registerNativeRerender(params, async (data) => {
232
+ const rerenderParams = this.withPromptData(params, data);
233
+ const children = preRendered
234
+ ?? (await this.renderChildPromptTemplates(params.childPrompts, rerenderParams, params.cancellationToken)).renderedTemplates;
235
+ return this.renderPromptWithChildTemplates(prompt, rerenderParams, children);
236
+ });
217
237
  }
218
238
  // Create parent prompt run for the final composed prompt execution
219
239
  parentPromptRun = await this.createPromptRun(prompt, selection.model, params, renderedPromptText, startTime, params.override?.vendorId, selection.selectionInfo);
@@ -240,6 +260,13 @@ export class AIPromptRunner extends BaseModelRunner {
240
260
  throw new Error(`Failed to render template for prompt ${prompt.Name}: ${renderedPrompt.Message}`);
241
261
  }
242
262
  renderedPromptText = renderedPrompt.Output;
263
+ this.registerNativeRerender(params, async (data) => {
264
+ const rerendered = await this.renderPromptTemplate(template, this.withPromptData(params, data));
265
+ if (!rerendered.Success) {
266
+ throw new Error(`Failed to re-render template for prompt ${prompt.Name}: ${rerendered.Message}`);
267
+ }
268
+ return rerendered.Output;
269
+ });
243
270
  }
244
271
  }
245
272
  // Check for cancellation after template rendering
@@ -400,9 +427,6 @@ export class AIPromptRunner extends BaseModelRunner {
400
427
  // Calculate execution metrics
401
428
  const endTime = new Date();
402
429
  const executionTimeMS = endTime.getTime() - startTime.getTime();
403
- // Layer 4 instrumentation: attribute this run to the path it actually took, before the update
404
- // persists it. Left NULL when no model call happened, which is the honest value.
405
- promptRun.ToolCallingMode = GetToolCallingMode(modelResult) ?? null;
406
430
  // Update the prompt run with results including validation attempts and cumulative tokens
407
431
  await this.updatePromptRun(promptRun, prompt, modelResult, parsedResult, endTime, executionTimeMS, validationAttempts, cumulativeTokens);
408
432
  const chatResult = modelResult;
@@ -1205,6 +1229,7 @@ export class AIPromptRunner extends BaseModelRunner {
1205
1229
  consideredModels.push({
1206
1230
  model: candidate.model,
1207
1231
  vendor: vendorEntity,
1232
+ driverClass: candidate.driverClass,
1208
1233
  priority: candidate.priority,
1209
1234
  available: false,
1210
1235
  unavailableReason: AIPromptRunner.NOT_EVALUATED_REASON
@@ -1227,6 +1252,7 @@ export class AIPromptRunner extends BaseModelRunner {
1227
1252
  const considered = {
1228
1253
  model: candidate.model,
1229
1254
  vendor: vendorEntity,
1255
+ driverClass: candidate.driverClass,
1230
1256
  priority: candidate.priority,
1231
1257
  available: hasCredentials,
1232
1258
  unavailableReason: hasCredentials ? undefined : `No credentials configured for driver ${candidate.driverClass}`
@@ -1264,37 +1290,14 @@ export class AIPromptRunner extends BaseModelRunner {
1264
1290
  }
1265
1291
  /**
1266
1292
  * Builds a descriptive error message when no model could be selected for a prompt.
1267
- * Includes details about which models were considered and why they were unavailable
1268
- * so the error message is actionable for end users (e.g., missing API credentials).
1293
+ *
1294
+ * The body lives in `no-model-found-message.ts` so it can be tested directly — as a private
1295
+ * method its only coverage was a re-implementation of it in the test file, which asserted
1296
+ * against its own copy rather than this code.
1269
1297
  */
1270
1298
  buildNoModelFoundMessage(promptName, selectionInfo, credentialScope) {
1271
- const base = `No suitable model found for prompt ${promptName}`;
1272
- // A selection step that threw (for example the model-type floor) records its error here; show it
1273
- // rather than the generic "no candidates" text. Every other reason keeps its detailed message below.
1274
- if (selectionInfo?.selectionReason?.startsWith('Error during model selection:')) {
1275
- return `${base}. ${selectionInfo.selectionReason}`;
1276
- }
1277
- if (!selectionInfo?.modelsConsidered || selectionInfo.modelsConsidered.length === 0) {
1278
- return `${base}. No model-vendor candidates were available. Please ensure AI models are configured for this prompt.`;
1279
- }
1280
- // Check if all models were unavailable due to missing credentials
1281
- const unavailableModels = selectionInfo.modelsConsidered.filter(m => !m.available);
1282
- if (unavailableModels.length === selectionInfo.modelsConsidered.length) {
1283
- const triedSummary = unavailableModels.slice(0, 5).map(m => {
1284
- const vendorName = m.vendor?.Name || 'default';
1285
- return `${m.model.Name}/${vendorName}`;
1286
- }).join(', ');
1287
- const suffix = unavailableModels.length > 5 ? ` (${unavailableModels.length} total)` : '';
1288
- // When the scope rules out the platform's credentials, "configure them" would point the reader
1289
- // at exactly the fallback the caller ruled out.
1290
- const platformAllowed = CredentialScopeAllows(credentialScope, 'Environment') || CredentialScopeAllows(credentialScope, 'PlatformCredential');
1291
- const remedy = platformAllowed
1292
- ? `Please configure API credentials in your environment or AI Credential settings.`
1293
- : `The credential scope is ${credentialScope}, so only the API keys supplied with this run count; supply a key for one of these vendors.`;
1294
- return `${base}. No valid API credentials/keys are configured for any of the candidate model-vendor combinations. ` +
1295
- `Tried: ${triedSummary}${suffix}. ${remedy}`;
1296
- }
1297
- return `${base}. ${selectionInfo.selectionReason || 'Unknown reason'}`;
1299
+ const platformAllowed = CredentialScopeAllows(credentialScope, 'Environment') || CredentialScopeAllows(credentialScope, 'PlatformCredential');
1300
+ return BuildNoModelFoundMessage(promptName, selectionInfo, credentialScope ? { Name: credentialScope, PlatformAllowed: platformAllowed } : undefined);
1298
1301
  }
1299
1302
  /**
1300
1303
  * Renders the prompt template with provided data
@@ -1495,6 +1498,91 @@ export class AIPromptRunner extends BaseModelRunner {
1495
1498
  _NATIVE_CONTROL_FLOW: current._NATIVE_CONTROL_FLOW ?? 'envelope'
1496
1499
  };
1497
1500
  }
1501
+ /**
1502
+ * Remembers how to render this request's template again with different template data, so a
1503
+ * failover attempt whose native decision differs from the one the template was rendered for can
1504
+ * get a prompt that matches what it actually sends (see {@link rerenderForNativeDecision}).
1505
+ */
1506
+ registerNativeRerender(params, render) {
1507
+ AIPromptRunner._nativeRerenderers.set(params, render);
1508
+ }
1509
+ /** Lets a copy of the params re-render the template the original registered — for the parallel path's per-task copies. */
1510
+ ShareNativeRerender(original, copy) {
1511
+ const render = AIPromptRunner._nativeRerenderers.get(original);
1512
+ if (render) {
1513
+ AIPromptRunner._nativeRerenderers.set(copy, render);
1514
+ }
1515
+ }
1516
+ /** A copy of the params with other template data — the original is shared with parallel attempts and must not change. */
1517
+ withPromptData(params, data) {
1518
+ return Object.assign(Object.create(Object.getPrototypeOf(params)), params, { data });
1519
+ }
1520
+ /**
1521
+ * The prompt text for this attempt's native decision.
1522
+ *
1523
+ * The template's native wording is set once, from the first candidate's decision. Failover
1524
+ * re-resolves the decision per attempt, so an attempt can land on a model on another path —
1525
+ * envelope after native, or hybrid after implicit — and would otherwise be taught a protocol it
1526
+ * is not being asked to use. When the decision differs from the one the template was rendered
1527
+ * for, the template is rendered again for this attempt; otherwise the text is returned as is.
1528
+ */
1529
+ async rerenderForNativeDecision(renderedPrompt, chatParams, params, model) {
1530
+ const decision = GetToolCallingDecision(chatParams);
1531
+ // A prompt rendered without the native flags (no agent-type system prompt) has no native
1532
+ // wording to correct, whatever the decision.
1533
+ if (!decision || params.data?._NATIVE_TOOL_CALLING === undefined) {
1534
+ return renderedPrompt;
1535
+ }
1536
+ const renderedNative = params.data?._NATIVE_TOOL_CALLING === true;
1537
+ const renderedFlow = params.data?._NATIVE_CONTROL_FLOW ?? 'envelope';
1538
+ if (renderedNative === decision.useNativeTools && (!decision.useNativeTools || renderedFlow === decision.controlFlow)) {
1539
+ return renderedPrompt;
1540
+ }
1541
+ this.logStatus(` Re-rendering the prompt for ${model.Name}: its tool-calling path (${decision.mode}) differs from the one the prompt was rendered for`, true, params);
1542
+ return this.rerenderOrKeep(renderedPrompt, params, this.ApplyNativeTemplateFlags(params.data, decision));
1543
+ }
1544
+ /**
1545
+ * The template rendered again with `data`, or `renderedPrompt` unchanged when the request
1546
+ * registered no renderer or the render fails. A failed re-render is the template's problem, not
1547
+ * the model's: the attempt goes ahead with the text it already had, and the error is logged.
1548
+ */
1549
+ async rerenderOrKeep(renderedPrompt, params, data) {
1550
+ const render = AIPromptRunner._nativeRerenderers.get(params);
1551
+ if (!render) {
1552
+ return renderedPrompt;
1553
+ }
1554
+ try {
1555
+ return await render(data);
1556
+ }
1557
+ catch (error) {
1558
+ LogError(`AIPromptRunner: re-rendering the prompt failed; sending the prompt as first rendered`, null, error);
1559
+ return renderedPrompt;
1560
+ }
1561
+ }
1562
+ /**
1563
+ * Swaps the rendered prompt inside an already-built message array, keeping anything appended to
1564
+ * it (the prefill fallback instruction). Returns the messages unchanged when the prompt is not found.
1565
+ */
1566
+ replaceRenderedPrompt(messages, from, to) {
1567
+ const at = messages.findIndex((m) => typeof m.content === 'string' && m.content.startsWith(from));
1568
+ if (at < 0 || from === to) {
1569
+ return messages;
1570
+ }
1571
+ const copy = [...messages];
1572
+ copy[at] = { ...copy[at], content: to + copy[at].content.slice(from.length) };
1573
+ return copy;
1574
+ }
1575
+ /** The prompt run's `Messages` for a result whose attempt sent a re-rendered prompt, or undefined. */
1576
+ RerenderedMessagesFor(result) {
1577
+ return AIPromptRunner._rerenderedMessages.get(result);
1578
+ }
1579
+ /** Records, for the prompt run, the messages an attempt sent when its prompt was rendered again. */
1580
+ recordRerenderedMessages(result, prompt, params, model, vendorId, renderedPrompt) {
1581
+ const json = this.storedMessagesJSON(prompt, params, model, renderedPrompt, vendorId ?? undefined);
1582
+ if (json) {
1583
+ AIPromptRunner._rerenderedMessages.set(result, json);
1584
+ }
1585
+ }
1498
1586
  /** @deprecated Use {@link ResolveNativeToolCallingDecision}. */
1499
1587
  resolveNativeToolCallingDecision(prompt, params, model, vendorId, promptModelConfiguration) {
1500
1588
  return this.ResolveNativeToolCallingDecision(prompt, params, model, vendorId, promptModelConfiguration);
@@ -1559,7 +1647,27 @@ export class AIPromptRunner extends BaseModelRunner {
1559
1647
  if (this.IsCallerCancellation(result.errorInfo)) {
1560
1648
  return false;
1561
1649
  }
1562
- return this.isToolSpecificFailureText(`${result.errorMessage ?? ''} ${result.statusText ?? ''}`);
1650
+ return this.isToolEligibleError(result.errorInfo)
1651
+ && this.isToolSpecificFailureText(`${result.errorMessage ?? ''} ${result.statusText ?? ''}`);
1652
+ }
1653
+ /**
1654
+ * Whether the provider's error could be a rejected tools payload.
1655
+ *
1656
+ * A 400 or 422 is a request error whatever the classifier made of its text: the classifier reads
1657
+ * keywords such as "balance" or "timeout" before the status, and a schema rejection quoting a
1658
+ * `Get_Account_Balance` tool or a `TimeoutMS` property would otherwise pass as a credit or network
1659
+ * failure. Without one of those statuses, only the classifications that are never about the
1660
+ * tools payload — a rate limit, an authentication failure, a cancellation, a context-length
1661
+ * error — are ruled out. An error with no classification is judged by its text alone.
1662
+ */
1663
+ isToolEligibleError(errorInfo) {
1664
+ if (!errorInfo) {
1665
+ return true;
1666
+ }
1667
+ if (errorInfo.httpStatusCode === 400 || errorInfo.httpStatusCode === 422) {
1668
+ return true;
1669
+ }
1670
+ return !AIPromptRunner.TOOL_INELIGIBLE_ERROR_TYPES.includes(errorInfo.errorType);
1563
1671
  }
1564
1672
  /**
1565
1673
  * Retries a native call once on today's exact path, with the tool declarations stripped.
@@ -1572,7 +1680,7 @@ export class AIPromptRunner extends BaseModelRunner {
1572
1680
  *
1573
1681
  * @param reason What the provider said, for the warning — a misconfiguration should be visible
1574
1682
  */
1575
- async retryWithToolsStripped(llm, chatParams, executionBound, model, vendorId, prompt, reason) {
1683
+ async retryWithToolsStripped(llm, chatParams, executionBound, model, vendorId, prompt, reason, params, renderedPrompt, firstRenderedPrompt) {
1576
1684
  console.warn(`AIPromptRunner: native tool calling failed on ${model.Name}${vendorId ? ` (vendor ${vendorId})` : ''} ` +
1577
1685
  `for prompt "${prompt.Name}" — retrying once on the envelope path with tools stripped. ` +
1578
1686
  `Provider error: ${reason}`);
@@ -1585,10 +1693,36 @@ export class AIPromptRunner extends BaseModelRunner {
1585
1693
  // the same request. Show the retry what the envelope path has always
1586
1694
  // shown: the calls' prose, and each result as an "[Action Result]" user message.
1587
1695
  chatParams.messages = EncodeToolTurnsAsText(chatParams.messages);
1696
+ // The prompt was rendered for native tools — no action catalog, "call the tool" wording. With
1697
+ // the tools gone, render it for the envelope, so the model can still act.
1698
+ const envelopePrompt = await this.rerenderOrKeep(renderedPrompt, params, { ...(params.data ?? {}), _NATIVE_TOOL_CALLING: false, _NATIVE_CONTROL_FLOW: 'envelope' });
1699
+ chatParams.messages = this.replaceRenderedPrompt(chatParams.messages, renderedPrompt, envelopePrompt);
1700
+ const sentPrefix = this.guardReplayedReasoningPrefix(chatParams, params, model);
1588
1701
  const fallbackResult = await this.runChatCompletionBounded(llm, chatParams, executionBound);
1589
1702
  RecordToolCallingMode(fallbackResult, 'NativeFallback');
1703
+ RecordSentPrefixFingerprint(fallbackResult, sentPrefix);
1704
+ // The prompt run holds the first-rendered prompt; record what this retry sent whenever it differs.
1705
+ if (envelopePrompt !== firstRenderedPrompt) {
1706
+ this.recordRerenderedMessages(fallbackResult, prompt, params, model, vendorId, envelopePrompt);
1707
+ }
1590
1708
  return fallbackResult;
1591
1709
  }
1710
+ /**
1711
+ * Sends a request without replayed reasoning when its system prompt or tools differ from the
1712
+ * previous request's (`params.ReplayedReasoningPrefix`): a provider that binds reasoning to an
1713
+ * unchanged prefix rejects it then — a skill that activated mid-run, a failover re-render.
1714
+ *
1715
+ * @returns This request's fingerprint, recorded on its result for the caller's next request
1716
+ */
1717
+ guardReplayedReasoningPrefix(chatParams, params, model) {
1718
+ const fingerprint = ReplayedReasoningPrefixFingerprint(chatParams);
1719
+ const previous = params.ReplayedReasoningPrefix;
1720
+ if (previous !== undefined && previous !== fingerprint && chatParams.messages.some((m) => m.reasoning)) {
1721
+ this.logStatus(` The system prompt or tools changed since the previous request to ${model.Name}; sending it without replayed reasoning`, true, params);
1722
+ chatParams.messages = WithoutReplayedReasoning(chatParams.messages);
1723
+ }
1724
+ return fingerprint;
1725
+ }
1592
1726
  /** Scans provider prose for a tools marker. Shared by the thrown-error and failed-result paths. */
1593
1727
  isToolSpecificFailureText(text) {
1594
1728
  const lowered = text.toLowerCase();
@@ -1742,6 +1876,8 @@ export class AIPromptRunner extends BaseModelRunner {
1742
1876
  // Resolved HERE rather than once per run because failover may land on a different
1743
1877
  // (model, vendor) that does not support tools.
1744
1878
  this.applyNativeToolCalling(chatParams, prompt, params, model, vendorId, promptModelConfiguration);
1879
+ const firstRenderedPrompt = renderedPrompt;
1880
+ renderedPrompt = await this.rerenderForNativeDecision(renderedPrompt, chatParams, params, model);
1745
1881
  // Build message array with rendered prompt and conversation messages
1746
1882
  chatParams.messages = this.buildMessageArray(renderedPrompt, conversationMessages, templateMessageRole);
1747
1883
  // Declarations and tool turns must travel TOGETHER. The gate above is re-resolved per
@@ -1770,13 +1906,68 @@ export class AIPromptRunner extends BaseModelRunner {
1770
1906
  // place streaming is configured for prompt execution, so the single-model path and the parallel
1771
1907
  // path (which bridges its per-task callbacks into params.onStreaming) stream through identical
1772
1908
  // code — no second streaming implementation that can drift.
1909
+ // Coalesce rapid token chunks within a 35ms window (~28 fps) to avoid flooding WebSocket/PubSub
1910
+ // while emitting the first chunk immediately and flushing synchronously on completion.
1911
+ let flushStreamingBuffer;
1773
1912
  if (params.onStreaming) {
1774
1913
  const onStreaming = params.onStreaming;
1914
+ const coalesceIntervalMs = 35;
1915
+ let bufferedContent = '';
1916
+ let lastEmitMs = 0;
1917
+ let flushTimer = null;
1918
+ const clearTimer = () => {
1919
+ if (flushTimer !== null) {
1920
+ clearTimeout(flushTimer);
1921
+ flushTimer = null;
1922
+ }
1923
+ };
1924
+ const emitNow = (content, isComplete) => {
1925
+ clearTimer();
1926
+ lastEmitMs = Date.now();
1927
+ onStreaming({ content, isComplete, modelName: model.Name });
1928
+ };
1929
+ flushStreamingBuffer = () => {
1930
+ clearTimer();
1931
+ if (bufferedContent.length > 0) {
1932
+ const pending = bufferedContent;
1933
+ bufferedContent = '';
1934
+ lastEmitMs = Date.now();
1935
+ onStreaming({ content: pending, isComplete: false, modelName: model.Name });
1936
+ }
1937
+ };
1775
1938
  chatParams.streaming = true;
1776
1939
  chatParams.streamingCallbacks = {
1777
- OnContent: (chunk, isComplete) => onStreaming({ content: chunk, isComplete, modelName: model.Name }),
1940
+ OnContent: (chunk, isComplete) => {
1941
+ if (isComplete) {
1942
+ const combined = bufferedContent + chunk;
1943
+ bufferedContent = '';
1944
+ emitNow(combined, true);
1945
+ return;
1946
+ }
1947
+ const now = Date.now();
1948
+ if (lastEmitMs === 0 || now - lastEmitMs >= coalesceIntervalMs) {
1949
+ const combined = bufferedContent + chunk;
1950
+ bufferedContent = '';
1951
+ emitNow(combined, false);
1952
+ return;
1953
+ }
1954
+ bufferedContent += chunk;
1955
+ if (flushTimer === null) {
1956
+ const delay = Math.max(1, coalesceIntervalMs - (now - lastEmitMs));
1957
+ flushTimer = setTimeout(() => {
1958
+ flushTimer = null;
1959
+ if (bufferedContent.length > 0) {
1960
+ const pending = bufferedContent;
1961
+ bufferedContent = '';
1962
+ lastEmitMs = Date.now();
1963
+ onStreaming({ content: pending, isComplete: false, modelName: model.Name });
1964
+ }
1965
+ }, delay);
1966
+ }
1967
+ },
1778
1968
  };
1779
1969
  }
1970
+ const sentPrefix = this.guardReplayedReasoningPrefix(chatParams, params, model);
1780
1971
  // Execute the model bounded by the composed abort signal (caller cancellation + prompt TimeoutMS)
1781
1972
  //
1782
1973
  // Layer 4 fallback, part one: some providers REJECT a tools payload instead of returning a
@@ -1786,13 +1977,21 @@ export class AIPromptRunner extends BaseModelRunner {
1786
1977
  // for gpt-5.6-luna in /v1/chat/completions`. Both shapes get the same one-shot retry.
1787
1978
  let chatResult;
1788
1979
  try {
1789
- chatResult = await this.runChatCompletionBounded(llm, chatParams, executionBound);
1980
+ try {
1981
+ chatResult = await this.runChatCompletionBounded(llm, chatParams, executionBound);
1982
+ }
1983
+ finally {
1984
+ flushStreamingBuffer?.();
1985
+ }
1790
1986
  }
1791
1987
  catch (error) {
1792
- if (!chatParams.tools?.length || !this.isToolSpecificFailureText(error instanceof Error ? error.message : String(error ?? ''))) {
1988
+ const thrownText = error instanceof Error ? error.message : String(error ?? '');
1989
+ if (!chatParams.tools?.length
1990
+ || !this.isToolEligibleError(ErrorAnalyzer.analyzeError(error, driverClass))
1991
+ || !this.isToolSpecificFailureText(thrownText)) {
1793
1992
  throw error;
1794
1993
  }
1795
- return await this.retryWithToolsStripped(llm, chatParams, executionBound, model, vendorId, prompt, error instanceof Error ? error.message : String(error));
1994
+ return await this.retryWithToolsStripped(llm, chatParams, executionBound, model, vendorId, prompt, error instanceof Error ? error.message : String(error), params, renderedPrompt, firstRenderedPrompt);
1796
1995
  }
1797
1996
  // Carry the gate's WHOLE decision from the request onto the result, which is what flows back up
1798
1997
  // to the prompt run (mode) and to the agent loop (`toolResults` — the loop answers native
@@ -1807,8 +2006,12 @@ export class AIPromptRunner extends BaseModelRunner {
1807
2006
  // TOOLS-specific reason retries the same way. Non-tool failures fall through to the existing
1808
2007
  // retry/failover machinery untouched.
1809
2008
  if (chatParams.tools?.length && this.isToolSpecificFailure(chatResult)) {
1810
- return await this.retryWithToolsStripped(llm, chatParams, executionBound, model, vendorId, prompt, chatResult.errorMessage || chatResult.statusText || 'unspecified');
2009
+ return await this.retryWithToolsStripped(llm, chatParams, executionBound, model, vendorId, prompt, chatResult.errorMessage || chatResult.statusText || 'unspecified', params, renderedPrompt, firstRenderedPrompt);
2010
+ }
2011
+ if (renderedPrompt !== firstRenderedPrompt) {
2012
+ this.recordRerenderedMessages(chatResult, prompt, params, model, vendorId, renderedPrompt);
1811
2013
  }
2014
+ RecordSentPrefixFingerprint(chatResult, sentPrefix);
1812
2015
  return chatResult;
1813
2016
  }
1814
2017
  catch (error) {
@@ -2099,6 +2302,8 @@ export class AIPromptRunner extends BaseModelRunner {
2099
2302
  }
2100
2303
  return messages;
2101
2304
  }
2305
+ /** Classified error types a rejected tools payload never arrives as. */
2306
+ static { this.TOOL_INELIGIBLE_ERROR_TYPES = ['RateLimit', 'Authentication', 'NoCredentials', 'Cancelled', 'ContextLengthExceeded']; }
2102
2307
  /**
2103
2308
  * Substrings that mark a provider failure as TOOLS-specific, so the native call is worth one
2104
2309
  * envelope retry (see {@link AIPromptRunner.isToolSpecificFailure}). Drawn from how the
@@ -2108,16 +2313,33 @@ export class AIPromptRunner extends BaseModelRunner {
2108
2313
  * Substring matching over provider prose is inherently approximate. It is deliberately biased
2109
2314
  * toward MISSING a tool failure rather than catching an unrelated one: a missed match just means
2110
2315
  * the existing retry/failover logic handles the error as it does today, whereas a false positive
2111
- * would silently strip tools from a run that should have kept them.
2316
+ * would silently strip tools from a run that should have kept them. So the markers name the
2317
+ * request's tool fields and the providers' own phrasing — never the bare words "tools" or
2318
+ * "tool call", which appear in errors that have nothing to do with the tools payload — and only
2319
+ * an error classified as a request error is matched at all (see `isToolEligibleError`).
2112
2320
  */
2113
2321
  static { this.TOOL_FAILURE_MARKERS = [
2114
2322
  'tool_use',
2115
2323
  'tool use',
2116
2324
  'tool_call',
2117
- 'tool call',
2325
+ 'tool call validation',
2326
+ 'invalid tool call',
2327
+ 'tool calling',
2328
+ 'tools is not supported',
2329
+ 'tools param',
2330
+ 'param: tools',
2118
2331
  'tool_choice',
2119
2332
  'tool choice',
2120
- 'tools',
2333
+ 'tools:',
2334
+ '"tools"',
2335
+ '`tools`',
2336
+ "'tools'",
2337
+ 'argument supplied: tools',
2338
+ 'tools.',
2339
+ 'tools[',
2340
+ 'function tools',
2341
+ 'support tools',
2342
+ 'tools are not supported',
2121
2343
  'function_call',
2122
2344
  'function call',
2123
2345
  'function_declaration',
@@ -2349,7 +2571,10 @@ export class AIPromptRunner extends BaseModelRunner {
2349
2571
  // Validation failed, check if we should retry
2350
2572
  // BUG FIX: Only retry in Strict mode, not in Warn or None modes
2351
2573
  const effectiveValidationBehavior = params?.validationBehavior || prompt.ValidationBehavior;
2352
- if (effectiveValidationBehavior === 'Strict' && attempt < maxRetries) {
2574
+ // A turn that called tools is answered by its calls; only its narration failed. Retrying
2575
+ // would ask again and throw the calls away, so the turn is kept as it is.
2576
+ const calledTools = (modelResult.data?.choices?.[0]?.message?.toolCalls?.length ?? 0) > 0;
2577
+ if (effectiveValidationBehavior === 'Strict' && attempt < maxRetries && !calledTools) {
2353
2578
  lastError = new Error(`Validation failed: ${validationErrors?.map(e => e.Message).join('; ')}`);
2354
2579
  LogStatus(` ⚠️ Validation failed on attempt ${attempt + 1}, will retry (Strict mode)`);
2355
2580
  continue; // Retry
@@ -2358,7 +2583,7 @@ export class AIPromptRunner extends BaseModelRunner {
2358
2583
  // Either not strict mode or no more retries, return what we have
2359
2584
  const reason = effectiveValidationBehavior !== 'Strict'
2360
2585
  ? `${effectiveValidationBehavior || 'None'} mode - continuing with invalid output (no retry)`
2361
- : 'max retries exceeded';
2586
+ : calledTools ? 'the turn called tools — its calls are kept' : 'max retries exceeded';
2362
2587
  LogStatus(` ⚠️ Validation failed on attempt ${attempt + 1}, stopping retries (${reason})`);
2363
2588
  return {
2364
2589
  modelResult,
@@ -3164,29 +3389,9 @@ export class AIPromptRunner extends BaseModelRunner {
3164
3389
  // (data, templateData) that the run's template-data capture mode allows.
3165
3390
  // Also capture callers that supply conversationMessages directly (e.g. templateMessageRole='none',
3166
3391
  // no rendered system prompt) — otherwise their assembled prompt would never be persisted.
3167
- if (params.data || params.templateData || systemPromptText || (params.conversationMessages?.length ?? 0) > 0) {
3168
- const messages = [];
3169
- if (systemPromptText) {
3170
- // Build the system prompt content, including prefill fallback if applicable
3171
- let systemContent = systemPromptText;
3172
- if (prompt.AssistantPrefill && prompt.PrefillFallbackMode === 'SystemInstruction') {
3173
- const fallbackTemplate = this.resolvePrefillFallbackText(model, vendorId);
3174
- // Function replacement: prefill text is authored content that routinely
3175
- // contains `$` (LaTeX `$$`, currency, JSON fragments), and a string
3176
- // replacement would expand it. See issue #3171.
3177
- const prefill = prompt.AssistantPrefill;
3178
- const fallbackInstruction = fallbackTemplate.replace(/\{\{prefill\}\}/g, () => prefill);
3179
- systemContent += '\n\n' + fallbackInstruction;
3180
- }
3181
- messages.push({
3182
- role: 'system',
3183
- content: systemContent
3184
- });
3185
- }
3186
- // Always include any caller-supplied conversation messages (previously only recorded when a
3187
- // template system prompt was present, which dropped them for the pure-conversationMessages path).
3188
- messages.push(...(params.conversationMessages || []));
3189
- promptRun.Messages = this.buildStoredMessagesJSON(prompt, params, messages);
3392
+ const storedMessages = this.storedMessagesJSON(prompt, params, model, systemPromptText, vendorId);
3393
+ if (storedMessages) {
3394
+ promptRun.Messages = storedMessages;
3190
3395
  }
3191
3396
  // Populate new retry tracking columns with initial values
3192
3397
  promptRun.ValidationBehavior = params.validationBehavior || prompt.ValidationBehavior || 'Warn';
@@ -3204,6 +3409,39 @@ export class AIPromptRunner extends BaseModelRunner {
3204
3409
  }
3205
3410
  return AIPromptRunner.serverTemplateDataCaptureDefault;
3206
3411
  }
3412
+ /**
3413
+ * The prompt run's `Messages`: the messages the model received, plus the template inputs (data,
3414
+ * templateData) the run's template-data capture mode allows. Undefined when there is nothing to
3415
+ * store. Also captures callers that supply conversationMessages directly (templateMessageRole
3416
+ * 'none', no rendered system prompt), whose assembled prompt would otherwise never be persisted.
3417
+ */
3418
+ storedMessagesJSON(prompt, params, model, systemPromptText, vendorId) {
3419
+ if (!(params.data || params.templateData || systemPromptText || (params.conversationMessages?.length ?? 0) > 0)) {
3420
+ return undefined;
3421
+ }
3422
+ const messages = [];
3423
+ if (systemPromptText) {
3424
+ // Build the system prompt content, including prefill fallback if applicable
3425
+ let systemContent = systemPromptText;
3426
+ if (prompt.AssistantPrefill && prompt.PrefillFallbackMode === 'SystemInstruction') {
3427
+ const fallbackTemplate = this.resolvePrefillFallbackText(model, vendorId);
3428
+ // Function replacement: prefill text is authored content that routinely
3429
+ // contains `$` (LaTeX `$$`, currency, JSON fragments), and a string
3430
+ // replacement would expand it. See issue #3171.
3431
+ const prefill = prompt.AssistantPrefill;
3432
+ const fallbackInstruction = fallbackTemplate.replace(/\{\{prefill\}\}/g, () => prefill);
3433
+ systemContent += '\n\n' + fallbackInstruction;
3434
+ }
3435
+ messages.push({
3436
+ role: 'system',
3437
+ content: systemContent
3438
+ });
3439
+ }
3440
+ // Always include any caller-supplied conversation messages (previously only recorded when a
3441
+ // template system prompt was present, which dropped them for the pure-conversationMessages path).
3442
+ messages.push(...(params.conversationMessages || []));
3443
+ return this.buildStoredMessagesJSON(prompt, params, messages);
3444
+ }
3207
3445
  /**
3208
3446
  * Serializes what this run stores in `AIPromptRun.Messages`, applying the template-data capture mode.
3209
3447
  * A capture error never fails the run: it is logged, and the run stores `None` with a fixed note and no template data.
@@ -3272,7 +3510,20 @@ export class AIPromptRunner extends BaseModelRunner {
3272
3510
  async updatePromptRun(promptRun, prompt, modelResult, parsedResult, endTime, executionTimeMS, validationAttempts, cumulativeTokens) {
3273
3511
  // A chat run succeeds only if the model call succeeded AND its output did not fail validation.
3274
3512
  const success = modelResult.success && (parsedResult.validationResult?.Success !== false);
3275
- return this.FinalizeRunRecord(promptRun, success, endTime, executionTimeMS, (run) => this.applyChatResultFields(run, prompt, modelResult, parsedResult, endTime, executionTimeMS, validationAttempts, cumulativeTokens));
3513
+ return this.FinalizeRunRecord(promptRun, success, endTime, executionTimeMS, (run) => {
3514
+ // Layer 4 instrumentation: attribute this run to the path it actually took. Set inside the
3515
+ // finalize callback, like every result field: FinalizeRunRecord re-applies only what it saw
3516
+ // change, after an in-flight INSERT's reload has reverted the record — a value set before it
3517
+ // is lost on any call that returns faster than the INSERT. Left NULL when no model call
3518
+ // happened, which is the honest value.
3519
+ run.ToolCallingMode = GetToolCallingMode(modelResult) ?? null;
3520
+ // The prompt this attempt actually sent, when it was rendered again for its own path.
3521
+ const rerenderedMessages = AIPromptRunner._rerenderedMessages.get(modelResult);
3522
+ if (rerenderedMessages) {
3523
+ run.Messages = rerenderedMessages;
3524
+ }
3525
+ this.applyChatResultFields(run, prompt, modelResult, parsedResult, endTime, executionTimeMS, validationAttempts, cumulativeTokens);
3526
+ });
3276
3527
  }
3277
3528
  /**
3278
3529
  * Populates a prompt-run's chat-specific finalized fields (result, tokens, cost, timing, validation)