@memberjunction/task-graph 6.2.0-edge.1 → 6.2.0-edge.3
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/AIDecisionTaskRunner.d.ts +7 -0
- package/dist/AIDecisionTaskRunner.d.ts.map +1 -0
- package/dist/AIDecisionTaskRunner.js +57 -0
- package/dist/AIDecisionTaskRunner.js.map +1 -0
- package/dist/TaskClaimStore.d.ts +4 -3
- package/dist/TaskClaimStore.d.ts.map +1 -1
- package/dist/TaskClaimStore.js +3 -2
- package/dist/TaskClaimStore.js.map +1 -1
- package/dist/TaskGraphDispatcher.d.ts +71 -2
- package/dist/TaskGraphDispatcher.d.ts.map +1 -1
- package/dist/TaskGraphDispatcher.js +279 -30
- package/dist/TaskGraphDispatcher.js.map +1 -1
- package/dist/TaskGraphService.d.ts +56 -3
- package/dist/TaskGraphService.d.ts.map +1 -1
- package/dist/TaskGraphService.js +121 -17
- package/dist/TaskGraphService.js.map +1 -1
- package/dist/condition-gate.d.ts +17 -2
- package/dist/condition-gate.d.ts.map +1 -1
- package/dist/condition-gate.js +25 -1
- package/dist/condition-gate.js.map +1 -1
- package/dist/decision-node.d.ts +150 -0
- package/dist/decision-node.d.ts.map +1 -0
- package/dist/decision-node.js +234 -0
- package/dist/decision-node.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/operations/TaskGraphOperations.d.ts +4 -0
- package/dist/operations/TaskGraphOperations.d.ts.map +1 -1
- package/dist/operations/TaskGraphOperations.js +10 -2
- package/dist/operations/TaskGraphOperations.js.map +1 -1
- package/dist/types.d.ts +44 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +11 -11
|
@@ -18,11 +18,13 @@
|
|
|
18
18
|
*
|
|
19
19
|
* @module @memberjunction/task-graph
|
|
20
20
|
*/
|
|
21
|
-
import { ComputeEligibleTasks, ComputeParentRollup, ComputeTasksToBlock, IsGraphStalled, ResolveExclusiveGroups, ComputeSkipCascade, ConfirmSkipSeeds, LayoutGraphNodes, ApplyOutputMapping, BuildMappedInput, ResolveMappedInput, LoadAgentRunTree, SumAgentRunTreeCost, WalkAgentRunTree, } from '@memberjunction/ai-core-plus';
|
|
21
|
+
import { ComputeEligibleTasks, ComputeParentRollup, ComputeTasksToBlock, IsGraphStalled, ResolveExclusiveGroups, ComputeSkipCascade, ConfirmSkipSeeds, LayoutGraphNodes, ApplyOutputMapping, BuildMappedInput, ResolveMappedInput, LoadAgentRunTree, SumAgentRunTreeCost, WalkAgentRunTree, FinalizeAgentRunStep, InitAgentRunStep, DecisionReferencesIn, ResolveDecisionState, } from '@memberjunction/ai-core-plus';
|
|
22
22
|
import { LogError, LogStatus, RunView } from '@memberjunction/core';
|
|
23
23
|
import { ShutdownRegistry, UUIDsEqual } from '@memberjunction/global';
|
|
24
24
|
import { TaskClaimStore, TERMINAL_PARENT_STATUSES, TERMINAL_PARENT_STATUS_SQL } from './TaskClaimStore.js';
|
|
25
|
-
import { BuildConditionContext, DecideGate, IsBrokenGuard, ParseConditionOutput, } from './condition-gate.js';
|
|
25
|
+
import { BuildConditionContext, DecideGate, EvaluateCondition, IsBrokenGuard, ParseConditionOutput, } from './condition-gate.js';
|
|
26
|
+
import { BuildDecisionStepOutput, DecisionStepOutputAnswers, DecisionsPayloadConflict, FailedDecisionIDs, KeptDecisionAnswers, PassOverFailedDecisionPaths, QuestionsToAsk, ReadsFailedDecision, ReadDecisionStepConfiguration, ResolveGraphDecisions, StillHoldingDecisionOutput, } from './decision-node.js';
|
|
27
|
+
import { AIDecisionTaskRunner } from './AIDecisionTaskRunner.js';
|
|
26
28
|
import { HumanTaskSQL, IsHumanTask } from './task-predicates.js';
|
|
27
29
|
import { IsSettlementExpired, IsSubmittingRunReady, SelectUnsettledGraphIDs, SweepCutoff, UNSETTLED_SWEEP_WINDOW_HOURS, UNSETTLED_STARTUP_WINDOW_HOURS, } from './settlement-rescue.js';
|
|
28
30
|
import { DispatcherConditionEvaluator } from './DispatcherConditionEvaluator.js';
|
|
@@ -219,7 +221,13 @@ export class TaskGraphDispatcher {
|
|
|
219
221
|
* Optional. Absent means this host cannot run prompt nodes; they stay Pending and visible
|
|
220
222
|
* rather than being failed, for the same reason action nodes do.
|
|
221
223
|
*/
|
|
222
|
-
promptRunner
|
|
224
|
+
promptRunner,
|
|
225
|
+
/**
|
|
226
|
+
* Answers Decision nodes. Defaults to {@link AIDecisionTaskRunner}, one `AIDecisionRunner`
|
|
227
|
+
* call per node, so every host that runs the dispatcher can run a Decision; supply one to
|
|
228
|
+
* decide differently, or to test without a model.
|
|
229
|
+
*/
|
|
230
|
+
decisionRunner = new AIDecisionTaskRunner()) {
|
|
223
231
|
this.providerFactory = providerFactory;
|
|
224
232
|
this.agentRunner = agentRunner;
|
|
225
233
|
this.contextUser = contextUser;
|
|
@@ -227,12 +235,22 @@ export class TaskGraphDispatcher {
|
|
|
227
235
|
this.observer = observer;
|
|
228
236
|
this.actionRunner = actionRunner;
|
|
229
237
|
this.promptRunner = promptRunner;
|
|
238
|
+
this.decisionRunner = decisionRunner;
|
|
230
239
|
/**
|
|
231
240
|
* Edges already reported as unevaluable, so the report is once per transition and not once per
|
|
232
241
|
* poll. Per-instance and in-memory by design: a restart re-reports, which is the right amount of
|
|
233
242
|
* noise for a condition that is still broken after a restart.
|
|
234
243
|
*/
|
|
235
244
|
this.reportedUnevaluableConditions = new Set();
|
|
245
|
+
/**
|
|
246
|
+
* Decision run-step logs in flight, by agent run.
|
|
247
|
+
*
|
|
248
|
+
* A logged step takes the run's next step number, which is read and then written, so two
|
|
249
|
+
* Decision steps logging on one run at once would take the same number. Chaining them per run
|
|
250
|
+
* closes that on this instance. Instances do not share it; the column has no unique constraint,
|
|
251
|
+
* so a collision across instances only misorders the run's timeline.
|
|
252
|
+
*/
|
|
253
|
+
this.runStepLogs = new Map();
|
|
236
254
|
/** Resolved once it EXISTS; null while it does not, so a fresh install is not cached blind. */
|
|
237
255
|
this.cachedWorkflowTaskTypeID = null;
|
|
238
256
|
/**
|
|
@@ -1488,23 +1506,29 @@ export class TaskGraphDispatcher {
|
|
|
1488
1506
|
* — recurses without bound while the cap it should be hitting compares against a permanent zero.
|
|
1489
1507
|
*/
|
|
1490
1508
|
async graphContext(provider, task) {
|
|
1509
|
+
const none = { Depth: 0, SubmittingAgentRunID: null, Invocation: {} };
|
|
1491
1510
|
if (!task.ParentID)
|
|
1492
|
-
return
|
|
1511
|
+
return none;
|
|
1493
1512
|
try {
|
|
1494
1513
|
const parent = await provider.GetEntityObject('MJ: Tasks', this.contextUser);
|
|
1495
|
-
if (!(await parent.Load(task.ParentID)))
|
|
1496
|
-
|
|
1514
|
+
if (!(await parent.Load(task.ParentID))) {
|
|
1515
|
+
LogError(`[TaskGraphDispatcher] Task ${task.ID}: parent ${task.ParentID} could not be loaded; running at depth 0 with no invocation data/context.`);
|
|
1516
|
+
return none;
|
|
1517
|
+
}
|
|
1518
|
+
const meta = ParseTaskGraphParentMetadata(parent.InputPayload);
|
|
1497
1519
|
return {
|
|
1498
|
-
Depth:
|
|
1499
|
-
// The graph's own row carries the run that submitted it
|
|
1500
|
-
//
|
|
1520
|
+
Depth: meta.reinvokeDepth + 1,
|
|
1521
|
+
// The graph's own row carries the run that submitted it and the invocation it was
|
|
1522
|
+
// submitted with. One load answers all three, which is why they are resolved together.
|
|
1501
1523
|
SubmittingAgentRunID: parent.AgentRunID,
|
|
1524
|
+
Invocation: { data: meta.invocation?.data, context: meta.invocation?.context },
|
|
1502
1525
|
};
|
|
1503
1526
|
}
|
|
1504
|
-
catch {
|
|
1527
|
+
catch (e) {
|
|
1505
1528
|
// An unreadable parent must not stop the work; depth zero is the safe reading, and the
|
|
1506
|
-
// submit-time cap still guards the next hop.
|
|
1507
|
-
|
|
1529
|
+
// submit-time cap still guards the next hop. Logged, because it also blanks `data.*`.
|
|
1530
|
+
LogError(`[TaskGraphDispatcher] Task ${task.ID}: reading parent ${task.ParentID} failed; running at depth 0 with no invocation data/context: ${e instanceof Error ? e.message : String(e)}`);
|
|
1531
|
+
return none;
|
|
1508
1532
|
}
|
|
1509
1533
|
}
|
|
1510
1534
|
/**
|
|
@@ -2050,7 +2074,12 @@ export class TaskGraphDispatcher {
|
|
|
2050
2074
|
// they cleared. Without a notification here a workflow simply stops, waiting on
|
|
2051
2075
|
// someone who was never told. That silent stall is the failure mode this exists to
|
|
2052
2076
|
// prevent, so it happens on the eligibility check rather than at submission.
|
|
2053
|
-
if (entity.
|
|
2077
|
+
if (entity.StepType === 'Decision') {
|
|
2078
|
+
// Tested before the key columns: a Decision carries its decision prompt in
|
|
2079
|
+
// PromptID, but it runs on the decision runner, which every dispatcher has — so
|
|
2080
|
+
// a host with no PROMPT runner must not leave it Pending.
|
|
2081
|
+
}
|
|
2082
|
+
else if (entity.ActionID) {
|
|
2054
2083
|
// An action node this host has no runner for is left Pending rather than
|
|
2055
2084
|
// claimed. Claiming it would take ownership of work this process cannot do, and
|
|
2056
2085
|
// the claim would then have to expire before any host that CAN do it gets a
|
|
@@ -2131,6 +2160,9 @@ export class TaskGraphDispatcher {
|
|
|
2131
2160
|
canActOn(entity) {
|
|
2132
2161
|
if (this.inFlight.has(entity.ID))
|
|
2133
2162
|
return false;
|
|
2163
|
+
// Before the PromptID test, for the reason given in `findClaimableTasks`.
|
|
2164
|
+
if (entity.StepType === 'Decision')
|
|
2165
|
+
return true;
|
|
2134
2166
|
if (entity.ActionID)
|
|
2135
2167
|
return !!this.actionRunner;
|
|
2136
2168
|
if (entity.PromptID)
|
|
@@ -2527,6 +2559,10 @@ export class TaskGraphDispatcher {
|
|
|
2527
2559
|
Data: parentMeta.invocation?.data,
|
|
2528
2560
|
Context: parentMeta.invocation?.context,
|
|
2529
2561
|
};
|
|
2562
|
+
// The graph's Decision answers, read ONCE from the Decision steps' own rows. Every condition
|
|
2563
|
+
// this pass evaluates sees the same answers, and one reading an answer that is not settled
|
|
2564
|
+
// holds instead of reading false (plan 4.5).
|
|
2565
|
+
const decisions = ResolveGraphDecisions(children);
|
|
2530
2566
|
// Conditional edges are resolved HERE, before eligibility runs, by dropping edges whose
|
|
2531
2567
|
// condition does not hold. Expressing it as edge removal rather than as a second rule inside
|
|
2532
2568
|
// the eligibility algorithm is what keeps one definition of "ready": a task with no live
|
|
@@ -2557,7 +2593,16 @@ export class TaskGraphDispatcher {
|
|
|
2557
2593
|
const decidingStatuses = failureSemantics === 'edges'
|
|
2558
2594
|
? new Set(['Complete', 'Failed'])
|
|
2559
2595
|
: new Set(['Complete']);
|
|
2560
|
-
|
|
2596
|
+
// A path reading a decision whose call FAILED is passed over when another path of its fork
|
|
2597
|
+
// is satisfied: that path is the author's recovery route, taken whatever its rank, exactly
|
|
2598
|
+
// as the in-run walker takes it. With no such path the fork still holds, so a Retry of the
|
|
2599
|
+
// failed Decision step can route it.
|
|
2600
|
+
const failedDecisions = FailedDecisionIDs(children);
|
|
2601
|
+
const conditionByEdge = new Map(exclusive.map((d) => [d.ID, d.Condition ?? '']));
|
|
2602
|
+
// Why each exclusive edge that cannot be evaluated is held, by edge — reported below, once the
|
|
2603
|
+
// resolution says whether its fork is actually held.
|
|
2604
|
+
const exclusiveHoldReasons = new Map();
|
|
2605
|
+
const resolution = ResolveExclusiveGroups(PassOverFailedDecisionPaths(exclusive.map((d) => ({
|
|
2561
2606
|
id: d.ID,
|
|
2562
2607
|
taskId: d.TaskID,
|
|
2563
2608
|
dependsOnTaskId: d.DependsOnTaskID,
|
|
@@ -2565,8 +2610,8 @@ export class TaskGraphDispatcher {
|
|
|
2565
2610
|
originStatus: (entityById.get(d.DependsOnTaskID)?.Status ?? 'Pending'),
|
|
2566
2611
|
priority: d.Priority ?? 0,
|
|
2567
2612
|
sequence: d.Sequence ?? 0,
|
|
2568
|
-
conditionOutcome: this.evaluateExclusiveCondition(d, entityById, invocation, debug),
|
|
2569
|
-
})),
|
|
2613
|
+
conditionOutcome: this.evaluateExclusiveCondition(d, entityById, invocation, decisions, debug, exclusiveHoldReasons),
|
|
2614
|
+
})), (edge) => ReadsFailedDecision(conditionByEdge.get(edge.id) ?? '', failedDecisions)),
|
|
2570
2615
|
// WHICH STATUSES MAY DECIDE — the graph's own failure dialect, not a constant.
|
|
2571
2616
|
//
|
|
2572
2617
|
// Under `'edges'`, a flow's failure handling IS its outgoing edges, so a Failed origin
|
|
@@ -2591,7 +2636,7 @@ export class TaskGraphDispatcher {
|
|
|
2591
2636
|
const gateDecisions = [];
|
|
2592
2637
|
for (const d of ordinary) {
|
|
2593
2638
|
if (d.Condition?.trim()) {
|
|
2594
|
-
const decision = this.evaluateEdgeCondition(d, entityById, failureSemantics, invocation, debug);
|
|
2639
|
+
const decision = this.evaluateEdgeCondition(d, entityById, failureSemantics, invocation, decisions, debug);
|
|
2595
2640
|
if (decision.decided) {
|
|
2596
2641
|
gateDecisions.push({
|
|
2597
2642
|
edge: d,
|
|
@@ -2656,13 +2701,19 @@ export class TaskGraphDispatcher {
|
|
|
2656
2701
|
const originStatus = entityById.get(d.DependsOnTaskID)?.Status ?? 'Pending';
|
|
2657
2702
|
if (!decidingStatuses.has(originStatus) && !OverrideVerdictFor(debug ?? {}, d.ID))
|
|
2658
2703
|
continue;
|
|
2704
|
+
const held = !loserEdgeIDs.has(d.ID) && exclusiveHolds.has(d.TaskID);
|
|
2705
|
+
// The edge that holds its fork says why — below its confidence, from a failed call — and
|
|
2706
|
+
// is logged once, as an ordinary edge is. Its siblings hold only because it does.
|
|
2707
|
+
const holdReason = held ? exclusiveHoldReasons.get(d.ID) : undefined;
|
|
2708
|
+
if (holdReason)
|
|
2709
|
+
this.logUnevaluableConditionOnce(d, holdReason);
|
|
2659
2710
|
gateDecisions.push({
|
|
2660
2711
|
edge: d,
|
|
2661
2712
|
verdict: loserEdgeIDs.has(d.ID)
|
|
2662
2713
|
? 'notTaken'
|
|
2663
|
-
:
|
|
2664
|
-
reason:
|
|
2665
|
-
? 'this fork is undecided — a path in its group cannot be answered yet'
|
|
2714
|
+
: held ? 'held' : 'satisfied',
|
|
2715
|
+
reason: held
|
|
2716
|
+
? holdReason ?? 'this fork is undecided — a path in its group cannot be answered yet'
|
|
2666
2717
|
: undefined,
|
|
2667
2718
|
});
|
|
2668
2719
|
}
|
|
@@ -2722,10 +2773,15 @@ export class TaskGraphDispatcher {
|
|
|
2722
2773
|
if (this.reportedUnevaluableConditions.has(key))
|
|
2723
2774
|
return;
|
|
2724
2775
|
this.reportedUnevaluableConditions.add(key);
|
|
2776
|
+
// A hold on a decision has a way out that a broken condition does not: ask again.
|
|
2777
|
+
const readsDecision = DecisionReferencesIn(dep.Condition ?? '').References.length > 0;
|
|
2725
2778
|
LogError(`[TaskGraphDispatcher] Dependency ${dep.ID} has an unevaluable condition ` +
|
|
2726
2779
|
`(${errorMessage}); condition text: ${JSON.stringify(dep.Condition)}. ` +
|
|
2727
2780
|
`Task ${dep.TaskID} is HELD — it will not run and will not be skipped until the ` +
|
|
2728
|
-
`condition can be evaluated. The graph reports as stalled while this holds.`
|
|
2781
|
+
`condition can be evaluated. The graph reports as stalled while this holds.` +
|
|
2782
|
+
(readsDecision
|
|
2783
|
+
? ' Retrying the Decision step it reads asks the questions it is holding again; an edge override answers the condition by hand.'
|
|
2784
|
+
: ''));
|
|
2729
2785
|
}
|
|
2730
2786
|
/**
|
|
2731
2787
|
* Decides whether a conditional dependency edge is live.
|
|
@@ -2734,7 +2790,7 @@ export class TaskGraphDispatcher {
|
|
|
2734
2790
|
* only information a runtime graph has to branch on. Returns `'drop'` only on a definite false;
|
|
2735
2791
|
* an unevaluable condition keeps the edge for the reason stated at the call site.
|
|
2736
2792
|
*/
|
|
2737
|
-
evaluateEdgeCondition(dep, entityById, failureSemantics, invocation, debug) {
|
|
2793
|
+
evaluateEdgeCondition(dep, entityById, failureSemantics, invocation, decisions, debug) {
|
|
2738
2794
|
// An operator's override answers the edge BEFORE the condition is consulted — an override
|
|
2739
2795
|
// exists precisely because the condition cannot be answered (or answered wrongly), so
|
|
2740
2796
|
// evaluating first would re-produce the hold the override exists to end.
|
|
@@ -2760,7 +2816,9 @@ export class TaskGraphDispatcher {
|
|
|
2760
2816
|
let evaluated = false;
|
|
2761
2817
|
const outcome = DecideGate(upstream.Status, failureSemantics, () => {
|
|
2762
2818
|
evaluated = true;
|
|
2763
|
-
|
|
2819
|
+
// A condition reading an unsettled decision is held here, before evaluation could read
|
|
2820
|
+
// its absence as a confident false.
|
|
2821
|
+
const result = EvaluateCondition(dep.Condition, BuildConditionContext(upstream, ParseConditionOutput(upstream.OutputPayload), invocation, decisions.Answers), decisions, (condition, context) => this.conditionEvaluator.Evaluate(condition, context));
|
|
2764
2822
|
if (!result.Success)
|
|
2765
2823
|
unevaluableError = result.ErrorMessage;
|
|
2766
2824
|
return result;
|
|
@@ -2791,7 +2849,7 @@ export class TaskGraphDispatcher {
|
|
|
2791
2849
|
* the branch, the second holds the whole group. The generic keep/drop path cannot express that
|
|
2792
2850
|
* difference, which is why exclusive edges take this route instead.
|
|
2793
2851
|
*/
|
|
2794
|
-
evaluateExclusiveCondition(dep, entityById, invocation, debug) {
|
|
2852
|
+
evaluateExclusiveCondition(dep, entityById, invocation, decisions, debug, holdReasons) {
|
|
2795
2853
|
// Same override-first rule as ordinary edges — see evaluateEdgeCondition.
|
|
2796
2854
|
const override = OverrideVerdictFor(debug ?? {}, dep.ID);
|
|
2797
2855
|
if (override)
|
|
@@ -2801,18 +2859,26 @@ export class TaskGraphDispatcher {
|
|
|
2801
2859
|
const upstream = entityById.get(dep.DependsOnTaskID);
|
|
2802
2860
|
if (!upstream)
|
|
2803
2861
|
return 'unevaluable';
|
|
2804
|
-
const result =
|
|
2862
|
+
const result = EvaluateCondition(dep.Condition,
|
|
2805
2863
|
// The invocation envelope rides the EXCLUSIVE dialect too. R3-3 threaded it into the
|
|
2806
2864
|
// ordinary path; a flow's XOR branch reading `data.userApproval` is the same documented
|
|
2807
2865
|
// condition on a different edge kind, and `BuildConditionContext`'s defaulted parameter
|
|
2808
2866
|
// made omitting it here silently evaluate those roots against nothing.
|
|
2809
|
-
BuildConditionContext(upstream, ParseConditionOutput(upstream.OutputPayload), invocation));
|
|
2867
|
+
BuildConditionContext(upstream, ParseConditionOutput(upstream.OutputPayload), invocation, decisions.Answers), decisions, (condition, context) => this.conditionEvaluator.Evaluate(condition, context));
|
|
2868
|
+
// A fork on a judgment that is not settled — below its confidence, or from a failed call —
|
|
2869
|
+
// holds the whole group rather than guessing a branch (plan 4.5). The reason is kept for the
|
|
2870
|
+
// caller to report, as an ordinary edge's is.
|
|
2871
|
+
const unevaluable = result.Unevaluable || (!result.Success && IsBrokenGuard(result.ErrorMessage));
|
|
2872
|
+
if (unevaluable && result.ErrorMessage)
|
|
2873
|
+
holdReasons?.set(dep.ID, result.ErrorMessage);
|
|
2874
|
+
if (unevaluable)
|
|
2875
|
+
return 'unevaluable';
|
|
2810
2876
|
// SAME CLASSIFICATION AS THE ORDINARY DIALECT (R2-3). The null-safe envelope already makes
|
|
2811
2877
|
// one level of absence read as false here, but a deeper absent chain still throws — and
|
|
2812
2878
|
// calling that 'unevaluable' would hold the whole group forever on a terminal origin, while
|
|
2813
2879
|
// `DecideGate` would have dropped the identical condition. Two dialects, one question.
|
|
2814
2880
|
if (!result.Success)
|
|
2815
|
-
return
|
|
2881
|
+
return 'unsatisfied';
|
|
2816
2882
|
return result.Value ? 'satisfied' : 'unsatisfied';
|
|
2817
2883
|
}
|
|
2818
2884
|
/**
|
|
@@ -2912,7 +2978,17 @@ export class TaskGraphDispatcher {
|
|
|
2912
2978
|
if (task.StepType === 'ForEach' || task.StepType === 'While') {
|
|
2913
2979
|
return { ...await this.runLoopTask(task, provider, payload, dependencyOutputs), PayloadAtStart: payload };
|
|
2914
2980
|
}
|
|
2915
|
-
|
|
2981
|
+
// Routed on StepType before the mappings below: a Decision reads its state from the merged
|
|
2982
|
+
// payload by path and writes its answers back under `decisions`, so it has no mapping of its
|
|
2983
|
+
// own. And it carries a PromptID, so the Prompt branch would otherwise take it.
|
|
2984
|
+
if (task.StepType === 'Decision') {
|
|
2985
|
+
return { ...await this.runDecisionNode(task, provider, payload, onProgress), PayloadAtStart: payload };
|
|
2986
|
+
}
|
|
2987
|
+
// `data.*` / `context.*` resolve against the invocation that submitted the graph, exactly as
|
|
2988
|
+
// the in-run walker resolves them and as branch conditions already see them (R3-3). Without
|
|
2989
|
+
// it a mapping like `RecordID: data.ID` reached the action as the literal "data.ID".
|
|
2990
|
+
const invocation = config?.inputMapping ? (await this.graphContext(provider, task)).Invocation : {};
|
|
2991
|
+
const { params, errors } = BuildMappedInput(config?.inputMapping, { payload, ...invocation });
|
|
2916
2992
|
for (const e of errors)
|
|
2917
2993
|
LogError(`[TaskGraphDispatcher] Task ${task.ID}: ${e}`);
|
|
2918
2994
|
// `payload`, NOT `inputPayload` — the MERGED value computed above, which includes what every
|
|
@@ -3036,7 +3112,7 @@ export class TaskGraphDispatcher {
|
|
|
3036
3112
|
// Bindings go INTO the payload rather than beside it, so an authored mapping reaches the
|
|
3037
3113
|
// current item the same way it reaches anything else: `payload.<itemVariable>`.
|
|
3038
3114
|
const iterationPayload = { ...livePayload, ...Bindings };
|
|
3039
|
-
const resolved = ResolveMappedInput(bodyMapping, { payload: iterationPayload });
|
|
3115
|
+
const resolved = ResolveMappedInput(bodyMapping, { payload: iterationPayload, ...graphContext.Invocation });
|
|
3040
3116
|
/**
|
|
3041
3117
|
* Folds an iteration's output into the running payload the next pass will see, and
|
|
3042
3118
|
* records what the pass produced.
|
|
@@ -3259,6 +3335,175 @@ export class TaskGraphDispatcher {
|
|
|
3259
3335
|
OnProgress: onProgress,
|
|
3260
3336
|
});
|
|
3261
3337
|
}
|
|
3338
|
+
/**
|
|
3339
|
+
* Runs a Decision step: ONE call that answers every question the node asks, about one state.
|
|
3340
|
+
*
|
|
3341
|
+
* The answers land in the step's output under `decisions.<tempId>`, where later steps can read
|
|
3342
|
+
* them, and the edges that route on them read the same answers from this row (see
|
|
3343
|
+
* `ResolveGraphDecisions`). A call that fails writes no answers and fails the step: under
|
|
3344
|
+
* `'block'` its dependents block, and under `'edges'` every condition that reads it holds. It
|
|
3345
|
+
* never reads as `false`.
|
|
3346
|
+
*
|
|
3347
|
+
* **A retry asks only what the step is holding.** A step retried from `Complete` keeps the usable
|
|
3348
|
+
* answers it already gave (`KeptDecisionAnswers`), because the graph has already acted on them,
|
|
3349
|
+
* and the call asks only the rest. If that call fails, or cannot be made, the step stays
|
|
3350
|
+
* `Complete` with the same usable answers, and the questions it asked again hold with the reason.
|
|
3351
|
+
*/
|
|
3352
|
+
async runDecisionNode(task, provider, payload, onProgress) {
|
|
3353
|
+
const config = ReadDecisionStepConfiguration(task.Configuration);
|
|
3354
|
+
if (!config)
|
|
3355
|
+
return this.decisionNotAsked(task, payload, 'it has no decision settings, so there is nothing to ask');
|
|
3356
|
+
const kept = KeptDecisionAnswers(task);
|
|
3357
|
+
const toAsk = QuestionsToAsk(config.questions, kept);
|
|
3358
|
+
const notAsked = (reason) => this.decisionNotAsked(task, payload, reason, { config, kept });
|
|
3359
|
+
if (!task.PromptID)
|
|
3360
|
+
return notAsked('it has no decision prompt to run on');
|
|
3361
|
+
const state = ResolveDecisionState(config.state, payload);
|
|
3362
|
+
if ('ErrorMessage' in state)
|
|
3363
|
+
return notAsked(state.ErrorMessage);
|
|
3364
|
+
// Checked before the call, not after: a step that cannot write its answers without destroying
|
|
3365
|
+
// data should not pay for the answers first.
|
|
3366
|
+
const conflict = DecisionsPayloadConflict(payload);
|
|
3367
|
+
if (conflict)
|
|
3368
|
+
return notAsked(conflict);
|
|
3369
|
+
const startedAt = new Date();
|
|
3370
|
+
const result = await this.decisionRunner.RunDecisionForTask({
|
|
3371
|
+
TaskID: task.ID,
|
|
3372
|
+
PromptID: task.PromptID,
|
|
3373
|
+
State: state.State,
|
|
3374
|
+
Questions: toAsk,
|
|
3375
|
+
Provider: provider,
|
|
3376
|
+
ContextUser: this.contextUser,
|
|
3377
|
+
OnProgress: onProgress,
|
|
3378
|
+
});
|
|
3379
|
+
await this.logDecisionStep(provider, task, config, toAsk, state.State, result, startedAt);
|
|
3380
|
+
if (!result.Success || !result.Answers) {
|
|
3381
|
+
const message = result.ErrorMessage || `Decision "${task.Name}" returned no answers.`;
|
|
3382
|
+
if (Object.keys(kept).length > 0)
|
|
3383
|
+
return this.decisionStillHolding(task, config, kept, message, result.PromptRunID);
|
|
3384
|
+
return {
|
|
3385
|
+
Success: false,
|
|
3386
|
+
AgentRunID: null,
|
|
3387
|
+
ErrorMessage: message,
|
|
3388
|
+
// The payload passes through WITHOUT answers, so nothing downstream can mistake a
|
|
3389
|
+
// failed decision for one that answered.
|
|
3390
|
+
Output: payload,
|
|
3391
|
+
// A failed call can still have cost tokens; the rollup reaches it through this.
|
|
3392
|
+
PromptRunID: result.PromptRunID,
|
|
3393
|
+
};
|
|
3394
|
+
}
|
|
3395
|
+
// A kept answer is never replaced, whatever the call returned for its question.
|
|
3396
|
+
const answers = { ...result.Answers, ...kept };
|
|
3397
|
+
return {
|
|
3398
|
+
Success: true,
|
|
3399
|
+
AgentRunID: null,
|
|
3400
|
+
// Only the answers a condition may act on; each other one is replaced by why it is held.
|
|
3401
|
+
Output: BuildDecisionStepOutput(payload, config.nodeId, DecisionStepOutputAnswers(task.Name, config.questions, answers)),
|
|
3402
|
+
PromptRunID: result.PromptRunID,
|
|
3403
|
+
};
|
|
3404
|
+
}
|
|
3405
|
+
/**
|
|
3406
|
+
* A Decision step that could not be asked — failed with the reason, its input passed through.
|
|
3407
|
+
* A retried step with answers to keep stays `Complete` and holds instead (see `runDecisionNode`).
|
|
3408
|
+
*/
|
|
3409
|
+
decisionNotAsked(task, payload, reason, retry) {
|
|
3410
|
+
if (retry && Object.keys(retry.kept).length > 0)
|
|
3411
|
+
return this.decisionStillHolding(task, retry.config, retry.kept, reason);
|
|
3412
|
+
return { Success: false, AgentRunID: null, ErrorMessage: `Decision "${task.Name}" was not asked: ${reason}.`, Output: payload };
|
|
3413
|
+
}
|
|
3414
|
+
/**
|
|
3415
|
+
* A retried Decision step that could not answer again. It keeps its usable answers and stays
|
|
3416
|
+
* `Complete`, and each question it asked again holds with `reason`, so it can be retried again.
|
|
3417
|
+
*/
|
|
3418
|
+
decisionStillHolding(task, config, kept, reason, promptRunID) {
|
|
3419
|
+
LogError(`[TaskGraphDispatcher] Decision "${task.Name}" (${task.ID}) was retried and could not answer again: ${reason}. ` +
|
|
3420
|
+
'It keeps the answers it already gave and still holds the rest; retry it again.');
|
|
3421
|
+
return {
|
|
3422
|
+
Success: true,
|
|
3423
|
+
AgentRunID: null,
|
|
3424
|
+
Output: StillHoldingDecisionOutput(task.OutputPayload, task.Name, config.nodeId, config.questions, kept, reason),
|
|
3425
|
+
PromptRunID: promptRunID,
|
|
3426
|
+
};
|
|
3427
|
+
}
|
|
3428
|
+
/**
|
|
3429
|
+
* Records a Decision step's call on the agent run that submitted the graph, as an
|
|
3430
|
+
* `AIAgentRunStep` with `StepType 'Decision'`.
|
|
3431
|
+
*
|
|
3432
|
+
* **`'Decision'` means exactly one typed decision call**: a fixed set of Likelihood, Choice or
|
|
3433
|
+
* Score questions answered about one state. `TargetID` is the decision prompt, `TargetLogID` the
|
|
3434
|
+
* call's `MJ: AI Prompt Runs` row, `InputData` the state and the questions asked, and
|
|
3435
|
+
* `OutputData` the answers. Some older writers use the value loosely for bookkeeping; this is the
|
|
3436
|
+
* meaning new code writes (see `TaskGraphNodeConfigMap['Decision']`). A retry asks only the
|
|
3437
|
+
* questions the step was holding, so its step lists only those.
|
|
3438
|
+
*
|
|
3439
|
+
* A graph no run submitted — a schedule, MCP, a person — has no run to log on; the call is still
|
|
3440
|
+
* recorded in its prompt run, which the task points at. Observability only: a failure to log is
|
|
3441
|
+
* reported, and the decision stands.
|
|
3442
|
+
*/
|
|
3443
|
+
async logDecisionStep(provider, task, config, asked, state, result, startedAt) {
|
|
3444
|
+
try {
|
|
3445
|
+
const { SubmittingAgentRunID: agentRunID } = await this.graphContext(provider, task);
|
|
3446
|
+
if (!agentRunID)
|
|
3447
|
+
return;
|
|
3448
|
+
// The number is read and the step saved as one unit per run, so two Decision steps
|
|
3449
|
+
// logging on the same run cannot take the same number.
|
|
3450
|
+
await this.oneRunStepLogAtATime(agentRunID, async () => {
|
|
3451
|
+
const step = await provider.GetEntityObject('MJ: AI Agent Run Steps', this.contextUser);
|
|
3452
|
+
step.NewRecord();
|
|
3453
|
+
InitAgentRunStep(step, {
|
|
3454
|
+
AgentRunID: agentRunID,
|
|
3455
|
+
StepNumber: await this.nextRunStepNumber(provider, agentRunID),
|
|
3456
|
+
StepType: 'Decision',
|
|
3457
|
+
StepName: `Decision: ${task.Name}`,
|
|
3458
|
+
TargetID: task.PromptID,
|
|
3459
|
+
InputData: JSON.stringify({ taskID: task.ID, decision: config.nodeId, state, questions: asked }),
|
|
3460
|
+
});
|
|
3461
|
+
step.StartedAt = startedAt;
|
|
3462
|
+
FinalizeAgentRunStep(step, {
|
|
3463
|
+
success: result.Success,
|
|
3464
|
+
errorMessage: result.ErrorMessage,
|
|
3465
|
+
targetLogID: result.PromptRunID,
|
|
3466
|
+
outputData: { answers: result.Answers ?? {} },
|
|
3467
|
+
});
|
|
3468
|
+
if (!(await step.Save())) {
|
|
3469
|
+
LogError(`[TaskGraphDispatcher] Could not log the Decision step for task ${task.ID}: ${step.LatestResult?.CompleteMessage ?? 'unknown error'}`);
|
|
3470
|
+
}
|
|
3471
|
+
});
|
|
3472
|
+
}
|
|
3473
|
+
catch (e) {
|
|
3474
|
+
LogError(`[TaskGraphDispatcher] Could not log the Decision step for task ${task.ID}: ${e instanceof Error ? e.message : String(e)}`);
|
|
3475
|
+
}
|
|
3476
|
+
}
|
|
3477
|
+
/**
|
|
3478
|
+
* Runs `write` after every earlier run-step log for the same agent run has finished, on this
|
|
3479
|
+
* instance. A failed write does not hold up the next one; its error still reaches the caller.
|
|
3480
|
+
*/
|
|
3481
|
+
async oneRunStepLogAtATime(agentRunID, write) {
|
|
3482
|
+
const key = agentRunID.toLowerCase();
|
|
3483
|
+
const current = (this.runStepLogs.get(key) ?? Promise.resolve()).then(write);
|
|
3484
|
+
const settled = current.catch(() => undefined);
|
|
3485
|
+
this.runStepLogs.set(key, settled);
|
|
3486
|
+
try {
|
|
3487
|
+
await current;
|
|
3488
|
+
}
|
|
3489
|
+
finally {
|
|
3490
|
+
if (this.runStepLogs.get(key) === settled)
|
|
3491
|
+
this.runStepLogs.delete(key);
|
|
3492
|
+
}
|
|
3493
|
+
}
|
|
3494
|
+
/** One past a run's highest step number, so a step logged from here sorts after the run's own. */
|
|
3495
|
+
async nextRunStepNumber(provider, agentRunID) {
|
|
3496
|
+
const result = await RunView.FromMetadataProvider(provider).RunView({
|
|
3497
|
+
EntityName: 'MJ: AI Agent Run Steps',
|
|
3498
|
+
ExtraFilter: `AgentRunID='${agentRunID}'`,
|
|
3499
|
+
Fields: ['StepNumber'],
|
|
3500
|
+
OrderBy: 'StepNumber DESC',
|
|
3501
|
+
MaxRows: 1,
|
|
3502
|
+
ResultType: 'simple',
|
|
3503
|
+
BypassCache: true,
|
|
3504
|
+
}, this.contextUser);
|
|
3505
|
+
return (result.Success ? result.Results?.[0]?.StepNumber ?? 0 : 0) + 1;
|
|
3506
|
+
}
|
|
3262
3507
|
/**
|
|
3263
3508
|
* Leaves exactly one open request standing for a task, withdrawing any others.
|
|
3264
3509
|
*
|
|
@@ -3379,8 +3624,12 @@ export class TaskGraphDispatcher {
|
|
|
3379
3624
|
const parent = await provider.GetEntityObject('MJ: Tasks', this.contextUser);
|
|
3380
3625
|
if (await parent.Load(parentTaskID))
|
|
3381
3626
|
return ParseTaskGraphParentMetadata(parent.InputPayload);
|
|
3627
|
+
LogError(`[TaskGraphDispatcher] Parent task ${parentTaskID} could not be loaded; using default graph metadata (no invocation data/context).`);
|
|
3628
|
+
}
|
|
3629
|
+
catch (e) {
|
|
3630
|
+
// Safe defaults still apply — but say so: a missing invocation turns every `data.*` mapping literal.
|
|
3631
|
+
LogError(`[TaskGraphDispatcher] Reading parent task ${parentTaskID} failed; using default graph metadata: ${e instanceof Error ? e.message : String(e)}`);
|
|
3382
3632
|
}
|
|
3383
|
-
catch { /* fall through to the safe defaults */ }
|
|
3384
3633
|
return ParseTaskGraphParentMetadata(null);
|
|
3385
3634
|
}
|
|
3386
3635
|
/**
|