@noetic-tools/core 5.15.1 → 5.16.1

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 (43) hide show
  1. package/dist/builders/custom-item.d.ts +37 -0
  2. package/dist/builders/custom-item.js +118 -0
  3. package/dist/builders/decide-builders.d.ts +1 -1
  4. package/dist/builders/dynamic-workflow.js +1 -1
  5. package/dist/builders/output-text.d.ts +5 -0
  6. package/dist/builders/output-text.js +13 -0
  7. package/dist/builders/provide-builder.d.ts +1 -1
  8. package/dist/builders/spawn-builder.d.ts +1 -1
  9. package/dist/builders/step-builders.d.ts +8 -7
  10. package/dist/builders/step-builders.js +2 -0
  11. package/dist/builders/workflow-custom-items.d.ts +38 -0
  12. package/dist/builders/workflow-custom-items.js +118 -0
  13. package/dist/builders/workflow-hydrator.d.ts +9 -2
  14. package/dist/builders/workflow-hydrator.js +41 -71
  15. package/dist/builders/workflow-step.d.ts +23 -5
  16. package/dist/builders/workflow-step.js +28 -13
  17. package/dist/expression/check.js +9 -5
  18. package/dist/harness/agent-harness.d.ts +19 -9
  19. package/dist/harness/agent-harness.js +18 -5
  20. package/dist/harness/deps/interpreter.d.ts +1 -0
  21. package/dist/harness/deps/interpreter.js +1 -0
  22. package/dist/harness/deps/runtime.d.ts +1 -0
  23. package/dist/harness/deps/runtime.js +1 -0
  24. package/dist/harness/deps/types.d.ts +1 -1
  25. package/dist/index.d.ts +7 -3
  26. package/dist/index.js +6 -0
  27. package/dist/interpreter/emit-items.d.ts +38 -8
  28. package/dist/interpreter/emit-items.js +267 -17
  29. package/dist/interpreter/execute-action.js +3 -1
  30. package/dist/interpreter/execute.js +4 -1
  31. package/dist/runtime/context-impl.d.ts +13 -1
  32. package/dist/runtime/context-impl.js +30 -0
  33. package/dist/runtime/durable/harness-checkpoints.js +21 -1
  34. package/dist/runtime/item-gates.d.ts +8 -0
  35. package/dist/runtime/item-gates.js +15 -0
  36. package/dist/runtime/item-log-impl.d.ts +7 -1
  37. package/dist/runtime/item-log-impl.js +8 -0
  38. package/dist/runtime/session-streams.js +8 -0
  39. package/dist/schemas/workflow.d.ts +1 -1
  40. package/dist/types/checkpoint.d.ts +1 -0
  41. package/dist/types/checkpoint.js +5 -0
  42. package/package.json +2 -2
  43. package/schema/noetic-workflow.schema.json +803 -119
