@noetic-tools/core 5.19.1 → 5.20.0-next.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 (146) hide show
  1. package/dist/adapters/openrouter.js +5 -0
  2. package/dist/builders/control-flow-builders.d.ts +15 -6
  3. package/dist/builders/control-flow-builders.js +8 -0
  4. package/dist/builders/decide-builders.d.ts +2 -5
  5. package/dist/builders/dynamic-workflow.d.ts +16 -1
  6. package/dist/builders/dynamic-workflow.js +222 -11
  7. package/dist/builders/every.d.ts +3 -3
  8. package/dist/builders/every.js +2 -1
  9. package/dist/builders/provide-builder.d.ts +3 -2
  10. package/dist/builders/provide-builder.js +2 -1
  11. package/dist/builders/sequence.d.ts +14 -0
  12. package/dist/builders/sequence.js +103 -0
  13. package/dist/builders/spawn-builder.d.ts +3 -2
  14. package/dist/builders/spawn-builder.js +3 -2
  15. package/dist/builders/step-builders.d.ts +80 -1
  16. package/dist/builders/step-builders.js +115 -1
  17. package/dist/builders/verify-builder.d.ts +79 -0
  18. package/dist/builders/verify-builder.js +69 -0
  19. package/dist/builders/workflow-child-nodes.d.ts +21 -0
  20. package/dist/builders/workflow-child-nodes.js +335 -0
  21. package/dist/builders/workflow-connection-nodes.d.ts +17 -0
  22. package/dist/builders/workflow-connection-nodes.js +160 -0
  23. package/dist/builders/workflow-connections.d.ts +90 -0
  24. package/dist/builders/workflow-connections.js +560 -0
  25. package/dist/builders/workflow-control-nodes.d.ts +13 -0
  26. package/dist/builders/workflow-control-nodes.js +213 -0
  27. package/dist/builders/workflow-hydrator.d.ts +44 -3
  28. package/dist/builders/workflow-hydrator.js +53 -495
  29. package/dist/builders/workflow-verify.d.ts +19 -0
  30. package/dist/builders/workflow-verify.js +194 -0
  31. package/dist/conditions/conditions.d.ts +7 -5
  32. package/dist/conditions/conditions.js +7 -4
  33. package/dist/connections/blobs.d.ts +33 -0
  34. package/dist/connections/blobs.js +77 -0
  35. package/dist/connections/cron-schedule.d.ts +32 -0
  36. package/dist/connections/cron-schedule.js +213 -0
  37. package/dist/connections/durability.d.ts +65 -0
  38. package/dist/connections/durability.js +54 -0
  39. package/dist/connections/errors.d.ts +30 -0
  40. package/dist/connections/errors.js +100 -0
  41. package/dist/connections/event-stream.d.ts +24 -0
  42. package/dist/connections/event-stream.js +176 -0
  43. package/dist/connections/gates.d.ts +94 -0
  44. package/dist/connections/gates.js +271 -0
  45. package/dist/connections/glob.d.ts +10 -0
  46. package/dist/connections/glob.js +46 -0
  47. package/dist/connections/handle.d.ts +22 -0
  48. package/dist/connections/handle.js +84 -0
  49. package/dist/connections/harness-wiring.d.ts +52 -0
  50. package/dist/connections/harness-wiring.js +143 -0
  51. package/dist/connections/in-memory-connection.d.ts +147 -0
  52. package/dist/connections/in-memory-connection.js +593 -0
  53. package/dist/connections/index.d.ts +34 -0
  54. package/dist/connections/index.js +23 -0
  55. package/dist/connections/json-schema.d.ts +28 -0
  56. package/dist/connections/json-schema.js +338 -0
  57. package/dist/connections/model-tools.d.ts +46 -0
  58. package/dist/connections/model-tools.js +466 -0
  59. package/dist/connections/negotiation.d.ts +30 -0
  60. package/dist/connections/negotiation.js +159 -0
  61. package/dist/connections/policy.d.ts +21 -0
  62. package/dist/connections/policy.js +34 -0
  63. package/dist/connections/pool.d.ts +111 -0
  64. package/dist/connections/pool.js +339 -0
  65. package/dist/connections/refs.d.ts +74 -0
  66. package/dist/connections/refs.js +316 -0
  67. package/dist/connections/registry-types.d.ts +141 -0
  68. package/dist/connections/registry-types.js +14 -0
  69. package/dist/connections/registry.d.ts +125 -0
  70. package/dist/connections/registry.js +775 -0
  71. package/dist/connections/secrets.d.ts +59 -0
  72. package/dist/connections/secrets.js +153 -0
  73. package/dist/connections/settle.d.ts +9 -0
  74. package/dist/connections/settle.js +26 -0
  75. package/dist/connections/sources.d.ts +27 -0
  76. package/dist/connections/sources.js +300 -0
  77. package/dist/connections/triggers.d.ts +78 -0
  78. package/dist/connections/triggers.js +310 -0
  79. package/dist/connections/values.d.ts +26 -0
  80. package/dist/connections/values.js +93 -0
  81. package/dist/connections/views.d.ts +31 -0
  82. package/dist/connections/views.js +176 -0
  83. package/dist/expression/check.js +80 -1
  84. package/dist/expression/jsonata.d.ts +14 -4
  85. package/dist/expression/jsonata.js +27 -9
  86. package/dist/expression/step-outputs.d.ts +25 -0
  87. package/dist/expression/step-outputs.js +78 -0
  88. package/dist/harness/agent-harness.d.ts +69 -166
  89. package/dist/harness/agent-harness.js +170 -262
  90. package/dist/harness/call-span-collector.d.ts +33 -0
  91. package/dist/harness/call-span-collector.js +83 -0
  92. package/dist/harness/connection-gate.d.ts +78 -0
  93. package/dist/harness/connection-gate.js +169 -0
  94. package/dist/harness/deps/interpreter.d.ts +1 -0
  95. package/dist/harness/deps/interpreter.js +1 -0
  96. package/dist/harness/deps/runtime.d.ts +1 -1
  97. package/dist/harness/deps/types.d.ts +1 -1
  98. package/dist/harness/harness-options.d.ts +153 -0
  99. package/dist/harness/harness-options.js +36 -0
  100. package/dist/harness/harness-tracing.d.ts +16 -0
  101. package/dist/harness/harness-tracing.js +35 -0
  102. package/dist/harness/llm-client.d.ts +71 -0
  103. package/dist/harness/llm-client.js +218 -0
  104. package/dist/harness/model-call.d.ts +2 -7
  105. package/dist/harness/model-call.js +21 -549
  106. package/dist/harness/model-request.d.ts +42 -0
  107. package/dist/harness/model-request.js +159 -0
  108. package/dist/harness/model-stream.d.ts +39 -0
  109. package/dist/harness/model-stream.js +131 -0
  110. package/dist/harness/model-tool-round.d.ts +37 -0
  111. package/dist/harness/model-tool-round.js +197 -0
  112. package/dist/harness/spend.d.ts +2 -0
  113. package/dist/harness/spend.js +5 -1
  114. package/dist/index.d.ts +31 -6
  115. package/dist/index.js +18 -1
  116. package/dist/interpreter/connection-steps.d.ts +194 -0
  117. package/dist/interpreter/connection-steps.js +537 -0
  118. package/dist/interpreter/execute-action.d.ts +2 -8
  119. package/dist/interpreter/execute-action.js +3 -178
  120. package/dist/interpreter/execute-call.d.ts +19 -0
  121. package/dist/interpreter/execute-call.js +99 -0
  122. package/dist/interpreter/execute-control.d.ts +6 -1
  123. package/dist/interpreter/execute-control.js +14 -0
  124. package/dist/interpreter/execute-invoke-tool.d.ts +11 -0
  125. package/dist/interpreter/execute-invoke-tool.js +183 -0
  126. package/dist/interpreter/execute-verify.d.ts +21 -0
  127. package/dist/interpreter/execute-verify.js +391 -0
  128. package/dist/interpreter/execute-wait.d.ts +21 -0
  129. package/dist/interpreter/execute-wait.js +233 -0
  130. package/dist/interpreter/execute.js +24 -133
  131. package/dist/interpreter/step-kind-dispatch.d.ts +24 -0
  132. package/dist/interpreter/step-kind-dispatch.js +157 -0
  133. package/dist/interpreter/step-walk.d.ts +2 -0
  134. package/dist/interpreter/step-walk.js +24 -0
  135. package/dist/interpreter/verify-host.d.ts +40 -0
  136. package/dist/interpreter/verify-host.js +245 -0
  137. package/dist/runtime/durable/step-ledger.d.ts +31 -1
  138. package/dist/runtime/durable/step-ledger.js +87 -1
  139. package/dist/runtime/in-memory-artifact-store.d.ts +24 -0
  140. package/dist/runtime/in-memory-artifact-store.js +240 -0
  141. package/dist/schemas/workflow.d.ts +2 -2
  142. package/dist/schemas/workflow.js +1 -1
  143. package/dist/util/harness-internals.d.ts +23 -0
  144. package/dist/util/harness-internals.js +35 -0
  145. package/package.json +3 -3
  146. package/schema/noetic-workflow.schema.json +1170 -92
