@noetic-tools/core 5.12.0 → 5.14.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.
Files changed (53) hide show
  1. package/dist/adapters/in-memory-subprocess/step-completion.d.ts +2 -2
  2. package/dist/adapters/in-memory-subprocess/step-completion.js +48 -52
  3. package/dist/adapters/in-memory-subprocess/types.d.ts +3 -6
  4. package/dist/adapters/in-memory-subprocess-adapter.js +30 -48
  5. package/dist/adapters/live-handles.d.ts +26 -0
  6. package/dist/adapters/live-handles.js +50 -0
  7. package/dist/builders/decide-builders.d.ts +2 -2
  8. package/dist/builders/dynamic-workflow.js +2 -0
  9. package/dist/builders/provide-builder.d.ts +2 -2
  10. package/dist/builders/spawn-builder.d.ts +2 -2
  11. package/dist/builders/step-builders.d.ts +5 -5
  12. package/dist/builders/workflow-hydrator.d.ts +1 -1
  13. package/dist/builders/workflow-hydrator.js +54 -6
  14. package/dist/expression/check.js +14 -0
  15. package/dist/expression/jsonata.d.ts +7 -0
  16. package/dist/expression/jsonata.js +11 -1
  17. package/dist/harness/agent-harness.d.ts +59 -5
  18. package/dist/harness/agent-harness.js +176 -25
  19. package/dist/harness/deps/runtime.d.ts +4 -0
  20. package/dist/harness/deps/runtime.js +2 -0
  21. package/dist/harness/model-call.js +69 -0
  22. package/dist/harness/model-rounds.d.ts +52 -0
  23. package/dist/harness/model-rounds.js +115 -0
  24. package/dist/harness/thread-record.d.ts +54 -0
  25. package/dist/harness/thread-record.js +159 -0
  26. package/dist/index.d.ts +7 -3
  27. package/dist/index.js +2 -0
  28. package/dist/interpreter/emit-items.d.ts +19 -0
  29. package/dist/interpreter/emit-items.js +106 -0
  30. package/dist/interpreter/execute-action.js +3 -0
  31. package/dist/interpreter/execute-control.js +3 -0
  32. package/dist/interpreter/execute.js +67 -12
  33. package/dist/interpreter/step-dispatcher.d.ts +2 -2
  34. package/dist/interpreter/step-dispatcher.js +3 -5
  35. package/dist/runtime/context-impl.d.ts +106 -4
  36. package/dist/runtime/context-impl.js +224 -14
  37. package/dist/runtime/durable/harness-checkpoints.d.ts +13 -3
  38. package/dist/runtime/durable/harness-checkpoints.js +66 -7
  39. package/dist/runtime/durable/session-store.d.ts +37 -0
  40. package/dist/runtime/durable/session-store.js +58 -0
  41. package/dist/runtime/durable/step-ledger.d.ts +77 -40
  42. package/dist/runtime/durable/step-ledger.js +193 -73
  43. package/dist/runtime/item-log-impl.d.ts +6 -0
  44. package/dist/runtime/item-log-impl.js +12 -0
  45. package/dist/runtime/session-runner.d.ts +25 -1
  46. package/dist/runtime/session-runner.js +83 -11
  47. package/dist/schemas/workflow.d.ts +1 -1
  48. package/dist/types/checkpoint.d.ts +21 -4
  49. package/dist/types/checkpoint.js +33 -3
  50. package/dist/util/detached-handle.d.ts +9 -20
  51. package/dist/util/detached-handle.js +7 -108
  52. package/package.json +2 -2
  53. package/schema/noetic-workflow.schema.json +391 -0
@@ -1,3 +1,3 @@
1
1
  import type { CompleteProcessRunParams, CompleteStepRunParams } from './types.js';
