@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
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import type { CompleteProcessRunParams, CompleteStepRunParams } from './types.js';
|
|
2
|
-
export declare function completeProcessRun({ request, handle, run,
|
|
3
|
-
export declare function completeStepRun({ request, handle, stepRunner,
|
|
2
|
+
export declare function completeProcessRun({ request, handle, run, live, clearIfDurable, }: CompleteProcessRunParams): Promise<void>;
|
|
3
|
+
export declare function completeStepRun({ request, handle, stepRunner, live, clearIfDurable, }: CompleteStepRunParams): Promise<void>;
|
|
@@ -1,42 +1,26 @@
|
|
|
1
1
|
import { nowIso, serializeError } from './metadata.js';
|
|
2
2
|
//#region Completion handlers
|
|
3
|
-
export async function completeProcessRun({ request, handle, run,
|
|
3
|
+
export async function completeProcessRun({ request, handle, run, live, clearIfDurable, }) {
|
|
4
4
|
try {
|
|
5
5
|
await run?.(request, handle);
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
}
|
|
10
|
-
active.delete(handle.id);
|
|
11
|
-
await save({
|
|
12
|
-
...latest,
|
|
6
|
+
await finish({
|
|
7
|
+
live,
|
|
8
|
+
clearIfDurable,
|
|
9
|
+
}, handle.id, {
|
|
13
10
|
status: 'completed',
|
|
14
|
-
updatedAt: nowIso(),
|
|
15
11
|
});
|
|
16
|
-
// Clear the durable handle manifest once the run has terminated so
|
|
17
|
-
// `listLive()` stops returning this handle. Without this call the
|
|
18
|
-
// manifest would persist until `stop()` was called, making every
|
|
19
|
-
// completed step look live from the adapter's persistence layer.
|
|
20
|
-
await clearIfDurable(handle.id);
|
|
21
12
|
}
|
|
22
13
|
catch (err) {
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
14
|
+
await finish({
|
|
15
|
+
live,
|
|
16
|
+
clearIfDurable,
|
|
17
|
+
}, handle.id, {
|
|
27
18
|
status: 'failed',
|
|
28
|
-
|
|
29
|
-
metadata: {
|
|
30
|
-
...(latest.metadata ?? {}),
|
|
31
|
-
error: serializeError(err),
|
|
32
|
-
},
|
|
19
|
+
error: serializeError(err),
|
|
33
20
|
});
|
|
34
|
-
// Same rationale as the success path above — clear the durable
|
|
35
|
-
// manifest so `listLive()` doesn't resurrect this handle on reboot.
|
|
36
|
-
await clearIfDurable(handle.id);
|
|
37
21
|
}
|
|
38
22
|
}
|
|
39
|
-
export async function completeStepRun({ request, handle, stepRunner,
|
|
23
|
+
export async function completeStepRun({ request, handle, stepRunner, live, clearIfDurable, }) {
|
|
40
24
|
try {
|
|
41
25
|
const executor = request._localExecutor;
|
|
42
26
|
let result;
|
|
@@ -50,37 +34,49 @@ export async function completeStepRun({ request, handle, stepRunner, handles, ac
|
|
|
50
34
|
throw new Error(`In-memory subprocess adapter has no executor for step "${request.stepId}". ` +
|
|
51
35
|
'Provide a stepRunner option or dispatch via AgentHarness.');
|
|
52
36
|
}
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
}
|
|
57
|
-
active.delete(handle.id);
|
|
58
|
-
await save({
|
|
59
|
-
...latest,
|
|
37
|
+
await finish({
|
|
38
|
+
live,
|
|
39
|
+
clearIfDurable,
|
|
40
|
+
}, handle.id, {
|
|
60
41
|
status: 'completed',
|
|
61
|
-
|
|
62
|
-
metadata: {
|
|
63
|
-
...(latest.metadata ?? {}),
|
|
64
|
-
result,
|
|
65
|
-
},
|
|
42
|
+
result,
|
|
66
43
|
});
|
|
67
|
-
// Clear the durable step manifest once the run has terminated —
|
|
68
|
-
// see `completeProcessRun` above for the rationale.
|
|
69
|
-
await clearIfDurable(handle.id);
|
|
70
44
|
}
|
|
71
45
|
catch (err) {
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
46
|
+
await finish({
|
|
47
|
+
live,
|
|
48
|
+
clearIfDurable,
|
|
49
|
+
}, handle.id, {
|
|
76
50
|
status: 'failed',
|
|
77
|
-
|
|
78
|
-
metadata: {
|
|
79
|
-
...(latest.metadata ?? {}),
|
|
80
|
-
error: serializeError(err),
|
|
81
|
-
},
|
|
51
|
+
error: serializeError(err),
|
|
82
52
|
});
|
|
83
|
-
await clearIfDurable(handle.id);
|
|
84
53
|
}
|
|
85
54
|
}
|
|
55
|
+
/**
|
|
56
|
+
* Settles a run that ended on its own. The caller hears first; the durable
|
|
57
|
+
* manifest clears after, so a slow storage write never delays the result.
|
|
58
|
+
* A handle already stopped has settled, so its late outcome is dropped.
|
|
59
|
+
*/
|
|
60
|
+
async function finish({ live, clearIfDurable }, handleId, outcome) {
|
|
61
|
+
const latest = live.get(handleId);
|
|
62
|
+
if (!latest) {
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
const metadata = {
|
|
66
|
+
...(latest.metadata ?? {}),
|
|
67
|
+
};
|
|
68
|
+
if (outcome.result !== undefined) {
|
|
69
|
+
metadata.result = outcome.result;
|
|
70
|
+
}
|
|
71
|
+
if (outcome.error !== undefined) {
|
|
72
|
+
metadata.error = outcome.error;
|
|
73
|
+
}
|
|
74
|
+
live.settle({
|
|
75
|
+
...latest,
|
|
76
|
+
status: outcome.status,
|
|
77
|
+
updatedAt: nowIso(),
|
|
78
|
+
metadata,
|
|
79
|
+
});
|
|
80
|
+
await clearIfDurable(handleId);
|
|
81
|
+
}
|
|
86
82
|
//#endregion
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { StorageAdapter } from '@noetic-tools/context';
|
|
2
2
|
import type { ProcessSubprocessRequest, StepSubprocessRequest, SubprocessHandle, SubprocessHandleMetadata, SubprocessRequest } from '@noetic-tools/types';
|
|
3
|
+
import type { LiveHandles } from '../live-handles.js';
|
|
3
4
|
/**
|
|
4
5
|
* @public
|
|
5
6
|
* Options for `createInMemorySubprocessAdapter`. All hooks are optional;
|
|
@@ -48,9 +49,7 @@ export interface CompleteProcessRunParams {
|
|
|
48
49
|
request: ProcessSubprocessRequest;
|
|
49
50
|
handle: SubprocessHandle;
|
|
50
51
|
run: CreateInMemorySubprocessAdapterOptions['run'];
|
|
51
|
-
|
|
52
|
-
active: Set<string>;
|
|
53
|
-
save: (handle: SubprocessHandle) => Promise<SubprocessHandle>;
|
|
52
|
+
live: LiveHandles;
|
|
54
53
|
/** Invoked on terminal transitions so the durable handle manifest
|
|
55
54
|
* does not linger after the step is done — otherwise `listLive()`
|
|
56
55
|
* would return phantom handles for every step ever completed
|
|
@@ -61,9 +60,7 @@ export interface CompleteStepRunParams {
|
|
|
61
60
|
request: StepSubprocessRequest;
|
|
62
61
|
handle: SubprocessHandle;
|
|
63
62
|
stepRunner: CreateInMemorySubprocessAdapterOptions['stepRunner'];
|
|
64
|
-
|
|
65
|
-
active: Set<string>;
|
|
66
|
-
save: (handle: SubprocessHandle) => Promise<SubprocessHandle>;
|
|
63
|
+
live: LiveHandles;
|
|
67
64
|
/** See `CompleteProcessRunParams.clearIfDurable`. */
|
|
68
65
|
clearIfDurable: (handleId: string) => Promise<void>;
|
|
69
66
|
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { clearManifest, listManifests, loadManifest, persistStepManifest, } from './in-memory-subprocess/manifest-persistence.js';
|
|
2
2
|
import { buildProcessMetadata, buildStepMetadata, isProcessRequest, isStepRequest, nowIso, } from './in-memory-subprocess/metadata.js';
|
|
3
3
|
import { completeProcessRun, completeStepRun } from './in-memory-subprocess/step-completion.js';
|
|
4
|
+
import { createLiveHandles } from './live-handles.js';
|
|
4
5
|
//#region Factory
|
|
5
6
|
/**
|
|
6
7
|
* @public
|
|
@@ -12,13 +13,8 @@ import { completeProcessRun, completeStepRun } from './in-memory-subprocess/step
|
|
|
12
13
|
* a live process (there is none to bind to for in-memory).
|
|
13
14
|
*/
|
|
14
15
|
export function createInMemorySubprocessAdapter(options = {}) {
|
|
15
|
-
const
|
|
16
|
-
const active = new Set();
|
|
16
|
+
const live = createLiveHandles();
|
|
17
17
|
const storage = options.storage;
|
|
18
|
-
async function save(handle) {
|
|
19
|
-
handles.set(handle.id, handle);
|
|
20
|
-
return handle;
|
|
21
|
-
}
|
|
22
18
|
/**
|
|
23
19
|
* Persist a step manifest after spawn so `reattach` and `listLive` can
|
|
24
20
|
* find this handle again on a subsequent adapter instance. Errors are
|
|
@@ -58,48 +54,40 @@ export function createInMemorySubprocessAdapter(options = {}) {
|
|
|
58
54
|
}
|
|
59
55
|
async function spawnStepHandle(request) {
|
|
60
56
|
const now = nowIso();
|
|
61
|
-
const
|
|
57
|
+
const spawned = live.add({
|
|
62
58
|
id: `subprocess-${crypto.randomUUID()}`,
|
|
63
59
|
status: 'running',
|
|
64
60
|
startedAt: now,
|
|
65
61
|
updatedAt: now,
|
|
66
62
|
metadata: injectMetadata(request, buildStepMetadata(request)),
|
|
67
|
-
};
|
|
68
|
-
|
|
69
|
-
await save(handle);
|
|
70
|
-
await persistIfDurable(request, handle);
|
|
63
|
+
});
|
|
64
|
+
await persistIfDurable(request, spawned.handle);
|
|
71
65
|
void completeStepRun({
|
|
72
66
|
request,
|
|
73
|
-
handle,
|
|
67
|
+
handle: spawned.handle,
|
|
74
68
|
stepRunner: options.stepRunner,
|
|
75
|
-
|
|
76
|
-
active,
|
|
77
|
-
save,
|
|
69
|
+
live,
|
|
78
70
|
clearIfDurable,
|
|
79
71
|
});
|
|
80
|
-
return
|
|
72
|
+
return spawned;
|
|
81
73
|
}
|
|
82
|
-
|
|
74
|
+
function spawnProcessHandle(request) {
|
|
83
75
|
const now = nowIso();
|
|
84
|
-
const
|
|
76
|
+
const spawned = live.add({
|
|
85
77
|
id: `subprocess-${crypto.randomUUID()}`,
|
|
86
78
|
status: 'running',
|
|
87
79
|
startedAt: now,
|
|
88
80
|
updatedAt: now,
|
|
89
81
|
metadata: injectMetadata(request, buildProcessMetadata(request)),
|
|
90
|
-
};
|
|
91
|
-
active.add(handle.id);
|
|
92
|
-
await save(handle);
|
|
82
|
+
});
|
|
93
83
|
void completeProcessRun({
|
|
94
84
|
request,
|
|
95
|
-
handle,
|
|
85
|
+
handle: spawned.handle,
|
|
96
86
|
run: options.run,
|
|
97
|
-
|
|
98
|
-
active,
|
|
99
|
-
save,
|
|
87
|
+
live,
|
|
100
88
|
clearIfDurable,
|
|
101
89
|
});
|
|
102
|
-
return
|
|
90
|
+
return spawned;
|
|
103
91
|
}
|
|
104
92
|
/**
|
|
105
93
|
* Build a hydrated handle from a persisted manifest. Status is `running`
|
|
@@ -134,19 +122,17 @@ export function createInMemorySubprocessAdapter(options = {}) {
|
|
|
134
122
|
throw new Error('Unsupported subprocess request variant.');
|
|
135
123
|
},
|
|
136
124
|
async get(handleId) {
|
|
137
|
-
return
|
|
125
|
+
return live.get(handleId) ?? null;
|
|
138
126
|
},
|
|
139
127
|
async stop(handleId, reason) {
|
|
140
|
-
const handle =
|
|
128
|
+
const handle = live.get(handleId);
|
|
141
129
|
if (!handle) {
|
|
142
130
|
return {
|
|
143
131
|
kind: 'not_found',
|
|
144
132
|
handleId,
|
|
145
133
|
};
|
|
146
134
|
}
|
|
147
|
-
|
|
148
|
-
await clearIfDurable(handleId);
|
|
149
|
-
const next = await save({
|
|
135
|
+
const next = {
|
|
150
136
|
...handle,
|
|
151
137
|
status: 'stopped',
|
|
152
138
|
updatedAt: nowIso(),
|
|
@@ -154,7 +140,9 @@ export function createInMemorySubprocessAdapter(options = {}) {
|
|
|
154
140
|
...(handle.metadata ?? {}),
|
|
155
141
|
stopReason: reason,
|
|
156
142
|
},
|
|
157
|
-
}
|
|
143
|
+
};
|
|
144
|
+
live.settle(next);
|
|
145
|
+
await clearIfDurable(handleId);
|
|
158
146
|
return {
|
|
159
147
|
kind: 'stopped',
|
|
160
148
|
handleId,
|
|
@@ -162,7 +150,7 @@ export function createInMemorySubprocessAdapter(options = {}) {
|
|
|
162
150
|
};
|
|
163
151
|
},
|
|
164
152
|
async pause(handleId) {
|
|
165
|
-
const handle =
|
|
153
|
+
const handle = live.get(handleId);
|
|
166
154
|
if (!handle) {
|
|
167
155
|
return {
|
|
168
156
|
kind: 'not_found',
|
|
@@ -176,7 +164,7 @@ export function createInMemorySubprocessAdapter(options = {}) {
|
|
|
176
164
|
};
|
|
177
165
|
},
|
|
178
166
|
async resume(handleId) {
|
|
179
|
-
const handle =
|
|
167
|
+
const handle = live.get(handleId);
|
|
180
168
|
if (!handle) {
|
|
181
169
|
return {
|
|
182
170
|
kind: 'not_found',
|
|
@@ -190,7 +178,7 @@ export function createInMemorySubprocessAdapter(options = {}) {
|
|
|
190
178
|
};
|
|
191
179
|
},
|
|
192
180
|
async isAlive(handle) {
|
|
193
|
-
return
|
|
181
|
+
return live.get(handle.id) !== undefined;
|
|
194
182
|
},
|
|
195
183
|
/**
|
|
196
184
|
* Idempotent re-run of a persisted step, not a "resume" — for in-memory
|
|
@@ -207,29 +195,23 @@ export function createInMemorySubprocessAdapter(options = {}) {
|
|
|
207
195
|
if (!manifest) {
|
|
208
196
|
return null;
|
|
209
197
|
}
|
|
210
|
-
|
|
211
|
-
active.add(handle.id);
|
|
212
|
-
await save(handle);
|
|
213
|
-
return handle;
|
|
198
|
+
return live.add(handleFromManifest(manifest)).handle;
|
|
214
199
|
},
|
|
215
200
|
async listLive() {
|
|
216
|
-
const
|
|
217
|
-
for (const
|
|
218
|
-
|
|
219
|
-
if (handle) {
|
|
220
|
-
live.set(handle.id, handle);
|
|
221
|
-
}
|
|
201
|
+
const found = new Map();
|
|
202
|
+
for (const handle of live.values()) {
|
|
203
|
+
found.set(handle.id, handle);
|
|
222
204
|
}
|
|
223
205
|
if (storage) {
|
|
224
206
|
const manifests = await listManifests(storage);
|
|
225
207
|
for (const manifest of manifests) {
|
|
226
|
-
if (!
|
|
227
|
-
|
|
208
|
+
if (!found.has(manifest.handleId)) {
|
|
209
|
+
found.set(manifest.handleId, handleFromManifest(manifest));
|
|
228
210
|
}
|
|
229
211
|
}
|
|
230
212
|
}
|
|
231
213
|
return [
|
|
232
|
-
...
|
|
214
|
+
...found.values(),
|
|
233
215
|
];
|
|
234
216
|
},
|
|
235
217
|
};
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The running handles a `SubprocessAdapter` holds, each paired with the
|
|
3
|
+
* promise its `spawn()` caller waits on. A handle leaves the table the moment
|
|
4
|
+
* it settles, so callers hear about a finished child at once (no polling) and
|
|
5
|
+
* the adapter keeps nothing once the result is delivered.
|
|
6
|
+
*/
|
|
7
|
+
import type { SpawnedSubprocess, SubprocessHandle } from '@noetic-tools/types';
|
|
8
|
+
/** @public Running handles keyed by id; see `createLiveHandles`. */
|
|
9
|
+
export interface LiveHandles {
|
|
10
|
+
/** Tracks a running handle. Returns what `spawn()` hands back. */
|
|
11
|
+
add(handle: SubprocessHandle): SpawnedSubprocess;
|
|
12
|
+
/** The running handle with this id, or `undefined` once it has settled. */
|
|
13
|
+
get(handleId: string): SubprocessHandle | undefined;
|
|
14
|
+
/** Replaces a running handle, e.g. on pause or resume. Ignored once it has settled. */
|
|
15
|
+
update(handle: SubprocessHandle): void;
|
|
16
|
+
/**
|
|
17
|
+
* Ends a handle: resolves its `settled` with `handle` (which carries the
|
|
18
|
+
* final status) and forgets it. Returns `false`, changing nothing, when the
|
|
19
|
+
* handle already settled — a stopped child that finishes late, say.
|
|
20
|
+
*/
|
|
21
|
+
settle(handle: SubprocessHandle): boolean;
|
|
22
|
+
/** Every running handle. */
|
|
23
|
+
values(): IterableIterator<SubprocessHandle>;
|
|
24
|
+
}
|
|
25
|
+
/** @public Creates an empty `LiveHandles` table for a `SubprocessAdapter`. */
|
|
26
|
+
export declare function createLiveHandles(): LiveHandles;
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The running handles a `SubprocessAdapter` holds, each paired with the
|
|
3
|
+
* promise its `spawn()` caller waits on. A handle leaves the table the moment
|
|
4
|
+
* it settles, so callers hear about a finished child at once (no polling) and
|
|
5
|
+
* the adapter keeps nothing once the result is delivered.
|
|
6
|
+
*/
|
|
7
|
+
//#endregion
|
|
8
|
+
//#region Public API
|
|
9
|
+
/** @public Creates an empty `LiveHandles` table for a `SubprocessAdapter`. */
|
|
10
|
+
export function createLiveHandles() {
|
|
11
|
+
const entries = new Map();
|
|
12
|
+
return {
|
|
13
|
+
add(handle) {
|
|
14
|
+
const settled = new Promise((resolve) => {
|
|
15
|
+
entries.set(handle.id, {
|
|
16
|
+
handle,
|
|
17
|
+
resolve,
|
|
18
|
+
});
|
|
19
|
+
});
|
|
20
|
+
return {
|
|
21
|
+
handle,
|
|
22
|
+
settled,
|
|
23
|
+
};
|
|
24
|
+
},
|
|
25
|
+
get(handleId) {
|
|
26
|
+
return entries.get(handleId)?.handle;
|
|
27
|
+
},
|
|
28
|
+
update(handle) {
|
|
29
|
+
const entry = entries.get(handle.id);
|
|
30
|
+
if (entry) {
|
|
31
|
+
entry.handle = handle;
|
|
32
|
+
}
|
|
33
|
+
},
|
|
34
|
+
settle(handle) {
|
|
35
|
+
const entry = entries.get(handle.id);
|
|
36
|
+
if (!entry) {
|
|
37
|
+
return false;
|
|
38
|
+
}
|
|
39
|
+
entries.delete(handle.id);
|
|
40
|
+
entry.resolve(handle);
|
|
41
|
+
return true;
|
|
42
|
+
},
|
|
43
|
+
*values() {
|
|
44
|
+
for (const entry of entries.values()) {
|
|
45
|
+
yield entry.handle;
|
|
46
|
+
}
|
|
47
|
+
},
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
//#endregion
|
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
*/
|
|
5
5
|
import type { ContextData, ContextLayer } from '@noetic-tools/context';
|
|
6
6
|
import type { AgentHarnessContract, Context, Step, Tool } from '@noetic-tools/types';
|
|
7
|
+
import type { ExpressionLimits } from '../expression/jsonata.js';
|
|
7
8
|
import type { WorkflowDocument } from '../schemas/workflow.js';
|
|
8
9
|
/** @public Options for creating a dynamic workflow step. */
|
|
9
10
|
export interface DynamicWorkflowOpts {
|
|
@@ -12,6 +13,8 @@ export interface DynamicWorkflowOpts {
|
|
|
12
13
|
tools: Tool[];
|
|
13
14
|
maxDepth?: number;
|
|
14
15
|
maxRevisions?: number;
|
|
16
|
+
/** Bounds on each expression evaluation; unset fields use `DEFAULT_EXPRESSION_LIMITS`. */
|
|
17
|
+
expressionLimits?: ExpressionLimits;
|
|
15
18
|
}
|
|
16
19
|
/**
|
|
17
20
|
* Creates a step that uses an LLM to generate a workflow as JSON, then
|
|
@@ -24,7 +27,10 @@ export interface DynamicWorkflowOpts {
|
|
|
24
27
|
* @param opts.tools - Tools the generated workflow may reference by name.
|
|
25
28
|
* @param opts.maxDepth - Maximum workflow tree depth. Default: 5.
|
|
26
29
|
* @param opts.maxRevisions - Retries with error feedback on validation failure. Default: 3.
|
|
30
|
+
* @param opts.expressionLimits - Bounds on each expression evaluation. Default: `DEFAULT_EXPRESSION_LIMITS`.
|
|
27
31
|
* @returns A `Step` that dynamically plans and executes.
|
|
32
|
+
* @throws `NoeticConfigError` with code `INVALID_EXPRESSION_LIMITS` (at execution) if `expressionLimits` holds a value that is not a positive integer or `Infinity`.
|
|
33
|
+
* @throws `NoeticConfigError` with code `EXPRESSION_LIMIT_EXCEEDED` (at execution) if an expression in the generated workflow exceeds its limits.
|
|
28
34
|
*/
|
|
29
35
|
export declare function dynamicWorkflow(opts: DynamicWorkflowOpts): Step<ContextData, string, string>;
|
|
30
36
|
/** @public Options for `parseAndRunWorkflow`. */
|
|
@@ -43,6 +49,14 @@ export interface ParseAndRunWorkflowOpts {
|
|
|
43
49
|
layers?: ReadonlyMap<string, ContextLayer>;
|
|
44
50
|
/** Named sub-workflows the document's `subflow` nodes may reference via `ref`. */
|
|
45
51
|
workflows?: ReadonlyMap<string, WorkflowDocument>;
|
|
52
|
+
/**
|
|
53
|
+
* Deepest allowed chain of named-ref resolutions on one execution path —
|
|
54
|
+
* named workflows may recurse up to this depth. Positive integer or
|
|
55
|
+
* `Infinity`. Default: 100.
|
|
56
|
+
*/
|
|
57
|
+
maxRecursionDepth?: number;
|
|
58
|
+
/** Bounds on each expression evaluation; unset fields use `DEFAULT_EXPRESSION_LIMITS`. */
|
|
59
|
+
expressionLimits?: ExpressionLimits;
|
|
46
60
|
}
|
|
47
61
|
/**
|
|
48
62
|
* Parses raw JSON into a `WorkflowDocument`, hydrates it into a live step
|
|
@@ -54,8 +68,13 @@ export interface ParseAndRunWorkflowOpts {
|
|
|
54
68
|
* @param opts.ctx - Execution context.
|
|
55
69
|
* @param opts.tools - Available tools the workflow may reference.
|
|
56
70
|
* @param opts.maxDepth - Maximum workflow tree depth. Default: 5.
|
|
71
|
+
* @param opts.maxRecursionDepth - Deepest allowed chain of named-ref resolutions. Default: 100.
|
|
72
|
+
* @param opts.expressionLimits - Bounds on each expression evaluation. Default: `DEFAULT_EXPRESSION_LIMITS`.
|
|
57
73
|
* @returns The string output of the executed workflow.
|
|
58
74
|
* @throws `NoeticConfigError` with code `WORKFLOW_VALIDATION_FAILED` if JSON is invalid.
|
|
75
|
+
* @throws `NoeticConfigError` with code `WORKFLOW_RECURSION_LIMIT` if named refs nest deeper than `maxRecursionDepth`.
|
|
59
76
|
* @throws `NoeticConfigError` with code `UNKNOWN_TOOL_REFERENCE` if a tool reference cannot be resolved.
|
|
77
|
+
* @throws `NoeticConfigError` with code `INVALID_EXPRESSION_LIMITS` if `expressionLimits` holds a value that is not a positive integer or `Infinity`.
|
|
78
|
+
* @throws `NoeticConfigError` with code `EXPRESSION_LIMIT_EXCEEDED` if an expression exceeds its limits.
|
|
60
79
|
*/
|
|
61
80
|
export declare function parseAndRunWorkflow(opts: ParseAndRunWorkflowOpts): Promise<string>;
|
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
*/
|
|
5
5
|
import { exportSpans } from '@noetic-tools/context';
|
|
6
6
|
import { frameworkCast, NoeticConfigError } from '@noetic-tools/types';
|
|
7
|
+
import { expressionErrors } from '../expression/check.js';
|
|
7
8
|
import { NoeticAttr } from '../observability/genai-attributes.js';
|
|
8
9
|
import { WorkflowDocumentSchema, workflowDepth, workflowGraph } from '../schemas/workflow.js';
|
|
9
10
|
import { callModel, runCode } from './step-builders.js';
|
|
@@ -25,10 +26,11 @@ A WorkflowNode is one of:
|
|
|
25
26
|
- { "kind": "callModel", "id": "<unique>", "instructions": "<prompt>", "model": "<optional>", "tools": [{ "type": "<tool-name>" }, ...] } (one LLM call)
|
|
26
27
|
- { "kind": "invokeTool", "id": "<unique>", "toolName": "<name>", "args": { ... } } (call one tool directly, no LLM)
|
|
27
28
|
- { "kind": "runCode", "id": "<unique>", "execute": "<source code>" } (runs the code in a subprocess with the step input on stdin; only emit if the task needs deterministic computation AND a subprocess adapter is available)
|
|
29
|
+
- { "kind": "compute", "id": "<unique>", "expr": "<JSONata expression>" } (computes a value from the input, read as JSON, with no LLM; e.g. "{ 'n': n - 1, 'sum': sum + n }")
|
|
28
30
|
- { "kind": "sequence", "id": "<unique>", "steps": [<WorkflowNode>, ...] } (run children in order, threading each output into the next)
|
|
29
31
|
- { "kind": "inParallel", "id": "<unique>", "mode": "all"|"race"|"settle", "paths": [<WorkflowNode>, ...], "merge": "last"|"first"|"concat" } (fan out; supply exactly one of "paths" or "each": <WorkflowNode> — with "each", add "over": "<key>" to fan out over an array in the input JSON)
|
|
30
|
-
- { "kind": "loop", "id": "<unique>", "body": <WorkflowNode>, "until": <UntilPredicate>, "maxIterations": <optional
|
|
31
|
-
- { "kind": "conditional", "id": "<unique>", "routes": [{ "match": "<substring>", "target": <WorkflowNode> }], "default": <WorkflowNode> } (route on a substring of the input)
|
|
32
|
+
- { "kind": "loop", "id": "<unique>", "body": <WorkflowNode>, "until": <UntilPredicate>, "maxIterations": <optional positive int, or "infinity" for no cap> } (repeat the body until the predicate holds)
|
|
33
|
+
- { "kind": "conditional", "id": "<unique>", "routes": [{ "match": "<substring>", "target": <WorkflowNode> }], "default": <WorkflowNode> } (route on a substring of the input; a route may carry "expr": "<JSONata test, e.g. n > 3>" instead of "match", taken if the test gives true)
|
|
32
34
|
- { "kind": "spawn", "id": "<unique>", "child": <WorkflowNode>, "timeout": <optional ms> } (run the child in an isolated sub-context)
|
|
33
35
|
- { "kind": "withContext", "id": "<unique>", "child": <WorkflowNode>, "layers": ["<layer-name>", ...] } (run the child with named context layers; only emit if the task names layers that exist, since this planner provides no layer registry and unknown names resolve to NO layers)
|
|
34
36
|
- { "kind": "schedule", "id": "<unique>", "step": <WorkflowNode>, "interval": <ms>, "onError": "continue"|"fail" } (re-runs the step forever on an interval and never returns — only emit for an explicitly daemon-style task)
|
|
@@ -41,7 +43,8 @@ Every entry of a callModel node's "tools" is an OBJECT, never a bare string. Use
|
|
|
41
43
|
An acp-agent node delegates a turn to an external coding agent over the Agent Client Protocol; only emit one if a matching agent adapter is registered for the workflow.
|
|
42
44
|
|
|
43
45
|
An UntilPredicate (the "until" field of a loop) is one of:
|
|
44
|
-
{ "kind": "maxSteps", "n": <positive int> }, { "kind": "maxCost", "usd": <positive number> }, { "kind": "maxDuration", "duration": <ms> }, { "kind": "noToolCalls" }, { "kind": "never" } (never stops — pair with "maxIterations"), { "kind": "outputContains", "marker": "<text>" }, { "kind": "outputEquals", "sentinel": "<text>" }, { "kind": "converged", "threshold": <optional 0-1> }, { "kind": "any", "predicates": [<UntilPredicate>, ...] }, { "kind": "all", "predicates": [<UntilPredicate>, ...] }.
|
|
46
|
+
{ "kind": "maxSteps", "n": <positive int> }, { "kind": "maxCost", "usd": <positive number> }, { "kind": "maxDuration", "duration": <ms> }, { "kind": "noToolCalls" }, { "kind": "never" } (never stops — pair with "maxIterations"), { "kind": "outputContains", "marker": "<text>" }, { "kind": "outputEquals", "sentinel": "<text>" }, { "kind": "converged", "threshold": <optional 0-1> }, { "kind": "expr", "expr": "<JSONata test on the last output, true stops, e.g. n = 0>" }, { "kind": "any", "predicates": [<UntilPredicate>, ...] }, { "kind": "all", "predicates": [<UntilPredicate>, ...] }.
|
|
47
|
+
A loop's "until" (or an entry of "any"/"all") may also be a decide node asking exactly one boolean question: { "kind": "decide", "id": "<unique>", "questions": { "<question-id>": { "type": "boolean", "instructions": "<question whose yes means stop>" } } } — a model reads the iteration's output; yes stops the loop, no or a refusal runs another iteration.
|
|
45
48
|
|
|
46
49
|
Respond with ONLY the JSON document, no markdown fences or explanation.`;
|
|
47
50
|
//#endregion
|
|
@@ -57,7 +60,10 @@ Respond with ONLY the JSON document, no markdown fences or explanation.`;
|
|
|
57
60
|
* @param opts.tools - Tools the generated workflow may reference by name.
|
|
58
61
|
* @param opts.maxDepth - Maximum workflow tree depth. Default: 5.
|
|
59
62
|
* @param opts.maxRevisions - Retries with error feedback on validation failure. Default: 3.
|
|
63
|
+
* @param opts.expressionLimits - Bounds on each expression evaluation. Default: `DEFAULT_EXPRESSION_LIMITS`.
|
|
60
64
|
* @returns A `Step` that dynamically plans and executes.
|
|
65
|
+
* @throws `NoeticConfigError` with code `INVALID_EXPRESSION_LIMITS` (at execution) if `expressionLimits` holds a value that is not a positive integer or `Infinity`.
|
|
66
|
+
* @throws `NoeticConfigError` with code `EXPRESSION_LIMIT_EXCEEDED` (at execution) if an expression in the generated workflow exceeds its limits.
|
|
61
67
|
*/
|
|
62
68
|
export function dynamicWorkflow(opts) {
|
|
63
69
|
const model = opts.model ?? DEFAULT_MODEL;
|
|
@@ -112,6 +118,7 @@ export function dynamicWorkflow(opts) {
|
|
|
112
118
|
const hydrationCtx = {
|
|
113
119
|
tools: toolMap,
|
|
114
120
|
executeStep,
|
|
121
|
+
expressionLimits: opts.expressionLimits,
|
|
115
122
|
};
|
|
116
123
|
const hydrated = hydrateWorkflow(parseResult.doc, hydrationCtx);
|
|
117
124
|
return frameworkCast(await executeStep(hydrated, input, ctx));
|
|
@@ -134,9 +141,14 @@ export function dynamicWorkflow(opts) {
|
|
|
134
141
|
* @param opts.ctx - Execution context.
|
|
135
142
|
* @param opts.tools - Available tools the workflow may reference.
|
|
136
143
|
* @param opts.maxDepth - Maximum workflow tree depth. Default: 5.
|
|
144
|
+
* @param opts.maxRecursionDepth - Deepest allowed chain of named-ref resolutions. Default: 100.
|
|
145
|
+
* @param opts.expressionLimits - Bounds on each expression evaluation. Default: `DEFAULT_EXPRESSION_LIMITS`.
|
|
137
146
|
* @returns The string output of the executed workflow.
|
|
138
147
|
* @throws `NoeticConfigError` with code `WORKFLOW_VALIDATION_FAILED` if JSON is invalid.
|
|
148
|
+
* @throws `NoeticConfigError` with code `WORKFLOW_RECURSION_LIMIT` if named refs nest deeper than `maxRecursionDepth`.
|
|
139
149
|
* @throws `NoeticConfigError` with code `UNKNOWN_TOOL_REFERENCE` if a tool reference cannot be resolved.
|
|
150
|
+
* @throws `NoeticConfigError` with code `INVALID_EXPRESSION_LIMITS` if `expressionLimits` holds a value that is not a positive integer or `Infinity`.
|
|
151
|
+
* @throws `NoeticConfigError` with code `EXPRESSION_LIMIT_EXCEEDED` if an expression exceeds its limits.
|
|
140
152
|
*/
|
|
141
153
|
export async function parseAndRunWorkflow(opts) {
|
|
142
154
|
const parseResult = tryParseWorkflow(opts.json, opts.maxDepth ?? DEFAULT_MAX_DEPTH);
|
|
@@ -153,6 +165,8 @@ export async function parseAndRunWorkflow(opts) {
|
|
|
153
165
|
executeStep,
|
|
154
166
|
layers: opts.layers,
|
|
155
167
|
workflows: opts.workflows,
|
|
168
|
+
maxRecursionDepth: opts.maxRecursionDepth,
|
|
169
|
+
expressionLimits: opts.expressionLimits,
|
|
156
170
|
};
|
|
157
171
|
const hydrated = hydrateWorkflow(parseResult.doc, hydrationCtx);
|
|
158
172
|
const runSpan = beginWorkflowRunSpan(opts.harness, opts.ctx, parseResult.doc);
|
|
@@ -229,6 +243,13 @@ function tryParseWorkflow(raw, maxDepth) {
|
|
|
229
243
|
error: `Workflow tree depth ${depth} exceeds maximum ${maxDepth}.`,
|
|
230
244
|
};
|
|
231
245
|
}
|
|
246
|
+
const errors = expressionErrors(result.data.root);
|
|
247
|
+
if (errors.length > 0) {
|
|
248
|
+
return {
|
|
249
|
+
ok: false,
|
|
250
|
+
error: errors.join(' '),
|
|
251
|
+
};
|
|
252
|
+
}
|
|
232
253
|
return {
|
|
233
254
|
ok: true,
|
|
234
255
|
doc: result.data,
|
|
@@ -8,8 +8,9 @@ export type LoopConfig<TContext = ContextData, I = unknown, O = unknown> = Omit<
|
|
|
8
8
|
* @public
|
|
9
9
|
* @param opts.id - Unique step identifier used in traces and error messages.
|
|
10
10
|
* @param opts.steps - Array of steps to execute sequentially on each iteration.
|
|
11
|
-
* @param opts.until - Termination predicate `(snapshot) => Verdict | Promise<Verdict>` evaluated after each iteration
|
|
12
|
-
*
|
|
11
|
+
* @param opts.until - Termination predicate `(snapshot) => Verdict | Promise<Verdict>` evaluated after each iteration,
|
|
12
|
+
* or a decide step asking one boolean question (yes stops; no or a refusal continues).
|
|
13
|
+
* @param opts.maxIterations - Hard cap on iterations (default: 1000); `Infinity` removes it.
|
|
13
14
|
* @param opts.maxHistorySize - Maximum entries kept in the snapshot history array (default: 100); oldest drop first.
|
|
14
15
|
* @param opts.inbox - Optional channel for injecting messages into the loop mid-execution.
|
|
15
16
|
* @param opts.parkTimeout - Ms to wait on inbox before the loop parks itself (default: 0).
|
|
@@ -19,5 +20,6 @@ export type LoopConfig<TContext = ContextData, I = unknown, O = unknown> = Omit<
|
|
|
19
20
|
* @throws `NoeticConfigError` with code `EMPTY_STEP_ID` if `id` is empty.
|
|
20
21
|
* @throws `NoeticConfigError` with code `MISSING_LOOP_BODY` if `steps` is empty.
|
|
21
22
|
* @throws `NoeticConfigError` with code `MISSING_UNTIL_PREDICATE` if `until` is not provided.
|
|
23
|
+
* @throws `NoeticConfigError` with code `INVALID_UNTIL_DECIDER` if `until` is a decide step that does not ask exactly one boolean question.
|
|
22
24
|
*/
|
|
23
25
|
export declare function loop<TContext = ContextData, I = unknown, O = unknown>(opts: LoopConfig<TContext, I, O>): StepLoop<TContext, I, O>;
|
|
@@ -1,13 +1,15 @@
|
|
|
1
1
|
import { NoeticConfigError } from '@noetic-tools/types';
|
|
2
2
|
import { getDefaultRegistrar } from '../types/step-registrar.js';
|
|
3
|
+
import { toUntil } from '../until/decider.js';
|
|
3
4
|
/**
|
|
4
5
|
* Creates a loop step that iterates a body step until a termination predicate is satisfied.
|
|
5
6
|
*
|
|
6
7
|
* @public
|
|
7
8
|
* @param opts.id - Unique step identifier used in traces and error messages.
|
|
8
9
|
* @param opts.steps - Array of steps to execute sequentially on each iteration.
|
|
9
|
-
* @param opts.until - Termination predicate `(snapshot) => Verdict | Promise<Verdict>` evaluated after each iteration
|
|
10
|
-
*
|
|
10
|
+
* @param opts.until - Termination predicate `(snapshot) => Verdict | Promise<Verdict>` evaluated after each iteration,
|
|
11
|
+
* or a decide step asking one boolean question (yes stops; no or a refusal continues).
|
|
12
|
+
* @param opts.maxIterations - Hard cap on iterations (default: 1000); `Infinity` removes it.
|
|
11
13
|
* @param opts.maxHistorySize - Maximum entries kept in the snapshot history array (default: 100); oldest drop first.
|
|
12
14
|
* @param opts.inbox - Optional channel for injecting messages into the loop mid-execution.
|
|
13
15
|
* @param opts.parkTimeout - Ms to wait on inbox before the loop parks itself (default: 0).
|
|
@@ -17,6 +19,7 @@ import { getDefaultRegistrar } from '../types/step-registrar.js';
|
|
|
17
19
|
* @throws `NoeticConfigError` with code `EMPTY_STEP_ID` if `id` is empty.
|
|
18
20
|
* @throws `NoeticConfigError` with code `MISSING_LOOP_BODY` if `steps` is empty.
|
|
19
21
|
* @throws `NoeticConfigError` with code `MISSING_UNTIL_PREDICATE` if `until` is not provided.
|
|
22
|
+
* @throws `NoeticConfigError` with code `INVALID_UNTIL_DECIDER` if `until` is a decide step that does not ask exactly one boolean question.
|
|
20
23
|
*/
|
|
21
24
|
export function loop(opts) {
|
|
22
25
|
if (!opts.id || opts.id.trim() === '') {
|
|
@@ -40,6 +43,8 @@ export function loop(opts) {
|
|
|
40
43
|
hint: 'Provide an until predicate, e.g. until.maxSteps(10).',
|
|
41
44
|
});
|
|
42
45
|
}
|
|
46
|
+
// Checks a decide step here, so a bad decider fails at build time, not mid-run.
|
|
47
|
+
toUntil(opts.until);
|
|
43
48
|
const built = {
|
|
44
49
|
kind: 'loop',
|
|
45
50
|
...opts,
|