@@ -83,7 +83,12 @@ export function extractSystemInstruction(items) {
83
83
  remaining,
84
84
  };
85
85
  }
86
+ /** Framework-owned extension items (`noetic:*`, e.g. a trigger's `noetic:connection_event`) are never sent to a provider. */
87
+ const FRAMEWORK_ITEM_PREFIX = 'noetic:';
86
88
  function itemToInputItem(item) {
89
+ if (typeof item.type === 'string' && item.type.startsWith(FRAMEWORK_ITEM_PREFIX)) {
90
+ return null;
91
+ }
87
92
  if (item.type === 'message' && 'content' in item && 'role' in item) {
88
93
  // All message types (input and output) are converted to EasyInputMessage
89
94
  // because the SDK's input union does not accept ResponsesOutputMessage directly.
@@ -1,16 +1,25 @@
1
1
  import type { ContextData } from '@noetic-tools/context';
2
- import type { StepConditional, StepInParallelAll, StepInParallelRace, StepInParallelSettle } from '@noetic-tools/types';
2
+ import type { Context, ExecuteStepFn, StepConditional, StepInParallelAll, StepInParallelRace, StepInParallelSettle, Steps } from '@noetic-tools/types';
3
3
  /**
4
4
  * Options for `inParallel()`, one shape per mode. `merge` is required for `all`
5
5
  * and `settle` and absent for `race`.
6
6
  * @public
7
7
  */
8
8
  export type InParallelOpts<TContext = ContextData, I = unknown, O = unknown> = InParallelRaceOpts<TContext, I, O> | InParallelAllOpts<TContext, I, O> | InParallelSettleOpts<TContext, I, O>;
9
- type InParallelRaceOpts<TContext, I, O> = Omit<StepInParallelRace<TContext, I, O>, 'kind'>;
10
- type InParallelAllOpts<TContext, I, O> = Omit<StepInParallelAll<TContext, I, O>, 'kind'>;
11
- type InParallelSettleOpts<TContext, I, O> = Omit<StepInParallelSettle<TContext, I, O>, 'kind'>;
12
- /** @public Options for `conditional()`. */
13
- export type ConditionalOpts<TContext = ContextData, I = unknown, O = unknown> = Omit<StepConditional<TContext, I, O>, 'kind'>;
9
+ /** Each parallel path is a step, or an array of steps run in sequence. */
10
+ interface PathsOpt<TContext, I, O> {
11
+ paths: (input: I, ctx: Context<TContext>) => Array<Steps<TContext, I, O>>;
12
+ }
13
+ type InParallelRaceOpts<TContext, I, O> = Omit<StepInParallelRace<TContext, I, O>, 'kind' | 'paths'> & PathsOpt<TContext, I, O>;
14
+ type InParallelAllOpts<TContext, I, O> = Omit<StepInParallelAll<TContext, I, O>, 'kind' | 'paths'> & PathsOpt<TContext, I, O>;
15
+ type InParallelSettleOpts<TContext, I, O> = Omit<StepInParallelSettle<TContext, I, O>, 'kind' | 'paths'> & PathsOpt<TContext, I, O>;
16
+ /**
17
+ * @public Options for `conditional()`. `route` may pick a step or an array of
18
+ * steps run in sequence.
19
+ */
20
+ export type ConditionalOpts<TContext = ContextData, I = unknown, O = unknown> = Omit<StepConditional<TContext, I, O>, 'kind' | 'route'> & {
21
+ route: (input: I, ctx: Context<TContext>, run: ExecuteStepFn) => Steps<TContext, I, O> | null | Promise<Steps<TContext, I, O> | null>;
22
+ };
14
23
  /**
15
24
  * Creates a parallel execution step that races paths and returns the first result.
16
25
  *
@@ -1,5 +1,6 @@
1
1
  import { frameworkCast, NoeticConfigError } from '@noetic-tools/types';
2
2
  import { getDefaultRegistrar } from '../types/step-registrar.js';
3
+ import { toStep } from './sequence.js';
3
4
  export function inParallel(opts) {
4
5
  if (!opts.id || opts.id.trim() === '') {
5
6
  throw new NoeticConfigError({
@@ -15,9 +16,11 @@ export function inParallel(opts) {
15
16
  hint: 'Provide a merge function that combines path results into a single output.',
16
17
  });
17
18
  }
19
+ const paths = opts.paths;
18
20
  const built = frameworkCast({
19
21
  kind: 'inParallel',
20
22
  ...opts,
23
+ paths: (input, ctx) => paths(input, ctx).map((path) => toStep(path)),
21
24
  });
22
25
  getDefaultRegistrar().register(built);
23
26
  return built;
@@ -49,9 +52,14 @@ export function conditional(opts) {
49
52
  hint: 'Provide a route function that selects the next step at runtime.',
50
53
  });
51
54
  }
55
+ const route = opts.route;
52
56
  const built = {
53
57
  kind: 'conditional',
54
58
  ...opts,
59
+ route: async (input, ctx, run) => {
60
+ const picked = await route(input, ctx, run);
61
+ return picked === null ? null : toStep(picked);
62
+ },
55
63
  };
56
64
  getDefaultRegistrar().register(built);
57
65
  return built;
@@ -24,10 +24,8 @@ export interface StepDecideOpts<TContext, Q extends DecideQuestions, I = unknown
24
24
  type NonEmpty<Q> = keyof Q extends never ? {
25
25
  'decide needs at least one question': never;
26
26
  } : unknown;
27
- /** @public The input a step takes. */
28
- export type StepInput<S> = S extends Step<infer _C, infer I, infer _O> ? I : never;
29
- /** @public The output a step produces. */
30
- export type StepOutput<S> = S extends Step<infer _C, infer _I, infer O> ? O : never;
27
+ import type { StepInput, StepOutput } from '@noetic-tools/types';
28
+ export type { StepInput, StepOutput };
31
29
  /** A step of any kind, as far as a case needs to be one. */
32
30
  type CaseStep = Pick<Step, 'kind' | 'id'>;
33
31
  /** Maps every key the switch does not route to onto `never`, so a misspelled case is a type error. */
@@ -83,4 +81,3 @@ export declare function decide<const Q extends DecideQuestions, TContext = Conte
83
81
  */
84
82
  export declare function routeSwitch<TContext, const Q extends DecideQuestions, const C extends string, const Cases extends Partial<Record<C, CaseStep>>, D extends CaseStep, U extends CaseStep = D>(opts: RouteSwitchByFunctionOpts<TContext, Q, C, Cases, D, U>): StepConditional<TContext, StepInput<Cases[keyof Cases] | D | U>, StepOutput<Cases[keyof Cases] | D | U>>;
85
83
  export declare function routeSwitch<TContext, const Q extends DecideQuestions, const K extends keyof Q & string, const Cases extends Record<CaseKeyOf<Q[K]>, CaseStep>, U extends CaseStep>(opts: RouteSwitchByKeyOpts<TContext, Q, K, Cases, U>): StepConditional<TContext, StepInput<Cases[keyof Cases] | U>, StepOutput<Cases[keyof Cases] | U>>;
86
- export {};
@@ -3,7 +3,7 @@
3
3
  * then hydrates and runs it within the same harness session.
4
4
  */
5
5
  import type { ContextData, ContextLayer } from '@noetic-tools/context';
6
- import type { AgentHarnessContract, Context, Step, Tool } from '@noetic-tools/types';
6
+ import type { AgentHarnessContract, ConnectionAllowlist, Context, Step, Tool } from '@noetic-tools/types';
7
7
  import type { ExpressionLimits } from '../expression/jsonata.js';
8
8
  import type { WorkflowDocument } from '../schemas/workflow.js';
9
9
  /** @public Options for creating a dynamic workflow step. */
@@ -15,6 +15,13 @@ export interface DynamicWorkflowOpts {
15
15
  maxRevisions?: number;
16
16
  /** Bounds on each expression evaluation; unset fields use `DEFAULT_EXPRESSION_LIMITS`. */
17
17
  expressionLimits?: ExpressionLimits;
18
+ /**
19
+ * What a generated document may use of the harness's connections (spec 35 §
20
+ * What a document may use). Required for the planner to use connections at
21
+ * all: a document asking for a connection without it fails validation with
22
+ * `CONNECTION_NOT_ALLOWED`. The planner is shown only these connections.
23
+ */
24
+ connections?: ConnectionAllowlist;
18
25
  }
19
26
  /**
20
27
  * Creates a step that uses an LLM to generate a workflow as JSON, then
@@ -57,6 +64,12 @@ export interface ParseAndRunWorkflowOpts {
57
64
  maxRecursionDepth?: number;
58
65
  /** Bounds on each expression evaluation; unset fields use `DEFAULT_EXPRESSION_LIMITS`. */
59
66
  expressionLimits?: ExpressionLimits;
67
+ /**
68
+ * What the document may use of the harness's connections (spec 35 § What a
69
+ * document may use). When given, a manifest asking for more fails with
70
+ * `CONNECTION_NOT_ALLOWED`.
71
+ */
72
+ connections?: ConnectionAllowlist;
60
73
  }
61
74
  /**
62
75
  * Parses raw JSON into a `WorkflowDocument`, hydrates it into a live step
@@ -76,5 +89,7 @@ export interface ParseAndRunWorkflowOpts {
76
89
  * @throws `NoeticConfigError` with code `UNKNOWN_TOOL_REFERENCE` if a tool reference cannot be resolved.
77
90
  * @throws `NoeticConfigError` with code `INVALID_EXPRESSION_LIMITS` if `expressionLimits` holds a value that is not a positive integer or `Infinity`.
78
91
  * @throws `NoeticConfigError` with code `EXPRESSION_LIMIT_EXCEEDED` if an expression exceeds its limits.
92
+ * @throws `NoeticConfigError` with code `CONNECTION_UNKNOWN` if a node uses a connection the document does not declare, or the allowlist names one the harness does not have.
93
+ * @throws `NoeticConfigError` with code `CONNECTION_NOT_ALLOWED` if the document asks for more than `connections` grants.
79
94
  */
80
95
  export declare function parseAndRunWorkflow(opts: ParseAndRunWorkflowOpts): Promise<string>;
@@ -3,11 +3,14 @@
3
3
  * then hydrates and runs it within the same harness session.
4
4
  */
5
5
  import { exportSpans } from '@noetic-tools/context';
6
- import { frameworkCast, NoeticConfigError } from '@noetic-tools/types';
6
+ import { frameworkCast, isNoeticConfigError, NoeticConfigError } from '@noetic-tools/types';
7
7
  import { expressionErrors } from '../expression/check.js';
8
8
  import { NoeticAttr } from '../observability/genai-attributes.js';
9
9
  import { WorkflowDocumentSchema, workflowDepth, workflowGraph } from '../schemas/workflow.js';
10
+ import { harnessInternal } from '../util/harness-internals.js';
11
+ import { outputText } from './output-text.js';
10
12
  import { callModel, runCode } from './step-builders.js';
13
+ import { checkConnectionAllowlist, checkDocumentConnections, globMatches, } from './workflow-connections.js';
11
14
  import { hydrateWorkflow } from './workflow-hydrator.js';
12
15
  //#endregion
13
16
  //#region Constants
@@ -83,11 +86,13 @@ export function dynamicWorkflow(opts) {
83
86
  hint: 'Execute this step via AgentHarness.run() or ensure ctx.harness is set.',
84
87
  });