2
- export declare function completeProcessRun({ request, handle, run, handles, active, save, clearIfDurable, }: CompleteProcessRunParams): Promise<void>;
3
- export declare function completeStepRun({ request, handle, stepRunner, handles, active, save, clearIfDurable, }: CompleteStepRunParams): Promise<void>;
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, handles, active, save, clearIfDurable, }) {
3
+ export async function completeProcessRun({ request, handle, run, live, clearIfDurable, }) {
4
4
  try {
5
5
  await run?.(request, handle);
6
- const latest = handles.get(handle.id);
7
- if (!latest || latest.status !== 'running') {
8
- return;
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
- active.delete(handle.id);
24
- const latest = handles.get(handle.id) ?? handle;
25
- await save({
26
- ...latest,
14
+ await finish({
15
+ live,
16
+ clearIfDurable,
17
+ }, handle.id, {
27
18
  status: 'failed',
28
- updatedAt: nowIso(),
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, handles, active, save, clearIfDurable, }) {
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
- const latest = handles.get(handle.id);
54
- if (!latest || latest.status !== 'running') {
55
- return;
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
- updatedAt: nowIso(),
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
- active.delete(handle.id);
73
- const latest = handles.get(handle.id) ?? handle;
74
- await save({
75
- ...latest,
46
+ await finish({
47
+ live,
48
+ clearIfDurable,
49
+ }, handle.id, {
76
50
  status: 'failed',
77
- updatedAt: nowIso(),
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
- handles: Map<string, SubprocessHandle>;
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
- handles: Map<string, SubprocessHandle>;
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 handles = new Map();
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 handle = {
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
- active.add(handle.id);
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
- handles,
76
- active,
77
- save,
69
+ live,
78
70
  clearIfDurable,
79
71
  });
80
- return handle;
72
+ return spawned;
81
73
  }
82
- async function spawnProcessHandle(request) {
74
+ function spawnProcessHandle(request) {
83
75
  const now = nowIso();
84
- const handle = {
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
- handles,
98
- active,
99
- save,
87
+ live,
100
88
  clearIfDurable,
101
89
  });
102
- return handle;
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 handles.get(handleId) ?? null;
125
+ return live.get(handleId) ?? null;
138
126
  },
139
127
  async stop(handleId, reason) {
140
- const handle = handles.get(handleId);
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
- active.delete(handleId);
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 = handles.get(handleId);
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 = handles.get(handleId);
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 active.has(handle.id);
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
- const handle = handleFromManifest(manifest);
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 live = new Map();
217
- for (const id of active) {
218
- const handle = handles.get(id);
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 (!live.has(manifest.handleId)) {
227
- live.set(manifest.handleId, handleFromManifest(manifest));
208
+ if (!found.has(manifest.handleId)) {
209
+ found.set(manifest.handleId, handleFromManifest(manifest));
228
210
  }
229
211
  }
230
212
  }
231
213
  return [
232
- ...live.values(),
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
@@ -1,6 +1,6 @@
1
- import type { AnsweredAll, CaseKeyOf, Context, ContextData, DecideQuestions, DecideStep, DecideView, Lazy, ProjectionPolicy, Step, StepConditional, StepReplay } from '@noetic-tools/types';
1
+ import type { AnsweredAll, CaseKeyOf, Context, ContextData, DecideAnswers, DecideQuestions, DecideStep, DecideView, Lazy, ProjectionPolicy, Step, StepConditional, StepEmitItems, StepReplay } from '@noetic-tools/types';
2
2
  /** @public Options for `decide()`. */
3
- export interface StepDecideOpts<TContext, Q extends DecideQuestions, I = unknown> extends StepReplay<TContext, I> {
3
+ export interface StepDecideOpts<TContext, Q extends DecideQuestions, I = unknown> extends StepReplay<TContext, I>, StepEmitItems<TContext, DecideAnswers<Q>> {
4
4
  id: string;
5
5
  /** Decision model id. Falls back to `harness.config.decisionModel`. */
6
6
  model?: Lazy<string, TContext>;
@@ -40,6 +40,8 @@ A WorkflowNode is one of:
40
40
 
41
41
  Every entry of a callModel node's "tools" is an OBJECT, never a bare string. Use { "type": "<tool-name>" } to let the model call one of the tools listed below. Two provider-executed tools are also available without being listed: { "type": "openrouter:web_search" } and { "type": "openrouter:web_fetch" }, each accepting an optional "parameters" object.
42
42
 
43
+ Any node may carry "emitItems": true to show its output to the user as an assistant message the moment it finishes, or "emitItems": { "expr": "<JSONata expression on the output, e.g. 'Done ' & n & ' items'>" } to show computed text (no value shows nothing). Add "as": "items" to emit conversation items instead (the expression, or the output itself, must give an object with a string "type", or a list of them; only use custom "prefix:name" types the task says are registered). Use it for progress inside loops: only the workflow's final output is shown otherwise.
44
+
43
45
  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.
44
46
 
45
47
  An UntilPredicate (the "until" field of a loop) is one of:
@@ -1,6 +1,6 @@
1
1
  import type { ContextConfig, ContextData, ContextLayer } from '@noetic-tools/context';
2
- import type { Step, StepReplay, StepWithContext } from '@noetic-tools/types';
3
- export interface WithContextOpts<TContext, I, O> extends StepReplay<TContext, I> {
2
+ import type { Step, StepEmitItems, StepReplay, StepWithContext } from '@noetic-tools/types';
3
+ export interface WithContextOpts<TContext, I, O> extends StepReplay<TContext, I>, StepEmitItems<TContext, O> {
4
4
  id: string;
5
5
  child: Step<TContext, I, O>;
6
6
  context: ContextConfig | ContextLayer[];
@@ -1,11 +1,11 @@
1
1
  import type { ContextConfig, ContextData, ContextLayer } from '@noetic-tools/context';
2
- import type { Step, StepReplay, StepSpawn, SubprocessAdapter } from '@noetic-tools/types';
2
+ import type { Step, StepEmitItems, StepReplay, StepSpawn, SubprocessAdapter } from '@noetic-tools/types';
3
3
  /**
4
4
  * Options for {@link spawn}.
5
5
  *
6
6
  * @public
7
7
  */
8
- export interface SpawnOpts<TContext = ContextData, I = unknown, O = unknown> extends StepReplay<TContext, I> {
8
+ export interface SpawnOpts<TContext = ContextData, I = unknown, O = unknown> extends StepReplay<TContext, I>, StepEmitItems<TContext, O> {
9
9
  id: string;
10
10
  child: Step<TContext, I, O>;
11
11
  context?: ContextConfig | ContextLayer[];
@@ -1,6 +1,6 @@
1
1
  import type { ContextData } from '@noetic-tools/context';
2
- import type { AcpAgent, AcpClientCapabilityConfig, AcpContentBlock, AcpMcpServer, AcpPermissionHandler, AcpPermissionPolicy, AcpSessionPolicy, Context, Lazy, ModelParams, OutputCodec, RetryPolicy, ServerToolSpec, StandardSchemaV1, StepAcpAgent, StepCallModel, StepInvokeTool, StepReplay, StepRunCode, SubprocessAdapter, Tool, ToolChoice } from '@noetic-tools/types';
3
- export interface RunCodeOpts<TContext, I, O> extends StepReplay<TContext, I> {
2
+ import type { AcpAgent, AcpClientCapabilityConfig, AcpContentBlock, AcpMcpServer, AcpPermissionHandler, AcpPermissionPolicy, AcpSessionPolicy, Context, Lazy, ModelParams, OutputCodec, RetryPolicy, ServerToolSpec, StandardSchemaV1, StepAcpAgent, StepCallModel, StepEmitItems, StepInvokeTool, StepReplay, StepRunCode, SubprocessAdapter, Tool, ToolChoice } from '@noetic-tools/types';
3
+ export interface RunCodeOpts<TContext, I, O> extends StepReplay<TContext, I>, StepEmitItems<TContext, O> {
4
4
  id: string;
5
5
  execute: (input: I, ctx: Context<TContext>) => Promise<O>;
6
6
  retry?: RetryPolicy;
@@ -11,7 +11,7 @@ export interface RunCodeOpts<TContext, I, O> extends StepReplay<TContext, I> {
11
11
  */
12
12
  subprocess?: SubprocessAdapter;
13
13
  }
14
- export interface CallModelOpts<TContext, O, I = unknown> extends StepReplay<TContext, I> {
14
+ export interface CallModelOpts<TContext, O, I = unknown> extends StepReplay<TContext, I>, StepEmitItems<TContext, O> {
15
15
  id: string;
16
16
  /** Model id. Eager string or `(ctx) => string` getter (resolved at step execution). */
17
17
  model: Lazy<string, TContext>;
@@ -38,12 +38,12 @@ export interface CallModelOpts<TContext, O, I = unknown> extends StepReplay<TCon
38
38
  params?: ModelParams;
39
39
  emit?: boolean | ((eventType: string, data: Record<string, unknown>) => boolean);
40
40
  }
41
- export interface InvokeToolOpts<I, O, TContext = ContextData> extends StepReplay<TContext, I> {
41
+ export interface InvokeToolOpts<I, O, TContext = ContextData> extends StepReplay<TContext, I>, StepEmitItems<TContext, O> {
42
42
  id: string;
43
43
  tool: Tool<StandardSchemaV1<unknown, I>, StandardSchemaV1<unknown, O>>;
44
44
  args?: Partial<I>;
45
45
  }
46
- export interface StepAcpAgentOpts<TContext, O, I = unknown> extends StepReplay<TContext, I> {
46
+ export interface StepAcpAgentOpts<TContext, O, I = unknown> extends StepReplay<TContext, I>, StepEmitItems<TContext, O> {
47
47
  id: string;
48
48
  /** An ACP agent adapter, e.g. `claudeCode()` from `@noetic-tools/acp`. Eager or `(ctx) => AcpAgent`. */
49
49
  agent: Lazy<AcpAgent, TContext>;
@@ -66,7 +66,7 @@ export interface HydrationContext {
66
66
  * @throws `NoeticConfigError` with code `UNKNOWN_WORKFLOW_REFERENCE` (at execution time) if a subflow ref names no registered workflow.
67
67
  * @throws `NoeticConfigError` with code `WORKFLOW_RECURSION_LIMIT` (at execution time) if named sub-workflow refs nest deeper than `maxRecursionDepth`.
68
68
  * @throws `NoeticConfigError` with code `INVALID_MAX_RECURSION_DEPTH` (at execution time) when a named ref resolves under a `maxRecursionDepth` that is not a positive integer or `Infinity`.
69
- * @throws `NoeticConfigError` with code `WORKFLOW_VALIDATION_FAILED` if a `compute` expression, a conditional route's `expr`, or an `expr` until predicate does not parse.
69
+ * @throws `NoeticConfigError` with code `WORKFLOW_VALIDATION_FAILED` if a `compute` expression, a conditional route's `expr`, an `expr` until predicate, or an `emitItems` expression does not parse.
70
70
  * @throws `NoeticConfigError` with code `INVALID_EXPRESSION_LIMITS` if an expression compiles under `expressionLimits` holding a value that is not a positive integer or `Infinity`.
71
71
  * @throws `NoeticConfigError` with code `EXPRESSION_FAILED` or `EXPRESSION_LIMIT_EXCEEDED` (at execution time) if an expression fails or exceeds its limits.
72
72
  */
@@ -5,8 +5,8 @@
5
5
  * `loop`, etc.) so hydrated steps are indistinguishable from programmatic
6
6
  * ones — they register in the step registry, carry retry policies, etc.
7
7
  */
8
- import { frameworkCast, isServerToolSpec, NoeticConfigError } from '@noetic-tools/types';
9
- import { compileExpression, compute, passes, readInput } from '../expression/jsonata.js';
8
+ import { frameworkCast, ItemSchema, isServerToolSpec, NoeticConfigError, } from '@noetic-tools/types';
9
+ import { compileExpression, compute, computeMaybe, passes, readInput } from '../expression/jsonata.js';
10
10
  import { all, any } from '../until/combinators.js';
11
11
  import { until } from '../until/predicates.js';
12
12
  import { DetachedHandleImpl } from '../util/detached-handle.js';
@@ -650,6 +650,53 @@ function parseJsonObject(text) {
650
650
  return text;
651
651
  }
652
652
  }
653
+ /**
654
+ * The object form of a node's `emitItems` builds an emit function: the value is the
655
+ * `expr` result, or the output itself read as JSON, and no value emits nothing, so one
656
+ * node can emit on some iterations of a loop and stay quiet on others.
657
+ */
658
+ function workflowEmitItems(nodeId, option, ctx) {
659
+ if (typeof option === 'boolean') {
660
+ return option;
661
+ }
662
+ const where = `emitItems of node '${nodeId}'`;
663
+ const expr = option.expr === undefined
664
+ ? undefined
665
+ : compileExpression(option.expr, where, ctx.expressionLimits);
666
+ const asItems = option.as === 'items';
667
+ if (!expr && !asItems) {
668
+ return true;
669
+ }
670
+ return async (output) => {
671
+ const value = expr ? await computeMaybe(expr, readInput(output)) : readInput(output);
672
+ if (value === undefined) {
673
+ return undefined;
674
+ }
675
+ return asItems ? itemList(value, where) : stringifyResult(value);
676
+ };
677
+ }
678
+ /**
679
+ * Reads a value as items: one object or a list of them, each with a string `type`.
680
+ * Whether a type is allowed is the item log's call, against the harness's item schemas.
681
+ *
682
+ * @throws `NoeticConfigError` with code `INVALID_EMIT_ITEMS` when the value is not an
683
+ * item or a list of items.
684
+ */
685
+ function itemList(value, where) {
686
+ const list = Array.isArray(value)
687
+ ? value
688
+ : [
689
+ value,
690
+ ];
691
+ if (!list.every((entry) => ItemSchema.safeParse(entry).success)) {
692
+ throw new NoeticConfigError({
693
+ code: 'INVALID_EMIT_ITEMS',
694
+ message: `The ${where} gave ${JSON.stringify(value)}, which is not an item or a list of items.`,
695
+ hint: 'With "as": "items", give an object with a string "type" (e.g. { "type": "message", "role": "assistant", ... } or a registered custom type like "myapp:progress"), or a list of them.',
696
+ });
697
+ }
698
+ return frameworkCast(list);
699
+ }
653
700
  function stringifyResult(value) {
654
701
  if (typeof value === 'string') {
655
702
  return value;
@@ -791,12 +838,10 @@ async function runCodeViaSubprocess(opts) {
791
838
  input,
792
839
  },
793
840
  };
794
- const spawnPromise = adapter.spawn(request);
795
841
  const handle = new DetachedHandleImpl({
796
842
  id: `run-${nodeId}`,
797
843
  stepId: nodeId,
798
- adapter,
799
- spawnPromise,
844
+ spawned: adapter.spawn(request),
800
845
  });
801
846
  const result = await handle.await();
802
847
  return stringifyResult(result);
@@ -817,7 +862,7 @@ async function runCodeViaSubprocess(opts) {
817
862
  * @throws `NoeticConfigError` with code `UNKNOWN_WORKFLOW_REFERENCE` (at execution time) if a subflow ref names no registered workflow.
818
863
  * @throws `NoeticConfigError` with code `WORKFLOW_RECURSION_LIMIT` (at execution time) if named sub-workflow refs nest deeper than `maxRecursionDepth`.
819
864
  * @throws `NoeticConfigError` with code `INVALID_MAX_RECURSION_DEPTH` (at execution time) when a named ref resolves under a `maxRecursionDepth` that is not a positive integer or `Infinity`.
820
- * @throws `NoeticConfigError` with code `WORKFLOW_VALIDATION_FAILED` if a `compute` expression, a conditional route's `expr`, or an `expr` until predicate does not parse.
865
+ * @throws `NoeticConfigError` with code `WORKFLOW_VALIDATION_FAILED` if a `compute` expression, a conditional route's `expr`, an `expr` until predicate, or an `emitItems` expression does not parse.
821
866
  * @throws `NoeticConfigError` with code `INVALID_EXPRESSION_LIMITS` if an expression compiles under `expressionLimits` holding a value that is not a positive integer or `Infinity`.
822
867
  * @throws `NoeticConfigError` with code `EXPRESSION_FAILED` or `EXPRESSION_LIMIT_EXCEEDED` (at execution time) if an expression fails or exceeds its limits.
823
868
  */
@@ -838,6 +883,9 @@ export function hydrateNode(node, ctx) {
838
883
  if (node.replayKey !== undefined) {
839
884
  hydrated.replayKey = workflowReplayKey(node.id, node.replayKey);
840
885
  }
886
+ if (node.emitItems !== undefined) {
887
+ hydrated.emitItems = workflowEmitItems(node.id, node.emitItems, ctx);
888
+ }
841
889
  return hydrated;
842
890
  }
843
891
  /**
@@ -26,6 +26,20 @@ export function expressionErrors(root) {
26
26
  //#endregion
27
27
  //#region Helpers
28
28
  function expressionsOf(node) {
29
+ const emitted = typeof node.emitItems === 'object' && node.emitItems.expr !== undefined
30
+ ? [
31
+ {
32
+ where: `emitItems of node '${node.id}'`,
33
+ source: node.emitItems.expr,
34
+ },
35
+ ]
36
+ : [];
37
+ return [
38
+ ...emitted,
39
+ ...kindExpressionsOf(node),
40
+ ];
41
+ }
42
+ function kindExpressionsOf(node) {
29
43
  if (node.kind === 'compute') {
30
44
  return [
31
45
  {
@@ -49,6 +49,13 @@ export declare function syntaxError(source: string): string | undefined;
49
49
  * @throws `NoeticConfigError` with code `EXPRESSION_FAILED` or `EXPRESSION_LIMIT_EXCEEDED`.
50
50
  */
51
51
  export declare function compute(expr: CompiledExpression, input: unknown): Promise<unknown>;
52
+ /**
53
+ * Evaluates like `compute`, except that "no value" resolves to `undefined`
54
+ * instead of failing, for callers where nothing is a valid answer.
55
+ *
56
+ * @throws `NoeticConfigError` with code `EXPRESSION_FAILED` or `EXPRESSION_LIMIT_EXCEEDED`.
57
+ */
58
+ export declare function computeMaybe(expr: CompiledExpression, input: unknown): Promise<unknown>;
52
59
  /**
53
60
  * Evaluates an `expr` test. `true` passes; `false` and JSONata's "no value"
54
61
  * (`undefined`, e.g. a path that matched nothing) do not; anything else fails.