@memberjunction/ai-agents 6.2.1 → 6.2.2
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/dist/PayloadManager.d.ts +46 -0
- package/dist/PayloadManager.d.ts.map +1 -1
- package/dist/PayloadManager.js +298 -67
- package/dist/PayloadManager.js.map +1 -1
- package/dist/agent-types/base-agent-type.d.ts.map +1 -1
- package/dist/agent-types/base-agent-type.js +8 -1
- package/dist/agent-types/base-agent-type.js.map +1 -1
- package/dist/base-agent.d.ts +73 -10
- package/dist/base-agent.d.ts.map +1 -1
- package/dist/base-agent.js +197 -34
- package/dist/base-agent.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/native-tools/agent-tool-circuit-breaker.d.ts +44 -0
- package/dist/native-tools/agent-tool-circuit-breaker.d.ts.map +1 -0
- package/dist/native-tools/agent-tool-circuit-breaker.js +71 -0
- package/dist/native-tools/agent-tool-circuit-breaker.js.map +1 -0
- package/dist/native-tools/agent-tools.d.ts +7 -0
- package/dist/native-tools/agent-tools.d.ts.map +1 -1
- package/dist/native-tools/agent-tools.js.map +1 -1
- package/dist/payload-path-keys.d.ts +54 -0
- package/dist/payload-path-keys.d.ts.map +1 -0
- package/dist/payload-path-keys.js +126 -0
- package/dist/payload-path-keys.js.map +1 -0
- package/dist/unsafe-object-keys.d.ts +20 -0
- package/dist/unsafe-object-keys.d.ts.map +1 -0
- package/dist/unsafe-object-keys.js +42 -0
- package/dist/unsafe-object-keys.js.map +1 -0
- package/package.json +20 -20
package/dist/base-agent.js
CHANGED
|
@@ -17,6 +17,7 @@ import { ApplyBoundActionParams, BindingsForAction, IsBoundParamName, UnboundPar
|
|
|
17
17
|
import { BuildNativeToolSet, COMPLETE_TASK_TOOL, SUB_AGENT_TOOL_PREFIX } from './native-tools/control-tools.js';
|
|
18
18
|
import { TurnToolCallingMode } from './native-tools/turn-mode.js';
|
|
19
19
|
import { NATIVE_CONTROL_TEMPLATE_DATA, NATIVE_ONLY_TEMPLATE_FLAG, ResolveNativeControlConfig } from './native-tools/native-control-config.js';
|
|
20
|
+
import { AgentToolCircuitBreaker } from './native-tools/agent-tool-circuit-breaker.js';
|
|
20
21
|
import { BuildFrameworkTools } from './native-tools/framework-tools.js';
|
|
21
22
|
import { BuildAssistantToolCallTurn, BuildToolResultTurn, CompactAnsweredToolCallArguments, CompactToolResultContent, CompactToolResultContentAsync } from './native-tools/tool-result-turns.js';
|
|
22
23
|
import { LooksLikeLoopEnvelope } from './native-tools/dual-channel.js';
|
|
@@ -207,6 +208,13 @@ export class BaseAgent {
|
|
|
207
208
|
* @private
|
|
208
209
|
*/
|
|
209
210
|
this._activeProvider = Metadata.Provider; // global-provider-ok: default until Execute() captures per-request provider
|
|
211
|
+
/**
|
|
212
|
+
* Payload changes sent with completions that were refused, in order. They are held, not
|
|
213
|
+
* committed: the next prompt sees the payload with them applied, and the next completion is
|
|
214
|
+
* built on top of them, so a model only has to send its corrections. They are committed with
|
|
215
|
+
* the next accepted completion, and dropped if the run ends without one.
|
|
216
|
+
*/
|
|
217
|
+
this._heldCompletionChanges = [];
|
|
210
218
|
/**
|
|
211
219
|
* Index in conversationMessages where this agent run began, used to accurately restore
|
|
212
220
|
* turn 1's trailing state message in append-only mode without corrupting prior chat turns.
|
|
@@ -239,6 +247,12 @@ export class BaseAgent {
|
|
|
239
247
|
* @private
|
|
240
248
|
*/
|
|
241
249
|
this._actionFailureHistory = new Map();
|
|
250
|
+
/**
|
|
251
|
+
* The same identical-arguments and attempt-budget rules for agent-local tools
|
|
252
|
+
* ({@link GetAgentTools}), which run outside the action dispatch path.
|
|
253
|
+
* @private
|
|
254
|
+
*/
|
|
255
|
+
this._agentToolBreaker = new AgentToolCircuitBreaker(IDENTICAL_FAILURE_THRESHOLD, ACTION_FAILURE_BUDGET);
|
|
242
256
|
/**
|
|
243
257
|
* This is state information that is specific to the agent type. BaseAgent doesn't know what
|
|
244
258
|
* this contains or care, it is just responsible for keeping this, giving the Agent Type the
|
|
@@ -847,6 +861,7 @@ export class BaseAgent {
|
|
|
847
861
|
this._fatalActionFailures.clear();
|
|
848
862
|
this._audienceLockedActions.clear();
|
|
849
863
|
this._actionFailureHistory.clear();
|
|
864
|
+
this._agentToolBreaker.Reset();
|
|
850
865
|
}
|
|
851
866
|
/**
|
|
852
867
|
* The blocked result for an action locked out for the run — refused for the audience (`'audience'`), or failed
|
|
@@ -2003,6 +2018,7 @@ export class BaseAgent {
|
|
|
2003
2018
|
this._agentConfig = undefined;
|
|
2004
2019
|
this._lastModelSelectionInfo = undefined;
|
|
2005
2020
|
this._lastVolatileStateMessage = undefined;
|
|
2021
|
+
this._heldCompletionChanges = [];
|
|
2006
2022
|
this._resolvedTrailingStateMode = undefined;
|
|
2007
2023
|
this._lastSentFingerprints = undefined;
|
|
2008
2024
|
this._lastSentPrefix = undefined;
|
|
@@ -4945,19 +4961,23 @@ export class BaseAgent {
|
|
|
4945
4961
|
});
|
|
4946
4962
|
// Whatever fails below, the step is finalized and the call answered — never left Running.
|
|
4947
4963
|
let outcome = { payload, content: '', isError: true };
|
|
4964
|
+
const breakerKey = this.agentToolBreakerKey(call);
|
|
4948
4965
|
try {
|
|
4949
|
-
const
|
|
4950
|
-
|
|
4951
|
-
|
|
4952
|
-
|
|
4953
|
-
|
|
4954
|
-
|
|
4955
|
-
|
|
4966
|
+
const refusal = breakerKey === null ? null : this._agentToolBreaker.Check(call.toolName, breakerKey);
|
|
4967
|
+
if (refusal) {
|
|
4968
|
+
this.logStatus(` ⚡ Circuit breaker: agent tool '${call.toolName}' not run (0ms)`, false, params);
|
|
4969
|
+
outcome = { payload, content: refusal, isError: true };
|
|
4970
|
+
}
|
|
4971
|
+
else {
|
|
4972
|
+
outcome = await this.runAndApplyAgentTool(call, payload, params);
|
|
4973
|
+
this.recordAgentToolOutcome(call.toolName, breakerKey, outcome.isError);
|
|
4974
|
+
}
|
|
4956
4975
|
}
|
|
4957
4976
|
catch (error) {
|
|
4958
4977
|
const message = error instanceof Error ? error.message : String(error);
|
|
4959
4978
|
LogError(`Agent '${params.agent?.Name}': applying agent tool '${call.toolName}' failed: ${message}`);
|
|
4960
4979
|
outcome = { payload, content: `The tool's change could not be applied: ${message}. Nothing was changed.`, isError: true };
|
|
4980
|
+
this.recordAgentToolOutcome(call.toolName, breakerKey, true);
|
|
4961
4981
|
}
|
|
4962
4982
|
finally {
|
|
4963
4983
|
step.PayloadAtEnd = this.serializePayloadAtEnd(outcome.payload);
|
|
@@ -4965,6 +4985,44 @@ export class BaseAgent {
|
|
|
4965
4985
|
}
|
|
4966
4986
|
return { payload: outcome.payload, result: { toolCallId: call.toolCallId, toolName: call.toolName, content: outcome.content, isError: outcome.isError } };
|
|
4967
4987
|
}
|
|
4988
|
+
/** Runs one call and applies its payload change; a refused change makes the call an error. */
|
|
4989
|
+
async runAndApplyAgentTool(call, payload, params) {
|
|
4990
|
+
const ran = await this.runAgentTool(call, payload, params);
|
|
4991
|
+
// payload_change_request keeps its single-call behaviour: the allowed parts apply.
|
|
4992
|
+
const partial = this._nativeToolBindings?.get(call.toolName)?.kind === 'payloadChange';
|
|
4993
|
+
const applied = !ran.IsError && ran.PayloadChange
|
|
4994
|
+
? this.applyAgentToolPayloadChange(payload, ran.PayloadChange, params, partial)
|
|
4995
|
+
: { payload, error: undefined };
|
|
4996
|
+
return { payload: applied.payload, content: applied.error ?? ran.Content, isError: ran.IsError || applied.error !== undefined };
|
|
4997
|
+
}
|
|
4998
|
+
/**
|
|
4999
|
+
* The identity of a call's arguments for the agent-tool circuit breaker, or null when the call is
|
|
5000
|
+
* not tracked: it is not an agent tool (`payload_change_request`, an unknown name), the agent type
|
|
5001
|
+
* opted out of the breaker (`UsesActionCircuitBreaker === false`), or the tool did
|
|
5002
|
+
* (`UsesCircuitBreaker === false`). Arguments are normalized like an action's.
|
|
5003
|
+
*/
|
|
5004
|
+
agentToolBreakerKey(call) {
|
|
5005
|
+
const binding = this._nativeToolBindings?.get(call.toolName);
|
|
5006
|
+
if (binding?.kind !== 'agentTool' || binding.definition.UsesCircuitBreaker === false) {
|
|
5007
|
+
return null;
|
|
5008
|
+
}
|
|
5009
|
+
if (this.AgentTypeInstance?.UsesActionCircuitBreaker === false) {
|
|
5010
|
+
return null;
|
|
5011
|
+
}
|
|
5012
|
+
return this.normalizeActionParams(call.arguments);
|
|
5013
|
+
}
|
|
5014
|
+
/** Updates the agent-tool circuit breaker after a call that ran (nothing for an untracked call). */
|
|
5015
|
+
recordAgentToolOutcome(toolName, breakerKey, isError) {
|
|
5016
|
+
if (breakerKey === null) {
|
|
5017
|
+
return;
|
|
5018
|
+
}
|
|
5019
|
+
if (isError) {
|
|
5020
|
+
this._agentToolBreaker.RecordFailure(toolName, breakerKey);
|
|
5021
|
+
}
|
|
5022
|
+
else {
|
|
5023
|
+
this._agentToolBreaker.RecordSuccess(toolName);
|
|
5024
|
+
}
|
|
5025
|
+
}
|
|
4968
5026
|
/** Calls the tool's handler; an undeclared tool or a thrown error becomes an error result. */
|
|
4969
5027
|
async runAgentTool(call, payload, params) {
|
|
4970
5028
|
const binding = this._nativeToolBindings?.get(call.toolName);
|
|
@@ -5345,26 +5403,78 @@ export class BaseAgent {
|
|
|
5345
5403
|
new ScopedPromptConfigResolver();
|
|
5346
5404
|
ApplyScopedPromptConfig(configResolver, scopedConfigPromptId, this.scopedPromptConfigScope(params), promptParams);
|
|
5347
5405
|
}
|
|
5406
|
+
return promptParams;
|
|
5407
|
+
}
|
|
5408
|
+
/**
|
|
5409
|
+
* Completes the prompt params once {@link preparePromptParams} — including any subclass override —
|
|
5410
|
+
* has returned: builds the trailing runtime-state message and checks the outgoing history for replayed
|
|
5411
|
+
* reasoning that no longer matches.
|
|
5412
|
+
*
|
|
5413
|
+
* This runs after the hook, not inside it, because building the trailing message can render the child
|
|
5414
|
+
* prompt (a relocated specialization) and caches that render for the prompt runner. Rendered inside the
|
|
5415
|
+
* hook, it would miss the template data a subclass adds after calling `super.preparePromptParams()`, and
|
|
5416
|
+
* the prompt would be sent without it. The history comes from `promptParams.conversationMessages`, so a
|
|
5417
|
+
* subclass's own changes to the outgoing messages are kept and the trailing message stays last.
|
|
5418
|
+
*/
|
|
5419
|
+
async finalizePromptParams(promptParams, config, payload, params) {
|
|
5348
5420
|
// Prompt-cache layout. The per-iteration state (and, when the child prompt is volatile, the
|
|
5349
5421
|
// specialization) never lives in the system prompt; it rides as the FINAL message of THIS request.
|
|
5350
5422
|
// In append-only mode (OpenAI prompt caching), prior runtime-state fragments are retained in history
|
|
5351
5423
|
// so each turn extends the exact byte prefix of the previous request, maintaining ~93% cache hits.
|
|
5352
5424
|
// In replace-in-place mode (Gemini/Cerebras), only the latest fragment is attached, keeping history lean.
|
|
5353
|
-
const volatileStateMessage = await this.buildVolatileStateMessage(params, promptParams, payload, childPrompt, agentType, systemPrompt);
|
|
5425
|
+
const volatileStateMessage = await this.buildVolatileStateMessage(params, promptParams, payload, config.childPrompt, config.agentType, config.systemPrompt);
|
|
5354
5426
|
if (volatileStateMessage) {
|
|
5355
5427
|
const isAppendOnly = this.shouldUseAppendOnlyTrailingState(promptParams);
|
|
5356
5428
|
this.restoreTurn1VolatileStateIfNeeded(params, isAppendOnly);
|
|
5357
|
-
promptParams.conversationMessages = this.assembleOutgoingMessages(params.conversationMessages, volatileStateMessage, isAppendOnly);
|
|
5429
|
+
promptParams.conversationMessages = this.assembleOutgoingMessages(promptParams.conversationMessages ?? params.conversationMessages, volatileStateMessage, isAppendOnly);
|
|
5358
5430
|
if (isAppendOnly) {
|
|
5359
5431
|
params.conversationMessages.push(volatileStateMessage);
|
|
5360
5432
|
}
|
|
5361
5433
|
this._lastVolatileStateMessage = volatileStateMessage;
|
|
5434
|
+
if (promptParams.data?._SPECIALIZATION_RELOCATED === true) {
|
|
5435
|
+
promptParams.OnTemplateDataFinalized = (finalParams) => this.refreshRelocatedSpecialization(finalParams, config, payload, params, volatileStateMessage);
|
|
5436
|
+
}
|
|
5362
5437
|
}
|
|
5363
5438
|
if (promptParams.conversationMessages) {
|
|
5364
5439
|
promptParams.conversationMessages = this.dropReasoningBehindChangedHistory(params, promptParams.conversationMessages, promptParams);
|
|
5365
5440
|
}
|
|
5366
5441
|
return promptParams;
|
|
5367
5442
|
}
|
|
5443
|
+
/**
|
|
5444
|
+
* Renders the trailing message again once the prompt runner has set the native tool-calling flags,
|
|
5445
|
+
* and swaps it in when the text changed.
|
|
5446
|
+
*
|
|
5447
|
+
* A relocated specialization is pre-rendered here, before a model is selected, so it renders
|
|
5448
|
+
* without the flags the runner sets from the selected model's tool-calling decision — a child
|
|
5449
|
+
* prompt that words its instructions for the native or envelope path would get the envelope
|
|
5450
|
+
* wording while the system prompt gets the native one. The runner calls this through
|
|
5451
|
+
* {@link AIPromptParams.OnTemplateDataFinalized}. On any failure the message already built is kept.
|
|
5452
|
+
*/
|
|
5453
|
+
async refreshRelocatedSpecialization(promptParams, config, payload, params, previous) {
|
|
5454
|
+
try {
|
|
5455
|
+
const rebuilt = await this.buildVolatileStateMessage(params, promptParams, payload, config.childPrompt, config.agentType, config.systemPrompt);
|
|
5456
|
+
if (!rebuilt || rebuilt.content === previous.content) {
|
|
5457
|
+
return;
|
|
5458
|
+
}
|
|
5459
|
+
const replace = (messages) => {
|
|
5460
|
+
const at = messages ? messages.indexOf(previous) : -1;
|
|
5461
|
+
if (messages && at >= 0) {
|
|
5462
|
+
messages[at] = rebuilt;
|
|
5463
|
+
}
|
|
5464
|
+
};
|
|
5465
|
+
replace(promptParams.conversationMessages);
|
|
5466
|
+
replace(params.conversationMessages);
|
|
5467
|
+
this._lastVolatileStateMessage = rebuilt;
|
|
5468
|
+
// The fingerprints were taken before the swap; without this, an append-only history
|
|
5469
|
+
// reads the swapped message as changed next turn and drops the reasoning after it.
|
|
5470
|
+
if (promptParams.conversationMessages) {
|
|
5471
|
+
this._lastSentFingerprints = promptParams.conversationMessages.map(BaseAgent.messageFingerprint);
|
|
5472
|
+
}
|
|
5473
|
+
}
|
|
5474
|
+
catch (error) {
|
|
5475
|
+
this.logStatus(`Kept the trailing message as first built: re-rendering it with the final template data failed (${error instanceof Error ? error.message : String(error)})`, true, params);
|
|
5476
|
+
}
|
|
5477
|
+
}
|
|
5368
5478
|
/**
|
|
5369
5479
|
* Drops replayed reasoning that the history before it no longer matches.
|
|
5370
5480
|
*
|
|
@@ -8306,9 +8416,12 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
8306
8416
|
* @protected
|
|
8307
8417
|
*/
|
|
8308
8418
|
async processNextStep(nextStep, params, agentType, promptResult, currentPayload, currentStep) {
|
|
8419
|
+
// Read before validation: a subclass may change the step in place (turn a Chat into a Success),
|
|
8420
|
+
// and only a change the prompt step held as a completion draft can have been discarded.
|
|
8421
|
+
const heldCompletionChange = BaseAgent.carriesCompletionChange(nextStep) ? nextStep.payloadChangeRequest : undefined;
|
|
8309
8422
|
const validatedNextStep = await this.validateNextStep(params, nextStep, currentPayload, this._agentRun, currentStep);
|
|
8310
8423
|
// Check guardrails if next step would continue execution
|
|
8311
|
-
const guardrailCheckedStep = this.
|
|
8424
|
+
const guardrailCheckedStep = this.noteHeldCompletionChange(heldCompletionChange, await this.checkExecutionGuardrails(params, validatedNextStep, currentPayload, this._agentRun, currentStep));
|
|
8312
8425
|
this.logStatus(`📌 Next step determined: ${guardrailCheckedStep.step}${guardrailCheckedStep.terminate ? ' (terminating)' : ''}`, true, params);
|
|
8313
8426
|
// the model's own call turn goes into history before anything answers it.
|
|
8314
8427
|
this.appendNativeAssistantTurn(params, guardrailCheckedStep);
|
|
@@ -8353,22 +8466,26 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
8353
8466
|
return guardrailCheckedStep;
|
|
8354
8467
|
}
|
|
8355
8468
|
/**
|
|
8356
|
-
* A completion refused with a payload change in hand: the change is
|
|
8357
|
-
*
|
|
8358
|
-
*
|
|
8359
|
-
*
|
|
8360
|
-
* applies it. Any other step is returned as it is.
|
|
8469
|
+
* A completion refused with a payload change in hand: the change is held, not applied (see
|
|
8470
|
+
* {@link _heldCompletionChanges}), so the refusal the model reads says so and asks for the
|
|
8471
|
+
* corrections only. The model sees the payload with the held change applied from the next turn,
|
|
8472
|
+
* and its next completion's change is applied on top of it. The change is removed from the step,
|
|
8473
|
+
* so nothing later applies it a second time. Any other step is returned as it is.
|
|
8474
|
+
*
|
|
8475
|
+
* `heldChange` is the change the prompt step held as a draft, read from the step before
|
|
8476
|
+
* validation, so a step a subclass changed in place is judged by what the model sent.
|
|
8361
8477
|
*/
|
|
8362
|
-
|
|
8363
|
-
if (!
|
|
8478
|
+
noteHeldCompletionChange(heldChange, step) {
|
|
8479
|
+
if (!heldChange || step.step === 'Success') {
|
|
8364
8480
|
return step;
|
|
8365
8481
|
}
|
|
8366
8482
|
const native = !!step.payloadToolCallId && this.nativeToolNameForCall(step, step.payloadToolCallId) === COMPLETE_TASK_TOOL;
|
|
8367
|
-
const
|
|
8368
|
-
|
|
8369
|
-
|
|
8483
|
+
const call = native ? 'complete_task call' : 'completion';
|
|
8484
|
+
const note = `The payloadChangeRequest sent with this ${call} was not applied yet: it is held, and the payload you see `
|
|
8485
|
+
+ `from now on includes it. It is applied together with your next ${call}. In that ${call}, send only the `
|
|
8486
|
+
+ `corrections, not the whole change again.`;
|
|
8370
8487
|
const field = step.retryInstructions ? 'retryInstructions' : step.message ? 'message' : 'errorMessage';
|
|
8371
|
-
const { payloadChangeRequest:
|
|
8488
|
+
const { payloadChangeRequest: _held, ...rest } = step;
|
|
8372
8489
|
return { ...rest, [field]: step[field] ? `${step[field]}\n\n${note}` : note };
|
|
8373
8490
|
}
|
|
8374
8491
|
/**
|
|
@@ -14074,15 +14191,57 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
14074
14191
|
return changeResult;
|
|
14075
14192
|
}
|
|
14076
14193
|
/**
|
|
14077
|
-
* The payload a completion would leave behind: the committed payload with the
|
|
14078
|
-
* change applied. Success validation (the minimum-execution check, then
|
|
14079
|
-
* checks this draft, and it becomes the payload only if the completion is
|
|
14080
|
-
*
|
|
14194
|
+
* The payload a completion would leave behind: the committed payload with the held changes and
|
|
14195
|
+
* then the completion's own change applied. Success validation (the minimum-execution check, then
|
|
14196
|
+
* `FinalPayloadValidation`) checks this draft, and it becomes the payload only if the completion is
|
|
14197
|
+
* accepted. A change identical to a held one is not applied again, so a model that resends its whole
|
|
14198
|
+
* refused change does not duplicate array elements. The opt-in payload change check is not asked
|
|
14199
|
+
* here: it never runs on a step that ends the run.
|
|
14081
14200
|
*/
|
|
14082
14201
|
buildCompletionDraft(params, step, committed, isUnmodifiedInheritedPayload) {
|
|
14083
|
-
const
|
|
14202
|
+
const working = this.withHeldCompletionChanges(params, committed);
|
|
14203
|
+
const change = step.payloadChangeRequest;
|
|
14204
|
+
if (!change || this.isHeldCompletionChange(change)) {
|
|
14205
|
+
return { payload: working, summary: undefined };
|
|
14206
|
+
}
|
|
14207
|
+
const changeResult = this.applyTurnPayloadChange(params, step, working, isUnmodifiedInheritedPayload && this._heldCompletionChanges.length === 0);
|
|
14084
14208
|
return { payload: changeResult.result, summary: this.buildPayloadChangeResultSummary(changeResult) };
|
|
14085
14209
|
}
|
|
14210
|
+
/** `payload` with the held completion changes applied in order; `payload` itself when none are held. */
|
|
14211
|
+
withHeldCompletionChanges(params, payload) {
|
|
14212
|
+
return this._heldCompletionChanges.reduce((current, held) => {
|
|
14213
|
+
const step = { step: 'Success', terminate: false, payloadChangeRequest: held.Change };
|
|
14214
|
+
return this.applyTurnPayloadChange(params, step, current, held.UnmodifiedInheritedPayload).result;
|
|
14215
|
+
}, payload);
|
|
14216
|
+
}
|
|
14217
|
+
/**
|
|
14218
|
+
* After a completion: an accepted one commits the held changes (they were in its draft), so the
|
|
14219
|
+
* list is cleared; a refused one adds its own change to the list, unless the same change is held.
|
|
14220
|
+
*/
|
|
14221
|
+
updateHeldCompletionChanges(step, committedDraft, isUnmodifiedInheritedPayload) {
|
|
14222
|
+
if (committedDraft) {
|
|
14223
|
+
this._heldCompletionChanges = [];
|
|
14224
|
+
return;
|
|
14225
|
+
}
|
|
14226
|
+
const change = BaseAgent.carriesCompletionChange(step) ? step.payloadChangeRequest : undefined;
|
|
14227
|
+
if (change && !this.isHeldCompletionChange(change)) {
|
|
14228
|
+
this._heldCompletionChanges.push({
|
|
14229
|
+
Change: change,
|
|
14230
|
+
UnmodifiedInheritedPayload: isUnmodifiedInheritedPayload && this._heldCompletionChanges.length === 0
|
|
14231
|
+
});
|
|
14232
|
+
}
|
|
14233
|
+
}
|
|
14234
|
+
/** Whether `change` is, key order aside, one of the held completion changes. */
|
|
14235
|
+
isHeldCompletionChange(change) {
|
|
14236
|
+
const key = BaseAgent.stableJSON(change);
|
|
14237
|
+
return this._heldCompletionChanges.some((held) => BaseAgent.stableJSON(held.Change) === key);
|
|
14238
|
+
}
|
|
14239
|
+
/** JSON with object keys sorted, so two equal values serialize the same. */
|
|
14240
|
+
static stableJSON(value) {
|
|
14241
|
+
return JSON.stringify(value, (_key, v) => v && typeof v === 'object' && !Array.isArray(v)
|
|
14242
|
+
? Object.fromEntries(Object.entries(v).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)))
|
|
14243
|
+
: v);
|
|
14244
|
+
}
|
|
14086
14245
|
/**
|
|
14087
14246
|
* The payload a turn leaves behind. A held completion draft is committed only when the step is
|
|
14088
14247
|
* still `Success` after validation; on a refusal the committed payload stands (a subclass that
|
|
@@ -14141,11 +14300,13 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
14141
14300
|
});
|
|
14142
14301
|
// PayloadAtStart was already serialized from this same `payload` by createStepEntity
|
|
14143
14302
|
// above (payloadAtStart: payload) — no need to re-serialize the (potentially large) payload here.
|
|
14144
|
-
|
|
14303
|
+
// The model sees the payload with any held completion changes applied (see _heldCompletionChanges).
|
|
14304
|
+
const workingPayload = this.withHeldCompletionChanges(params, payload);
|
|
14305
|
+
let downstreamPayload = workingPayload; // Start with current payload
|
|
14145
14306
|
if (params.agent.PayloadSelfReadPaths) {
|
|
14146
14307
|
const downstreamPaths = JSON.parse(params.agent.PayloadSelfReadPaths);
|
|
14147
14308
|
// Extract only allowed downstream payload
|
|
14148
|
-
downstreamPayload = this._payloadManager.extractDownstreamPayload(`Self: ${params.agent.Name}`,
|
|
14309
|
+
downstreamPayload = this._payloadManager.extractDownstreamPayload(`Self: ${params.agent.Name}`, workingPayload, // our inbound payload before prompt
|
|
14149
14310
|
downstreamPaths);
|
|
14150
14311
|
}
|
|
14151
14312
|
// now prep the params using the downstream payload - which is often the full
|
|
@@ -14163,7 +14324,7 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
14163
14324
|
this._agentRun.TotalPromptIterations = (this._agentRun.TotalPromptIterations || 0) + 1;
|
|
14164
14325
|
// don't need to save here, the run will be saved later
|
|
14165
14326
|
}
|
|
14166
|
-
const promptParams = await this.preparePromptParams(promptConfig, downstreamPayload, params);
|
|
14327
|
+
const promptParams = await this.finalizePromptParams(await this.preparePromptParams(promptConfig, downstreamPayload, params), promptConfig, downstreamPayload, params);
|
|
14167
14328
|
// Pass cancellation token and streaming callbacks to prompt execution.
|
|
14168
14329
|
// Coalesce rapid token chunks within a ~35ms window while emitting the first chunk immediately
|
|
14169
14330
|
// and flushing synchronously on completion so downstream GraphQL/PubSub/WebSocket callbacks
|
|
@@ -14331,7 +14492,8 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
14331
14492
|
let currentStepPayloadChangeResult = undefined;
|
|
14332
14493
|
// A completion's payload change is held as a draft until Success validation accepts it
|
|
14333
14494
|
// (see buildCompletionDraft); every other step's change is applied now, as it always was.
|
|
14334
|
-
const holdsCompletionChange = BaseAgent.carriesCompletionChange(initialNextStep)
|
|
14495
|
+
const holdsCompletionChange = BaseAgent.carriesCompletionChange(initialNextStep)
|
|
14496
|
+
|| (initialNextStep.step === 'Success' && this._heldCompletionChanges.length > 0);
|
|
14335
14497
|
if (initialNextStep.payloadChangeRequest && !holdsCompletionChange) {
|
|
14336
14498
|
const changeResult = this.applyTurnPayloadChange(params, initialNextStep, payload, isUnmodifiedInheritedPayload);
|
|
14337
14499
|
// Store payload change metadata for audit trail; merged into outputData later
|
|
@@ -14432,8 +14594,9 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
14432
14594
|
// sub-classes may have modified the payload, and we allow that, and so we need to update finalPayload to map to the updatedNextStep.newPayload
|
|
14433
14595
|
const resolved = this.resolveTurnPayload(updatedNextStep, finalPayload, draft);
|
|
14434
14596
|
finalPayload = resolved.payload;
|
|
14435
|
-
const
|
|
14436
|
-
|
|
14597
|
+
const heldCompletionChange = holdsCompletionChange && !resolved.committedDraft;
|
|
14598
|
+
this.updateHeldCompletionChanges(initialNextStep, resolved.committedDraft, finalPayload === params.payload);
|
|
14599
|
+
if (heldCompletionChange && currentStepPayloadChangeResult) {
|
|
14437
14600
|
currentStepPayloadChangeResult = { ...currentStepPayloadChangeResult, applied: { additions: 0, updates: 0, deletions: 0 } };
|
|
14438
14601
|
}
|
|
14439
14602
|
// Prepare output data, these are simple elements of the state that are not typically
|
|
@@ -14450,8 +14613,8 @@ The context is now within limits. Please retry your request with the recovered c
|
|
|
14450
14613
|
payloadChangeResult: currentStepPayloadChangeResult
|
|
14451
14614
|
}),
|
|
14452
14615
|
// A completion's change that was not applied because the completion was refused
|
|
14453
|
-
...(
|
|
14454
|
-
|
|
14616
|
+
...(heldCompletionChange && {
|
|
14617
|
+
payloadChangeHeld: 'The completion was refused, so its payload change is held: it is applied with the next accepted completion, or dropped if the run ends without one.'
|
|
14455
14618
|
}),
|
|
14456
14619
|
// Include scratchpad snapshot after changes for audit/training data
|
|
14457
14620
|
...(this._scratchpadManager.HasContent() && {
|