85
88
  }
89
+ checkAllowlistNames(opts.connections, ctx);
86
90
  const toolList = opts.tools.map((t) => `- ${t.name}: ${t.description}`).join('\n');
87
91
  const basePrompt = [
88
92
  opts.instructions,
89
93
  PLANNER_INSTRUCTIONS,
90
94
  `\nAvailable tools:\n${toolList}`,
95
+ connectionsPrompt(opts.connections, plannerConnections(opts.connections, ctx)),
91
96
  `\nTask: ${input}`,
92
97
  ]
93
98
  .filter(Boolean)
@@ -97,17 +102,26 @@ export function dynamicWorkflow(opts) {
97
102
  const prompt = lastError
98
103
  ? `${basePrompt}\n\nPrevious attempt failed with error: ${lastError}\nPlease fix the workflow and try again.`
99
104
  : basePrompt;
105
+ // The planner only writes the document: it never sees the harness's tools or
106
+ // connections, so it cannot drive a connection around the allowlist.
100
107
  const plannerStep = callModel({
101
108
  id: `dynamic-workflow-planner-${revision}`,
102
109
  model,
103
110
  instructions: prompt,
111
+ tools: [],
104
112
  });
105
113
  const executeStep = frameworkCast(harness.run.bind(harness));
106
114
  const rawOutput = await executeStep(plannerStep, input, ctx);
107
115
  const text = coerceToString(rawOutput);
108
- const parseResult = tryParseWorkflow(text, maxDepth);
116
+ const parseResult = tryParseWorkflow(text, maxDepth, {
117
+ allowlist: opts.connections ?? {},
118
+ ranges: profileVersions(ctx),
119
+ });
109
120
  if (!parseResult.ok) {
110
121
  lastError = parseResult.error;
122
+ if (revision === maxRevisions - 1 && parseResult.configError) {
123
+ throw parseResult.configError;
124
+ }
111
125
  if (revision === maxRevisions - 1) {
112
126
  throw new NoeticConfigError({
113
127
  code: 'WORKFLOW_VALIDATION_FAILED',
@@ -151,9 +165,17 @@ export function dynamicWorkflow(opts) {
151
165
  * @throws `NoeticConfigError` with code `UNKNOWN_TOOL_REFERENCE` if a tool reference cannot be resolved.
152
166
  * @throws `NoeticConfigError` with code `INVALID_EXPRESSION_LIMITS` if `expressionLimits` holds a value that is not a positive integer or `Infinity`.
153
167
  * @throws `NoeticConfigError` with code `EXPRESSION_LIMIT_EXCEEDED` if an expression exceeds its limits.
168
+ * @throws `NoeticConfigError` with code `CONNECTION_UNKNOWN` if a node uses a connection the document does not declare, or the allowlist names one the harness does not have.
169
+ * @throws `NoeticConfigError` with code `CONNECTION_NOT_ALLOWED` if the document asks for more than `connections` grants.
154
170
  */
155
171
  export async function parseAndRunWorkflow(opts) {
156
- const parseResult = tryParseWorkflow(opts.json, opts.maxDepth ?? DEFAULT_MAX_DEPTH);
172
+ checkAllowlistNames(opts.connections, opts.ctx);
173
+ const parseResult = tryParseWorkflow(opts.json, opts.maxDepth ?? DEFAULT_MAX_DEPTH, {
174
+ allowlist: opts.connections,
175
+ });
176
+ if (!parseResult.ok && parseResult.configError) {
177
+ throw parseResult.configError;
178
+ }
157
179
  if (!parseResult.ok) {
158
180
  throw new NoeticConfigError({
159
181
  code: 'WORKFLOW_VALIDATION_FAILED',
@@ -217,25 +239,32 @@ function buildToolMap(tools) {
217
239
  t,
218
240
  ]));
219
241
  }
242
+ /** A workflow's output as text, written the way every node writes its output (objects as JSON). */
220
243
  function coerceToString(value) {
221
- if (typeof value === 'string') {
222
- return value;
223
- }
224
- return String(value ?? '');
244
+ return outputText(value);
225
245
  }
226
- function tryParseWorkflow(raw, maxDepth) {
227
- const parsed = typeof raw === 'string' ? safeParse(raw) : raw;
228
- if (parsed === null) {
246
+ function tryParseWorkflow(raw, maxDepth, check = {}) {
247
+ const json = typeof raw === 'string' ? safeParse(raw) : raw;
248
+ if (json === null) {
229
249
  return {
230
250
  ok: false,
231
251
  error: 'Input is not valid JSON.',
232
252
  };
233
253
  }
254
+ const parsed = check.ranges ? withProfileRanges(json, check.ranges) : json;
234
255
  const result = WorkflowDocumentSchema.safeParse(parsed);
235
256
  if (!result.success) {
257
+ const manifestError = manifestErrorOf(result.error.issues);
236
258
  return {
237
259
  ok: false,
238
- error: result.error.message,
260
+ error: manifestError
261
+ ? `${manifestError.code}: ${manifestError.message} ${manifestError.hint}`
262
+ : result.error.message,
263
+ ...(manifestError
264
+ ? {
265
+ configError: manifestError,
266
+ }
267
+ : {}),
239
268
  };
240
269
  }
241
270
  const depth = workflowDepth(result.data.root);
@@ -252,11 +281,193 @@ function tryParseWorkflow(raw, maxDepth) {
252
281
  error: errors.join(' '),
253
282
  };
254
283
  }
284
+ const connectionError = connectionErrorOf(result.data, check);
285
+ if (connectionError) {
286
+ return {
287
+ ok: false,
288
+ error: `${connectionError.code}: ${connectionError.message} ${connectionError.hint}`,
289
+ configError: connectionError,
290
+ };
291
+ }
255
292
  return {
256
293
  ok: true,
257
294
  doc: result.data,
258
295
  };
259
296
  }
297
+ /** The connection error a document has, checked against its manifest and (when given) the host allowlist. */
298
+ function connectionErrorOf(doc, check) {
299
+ try {
300
+ if (check.allowlist === undefined) {
301
+ checkDocumentConnections(doc);
302
+ }
303
+ else {
304
+ checkConnectionAllowlist(doc, check.allowlist);
305
+ }
306
+ return undefined;
307
+ }
308
+ catch (error) {
309
+ if (isNoeticConfigError(error)) {
310
+ return error;
311
+ }
312
+ throw error;
313
+ }
314
+ }
315
+ /**
316
+ * Checks an allowlist names only connections the harness has, when the harness
317
+ * has a connection registry to ask.
318
+ *
319
+ * @throws `NoeticConfigError` `CONNECTION_UNKNOWN` for a name the harness does not have.
320
+ */
321
+ function checkAllowlistNames(allowlist, ctx) {
322
+ // Structural: builders sit below the connection registry and must not import it.
323
+ const registry = harnessInternal(ctx.harness, 'connectionRegistry');
324
+ if (!allowlist || !registry) {
325
+ return;
326
+ }
327
+ const known = new Set(registry.names());
328
+ for (const name of Object.keys(allowlist)) {
329
+ if (known.has(name)) {
330
+ continue;
331
+ }
332
+ throw new NoeticConfigError({
333
+ code: 'CONNECTION_UNKNOWN',
334
+ message: `The connection allowlist names '${name}', which the harness does not have.`,
335
+ hint: `Harness connections: ${[
336
+ ...known,
337
+ ].join(', ') || '(none)'}.`,
338
+ });
339
+ }
340
+ }
341
+ /**
342
+ * A malformed manifest entry (spec 35 § Errors) is `CONNECTION_INVALID`, not a
343
+ * generic validation failure: the issues under the root `connections` map.
344
+ */
345
+ function manifestErrorOf(issues) {
346
+ const manifest = issues.filter((issue) => issue.path[0] === 'connections');
347
+ if (manifest.length === 0) {
348
+ return undefined;
349
+ }
350
+ const detail = manifest
351
+ .map((issue) => `${issue.path.map(String).join('.')}: ${issue.message}`)
352
+ .join('; ');
353
+ return new NoeticConfigError({
354
+ code: 'CONNECTION_INVALID',
355
+ message: `The document's connections map is malformed: ${detail}`,
356
+ hint: 'Each entry is { "profile": "<profile>@<range>", "extensions"?, "from"?, "fresh"?, "setup"? } or { "events": [...] }.',
357
+ });
358
+ }
359
+ function registryOf(ctx) {
360
+ return harnessInternal(ctx.harness, 'connectionRegistry');
361
+ }
362
+ /** The profile versions each harness connection serves right now. */
363
+ function profileVersions(ctx) {
364
+ const registry = registryOf(ctx);
365
+ const versions = new Map();
366
+ for (const name of registry?.names() ?? []) {
367
+ const profiles = registry?.current?.(name)?.manifest.profiles;
368
+ if (profiles) {
369
+ versions.set(name, profiles);
370
+ }
371
+ }
372
+ return versions;
373
+ }
374
+ /** `^<major>` of `version`, or undefined when it is not a version. */
375
+ function caretRange(version) {
376
+ const major = version?.split('.')[0];
377
+ return major && /^\d+$/.test(major) ? `^${major}` : undefined;
378
+ }
379
+ /** `json` with each manifest entry's bare `"profile": "<name>"` given the range its connection serves. */
380
+ function withProfileRanges(json, ranges) {
381
+ if (!isRecord(json) || !isRecord(json.connections)) {
382
+ return json;
383
+ }
384
+ const connections = {};
385
+ for (const [name, entry] of Object.entries(json.connections)) {
386
+ connections[name] = withProfileRange(name, entry, ranges);
387
+ }
388
+ return {
389
+ ...json,
390
+ connections,
391
+ };
392
+ }
393
+ function withProfileRange(name, entry, ranges) {
394
+ if (!isRecord(entry) || typeof entry.profile !== 'string' || entry.profile.includes('@')) {
395
+ return entry;
396
+ }
397
+ const target = typeof entry.from === 'string' ? entry.from : name;
398
+ const range = caretRange(ranges.get(target)?.[entry.profile]);
399
+ return range
400
+ ? {
401
+ ...entry,
402
+ profile: `${entry.profile}@${range}`,
403
+ }
404
+ : entry;
405
+ }
406
+ function isRecord(value) {
407
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
408
+ }
409
+ /** What the planner may see of each allowed connection: its profiles and allowed operations with their schemas. */
410
+ function plannerConnections(allowlist, ctx) {
411
+ const registry = registryOf(ctx);
412
+ const out = new Map();
413
+ for (const [name, entry] of Object.entries(allowlist ?? {})) {
414
+ const manifest = registry?.current?.(name)?.manifest;
415
+ if (!manifest) {
416
+ continue;
417
+ }
418
+ const operations = Object.entries(manifest.operations)
419
+ .filter(([op]) => (entry.ops ?? []).some((pattern) => globMatches(pattern, op)))
420
+ .map(([op, info]) => ({
421
+ name: op,
422
+ inputSchema: info.inputSchema,
423
+ }));
424
+ out.set(name, {
425
+ profiles: manifest.profiles,
426
+ operations,
427
+ });
428
+ }
429
+ return out;
430
+ }
431
+ function connectionLine(name, entry, known) {
432
+ const profiles = Object.keys(known?.profiles ?? {});
433
+ const parts = [
434
+ ...(profiles.length > 0
435
+ ? [
436
+ `profiles: ${profiles.join(', ')}`,
437
+ ]
438
+ : []),
439
+ `ops: ${(entry.ops ?? []).join(', ') || '(none)'}`,
440
+ `events: ${(entry.events ?? []).join(', ') || '(none)'}`,
441
+ ];
442
+ if (entry.setup) {
443
+ parts.push(`setup fields: ${Object.keys(entry.setup).join(', ')}`);
444
+ }
445
+ if (entry.secrets) {
446
+ parts.push(`secrets: ${Object.entries(entry.secrets)
447
+ .map(([secret, field]) => `${secret} (only in ${field})`)
448
+ .join(', ')}`);
449
+ }
450
+ const schemas = (known?.operations ?? []).map((op) => ` - ${op.name} args: ${JSON.stringify(op.inputSchema)}`);
451
+ return [
452
+ `- ${name}: ${parts.join('; ')}`,
453
+ ...schemas,
454
+ ].join('\n');
455
+ }
456
+ /** The planner's view of the connections it may use: only the allowed ones, with their operations and argument schemas. */
457
+ function connectionsPrompt(allowlist, known) {
458
+ const entries = Object.entries(allowlist ?? {});
459
+ if (entries.length === 0) {
460
+ return '\nNo connections are available: do not emit call, wait or verify nodes or a "connections" map.';
461
+ }
462
+ const lines = entries.map(([name, entry]) => connectionLine(name, entry, known.get(name)));
463
+ return `\nConnections you may use (a document lists the ones it needs in a root "connections" map, e.g. "connections": { "app": { "profile": "<profile>", "from": "<connection>" } } — the version range is filled in for you — or { "events": [...] } for an event source):
464
+ ${lines.join('\n')}
465
+ Connection nodes:
466
+ - { "kind": "call", "id": "<unique>", "connection": "<name>", "op": "<operation>", "args": { ... } } (run one operation; values may be { "$expr": "<JSONata on the input; $steps.<id> reads an earlier node's output>" }, { "$literal": ... }, or { "$secret": "<name>" })
467
+ - { "kind": "wait", "id": "<unique>", "connection": "<name>", "event": "<event>", "filter": "<JSONata test on { event, input }>", "around": [<steps>], "timeoutMs": <ms> } (listen, run around, then wait for the event)
468
+ - { "kind": "verify", "id": "<unique>", "subject": "<name>", "expect": [{ "<sense>": "<pattern>" }, ...], "never": [<matchers>], "act": [<steps>], "witnesses": ["<name>"], "close": { "until": "quiet"|"event"|"done"|"exit" } } (run act on the subject and check what was expected happened; act names operations by name)
469
+ Inside "around", "act" or a sequence's "steps", { "<operation>": { ...args } } is a call on the enclosing connection.`;
470
+ }
260
471
  function safeParse(text) {
261
472
  try {
262
473
  return JSON.parse(text);
@@ -1,5 +1,5 @@
1
1
  import type { ContextData } from '@noetic-tools/context';
2
- import type { Channel, ScheduleErrorPolicy, Step, StepReplay, StepSchedule } from '@noetic-tools/types';
2
+ import type { Channel, ScheduleErrorPolicy, StepReplay, StepSchedule, Steps } from '@noetic-tools/types';
3
3
  /**
4
4
  * Configuration options accepted by the `schedule()` builder, excluding the `kind`
5
5
  * discriminant. `schedule()` schedules a body step on a fixed-interval, optionally
@@ -10,8 +10,8 @@ import type { Channel, ScheduleErrorPolicy, Step, StepReplay, StepSchedule } fro
10
10
  export interface ScheduleOptions<TContext = ContextData, I = unknown, O = unknown> extends StepReplay<TContext, I> {
11
11
  /** Unique step identifier used in traces and error messages. */
12
12
  id: string;
13
- /** Body step executed on each iteration. */
14
- step: Step<TContext, I, O>;
13
+ /** Body executed on each iteration: a step, or an array of steps run in sequence. */
14
+ step: Steps<TContext, I, O>;
15
15
  /** Park duration between iterations in milliseconds. Must be >= 0. */
16
16
  interval: number;
17
17
  /** Optional channel that wakes the parking interval when any value arrives. */
@@ -1,5 +1,6 @@
1
1
  import { NoeticConfigError } from '@noetic-tools/types';
2
2
  import { getDefaultRegistrar } from '../types/step-registrar.js';
3
+ import { toStep } from './sequence.js';
3
4
  /**
4
5
  * Creates a `schedule` step that runs a body step on a fixed-interval schedule.
5
6
  *
@@ -52,7 +53,7 @@ export function schedule(opts) {
52
53
  const built = {
53
54
  kind: 'schedule',
54
55
  id: opts.id,
55
- step: opts.step,
56
+ step: toStep(opts.step),
56
57
  interval: opts.interval,
57
58
  inbox: opts.inbox,
58
59
  onError: opts.onError ?? 'continue',
@@ -1,8 +1,9 @@
1
1
  import type { ContextConfig, ContextData, ContextLayer } from '@noetic-tools/context';
2
- import type { Step, StepEmitItems, StepReplay, StepWithContext } from '@noetic-tools/types';
2
+ import type { StepEmitItems, StepReplay, Steps, StepWithContext } from '@noetic-tools/types';
3
3
  export interface WithContextOpts<TContext, I, O> extends StepReplay<TContext, I>, StepEmitItems<TContext, I, O> {
4
4
  id: string;
5
- child: Step<TContext, I, O>;
5
+ /** The child step, or an array of steps run in sequence. */
6
+ child: Steps<TContext, I, O>;
6
7
  context: ContextConfig | ContextLayer[];
7
8
  }
8
9
  /**
@@ -1,5 +1,6 @@
1
1
  import { NoeticConfigError } from '@noetic-tools/types';
2
2
  import { getDefaultRegistrar } from '../types/step-registrar.js';
3
+ import { toStep } from './sequence.js';
3
4
  /**
4
5
  * Creates a provide step that attaches context layers to its child without creating an isolated context.
5
6
  * Like React's Context.Provider — layers are available to all descendant steps.
@@ -40,7 +41,7 @@ export function withContext(opts) {
40
41
  const built = {
41
42
  kind: 'withContext',
42
43
  id: opts.id,
43
- child: opts.child,
44
+ child: toStep(opts.child),
44
45
  context: layers,
45
46
  durable: opts.durable,
46
47
  replayKey: opts.replayKey,
@@ -0,0 +1,14 @@
1
+ import type { ContextData, Step, Steps } from '@noetic-tools/types';
2
+ /**
3
+ * A step from a step or an array of steps. An array of two or more becomes a
4
+ * `sequence` step whose id joins its children's ids; a one-element array is its
5
+ * element. The sequence holds a frozen copy of the array, so changing the
6
+ * array afterwards changes nothing. Builders that take `Steps` call this, so an
7
+ * array runs in sequence wherever they take a step.
8
+ *
9
+ * @throws `NoeticConfigError` with code `EMPTY_STEP_ARRAY` for an empty array.
10
+ * @throws `NoeticConfigError` with code `INVALID_STEP_IN_ARRAY` when an element
11
+ * is not a step (a nested array, `null`, or an object without a step kind
12
+ * and string id). Nested arrays are rejected, not flattened.
13
+ */
14
+ export declare function toStep<TContext = ContextData, I = unknown, O = unknown>(steps: Steps<TContext, I, O>): Step<TContext, I, O>;
@@ -0,0 +1,103 @@
1
+ import { frameworkCast, NoeticConfigError } from '@noetic-tools/types';
2
+ //#region Helpers
3
+ /** Every step kind, so an array element can be checked before it runs. */
4
+ const STEP_KINDS = {
5
+ runCode: true,
6
+ callModel: true,
7
+ 'acp-agent': true,
8
+ invokeTool: true,
9
+ decide: true,
10
+ conditional: true,
11
+ inParallel: true,
12
+ spawn: true,
13
+ withContext: true,
14
+ loop: true,
15
+ schedule: true,
16
+ call: true,
17
+ wait: true,
18
+ verify: true,
19
+ sequence: true,
20
+ };
21
+ function isStepList(steps) {
22
+ return Array.isArray(steps);
23
+ }
24
+ function isStepKind(kind) {
25
+ return typeof kind === 'string' && Object.hasOwn(STEP_KINDS, kind);
26
+ }
27
+ /** What is wrong with an array element, or `undefined` when it is a step. */
28
+ function elementProblem(element) {
29
+ if (Array.isArray(element)) {
30
+ return 'is a nested array';
31
+ }
32
+ if (typeof element !== 'object' || element === null) {
33
+ return `is ${element === null ? 'null' : typeof element}, not a step`;
34
+ }
35
+ const { kind, id } = frameworkCast(element);
36
+ if (!isStepKind(kind)) {
37
+ return `has no known step kind (got ${JSON.stringify(kind)})`;
38
+ }
39
+ if (typeof id !== 'string') {
40
+ return 'has no string id';
41
+ }
42
+ return undefined;
43
+ }
44
+ /**
45
+ * Checks every element is a step, so a bad array fails where it is built
46
+ * rather than as a raw TypeError when it runs.
47
+ *
48
+ * @throws `NoeticConfigError` `INVALID_STEP_IN_ARRAY` naming the first bad element.
49
+ */
50
+ function requireSteps(list) {
51
+ for (const [index, element] of list.entries()) {
52
+ const problem = elementProblem(element);
53
+ if (problem === undefined) {
54
+ continue;
55
+ }
56
+ throw new NoeticConfigError({
57
+ code: 'INVALID_STEP_IN_ARRAY',
58
+ message: `Element ${index} of an array of steps ${problem}.`,
59
+ hint: 'An array of steps holds steps only. Spread a nested array into its parent (`[a, ...rest]`); arrays are not flattened.',
60
+ });
61
+ }
62
+ return frameworkCast(list);
63
+ }
64
+ //#endregion
65
+ //#region Public API
66
+ /**
67
+ * A step from a step or an array of steps. An array of two or more becomes a
68
+ * `sequence` step whose id joins its children's ids; a one-element array is its
69
+ * element. The sequence holds a frozen copy of the array, so changing the
70
+ * array afterwards changes nothing. Builders that take `Steps` call this, so an
71
+ * array runs in sequence wherever they take a step.
72
+ *
73
+ * @throws `NoeticConfigError` with code `EMPTY_STEP_ARRAY` for an empty array.
74
+ * @throws `NoeticConfigError` with code `INVALID_STEP_IN_ARRAY` when an element
75
+ * is not a step (a nested array, `null`, or an object without a step kind
76
+ * and string id). Nested arrays are rejected, not flattened.
77
+ */
78
+ export function toStep(steps) {
79
+ if (!isStepList(steps)) {
80
+ return frameworkCast(steps);
81
+ }
82
+ const list = requireSteps(steps);
83
+ const [first] = list;
84
+ if (!first) {
85
+ throw new NoeticConfigError({
86
+ code: 'EMPTY_STEP_ARRAY',
87
+ message: 'An array of steps must contain at least one step.',
88
+ hint: 'Pass the steps to run in sequence, or a single step.',
89
+ });
90
+ }
91
+ if (list.length === 1) {
92
+ return frameworkCast(first);
93
+ }
94
+ const children = Object.freeze(frameworkCast([
95
+ ...list,
96
+ ]));
97
+ return {
98
+ kind: 'sequence',
99
+ id: children.map((child) => child.id).join(' > '),
100
+ steps: children,
101
+ };
102
+ }
103
+ //#endregion
@@ -1,5 +1,5 @@
1
1
  import type { ContextConfig, ContextData, ContextLayer } from '@noetic-tools/context';
2
- import type { Step, StepEmitItems, StepReplay, StepSpawn, SubprocessAdapter } from '@noetic-tools/types';
2
+ import type { StepEmitItems, StepReplay, StepSpawn, Steps, SubprocessAdapter } from '@noetic-tools/types';
3
3
  /**
4
4
  * Options for {@link spawn}.
5
5
  *
@@ -7,7 +7,8 @@ import type { Step, StepEmitItems, StepReplay, StepSpawn, SubprocessAdapter } fr
7
7
  */
8
8
  export interface SpawnOpts<TContext = ContextData, I = unknown, O = unknown> extends StepReplay<TContext, I>, StepEmitItems<TContext, I, O> {
9
9
  id: string;
10
- child: Step<TContext, I, O>;
10
+ /** The child step, or an array of steps run in sequence. */
11
+ child: Steps<TContext, I, O>;
11
12
  context?: ContextConfig | ContextLayer[];
12
13
  timeout?: number;
13
14
  /**