@@ -0,0 +1,37 @@
1
+ import type { CustomItem, CustomItemMap, CustomItemType, InferShape, ItemShape } from '@noetic-tools/types';
2
+ interface CustomItemConfig<T extends CustomItemType, E extends ItemShape, O extends ItemShape> {
3
+ /** `prefix:name`, after the Open Responses convention for extension items. */
4
+ type: T;
5
+ description?: string;
6
+ /** What streams while a step works on the item. Omit for an item with no events. */
7
+ event?: E;
8
+ /** The final item's own fields. The runtime adds `id` and `type`. */
9
+ output: O;
10
+ }
11
+ /**
12
+ * Declares a custom item a workflow may emit (spec 34), shaped like `tool()`: an
13
+ * optional `event` schema for what streams and an `output` schema for the final
14
+ * item. Each takes a Standard Schema or a JSON Schema object; a JSON Schema
15
+ * validates through `z.fromJSONSchema`, so no code is generated.
16
+ *
17
+ * @public
18
+ * @throws `NoeticConfigError` with code `INVALID_CUSTOM_ITEM_TYPE` when `type` has no `prefix:` part.
19
+ * @throws `NoeticConfigError` with code `INVALID_CUSTOM_ITEM_SHAPE` when a JSON Schema does not
20
+ * load, or `output` does not describe an object or declares `id` or `type`.
21
+ */
22
+ export declare function customItem<T extends CustomItemType, O extends ItemShape, E extends ItemShape = never>(config: CustomItemConfig<T, E, O>): CustomItem<T, InferShape<E>, InferShape<O>>;
23
+ /**
24
+ * @internal
25
+ * Build-time checks on a programmatic step's `emitItems`: a named item must be one the
26
+ * step declares, and a step that yields events (a generator `execute`) must name an
27
+ * item that has them.
28
+ *
29
+ * @throws `NoeticConfigError` with code `UNKNOWN_CUSTOM_ITEM` or `CUSTOM_ITEM_HAS_NO_EVENTS`.
30
+ */
31
+ export declare function checkEmitItems(stepId: string, step: {
32
+ emitItems?: unknown;
33
+ customItems?: CustomItemMap;
34
+ }, yields: boolean): void;
35
+ /** @internal True for a `function*` or `async function*`. */
36
+ export declare function isGeneratorFunction(fn: unknown): boolean;
37
+ export {};
@@ -0,0 +1,118 @@
1
+ import { frameworkCast, isZodSchema, NoeticConfigError } from '@noetic-tools/types';
2
+ import { z } from 'zod';
3
+ //#endregion
4
+ //#region Public API
5
+ /**
6
+ * Declares a custom item a workflow may emit (spec 34), shaped like `tool()`: an
7
+ * optional `event` schema for what streams and an `output` schema for the final
8
+ * item. Each takes a Standard Schema or a JSON Schema object; a JSON Schema
9
+ * validates through `z.fromJSONSchema`, so no code is generated.
10
+ *
11
+ * @public
12
+ * @throws `NoeticConfigError` with code `INVALID_CUSTOM_ITEM_TYPE` when `type` has no `prefix:` part.
13
+ * @throws `NoeticConfigError` with code `INVALID_CUSTOM_ITEM_SHAPE` when a JSON Schema does not
14
+ * load, or `output` does not describe an object or declares `id` or `type`.
15
+ */
16
+ export function customItem(config) {
17
+ if (!/^[^:]+:.+$/.test(config.type)) {
18
+ throw new NoeticConfigError({
19
+ code: 'INVALID_CUSTOM_ITEM_TYPE',
20
+ message: `Custom item type '${config.type}' has no 'prefix:' part.`,
21
+ hint: "Name it 'prefix:name' after the Open Responses convention, e.g. 'myapp:progress'.",
22
+ });
23
+ }
24
+ const output = toSchema(config.output, config.type, 'output');
25
+ checkFields(output, config.type);
26
+ return {
27
+ type: config.type,
28
+ description: config.description,
29
+ event: config.event === undefined
30
+ ? undefined
31
+ : frameworkCast(toSchema(config.event, config.type, 'event')),
32
+ output: frameworkCast(output),
33
+ };
34
+ }
35
+ /**
36
+ * @internal
37
+ * Build-time checks on a programmatic step's `emitItems`: a named item must be one the
38
+ * step declares, and a step that yields events (a generator `execute`) must name an
39
+ * item that has them.
40
+ *
41
+ * @throws `NoeticConfigError` with code `UNKNOWN_CUSTOM_ITEM` or `CUSTOM_ITEM_HAS_NO_EVENTS`.
42
+ */
43
+ export function checkEmitItems(stepId, step, yields) {
44
+ const name = emitItemName(step.emitItems);
45
+ if (name !== undefined && !step.customItems?.[name]) {
46
+ throw new NoeticConfigError({
47
+ code: 'UNKNOWN_CUSTOM_ITEM',
48
+ message: `Step '${stepId}' emits custom item '${name}', which it does not declare.`,
49
+ hint: `Declare it on the step: customItems: { ${name}: customItem({ type: 'myapp:${name}', output }) }.`,
50
+ });
51
+ }
52
+ if (!yields) {
53
+ return;
54
+ }
55
+ if (name === undefined || !step.customItems?.[name]?.event) {
56
+ throw new NoeticConfigError({
57
+ code: 'CUSTOM_ITEM_HAS_NO_EVENTS',
58
+ message: `Step '${stepId}' yields events, but ${name === undefined ? 'its emitItems names no item' : `custom item '${name}' declares no event schema`}.`,
59
+ hint: "Name an item with an event schema: emitItems: { item: 'progress' }, with customItem({ type, event, output }).",
60
+ });
61
+ }
62
+ }
63
+ /** @internal True for a `function*` or `async function*`. */
64
+ export function isGeneratorFunction(fn) {
65
+ const name = typeof fn === 'function' ? fn.constructor.name : '';
66
+ return name === 'GeneratorFunction' || name === 'AsyncGeneratorFunction';
67
+ }
68
+ //#endregion
69
+ //#region Helpers
70
+ function emitItemName(option) {
71
+ if (typeof option !== 'object' || option === null || !('item' in option)) {
72
+ return undefined;
73
+ }
74
+ return typeof option.item === 'string' ? option.item : undefined;
75
+ }
76
+ function toSchema(shape, type, part) {
77
+ if (isStandardSchema(shape)) {
78
+ return shape;
79
+ }
80
+ try {
81
+ return z.fromJSONSchema(frameworkCast(shape));
82
+ }
83
+ catch (error) {
84
+ throw new NoeticConfigError({
85
+ code: 'INVALID_CUSTOM_ITEM_SHAPE',
86
+ message: `The ${part} JSON Schema of custom item '${type}' does not load: ${error instanceof Error ? error.message : String(error)}`,
87
+ hint: 'Give a JSON Schema object (draft 2020-12), e.g. { "type": "object", "properties": { … } }.',
88
+ });
89
+ }
90
+ }
91
+ function isStandardSchema(shape) {
92
+ return '~standard' in shape;
93
+ }
94
+ /**
95
+ * The fields check needs a schema it can see into: a Zod object, which every JSON
96
+ * Schema becomes. Other vendors are checked when a value is emitted instead.
97
+ */
98
+ function checkFields(output, type) {
99
+ if (!isZodSchema(output)) {
100
+ return;
101
+ }
102
+ if (!(output instanceof z.ZodObject)) {
103
+ throw new NoeticConfigError({
104
+ code: 'INVALID_CUSTOM_ITEM_SHAPE',
105
+ message: `The output of custom item '${type}' does not describe an object.`,
106
+ hint: 'A final item is its fields plus the id and type the runtime adds, so output must be an object schema.',
107
+ });
108
+ }
109
+ const reserved = Object.keys(output.shape).filter((key) => key === 'id' || key === 'type');
110
+ if (reserved.length > 0) {
111
+ throw new NoeticConfigError({
112
+ code: 'INVALID_CUSTOM_ITEM_SHAPE',
113
+ message: `The output of custom item '${type}' declares ${reserved.map((key) => `'${key}'`).join(' and ')}, which the runtime adds.`,
114
+ hint: 'Drop id and type from the output schema; every final item gets both.',
115
+ });
116
+ }
117
+ }
118
+ //#endregion
@@ -1,6 +1,6 @@
1
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>, StepEmitItems<TContext, DecideAnswers<Q>> {
3
+ export interface StepDecideOpts<TContext, Q extends DecideQuestions, I = unknown> extends StepReplay<TContext, I>, StepEmitItems<TContext, I, DecideAnswers<Q>> {
4
4
  id: string;
5
5
  /** Decision model id. Falls back to `harness.config.decisionModel`. */
6
6
  model?: Lazy<string, TContext>;
@@ -40,7 +40,7 @@ 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.
43
+ Any node may carry "emitItems": true to show its output to the user as an assistant message the moment it finishes, or "emitItems": { "onDone": "<JSONata expression on the output, e.g. 'Done ' & n & ' items'>" } to show computed text (no value shows nothing). Use it for progress inside loops: only the workflow's final output is shown otherwise. To stream a structured progress item, declare it in the document's root "customItems" map ({ "<name>": { "type": "<prefix>:<name>", "event": <JSON Schema>, "output": <JSON Schema of an object, without id or type> } }) and emit it with "emitItems": { "item": "<name>", "onStart": "<JSONata on the input: one event>", "onDone": "<JSONata on the output: the final fields>" }.
44
44
 
45
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.
46
46
 
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Writes a value the way every JSON workflow node writes its output (spec 26 § `compute`):
3
+ * a string as is, `null` or `undefined` as the empty string, anything else as JSON.
4
+ */
5
+ export declare function outputText(value: unknown): string;
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Writes a value the way every JSON workflow node writes its output (spec 26 § `compute`):
3
+ * a string as is, `null` or `undefined` as the empty string, anything else as JSON.
4
+ */
5
+ export function outputText(value) {
6
+ if (typeof value === 'string') {
7
+ return value;
8
+ }
9
+ if (value === null || value === undefined) {
10
+ return '';
11
+ }
12
+ return JSON.stringify(value);
13
+ }
@@ -1,6 +1,6 @@
1
1
  import type { ContextConfig, ContextData, ContextLayer } from '@noetic-tools/context';
2
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> {
3
+ export interface WithContextOpts<TContext, I, O> extends StepReplay<TContext, I>, StepEmitItems<TContext, I, O> {
4
4
  id: string;
5
5
  child: Step<TContext, I, O>;
6
6
  context: ContextConfig | ContextLayer[];
@@ -5,7 +5,7 @@ import type { Step, StepEmitItems, StepReplay, StepSpawn, SubprocessAdapter } fr
5
5
  *
6
6
  * @public
7
7
  */
8
- export interface SpawnOpts<TContext = ContextData, I = unknown, O = unknown> extends StepReplay<TContext, I>, StepEmitItems<TContext, O> {
8
+ export interface SpawnOpts<TContext = ContextData, I = unknown, O = unknown> extends StepReplay<TContext, I>, StepEmitItems<TContext, I, O> {
9
9
  id: string;
10
10
  child: Step<TContext, I, O>;
11
11
  context?: ContextConfig | ContextLayer[];
@@ -1,8 +1,9 @@
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, 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> {
2
+ import type { AcpAgent, AcpClientCapabilityConfig, AcpContentBlock, AcpMcpServer, AcpPermissionHandler, AcpPermissionPolicy, AcpSessionPolicy, CustomItemMap, CustomItemsBrand, Lazy, ModelParams, OutputCodec, RetryPolicy, RunCodeExecute, ServerToolSpec, StandardSchemaV1, StepAcpAgent, StepCallModel, StepEmitItems, StepInvokeTool, StepReplay, StepRunCode, SubprocessAdapter, Tool, ToolChoice } from '@noetic-tools/types';
3
+ export interface RunCodeOpts<TContext, I, O, M extends CustomItemMap = CustomItemMap> extends StepReplay<TContext, I>, StepEmitItems<TContext, I, O, M> {
4
4
  id: string;
5
- execute: (input: I, ctx: Context<TContext>) => Promise<O>;
5
+ /** Async, or a generator whose yields are events of the item `emitItems` names. */
6
+ execute: RunCodeExecute<TContext, I, O>;
6
7
  retry?: RetryPolicy;
7
8
  /**
8
9
  * Optional subprocess adapter override. When set, `execute()` is routed
@@ -11,7 +12,7 @@ export interface RunCodeOpts<TContext, I, O> extends StepReplay<TContext, I>, St
11
12
  */
12
13
  subprocess?: SubprocessAdapter;
13
14
  }
14
- export interface CallModelOpts<TContext, O, I = unknown> extends StepReplay<TContext, I>, StepEmitItems<TContext, O> {
15
+ export interface CallModelOpts<TContext, O, I = unknown> extends StepReplay<TContext, I>, StepEmitItems<TContext, I, O> {
15
16
  id: string;
16
17
  /** Model id. Eager string or `(ctx) => string` getter (resolved at step execution). */
17
18
  model: Lazy<string, TContext>;
@@ -38,12 +39,12 @@ export interface CallModelOpts<TContext, O, I = unknown> extends StepReplay<TCon
38
39
  params?: ModelParams;
39
40
  emit?: boolean | ((eventType: string, data: Record<string, unknown>) => boolean);
40
41
  }
41
- export interface InvokeToolOpts<I, O, TContext = ContextData> extends StepReplay<TContext, I>, StepEmitItems<TContext, O> {
42
+ export interface InvokeToolOpts<I, O, TContext = ContextData> extends StepReplay<TContext, I>, StepEmitItems<TContext, I, O> {
42
43
  id: string;
43
44
  tool: Tool<StandardSchemaV1<unknown, I>, StandardSchemaV1<unknown, O>>;
44
45
  args?: Partial<I>;
45
46
  }
46
- export interface StepAcpAgentOpts<TContext, O, I = unknown> extends StepReplay<TContext, I>, StepEmitItems<TContext, O> {
47
+ export interface StepAcpAgentOpts<TContext, O, I = unknown> extends StepReplay<TContext, I>, StepEmitItems<TContext, I, O> {
47
48
  id: string;
48
49
  /** An ACP agent adapter, e.g. `claudeCode()` from `@noetic-tools/acp`. Eager or `(ctx) => AcpAgent`. */
49
50
  agent: Lazy<AcpAgent, TContext>;
@@ -89,7 +90,7 @@ export interface StepAcpAgentOpts<TContext, O, I = unknown> extends StepReplay<T
89
90
  * @throws `NoeticConfigError` with code `EMPTY_STEP_ID` if `id` is empty.
90
91
  * @throws `NoeticConfigError` with code `MISSING_EXECUTE_FUNCTION` if `execute` is not provided.
91
92
  */
92
- export declare function runCode<TContext = ContextData, I = unknown, O = unknown>(opts: RunCodeOpts<TContext, I, O>): StepRunCode<TContext, I, O>;
93
+ export declare function runCode<TContext = ContextData, I = unknown, O = unknown, M extends CustomItemMap = CustomItemMap>(opts: RunCodeOpts<TContext, I, O, M>): StepRunCode<TContext, I, O> & CustomItemsBrand<M[keyof M]>;
93
94
  /**
94
95
  * Creates a model call step with optional tools and structured output.
95
96
  *
@@ -1,5 +1,6 @@
1
1
  import { isServerToolSpec, NoeticConfigError } from '@noetic-tools/types';
2
2
  import { getDefaultRegistrar } from '../types/step-registrar.js';
3
+ import { checkEmitItems, isGeneratorFunction } from './custom-item.js';
3
4
  //#endregion
4
5
  //#region ACP agent builder helper
5
6
  /**
@@ -87,6 +88,7 @@ export function runCode(opts) {
87
88
  hint: 'Provide an async execute function, e.g. execute: async (input, ctx) => result.',
88
89
  });
89
90
  }
91
+ checkEmitItems(opts.id, opts, isGeneratorFunction(opts.execute));
90
92
  const built = {
91
93
  kind: 'runCode',
92
94
  ...opts,
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Custom items in JSON workflows (spec 34): live items from a document's JSON Schema
3
+ * declarations, their scopes (document root, node, subflow), and a node's `emitItems`
4
+ * hooks built from expressions.
5
+ */
6
+ import type { CustomItemMap, StepEmitItemsOption, WorkflowDocument, WorkflowEmitItems, WorkflowNode } from '@noetic-tools/types';
7
+ import type { ExpressionLimits } from '../expression/jsonata.js';
8
+ /**
9
+ * The items a document's steps may emit. Precedence, lowest first: the enclosing
10
+ * scope, the document's root `customItems`, then `typed` (TypeScript declarations for
11
+ * this document). A name in both `typed` and the document must carry one `type`.
12
+ *
13
+ * @throws `NoeticConfigError` with code `CUSTOM_ITEM_MISMATCH` when `typed` and the
14
+ * document declare one name with different types, and anything `customItem()` throws.
15
+ */
16
+ export declare function documentScope(doc: WorkflowDocument, outer: CustomItemMap | undefined, typed?: CustomItemMap): CustomItemMap;
17
+ /** The items one node may emit: its scope plus the node's own declarations. */
18
+ export declare function nodeScope(node: WorkflowNode, scope: CustomItemMap | undefined): CustomItemMap;
19
+ /**
20
+ * Every custom item a document declares at any level (its root, its nodes, its inline
21
+ * subflows), keyed by type, so a harness can accept a log that holds any of them.
22
+ */
23
+ export declare function everyDocumentItem(doc: WorkflowDocument): CustomItemMap;
24
+ /**
25
+ * Hydrates a node's `emitItems`. `true` and `false` pass through. The hook form's
26
+ * `onStart` expression, read against the input, yields one event of the named item;
27
+ * `onDone`, read against the output, gives its final fields, or message text when no
28
+ * item is named. An expression that gives no value emits nothing for that hook.
29
+ *
30
+ * @throws `NoeticConfigError` with code `UNKNOWN_CUSTOM_ITEM` when `item` names no item
31
+ * in `scope`, and `WORKFLOW_VALIDATION_FAILED` when an expression does not parse.
32
+ */
33
+ export declare function hydrateEmitItems({ nodeId, option, scope, limits, }: {
34
+ nodeId: string;
35
+ option: WorkflowEmitItems;
36
+ scope: CustomItemMap;
37
+ limits: ExpressionLimits | undefined;
38
+ }): StepEmitItemsOption;
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Custom items in JSON workflows (spec 34): live items from a document's JSON Schema
3
+ * declarations, their scopes (document root, node, subflow), and a node's `emitItems`
4
+ * hooks built from expressions.
5
+ */
6
+ import { frameworkCast, NoeticConfigError, walkWorkflow } from '@noetic-tools/types';
7
+ import { compileExpression, computeMaybe, readInput } from '../expression/jsonata.js';
8
+ import { customItem } from './custom-item.js';
9
+ import { outputText } from './output-text.js';
10
+ //#region Public API
11
+ /**
12
+ * The items a document's steps may emit. Precedence, lowest first: the enclosing
13
+ * scope, the document's root `customItems`, then `typed` (TypeScript declarations for
14
+ * this document). A name in both `typed` and the document must carry one `type`.
15
+ *
16
+ * @throws `NoeticConfigError` with code `CUSTOM_ITEM_MISMATCH` when `typed` and the
17
+ * document declare one name with different types, and anything `customItem()` throws.
18
+ */
19
+ export function documentScope(doc, outer, typed) {
20
+ const declared = liveItems(doc.customItems);
21
+ for (const [name, item] of Object.entries(typed ?? {})) {
22
+ const own = declared[name];
23
+ if (own && own.type !== item.type) {
24
+ throw new NoeticConfigError({
25
+ code: 'CUSTOM_ITEM_MISMATCH',
26
+ message: `Custom item '${name}' is '${item.type}' in workflow() but '${own.type}' in its document.`,
27
+ hint: 'Give both declarations the same type, or rename one of them.',
28
+ });
29
+ }
30
+ }
31
+ return {
32
+ ...outer,
33
+ ...declared,
34
+ ...typed,
35
+ };
36
+ }
37
+ /** The items one node may emit: its scope plus the node's own declarations. */
38
+ export function nodeScope(node, scope) {
39
+ return {
40
+ ...scope,
41
+ ...liveItems(node.customItems),
42
+ };
43
+ }
44
+ /**
45
+ * Every custom item a document declares at any level (its root, its nodes, its inline
46
+ * subflows), keyed by type, so a harness can accept a log that holds any of them.
47
+ */
48
+ export function everyDocumentItem(doc) {
49
+ const found = Object.values(liveItems(doc.customItems));
50
+ for (const node of walkWorkflow(doc.root)) {
51
+ found.push(...Object.values(liveItems(node.customItems)));
52
+ if (node.kind === 'subflow' && node.document) {
53
+ found.push(...Object.values(liveItems(node.document.customItems)));
54
+ }
55
+ }
56
+ return Object.fromEntries(found.map((item) => [
57
+ item.type,
58
+ item,
59
+ ]));
60
+ }
61
+ /**
62
+ * Hydrates a node's `emitItems`. `true` and `false` pass through. The hook form's
63
+ * `onStart` expression, read against the input, yields one event of the named item;
64
+ * `onDone`, read against the output, gives its final fields, or message text when no
65
+ * item is named. An expression that gives no value emits nothing for that hook.
66
+ *
67
+ * @throws `NoeticConfigError` with code `UNKNOWN_CUSTOM_ITEM` when `item` names no item
68
+ * in `scope`, and `WORKFLOW_VALIDATION_FAILED` when an expression does not parse.
69
+ */
70
+ export function hydrateEmitItems({ nodeId, option, scope, limits, }) {
71
+ if (typeof option === 'boolean') {
72
+ return option;
73
+ }
74
+ const where = `emitItems of node '${nodeId}'`;
75
+ const onStart = option.onStart === undefined ? undefined : compileExpression(option.onStart, where, limits);
76
+ const onDone = option.onDone === undefined ? undefined : compileExpression(option.onDone, where, limits);
77
+ if (option.item === undefined) {
78
+ return {
79
+ onDone: onDone && (async (output) => textOf(await computeMaybe(onDone, readInput(output)))),
80
+ };
81
+ }
82
+ if (!scope[option.item]) {
83
+ throw new NoeticConfigError({
84
+ code: 'UNKNOWN_CUSTOM_ITEM',
85
+ message: `Node '${nodeId}' emits custom item '${option.item}', which is not in its scope.`,
86
+ hint: "Declare it in the node's customItems or the document root's customItems.",
87
+ });
88
+ }
89
+ return {
90
+ item: option.item,
91
+ onStart: onStart &&
92
+ async function* (input) {
93
+ const event = await computeMaybe(onStart, readInput(input));
94
+ if (event !== undefined) {
95
+ yield event;
96
+ }
97
+ return undefined;
98
+ },
99
+ onDone: onDone && ((output) => computeMaybe(onDone, readInput(output))),
100
+ };
101
+ }
102
+ //#endregion
103
+ //#region Helpers
104
+ function liveItems(declared) {
105
+ return Object.fromEntries(Object.entries(declared ?? {}).map(([name, item]) => [
106
+ name,
107
+ customItem({
108
+ type: frameworkCast(item.type),
109
+ description: item.description,
110
+ event: item.event,
111
+ output: item.output,
112
+ }),
113
+ ]));
114
+ }
115
+ function textOf(value) {
116
+ return value === undefined ? undefined : outputText(value);
117
+ }
118
+ //#endregion
@@ -6,7 +6,7 @@
6
6
  * ones — they register in the step registry, carry retry policies, etc.
7
7
  */
8
8
  import type { ContextData, ContextLayer } from '@noetic-tools/context';
9
- import type { AcpAgent, ExecuteStepFn, OutputCodec, Step, SubprocessAdapter, Tool } from '@noetic-tools/types';
9
+ import type { AcpAgent, CustomItemMap, ExecuteStepFn, OutputCodec, Step, SubprocessAdapter, Tool } from '@noetic-tools/types';
10
10
  import type { ExpressionLimits } from '../expression/jsonata.js';
11
11
  import type { WorkflowDocument, WorkflowNode } from '../schemas/workflow.js';
12
12
  /** @public Context required to hydrate a JSON workflow into live steps. */
@@ -51,6 +51,11 @@ export interface HydrationContext {
51
51
  recursionDepth?: number;
52
52
  /** Bounds on each expression evaluation; unset fields use `DEFAULT_EXPRESSION_LIMITS`. */
53
53
  expressionLimits?: ExpressionLimits;
54
+ /**
55
+ * Custom items the nodes being hydrated may emit (spec 34): the enclosing document's
56
+ * root scope. Threaded by `hydrateWorkflow` and the subflow hydrator.
57
+ */
58
+ customItems?: CustomItemMap;
54
59
  }
55
60
  /**
56
61
  * Hydrates a single `WorkflowNode` into a live `Step`.
@@ -77,6 +82,8 @@ export declare function hydrateNode(node: WorkflowNode, ctx: HydrationContext):
77
82
  * @public
78
83
  * @param doc - Validated workflow document (version 1).
79
84
  * @param ctx - Hydration context with tool registry and step executor.
85
+ * @param customItems - TypeScript declarations of the document's root custom items (spec 34).
80
86
  * @returns The root `Step` of the hydrated workflow.
87
+ * @throws `NoeticConfigError` with code `CUSTOM_ITEM_MISMATCH` when `customItems` and the document give one name different types.
81
88
  */
82
- export declare function hydrateWorkflow(doc: WorkflowDocument, ctx: HydrationContext): Step<ContextData, string, string>;
89
+ export declare function hydrateWorkflow(doc: WorkflowDocument, ctx: HydrationContext, customItems?: CustomItemMap): Step<ContextData, string, string>;