@noetic-tools/core 5.11.0 → 5.13.0
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/adapters/in-memory-subprocess/step-completion.d.ts +2 -2
- package/dist/adapters/in-memory-subprocess/step-completion.js +48 -52
- package/dist/adapters/in-memory-subprocess/types.d.ts +3 -6
- package/dist/adapters/in-memory-subprocess-adapter.js +30 -48
- package/dist/adapters/live-handles.d.ts +26 -0
- package/dist/adapters/live-handles.js +50 -0
- package/dist/builders/dynamic-workflow.d.ts +19 -0
- package/dist/builders/dynamic-workflow.js +24 -3
- package/dist/builders/loop-builder.d.ts +4 -2
- package/dist/builders/loop-builder.js +7 -2
- package/dist/builders/workflow-hydrator.d.ts +17 -4
- package/dist/builders/workflow-hydrator.js +93 -32
- package/dist/builders/workflow-step.d.ts +10 -3
- package/dist/builders/workflow-step.js +8 -8
- package/dist/expression/check.d.ts +11 -0
- package/dist/expression/check.js +66 -0
- package/dist/expression/jsonata.d.ts +63 -0
- package/dist/expression/jsonata.js +258 -0
- package/dist/index.d.ts +15 -4
- package/dist/index.js +6 -3
- package/dist/interpreter/execute-control.js +50 -15
- package/dist/interpreter/execute-decide.d.ts +3 -1
- package/dist/interpreter/execute-decide.js +10 -0
- package/dist/interpreter/execute.js +1 -3
- package/dist/interpreter/step-dispatcher.d.ts +2 -2
- package/dist/interpreter/step-dispatcher.js +3 -5
- package/dist/interpreter/step-walk.js +8 -1
- package/dist/schemas/workflow.d.ts +1 -1
- package/dist/until/combinators.d.ts +12 -5
- package/dist/until/combinators.js +17 -8
- package/dist/until/decider.d.ts +11 -0
- package/dist/until/decider.js +63 -0
- package/dist/util/detached-handle.d.ts +9 -20
- package/dist/util/detached-handle.js +7 -108
- package/package.json +4 -3
- package/schema/noetic-workflow.schema.json +291 -4
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The one adapter between Noetic and JSONata (spec 33). It compiles
|
|
3
|
+
* expressions with evaluation limits, reads node input, and turns JSONata's
|
|
4
|
+
* thrown error objects into `NoeticConfigError`s, so no other module touches
|
|
5
|
+
* the library or its error shapes.
|
|
6
|
+
*/
|
|
7
|
+
import { frameworkCast, NoeticConfigError } from '@noetic-tools/types';
|
|
8
|
+
import jsonata from 'jsonata';
|
|
9
|
+
//#endregion
|
|
10
|
+
//#region Constants
|
|
11
|
+
/** The code the step hook throws; not one of JSONata's. */
|
|
12
|
+
const STEPS_CODE = 'NOETIC_STEPS';
|
|
13
|
+
/** @public The limits an expression runs under unless the host sets its own. */
|
|
14
|
+
export const DEFAULT_EXPRESSION_LIMITS = {
|
|
15
|
+
timeout: 1e3,
|
|
16
|
+
depth: 500,
|
|
17
|
+
length: 1e6,
|
|
18
|
+
steps: 1e6,
|
|
19
|
+
};
|
|
20
|
+
/** The codes thrown when a guard trips, mapped to the limit each enforces. */
|
|
21
|
+
const LIMIT_CODES = {
|
|
22
|
+
D1011: 'depth',
|
|
23
|
+
D1012: 'timeout',
|
|
24
|
+
D2015: 'length',
|
|
25
|
+
[STEPS_CODE]: 'steps',
|
|
26
|
+
};
|
|
27
|
+
/** JSONata's code for its fixed cap of 1e7 items on a range, which holds whatever `length` is. */
|
|
28
|
+
const RANGE_CAP_CODE = 'D2014';
|
|
29
|
+
/**
|
|
30
|
+
* JSONata calls the function bound to this symbol as each sub-expression
|
|
31
|
+
* starts. The hook is undocumented (JSONata's own test suite builds its
|
|
32
|
+
* timebox on it), which is one reason the library's version is pinned.
|
|
33
|
+
*/
|
|
34
|
+
const EVALUATE_ENTRY = Symbol.for('jsonata.__evaluate_entry');
|
|
35
|
+
//#endregion
|
|
36
|
+
//#region Public API
|
|
37
|
+
/**
|
|
38
|
+
* Compiles `source` under `limits`. Every `run` gets fresh budgets: the clock,
|
|
39
|
+
* depth, and step count start over per evaluation.
|
|
40
|
+
*
|
|
41
|
+
* @throws `NoeticConfigError` with code `INVALID_EXPRESSION_LIMITS` when a limit is not a positive integer or `Infinity`.
|
|
42
|
+
* @throws `NoeticConfigError` with code `WORKFLOW_VALIDATION_FAILED` when `source` does not parse.
|
|
43
|
+
*/
|
|
44
|
+
export function compileExpression(source, where, limits) {
|
|
45
|
+
const bounds = checkLimits(limits);
|
|
46
|
+
let compiled;
|
|
47
|
+
try {
|
|
48
|
+
compiled = jsonata(source, {
|
|
49
|
+
timeout: bounds.timeout,
|
|
50
|
+
stack: bounds.depth,
|
|
51
|
+
sequence: bounds.length,
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
catch (e) {
|
|
55
|
+
throw new NoeticConfigError({
|
|
56
|
+
code: 'WORKFLOW_VALIDATION_FAILED',
|
|
57
|
+
message: `Expression in ${where} does not parse: ${describe(e)}`,
|
|
58
|
+
hint: 'Fix the JSONata syntax; see https://docs.jsonata.org for the language.',
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
countSteps(compiled, bounds.steps);
|
|
62
|
+
return {
|
|
63
|
+
where,
|
|
64
|
+
run: async (input) => {
|
|
65
|
+
try {
|
|
66
|
+
return await compiled.evaluate(input);
|
|
67
|
+
}
|
|
68
|
+
catch (e) {
|
|
69
|
+
throw translate(e, where, bounds);
|
|
70
|
+
}
|
|
71
|
+
},
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
/** The parse error in `source`, or `undefined` when it compiles. */
|
|
75
|
+
export function syntaxError(source) {
|
|
76
|
+
try {
|
|
77
|
+
jsonata(source);
|
|
78
|
+
return undefined;
|
|
79
|
+
}
|
|
80
|
+
catch (e) {
|
|
81
|
+
return describe(e);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Evaluates a `compute` expression. JSONata's "no value" (`undefined`) and a
|
|
86
|
+
* result holding a function, at any depth, have no JSON form, so both fail
|
|
87
|
+
* rather than turn silently into empty or garbled output.
|
|
88
|
+
*
|
|
89
|
+
* @throws `NoeticConfigError` with code `EXPRESSION_FAILED` or `EXPRESSION_LIMIT_EXCEEDED`.
|
|
90
|
+
*/
|
|
91
|
+
export async function compute(expr, input) {
|
|
92
|
+
const result = await expr.run(input);
|
|
93
|
+
if (result === undefined) {
|
|
94
|
+
throw failed(expr.where, 'the expression gave no value; check the paths it reads.');
|
|
95
|
+
}
|
|
96
|
+
if (holdsFunction(result)) {
|
|
97
|
+
throw failed(expr.where, 'the expression gave a function, which has no JSON form.');
|
|
98
|
+
}
|
|
99
|
+
return result;
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Evaluates an `expr` test. `true` passes; `false` and JSONata's "no value"
|
|
103
|
+
* (`undefined`, e.g. a path that matched nothing) do not; anything else fails.
|
|
104
|
+
*
|
|
105
|
+
* @throws `NoeticConfigError` with code `EXPRESSION_FAILED` or `EXPRESSION_LIMIT_EXCEEDED`.
|
|
106
|
+
*/
|
|
107
|
+
export async function passes(expr, input) {
|
|
108
|
+
const result = await expr.run(input);
|
|
109
|
+
if (result === undefined) {
|
|
110
|
+
return false;
|
|
111
|
+
}
|
|
112
|
+
if (typeof result === 'boolean') {
|
|
113
|
+
return result;
|
|
114
|
+
}
|
|
115
|
+
throw failed(expr.where, `a test must give a boolean, got ${typeName(result)}.`);
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Reads a node's input as an expression sees it: a string is parsed as JSON
|
|
119
|
+
* when it parses, else kept as the raw string; any other value is used as is.
|
|
120
|
+
*/
|
|
121
|
+
export function readInput(value) {
|
|
122
|
+
if (typeof value !== 'string') {
|
|
123
|
+
return value;
|
|
124
|
+
}
|
|
125
|
+
try {
|
|
126
|
+
return JSON.parse(value);
|
|
127
|
+
}
|
|
128
|
+
catch {
|
|
129
|
+
return value;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
//#endregion
|
|
133
|
+
//#region Helpers
|
|
134
|
+
/** `limits` over the defaults (an unset field takes its default); anything but a positive integer or `Infinity` throws. */
|
|
135
|
+
function checkLimits(limits) {
|
|
136
|
+
const bounds = {
|
|
137
|
+
timeout: limits?.timeout ?? DEFAULT_EXPRESSION_LIMITS.timeout,
|
|
138
|
+
depth: limits?.depth ?? DEFAULT_EXPRESSION_LIMITS.depth,
|
|
139
|
+
length: limits?.length ?? DEFAULT_EXPRESSION_LIMITS.length,
|
|
140
|
+
steps: limits?.steps ?? DEFAULT_EXPRESSION_LIMITS.steps,
|
|
141
|
+
};
|
|
142
|
+
for (const [name, value] of Object.entries(bounds)) {
|
|
143
|
+
if (value !== Number.POSITIVE_INFINITY && !(Number.isInteger(value) && value >= 1)) {
|
|
144
|
+
throw new NoeticConfigError({
|
|
145
|
+
code: 'INVALID_EXPRESSION_LIMITS',
|
|
146
|
+
message: `Expression limit '${name}' must be a positive integer or Infinity, got ${value}.`,
|
|
147
|
+
hint: 'Pass positive integers (see DEFAULT_EXPRESSION_LIMITS for the defaults), or Infinity to lift one bound.',
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
return bounds;
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Bounds each evaluation of `compiled` to `max` sub-expressions. JSONata's
|
|
155
|
+
* depth guard misses tail calls, which it runs in a loop, and its timeout
|
|
156
|
+
* reads a clock that Workers freeze during CPU work, so this count is the
|
|
157
|
+
* one bound on every runtime. JSONata gives each evaluation a fresh root
|
|
158
|
+
* frame (`base`), so counts keyed on it never mix between concurrent runs.
|
|
159
|
+
*/
|
|
160
|
+
function countSteps(compiled, max) {
|
|
161
|
+
if (max === Number.POSITIVE_INFINITY) {
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
const used = new WeakMap();
|
|
165
|
+
const hook = (_expr, _input, frame) => {
|
|
166
|
+
const n = (used.get(frame.base) ?? 0) + 1;
|
|
167
|
+
if (n > max) {
|
|
168
|
+
throw {
|
|
169
|
+
code: STEPS_CODE,
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
used.set(frame.base, n);
|
|
173
|
+
};
|
|
174
|
+
// JSONata's types name bindings by string, but its frames take symbols too.
|
|
175
|
+
compiled.assign(frameworkCast(EVALUATE_ENTRY), hook);
|
|
176
|
+
}
|
|
177
|
+
/** JSONata gives a lambda or a bound built-in as a tagged object, a native function as itself. */
|
|
178
|
+
function isJsonataFailure(e) {
|
|
179
|
+
return typeof e === 'object' && e !== null && 'code' in e && typeof e.code === 'string';
|
|
180
|
+
}
|
|
181
|
+
function describe(e) {
|
|
182
|
+
if (!isJsonataFailure(e)) {
|
|
183
|
+
return e instanceof Error ? e.message : String(e);
|
|
184
|
+
}
|
|
185
|
+
const at = e.position === undefined ? '' : ` at position ${e.position}`;
|
|
186
|
+
return `${e.message ?? 'JSONata error'} (${e.code}${at})`;
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Turns what an evaluation threw into a Noetic error. JSONata's failures and
|
|
190
|
+
* the JS errors its built-ins throw on bad input (a `TypeError` from
|
|
191
|
+
* `$base64encode` where no `Buffer` exists, say) are the expression's fault,
|
|
192
|
+
* so both become `NoeticConfigError`s. A native stack overflow is a limit:
|
|
193
|
+
* evaluation itself never grows the JS stack (each sub-expression awaits),
|
|
194
|
+
* but a built-in that walks deeply nested input (`$string`, `**`) recurses
|
|
195
|
+
* natively, outside the `depth` count. Anything else is a defect and passes through.
|
|
196
|
+
*/
|
|
197
|
+
function translate(e, where, bounds) {
|
|
198
|
+
if (e instanceof RangeError && e.message.includes('call stack')) {
|
|
199
|
+
return exceeded(where, 'the JavaScript call stack; the data it walks nests too deeply');
|
|
200
|
+
}
|
|
201
|
+
if (e instanceof Error) {
|
|
202
|
+
return failed(where, `${e.name}: ${e.message}`);
|
|
203
|
+
}
|
|
204
|
+
if (!isJsonataFailure(e)) {
|
|
205
|
+
return e;
|
|
206
|
+
}
|
|
207
|
+
if (e.code === RANGE_CAP_CODE) {
|
|
208
|
+
return exceeded(where, "JSONata's fixed cap of 1e7 items on a range");
|
|
209
|
+
}
|
|
210
|
+
const limit = LIMIT_CODES[e.code];
|
|
211
|
+
if (limit !== undefined) {
|
|
212
|
+
return exceeded(where, `its ${limit} limit of ${bounds[limit]}`);
|
|
213
|
+
}
|
|
214
|
+
return failed(where, describe(e));
|
|
215
|
+
}
|
|
216
|
+
function exceeded(where, what) {
|
|
217
|
+
return new NoeticConfigError({
|
|
218
|
+
code: 'EXPRESSION_LIMIT_EXCEEDED',
|
|
219
|
+
message: `Expression in ${where} exceeded ${what}.`,
|
|
220
|
+
hint: 'Bound the recursion or data size in the expression, or raise expressionLimits (Infinity lifts one bound).',
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
function failed(where, message) {
|
|
224
|
+
return new NoeticConfigError({
|
|
225
|
+
code: 'EXPRESSION_FAILED',
|
|
226
|
+
message: `Expression in ${where} failed: ${message}`,
|
|
227
|
+
hint: 'Fix the expression or the input it reads; see https://docs.jsonata.org for the language.',
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* True when `value` is or contains a function. JSONata hands back its
|
|
232
|
+
* functions as plain objects tagged `_jsonata_function` (built-ins) or
|
|
233
|
+
* `_jsonata_lambda` (user lambdas, whose captured scope can be cyclic), so a
|
|
234
|
+
* `typeof` check alone misses them.
|
|
235
|
+
*/
|
|
236
|
+
function holdsFunction(value) {
|
|
237
|
+
if (typeof value === 'function') {
|
|
238
|
+
return true;
|
|
239
|
+
}
|
|
240
|
+
if (Array.isArray(value)) {
|
|
241
|
+
// Only items count: a sequence under the length limit carries its own `push` guard.
|
|
242
|
+
return value.some(holdsFunction);
|
|
243
|
+
}
|
|
244
|
+
if (typeof value !== 'object' || value === null) {
|
|
245
|
+
return false;
|
|
246
|
+
}
|
|
247
|
+
if ('_jsonata_function' in value || '_jsonata_lambda' in value) {
|
|
248
|
+
return true;
|
|
249
|
+
}
|
|
250
|
+
return Object.values(value).some(holdsFunction);
|
|
251
|
+
}
|
|
252
|
+
function typeName(value) {
|
|
253
|
+
if (value === null) {
|
|
254
|
+
return 'null';
|
|
255
|
+
}
|
|
256
|
+
return Array.isArray(value) ? 'array' : typeof value;
|
|
257
|
+
}
|
|
258
|
+
//#endregion
|
package/dist/index.d.ts
CHANGED
|
@@ -100,6 +100,10 @@ export type { DynamicWorkflowOpts, ParseAndRunWorkflowOpts } from './builders/dy
|
|
|
100
100
|
/** @public */
|
|
101
101
|
export { dynamicWorkflow, parseAndRunWorkflow } from './builders/dynamic-workflow.js';
|
|
102
102
|
/** @public */
|
|
103
|
+
export type { ExpressionLimits } from './expression/jsonata.js';
|
|
104
|
+
/** @public */
|
|
105
|
+
export { DEFAULT_EXPRESSION_LIMITS } from './expression/jsonata.js';
|
|
106
|
+
/** @public */
|
|
103
107
|
export type { AgentEnvironmentConfig, StorageEnvironmentConfig, } from './harness/agent-harness.js';
|
|
104
108
|
/** @public */
|
|
105
109
|
export { AgentHarness } from './harness/agent-harness.js';
|
|
@@ -110,9 +114,12 @@ export { CheckpointKeys, createCheckpointStore, createDetachedSignal, createNudg
|
|
|
110
114
|
/** @public */
|
|
111
115
|
export { getRegistry, lookupStep, registerStep } from './runtime/step-registry.js';
|
|
112
116
|
/** @public */
|
|
113
|
-
export {
|
|
117
|
+
export type { Expression } from '@noetic-tools/types';
|
|
118
|
+
/** @public */
|
|
114
119
|
/** @public */
|
|
115
|
-
export
|
|
120
|
+
export { defaultItemSchemaRegistry, ExpressionSchema, ItemSchema, ItemSchemaRegistry, } from '@noetic-tools/types';
|
|
121
|
+
/** @public */
|
|
122
|
+
export type { AcpAgentWorkflowNode, CallModelWorkflowNode, ComputeWorkflowNode, ConditionalRoute, ConditionalWorkflowNode, DecideWorkflowNode, InParallelWorkflowNode, InvokeToolWorkflowNode, LoopWorkflowNode, MergeStrategy, RouteSwitchWorkflowNode, ScheduleWorkflowNode, SequenceWorkflowNode, SpawnWorkflowNode, SubflowWorkflowNode, UntilPredicate, WithContextWorkflowNode, WorkflowDocument, WorkflowNode, } from './schemas/workflow.js';
|
|
116
123
|
/** @public */
|
|
117
124
|
export { MergeStrategySchema, UntilPredicateSchema, validateWorkflow, WorkflowDocumentSchema, WorkflowNodeSchema, walkWorkflow, workflowDepth, } from './schemas/workflow.js';
|
|
118
125
|
/** @public */
|
|
@@ -159,7 +166,7 @@ export type { AfterModelCallParams, AfterModelCallResult, ApproveToolCallParams,
|
|
|
159
166
|
/** @public */
|
|
160
167
|
export { LedgerEntryKind, SteeringAction } from '@noetic-tools/types';
|
|
161
168
|
/** @public */
|
|
162
|
-
export type { ExecuteStepFn, MergeFn, SettleResult, Snapshot, Step, StepAcpAgent, StepCallModel, StepConditional, StepInParallel, StepInParallelAll, StepInParallelRace, StepInParallelSettle, StepInvokeTool, StepLoop, StepReplay, StepRunCode, StepSpawn, StepWithContext, Until, Verdict, } from '@noetic-tools/types';
|
|
169
|
+
export type { ExecuteStepFn, MergeFn, SettleResult, Snapshot, Step, StepAcpAgent, StepCallModel, StepConditional, StepInParallel, StepInParallelAll, StepInParallelRace, StepInParallelSettle, StepInvokeTool, StepLoop, StepReplay, StepRunCode, StepSpawn, StepWithContext, Until, UntilRun, Verdict, } from '@noetic-tools/types';
|
|
163
170
|
/** @public */
|
|
164
171
|
export type { AnsweredAll, AnswerFor, BooleanAnswer, BooleanQuestion, CaseKeyOf, ChoiceAnswer, ChoiceQuestion, ChoiceValues, DecideAnswer, DecideAnswers, DecideQuestion, DecideQuestions, DecideRequest, DecideResponse, DecideStatePart, DecideStep, DecideView, DecisionMeta, DecisionRecord, DecisionSource, LevelLabels, OnDecisionParams, RecallOptions, ScoreAnswer, ScoreLevel, ScoreQuestion, StepDecide, } from '@noetic-tools/types';
|
|
165
172
|
/** @public */
|
|
@@ -174,11 +181,15 @@ export { ACP_AGENT_STEP_KIND, AcpCapabilityError, AcpConnectError, AcpPermission
|
|
|
174
181
|
export type { FsAdapter, FsStats } from '@noetic-tools/types';
|
|
175
182
|
/** @public */
|
|
176
183
|
/** @public */
|
|
177
|
-
export type { ProcessSubprocessRequest, SerializedError, ShellAdapter, ShellExecOptions, ShellExecResult, StepSubprocessOverrides, StepSubprocessRequest, SubprocessAdapter, SubprocessControlResult, SubprocessHandle, SubprocessHandleMetadata, SubprocessRequest, SubprocessStatus, SubprocessStopResult, } from '@noetic-tools/types';
|
|
184
|
+
export type { ProcessSubprocessRequest, SerializedError, ShellAdapter, ShellExecOptions, ShellExecResult, SpawnedSubprocess, StepSubprocessOverrides, StepSubprocessRequest, SubprocessAdapter, SubprocessControlResult, SubprocessHandle, SubprocessHandleMetadata, SubprocessRequest, SubprocessStatus, SubprocessStopResult, } from '@noetic-tools/types';
|
|
178
185
|
/** @public */
|
|
179
186
|
export { TIMEOUT_ERROR_PREFIX } from '@noetic-tools/types';
|
|
180
187
|
/** @public Reusable error-serialiser used by custom SubprocessAdapter implementations. */
|
|
181
188
|
export { serializeError } from './adapters/in-memory-subprocess/metadata.js';
|
|
189
|
+
/** @public Running-handle table that custom SubprocessAdapter implementations settle through. */
|
|
190
|
+
export type { LiveHandles } from './adapters/live-handles.js';
|
|
191
|
+
/** @public */
|
|
192
|
+
export { createLiveHandles } from './adapters/live-handles.js';
|
|
182
193
|
/** @public */
|
|
183
194
|
export type { ToolContext, ToolExecutionContext } from '@noetic-tools/types';
|
|
184
195
|
/** @public */
|
package/dist/index.js
CHANGED
|
@@ -78,15 +78,16 @@ export { createInMemoryStorage } from './runtime/in-memory-storage.js';
|
|
|
78
78
|
/** @public */
|
|
79
79
|
export { dynamicWorkflow, parseAndRunWorkflow } from './builders/dynamic-workflow.js';
|
|
80
80
|
/** @public */
|
|
81
|
+
export { DEFAULT_EXPRESSION_LIMITS } from './expression/jsonata.js';
|
|
82
|
+
/** @public */
|
|
81
83
|
export { AgentHarness } from './harness/agent-harness.js';
|
|
82
84
|
/** @public */
|
|
83
85
|
export { CheckpointKeys, createCheckpointStore, createDetachedSignal, createNudgeMessage, createStallNudgeHook, DEFAULT_NUDGE_MESSAGE_TEXT, DEFAULT_STEP_LEDGER_RETENTION, runnableLoop, seedFromItems, } from './runtime/durable/index.js';
|
|
84
86
|
/** @public */
|
|
85
87
|
export { getRegistry, lookupStep, registerStep } from './runtime/step-registry.js';
|
|
86
|
-
//#endregion
|
|
87
|
-
//#region Schemas
|
|
88
88
|
/** @public */
|
|
89
|
-
|
|
89
|
+
/** @public */
|
|
90
|
+
export { defaultItemSchemaRegistry, ExpressionSchema, ItemSchema, ItemSchemaRegistry, } from '@noetic-tools/types';
|
|
90
91
|
/** @public */
|
|
91
92
|
export { MergeStrategySchema, UntilPredicateSchema, validateWorkflow, WorkflowDocumentSchema, WorkflowNodeSchema, walkWorkflow, workflowDepth, } from './schemas/workflow.js';
|
|
92
93
|
/** @public */
|
|
@@ -109,6 +110,8 @@ export { ACP_AGENT_STEP_KIND, AcpCapabilityError, AcpConnectError, AcpPermission
|
|
|
109
110
|
export { TIMEOUT_ERROR_PREFIX } from '@noetic-tools/types';
|
|
110
111
|
/** @public Reusable error-serialiser used by custom SubprocessAdapter implementations. */
|
|
111
112
|
export { serializeError } from './adapters/in-memory-subprocess/metadata.js';
|
|
113
|
+
/** @public */
|
|
114
|
+
export { createLiveHandles } from './adapters/live-handles.js';
|
|
112
115
|
//#endregion
|
|
113
116
|
//#region Until
|
|
114
117
|
/** @public */
|
|
@@ -1,13 +1,15 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Control-flow step handlers: conditional, inParallel, loop, schedule.
|
|
3
3
|
*/
|
|
4
|
-
import { createMessage, frameworkCast, isNoeticError, NoeticErrorImpl } from '@noetic-tools/types';
|
|
4
|
+
import { createMessage, frameworkCast, isNoeticConfigError, isNoeticError, NoeticErrorImpl, } from '@noetic-tools/types';
|
|
5
5
|
import { NoeticAttr, NoeticEvent } from '../observability/genai-attributes.js';
|
|
6
6
|
import { ContextImpl } from '../runtime/context-impl.js';
|
|
7
7
|
import { snapshotCwdState } from '../runtime/cwd-helpers.js';
|
|
8
|
+
import { toUntil } from '../until/decider.js';
|
|
8
9
|
import { contextToExecCtx, returnLayers, spawnLayers } from './action-deps.js';
|
|
9
10
|
import { closeUnstartedSpan, openChildSpan, traceChild } from './child-span.js';
|
|
10
11
|
import { cloneWithGuard } from './clone-guard.js';
|
|
12
|
+
import { forgetAnswers } from './execute-decide.js';
|
|
11
13
|
import { getContextChannelStore, isContextImpl, isMutableContext } from './typeguards.js';
|
|
12
14
|
//#region conditional
|
|
13
15
|
export async function executeConditional(step, input, ctx, executeStep) {
|
|
@@ -449,6 +451,49 @@ function prepareNextInput(step, lastOutput, verdict, ctx) {
|
|
|
449
451
|
// back as input. Callers must ensure I and O are compatible types.
|
|
450
452
|
return frameworkCast(lastOutput);
|
|
451
453
|
}
|
|
454
|
+
/** A loop cap is a positive integer, or `Infinity` for a loop only its `until` predicate (or an error/abort) ends. */
|
|
455
|
+
function isValidIterationCap(cap) {
|
|
456
|
+
return cap === Number.POSITIVE_INFINITY || (Number.isInteger(cap) && cap >= 1);
|
|
457
|
+
}
|
|
458
|
+
/**
|
|
459
|
+
* Runs steps for an until predicate. A decide step forgets its earlier answers
|
|
460
|
+
* first: each iteration is a new question even when the output and the
|
|
461
|
+
* conversation length repeat, and decide's reuse within an execution would
|
|
462
|
+
* otherwise hand back the first iteration's answer forever.
|
|
463
|
+
*/
|
|
464
|
+
function untilRun(ctx, executeStep) {
|
|
465
|
+
return {
|
|
466
|
+
ctx: frameworkCast(ctx),
|
|
467
|
+
executeStep: (s, input, stepCtx) => {
|
|
468
|
+
if (s.kind === 'decide') {
|
|
469
|
+
forgetAnswers(frameworkCast(stepCtx), s.id);
|
|
470
|
+
}
|
|
471
|
+
return executeStep(s, input, stepCtx);
|
|
472
|
+
},
|
|
473
|
+
};
|
|
474
|
+
}
|
|
475
|
+
/**
|
|
476
|
+
* A predicate that throws stops the loop, with two exceptions that propagate:
|
|
477
|
+
* cancellation (spec 09), and a `NoeticConfigError`, which marks a broken
|
|
478
|
+
* loop definition that a stop would pass off as done.
|
|
479
|
+
*/
|
|
480
|
+
async function judge(until, snapshot, run) {
|
|
481
|
+
try {
|
|
482
|
+
return await until(snapshot, run);
|
|
483
|
+
}
|
|
484
|
+
catch (predicateError) {
|
|
485
|
+
if (isNoeticConfigError(predicateError)) {
|
|
486
|
+
throw predicateError;
|
|
487
|
+
}
|
|
488
|
+
if (isNoeticError(predicateError) && predicateError.noeticError.kind === 'cancelled') {
|
|
489
|
+
throw predicateError;
|
|
490
|
+
}
|
|
491
|
+
return {
|
|
492
|
+
stop: true,
|
|
493
|
+
reason: `Predicate error: ${predicateError instanceof Error ? predicateError.message : String(predicateError)}`,
|
|
494
|
+
};
|
|
495
|
+
}
|
|
496
|
+
}
|
|
452
497
|
export async function executeLoop(step, input, ctx, executeStep) {
|
|
453
498
|
const baseCtx = frameworkCast(ctx);
|
|
454
499
|
let currentInput = input;
|
|
@@ -460,8 +505,7 @@ export async function executeLoop(step, input, ctx, executeStep) {
|
|
|
460
505
|
const maxIterations = step.maxIterations ?? 1e3;
|
|
461
506
|
const maxHistory = step.maxHistorySize ?? DEFAULT_MAX_HISTORY;
|
|
462
507
|
let totalIterations = 0;
|
|
463
|
-
|
|
464
|
-
if (!Number.isFinite(maxIterations) || maxIterations < 1) {
|
|
508
|
+
if (!isValidIterationCap(maxIterations)) {
|
|
465
509
|
throw new NoeticErrorImpl({
|
|
466
510
|
kind: 'step_failed',
|
|
467
511
|
stepId: step.id,
|
|
@@ -469,6 +513,8 @@ export async function executeLoop(step, input, ctx, executeStep) {
|
|
|
469
513
|
retriesExhausted: false,
|
|
470
514
|
});
|
|
471
515
|
}
|
|
516
|
+
const until = toUntil(step.until);
|
|
517
|
+
const run = untilRun(ctx, executeStep);
|
|
472
518
|
while (true) {
|
|
473
519
|
// Abort check at top of each iteration
|
|
474
520
|
if (ctx.aborted) {
|
|
@@ -552,18 +598,7 @@ export async function executeLoop(step, input, ctx, executeStep) {
|
|
|
552
598
|
depth: ctx.depth,
|
|
553
599
|
lastStepMeta: isMutableContext(baseCtx) ? baseCtx.lastStepMeta : null,
|
|
554
600
|
};
|
|
555
|
-
|
|
556
|
-
let verdict;
|
|
557
|
-
try {
|
|
558
|
-
verdict = await step.until(snapshot);
|
|
559
|
-
}
|
|
560
|
-
catch (predicateError) {
|
|
561
|
-
// Per spec: if until predicate throws, treat as stop
|
|
562
|
-
verdict = {
|
|
563
|
-
stop: true,
|
|
564
|
-
reason: `Predicate error: ${predicateError instanceof Error ? predicateError.message : String(predicateError)}`,
|
|
565
|
-
};
|
|
566
|
-
}
|
|
601
|
+
const verdict = await judge(until, snapshot, run);
|
|
567
602
|
recordVerdict(ctx, step.id, totalIterations, verdict);
|
|
568
603
|
if (verdict.stop) {
|
|
569
604
|
if (lastOutput === undefined) {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { Context, ContextLayer, StepDecide } from './action-types.js';
|
|
1
|
+
import type { Context, ContextData, ContextLayer, StepDecide } from './action-types.js';
|
|
2
2
|
/**
|
|
3
3
|
* Run a `decide` step: build state from the input, the context view, and the
|
|
4
4
|
* step's context selector; ask the harness; validate; record. The conversation
|
|
@@ -8,3 +8,5 @@ import type { Context, ContextLayer, StepDecide } from './action-types.js';
|
|
|
8
8
|
* @internal
|
|
9
9
|
*/
|
|
10
10
|
export declare function executeDecide<TContext, I, O>(step: StepDecide<TContext, I, O>, input: I, ctx: Context<TContext>, layers?: ContextLayer[]): Promise<O>;
|
|
11
|
+
/** Drops the answers `stepId` gave in this execution, so its next ask goes to the model. */
|
|
12
|
+
export declare function forgetAnswers(ctx: Context<ContextData>, stepId: string): void;
|
|
@@ -119,6 +119,16 @@ function answered(ctx) {
|
|
|
119
119
|
}
|
|
120
120
|
return map;
|
|
121
121
|
}
|
|
122
|
+
/** Drops the answers `stepId` gave in this execution, so its next ask goes to the model. */
|
|
123
|
+
export function forgetAnswers(ctx, stepId) {
|
|
124
|
+
const map = answered(ctx);
|
|
125
|
+
const prefix = `${stepId}\u0000`;
|
|
126
|
+
for (const key of map.keys()) {
|
|
127
|
+
if (key.startsWith(prefix)) {
|
|
128
|
+
map.delete(key);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
}
|
|
122
132
|
/** `undefined` when the input cannot be keyed (it does not survive JSON), so it is never reused. */
|
|
123
133
|
function memoKey(stepId, input, logLength) {
|
|
124
134
|
try {
|
|
@@ -81,12 +81,10 @@ async function dispatchViaAdapter(step, input, ctx, executionId, executor) {
|
|
|
81
81
|
},
|
|
82
82
|
_localExecutor: () => executor(),
|
|
83
83
|
};
|
|
84
|
-
const spawnPromise = adapter.spawn(request);
|
|
85
84
|
const handle = new DetachedHandleImpl({
|
|
86
85
|
id: executionId,
|
|
87
86
|
stepId: step.id,
|
|
88
|
-
adapter,
|
|
89
|
-
spawnPromise,
|
|
87
|
+
spawned: adapter.spawn(request),
|
|
90
88
|
});
|
|
91
89
|
return handle.await();
|
|
92
90
|
}
|
|
@@ -43,8 +43,8 @@ export interface DetachedSpawnOverrides {
|
|
|
43
43
|
}
|
|
44
44
|
/**
|
|
45
45
|
* Route a step through the configured subprocess adapter and return a
|
|
46
|
-
* `DetachedHandle` that
|
|
47
|
-
*
|
|
46
|
+
* `DetachedHandle` that settles when the adapter reports the child
|
|
47
|
+
* finished. The adapter's `spawn()` may be async (the default in-memory
|
|
48
48
|
* adapter schedules the step body on the microtask queue, and
|
|
49
49
|
* out-of-process adapters may await an OS spawn).
|
|
50
50
|
*
|
|
@@ -24,8 +24,8 @@ export function resolveStepAdapter(step, callOverride, fallback) {
|
|
|
24
24
|
//#region Dispatcher
|
|
25
25
|
/**
|
|
26
26
|
* Route a step through the configured subprocess adapter and return a
|
|
27
|
-
* `DetachedHandle` that
|
|
28
|
-
*
|
|
27
|
+
* `DetachedHandle` that settles when the adapter reports the child
|
|
28
|
+
* finished. The adapter's `spawn()` may be async (the default in-memory
|
|
29
29
|
* adapter schedules the step body on the microtask queue, and
|
|
30
30
|
* out-of-process adapters may await an OS spawn).
|
|
31
31
|
*
|
|
@@ -57,12 +57,10 @@ export function dispatchStepThroughAdapter(h, s, input, parentCtx, overrides) {
|
|
|
57
57
|
},
|
|
58
58
|
_localExecutor: () => executeNoAdapter(s, input, childCtx),
|
|
59
59
|
};
|
|
60
|
-
const spawnPromise = adapter.spawn(request);
|
|
61
60
|
return new DetachedHandleImpl({
|
|
62
61
|
id: childCtx.id,
|
|
63
62
|
stepId: s.id,
|
|
64
|
-
adapter,
|
|
65
|
-
spawnPromise,
|
|
63
|
+
spawned: adapter.spawn(request),
|
|
66
64
|
});
|
|
67
65
|
}
|
|
68
66
|
//#endregion
|
|
@@ -29,7 +29,14 @@ export function stepChildren(step) {
|
|
|
29
29
|
step.child,
|
|
30
30
|
];
|
|
31
31
|
case 'loop':
|
|
32
|
-
|
|
32
|
+
// A decide step used as `until` is a child too; one inside any/all is
|
|
33
|
+
// hidden in a closure.
|
|
34
|
+
return typeof step.until === 'function'
|
|
35
|
+
? step.steps
|
|
36
|
+
: [
|
|
37
|
+
...step.steps,
|
|
38
|
+
step.until,
|
|
39
|
+
];
|
|
33
40
|
case 'schedule':
|
|
34
41
|
return [
|
|
35
42
|
step.step,
|
|
@@ -3,5 +3,5 @@
|
|
|
3
3
|
* consumers can validate workflow documents without importing core.
|
|
4
4
|
* This barrel keeps core's public and intra-core import paths unchanged.
|
|
5
5
|
*/
|
|
6
|
-
export type { AcpAgentWorkflowNode, CallModelWorkflowNode, ConditionalRoute, ConditionalWorkflowNode, DecideWorkflowNode, InParallelWorkflowNode, InvokeToolWorkflowNode, LoopWorkflowNode, OutputCodecRef, RouteSwitchWorkflowNode, RunCodeWorkflowNode, ScheduleWorkflowNode, SequenceWorkflowNode, SpawnWorkflowNode, SubflowWorkflowNode, UntilPredicate, WithContextWorkflowNode, WorkflowDocument, WorkflowGraph, WorkflowNode, WorkflowReplayKey, } from '@noetic-tools/types';
|
|
6
|
+
export type { AcpAgentWorkflowNode, CallModelWorkflowNode, ComputeWorkflowNode, ConditionalRoute, ConditionalWorkflowNode, DecideWorkflowNode, InParallelWorkflowNode, InvokeToolWorkflowNode, LoopWorkflowNode, OutputCodecRef, RouteSwitchWorkflowNode, RunCodeWorkflowNode, ScheduleWorkflowNode, SequenceWorkflowNode, SpawnWorkflowNode, SubflowWorkflowNode, UntilPredicate, WithContextWorkflowNode, WorkflowDocument, WorkflowGraph, WorkflowNode, WorkflowReplayKey, } from '@noetic-tools/types';
|
|
7
7
|
export { MergeStrategy, MergeStrategySchema, UntilPredicateSchema, validateWorkflow, WorkflowDocumentSchema, WorkflowNodeSchema, walkWorkflow, workflowDepth, workflowGraph, } from '@noetic-tools/types';
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { ContextData } from '@noetic-tools/context';
|
|
2
|
+
import type { StepDecide, Until } from '@noetic-tools/types';
|
|
2
3
|
/**
|
|
3
4
|
* Combines predicates with OR semantics; stops the loop when any predicate says stop.
|
|
4
5
|
*
|
|
@@ -7,11 +8,14 @@ import type { Until } from '@noetic-tools/types';
|
|
|
7
8
|
* predicate's `reason` (joined with `'; '`) and `feedback` (joined with `'\n'`),
|
|
8
9
|
* so a failing `until.verified()` still hands its feedback to `prepareNext`.
|
|
9
10
|
*
|
|
11
|
+
* A predicate may be a decide step asking one boolean question (see `loop`).
|
|
12
|
+
*
|
|
10
13
|
* @public
|
|
11
|
-
* @param predicates - Until predicates to evaluate.
|
|
14
|
+
* @param predicates - Until predicates or decide steps to evaluate.
|
|
12
15
|
* @returns A combined `Until` that short-circuits on the first stop verdict.
|
|
16
|
+
* @throws `NoeticConfigError` `INVALID_UNTIL_DECIDER` if a decide step does not ask exactly one boolean question.
|
|
13
17
|
*/
|
|
14
|
-
export declare function any(...predicates: Until
|
|
18
|
+
export declare function any<TContext = ContextData>(...predicates: Array<Until | StepDecide<TContext>>): Until;
|
|
15
19
|
/**
|
|
16
20
|
* Combines predicates with AND semantics; stops the loop only when all predicates say stop.
|
|
17
21
|
*
|
|
@@ -20,8 +24,11 @@ export declare function any(...predicates: Until[]): Until;
|
|
|
20
24
|
* predicate's `reason` (joined with `'; '`, default `'All predicates
|
|
21
25
|
* satisfied'`) and `feedback` (joined with `'\n'`).
|
|
22
26
|
*
|
|
27
|
+
* A predicate may be a decide step asking one boolean question (see `loop`).
|
|
28
|
+
*
|
|
23
29
|
* @public
|
|
24
|
-
* @param predicates - Until predicates to evaluate.
|
|
30
|
+
* @param predicates - Until predicates or decide steps to evaluate.
|
|
25
31
|
* @returns A combined `Until` that requires all predicates to be satisfied.
|
|
32
|
+
* @throws `NoeticConfigError` `INVALID_UNTIL_DECIDER` if a decide step does not ask exactly one boolean question.
|
|
26
33
|
*/
|
|
27
|
-
export declare function all(...predicates: Until
|
|
34
|
+
export declare function all<TContext = ContextData>(...predicates: Array<Until | StepDecide<TContext>>): Until;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { toUntil } from './decider.js';
|
|
1
2
|
/**
|
|
2
3
|
* Combines predicates with OR semantics; stops the loop when any predicate says stop.
|
|
3
4
|
*
|
|
@@ -6,15 +7,19 @@
|
|
|
6
7
|
* predicate's `reason` (joined with `'; '`) and `feedback` (joined with `'\n'`),
|
|
7
8
|
* so a failing `until.verified()` still hands its feedback to `prepareNext`.
|
|
8
9
|
*
|
|
10
|
+
* A predicate may be a decide step asking one boolean question (see `loop`).
|
|
11
|
+
*
|
|
9
12
|
* @public
|
|
10
|
-
* @param predicates - Until predicates to evaluate.
|
|
13
|
+
* @param predicates - Until predicates or decide steps to evaluate.
|
|
11
14
|
* @returns A combined `Until` that short-circuits on the first stop verdict.
|
|
15
|
+
* @throws `NoeticConfigError` `INVALID_UNTIL_DECIDER` if a decide step does not ask exactly one boolean question.
|
|
12
16
|
*/
|
|
13
17
|
export function any(...predicates) {
|
|
14
|
-
|
|
18
|
+
const untils = predicates.map(toUntil);
|
|
19
|
+
return async (snapshot, run) => {
|
|
15
20
|
const verdicts = [];
|
|
16
|
-
for (const pred of
|
|
17
|
-
const verdict = await pred(snapshot);
|
|
21
|
+
for (const pred of untils) {
|
|
22
|
+
const verdict = await pred(snapshot, run);
|
|
18
23
|
if (verdict.stop) {
|
|
19
24
|
return verdict;
|
|
20
25
|
}
|
|
@@ -31,15 +36,19 @@ export function any(...predicates) {
|
|
|
31
36
|
* predicate's `reason` (joined with `'; '`, default `'All predicates
|
|
32
37
|
* satisfied'`) and `feedback` (joined with `'\n'`).
|
|
33
38
|
*
|
|
39
|
+
* A predicate may be a decide step asking one boolean question (see `loop`).
|
|
40
|
+
*
|
|
34
41
|
* @public
|
|
35
|
-
* @param predicates - Until predicates to evaluate.
|
|
42
|
+
* @param predicates - Until predicates or decide steps to evaluate.
|
|
36
43
|
* @returns A combined `Until` that requires all predicates to be satisfied.
|
|
44
|
+
* @throws `NoeticConfigError` `INVALID_UNTIL_DECIDER` if a decide step does not ask exactly one boolean question.
|
|
37
45
|
*/
|
|
38
46
|
export function all(...predicates) {
|
|
39
|
-
|
|
47
|
+
const untils = predicates.map(toUntil);
|
|
48
|
+
return async (snapshot, run) => {
|
|
40
49
|
const verdicts = [];
|
|
41
|
-
for (const pred of
|
|
42
|
-
const verdict = await pred(snapshot);
|
|
50
|
+
for (const pred of untils) {
|
|
51
|
+
const verdict = await pred(snapshot, run);
|
|
43
52
|
if (!verdict.stop) {
|
|
44
53
|
return verdict;
|
|
45
54
|
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { StepDecide, Until } from '@noetic-tools/types';
|
|
2
|
+
/**
|
|
3
|
+
* Turns a loop's `until` value into a predicate. A function passes through; a
|
|
4
|
+
* decide step becomes a predicate that runs it on the iteration's output and
|
|
5
|
+
* stops on a yes. Throws at once when the decide step is not a valid decider,
|
|
6
|
+
* so a bad loop fails where it is built.
|
|
7
|
+
*
|
|
8
|
+
* @throws `NoeticConfigError` `INVALID_UNTIL_DECIDER` unless the decide step
|
|
9
|
+
* asks exactly one question and that question is boolean.
|
|
10
|
+
*/
|
|
11
|
+
export declare function toUntil<TContext>(pred: Until | StepDecide<TContext>): Until;
|