@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
@@ -2,7 +2,7 @@
2
2
  * Finds expressions in a workflow tree that do not parse, so a document's
3
3
  * JSONata syntax errors fail validation instead of surfacing mid-run.
4
4
  */
5
- import { walkWorkflow } from '@noetic-tools/types';
5
+ import { isWorkflowOpShorthand, stepListEntries, walkWorkflow } from '@noetic-tools/types';
6
6
  import { syntaxError } from './jsonata.js';
7
7
  //#endregion
8
8
  //#region Public API
@@ -44,6 +44,10 @@ function expressionsOf(node) {
44
44
  ];
45
45
  }
46
46
  function kindExpressionsOf(node) {
47
+ const connection = connectionExpressionsOf(node);
48
+ if (connection !== undefined) {
49
+ return connection;
50
+ }
47
51
  if (node.kind === 'compute') {
48
52
  return [
49
53
  {
@@ -67,6 +71,81 @@ function kindExpressionsOf(node) {
67
71
  }
68
72
  return [];
69
73
  }
74
+ /** Expressions in connection nodes (spec 35): `$expr` values, connection refs, wait filters, verify subjects, and shorthand args. */
75
+ function connectionExpressionsOf(node) {
76
+ switch (node.kind) {
77
+ case 'call':
78
+ return [
79
+ ...refExpressions(node.connection, `connection of call node '${node.id}'`),
80
+ ...valueExpressions(node.args, `args of call node '${node.id}'`),
81
+ ];
82
+ case 'wait':
83
+ return [
84
+ ...refExpressions(node.connection, `connection of wait node '${node.id}'`),
85
+ ...(node.filter === undefined
86
+ ? []
87
+ : [
88
+ {
89
+ where: `filter of wait node '${node.id}'`,
90
+ source: node.filter,
91
+ },
92
+ ]),
93
+ ...shorthandExpressions(node.around, node.id),
94
+ ];
95
+ case 'verify':
96
+ return [
97
+ ...(Array.isArray(node.subject) || typeof node.subject === 'string'
98
+ ? []
99
+ : refExpressions(node.subject, `subject of verify node '${node.id}'`)),
100
+ ...shorthandExpressions(node.act, node.id),
101
+ ];
102
+ case 'sequence':
103
+ return shorthandExpressions(node.steps, node.id);
104
+ default:
105
+ return undefined;
106
+ }
107
+ }
108
+ function refExpressions(ref, where) {
109
+ if (ref === undefined || typeof ref === 'string') {
110
+ return [];
111
+ }
112
+ return [
113
+ {
114
+ where,
115
+ source: ref.$expr,
116
+ },
117
+ ];
118
+ }
119
+ /** Every `{ "$expr" }` in a value; `$literal` contents are data, not expressions. */
120
+ function valueExpressions(value, where) {
121
+ if (Array.isArray(value)) {
122
+ return value.flatMap((v) => valueExpressions(v, where));
123
+ }
124
+ if (typeof value !== 'object' || value === null) {
125
+ return [];
126
+ }
127
+ if ('$literal' in value) {
128
+ return [];
129
+ }
130
+ if ('$expr' in value && typeof value.$expr === 'string') {
131
+ return [
132
+ {
133
+ where,
134
+ source: value.$expr,
135
+ },
136
+ ];
137
+ }
138
+ return Object.values(value).flatMap((v) => valueExpressions(v, where));
139
+ }
140
+ /** Expressions in the args of operations written by name in a step list. */
141
+ function shorthandExpressions(list, parentId) {
142
+ if (list === undefined) {
143
+ return [];
144
+ }
145
+ return stepListEntries(list).flatMap((entry) => isWorkflowOpShorthand(entry)
146
+ ? Object.entries(entry).flatMap(([op, args]) => valueExpressions(args, `args of operation '${op}' in node '${parentId}'`))
147
+ : []);
148
+ }
70
149
  function untilTests(pred, where) {
71
150
  if (pred.kind === 'expr') {
72
151
  return [
@@ -22,12 +22,22 @@ export interface ExpressionLimits {
22
22
  /** How many sub-expressions one evaluation may evaluate, counting each repeat. Independent of the clock. */
23
23
  steps?: number;
24
24
  }
25
+ /**
26
+ * Per-evaluation bindings (spec 33 § The Input). `$refId` is bound on every
27
+ * compiled expression; these change with each evaluation.
28
+ */
29
+ export interface ExpressionBindings {
30
+ /** `$steps`: outputs of nodes already completed in the enclosing workflow, by node id, each read by `readInput`. */
31
+ steps?: Readonly<Record<string, unknown>>;
32
+ /** `$item`: the connection name a fan-out path runs on (spec 35 § Fan-out). */
33
+ item?: unknown;
34
+ }
25
35
  /** A compiled expression, ready to run against node input. */
26
36
  export interface CompiledExpression {
27
37
  /** Names the expression's owner in error messages, e.g. `compute node 'step'`. */
28
38
  where: string;
29
39
  /** Evaluates against `input`, already read by `readInput`. Resolves to JSONata's raw result. */
30
- run(input: unknown): Promise<unknown>;
40
+ run(input: unknown, bindings?: ExpressionBindings): Promise<unknown>;
31
41
  }
32
42
  /** @public The limits an expression runs under unless the host sets its own. */
33
43
  export declare const DEFAULT_EXPRESSION_LIMITS: Readonly<Required<ExpressionLimits>>;
@@ -48,21 +58,21 @@ export declare function syntaxError(source: string): string | undefined;
48
58
  *
49
59
  * @throws `NoeticConfigError` with code `EXPRESSION_FAILED` or `EXPRESSION_LIMIT_EXCEEDED`.
50
60
  */
51
- export declare function compute(expr: CompiledExpression, input: unknown): Promise<unknown>;
61
+ export declare function compute(expr: CompiledExpression, input: unknown, bindings?: ExpressionBindings): Promise<unknown>;
52
62
  /**
53
63
  * Evaluates like `compute`, except that "no value" resolves to `undefined`
54
64
  * instead of failing, for callers where nothing is a valid answer.
55
65
  *
56
66
  * @throws `NoeticConfigError` with code `EXPRESSION_FAILED` or `EXPRESSION_LIMIT_EXCEEDED`.
57
67
  */
58
- export declare function computeMaybe(expr: CompiledExpression, input: unknown): Promise<unknown>;
68
+ export declare function computeMaybe(expr: CompiledExpression, input: unknown, bindings?: ExpressionBindings): Promise<unknown>;
59
69
  /**
60
70
  * Evaluates an `expr` test. `true` passes; `false` and JSONata's "no value"
61
71
  * (`undefined`, e.g. a path that matched nothing) do not; anything else fails.
62
72
  *
63
73
  * @throws `NoeticConfigError` with code `EXPRESSION_FAILED` or `EXPRESSION_LIMIT_EXCEEDED`.
64
74
  */
65
- export declare function passes(expr: CompiledExpression, input: unknown): Promise<boolean>;
75
+ export declare function passes(expr: CompiledExpression, input: unknown, bindings?: ExpressionBindings): Promise<boolean>;
66
76
  /**
67
77
  * Reads a node's input as an expression sees it: a string is parsed as JSON
68
78
  * when it parses, else kept as the raw string; any other value is used as is.
@@ -4,7 +4,7 @@
4
4
  * thrown error objects into `NoeticConfigError`s, so no other module touches
5
5
  * the library or its error shapes.
6
6
  */
7
- import { frameworkCast, NoeticConfigError } from '@noetic-tools/types';
7
+ import { frameworkCast, isRef, NoeticConfigError, refId } from '@noetic-tools/types';
8
8
  import jsonata from 'jsonata';
9
9
  //#endregion
10
10
  //#region Constants
@@ -59,11 +59,12 @@ export function compileExpression(source, where, limits) {
59
59
  });
60
60
  }
61
61
  countSteps(compiled, bounds.steps);
62
+ compiled.assign('refId', refIdBinding);
62
63
  return {
63
64
  where,
64
- run: async (input) => {
65
+ run: async (input, bindings) => {
65
66
  try {
66
- return await compiled.evaluate(input);
67
+ return await compiled.evaluate(input, jsonataBindings(bindings));
67
68
  }
68
69
  catch (e) {
69
70
  throw translate(e, where, bounds);
@@ -88,8 +89,8 @@ export function syntaxError(source) {
88
89
  *
89
90
  * @throws `NoeticConfigError` with code `EXPRESSION_FAILED` or `EXPRESSION_LIMIT_EXCEEDED`.
90
91
  */
91
- export async function compute(expr, input) {
92
- const result = await computeMaybe(expr, input);
92
+ export async function compute(expr, input, bindings) {
93
+ const result = await computeMaybe(expr, input, bindings);
93
94
  if (result === undefined) {
94
95
  throw failed(expr.where, 'the expression gave no value; check the paths it reads.');
95
96
  }
@@ -101,8 +102,8 @@ export async function compute(expr, input) {
101
102
  *
102
103
  * @throws `NoeticConfigError` with code `EXPRESSION_FAILED` or `EXPRESSION_LIMIT_EXCEEDED`.
103
104
  */
104
- export async function computeMaybe(expr, input) {
105
- const result = await expr.run(input);
105
+ export async function computeMaybe(expr, input, bindings) {
106
+ const result = await expr.run(input, bindings);
106
107
  if (holdsFunction(result)) {
107
108
  throw failed(expr.where, 'the expression gave a function, which has no JSON form.');
108
109
  }
@@ -114,8 +115,8 @@ export async function computeMaybe(expr, input) {
114
115
  *
115
116
  * @throws `NoeticConfigError` with code `EXPRESSION_FAILED` or `EXPRESSION_LIMIT_EXCEEDED`.
116
117
  */
117
- export async function passes(expr, input) {
118
- const result = await expr.run(input);
118
+ export async function passes(expr, input, bindings) {
119
+ const result = await expr.run(input, bindings);
119
120
  if (result === undefined) {
120
121
  return false;
121
122
  }
@@ -141,6 +142,23 @@ export function readInput(value) {
141
142
  }
142
143
  //#endregion
143
144
  //#region Helpers
145
+ /**
146
+ * `$refId(x)`: the id inside a connection ref, since JSONata paths cannot step
147
+ * into `$`-prefixed keys. No value for anything that is not a ref.
148
+ */
149
+ function refIdBinding(value) {
150
+ return isRef(value) ? refId(value) : undefined;
151
+ }
152
+ /** The JSONata bindings for one evaluation: `$steps` always (empty when nothing ran), `$item` when set. */
153
+ function jsonataBindings(bindings) {
154
+ const out = {
155
+ steps: bindings?.steps ?? {},
156
+ };
157
+ if (bindings?.item !== undefined) {
158
+ out.item = bindings.item;
159
+ }
160
+ return out;
161
+ }
144
162
  /** `limits` over the defaults (an unset field takes its default); anything but a positive integer or `Infinity` throws. */
145
163
  function checkLimits(limits) {
146
164
  const bounds = {
@@ -0,0 +1,25 @@
1
+ /**
2
+ * The `$steps` binding's store (spec 33 § The Input): the outputs of workflow
3
+ * nodes that have completed in the enclosing workflow, by node id.
4
+ *
5
+ * One store per run and per hydrated document: keyed on the run's root context,
6
+ * so concurrent runs of the same document never read each other's outputs, and
7
+ * on the document, so two documents run in one run (a model writing and running
8
+ * two `dynamicWorkflow` documents) never read each other's node ids. Spawned and
9
+ * parallel children share their root's store.
10
+ */
11
+ import type { Context } from '@noetic-tools/types';
12
+ /**
13
+ * Marks a step so the interpreter records its output for `$steps` when it
14
+ * completes, in the store of the document `scope` stands for.
15
+ */
16
+ export declare function markRecorded(step: object, scope: object): void;
17
+ /** The document scope a step's output is recorded under, when the interpreter records it for `$steps`. */
18
+ export declare function recordedScopeOf(step: object): object | undefined;
19
+ /** Records a completed node's output under its id for later `$steps` reads in its document. A later run of the same id replaces it. */
20
+ export declare function recordStepOutput(ctx: Context, node: {
21
+ readonly scope: object;
22
+ readonly id: string;
23
+ }, output: unknown): void;
24
+ /** The `$steps` value for an expression of document `scope` evaluated in `ctx`: its recorded outputs, read by `readInput`. */
25
+ export declare function stepOutputsOf(ctx: Context, scope: object): Readonly<Record<string, unknown>>;
@@ -0,0 +1,78 @@
1
+ /**
2
+ * The `$steps` binding's store (spec 33 § The Input): the outputs of workflow
3
+ * nodes that have completed in the enclosing workflow, by node id.
4
+ *
5
+ * One store per run and per hydrated document: keyed on the run's root context,
6
+ * so concurrent runs of the same document never read each other's outputs, and
7
+ * on the document, so two documents run in one run (a model writing and running
8
+ * two `dynamicWorkflow` documents) never read each other's node ids. Spawned and
9
+ * parallel children share their root's store.
10
+ */
11
+ import { frameworkCast } from '@noetic-tools/types';
12
+ import { readInput } from './jsonata.js';
13
+ //#region State
14
+ /** Run → document scope → node id → output. */
15
+ const stores = new WeakMap();
16
+ /** Steps whose outputs are recorded — those hydrated from a JSON workflow — and the document each belongs to. */
17
+ const recorded = new WeakMap();
18
+ //#endregion
19
+ //#region Helpers
20
+ /** The topmost ancestor of `ctx`: the run's root context. */
21
+ function rootOf(ctx) {
22
+ let current = ctx;
23
+ while (current.parent) {
24
+ current = current.parent;
25
+ }
26
+ return current;
27
+ }
28
+ /**
29
+ * A key that stays the same for every view of the run's root context. Steps run
30
+ * on lanes — proxies over their context — so the context object itself differs
31
+ * per step; its abort signal does not.
32
+ */
33
+ function runKey(ctx) {
34
+ const root = rootOf(ctx);
35
+ return (frameworkCast(root).abortSignal ?? root);
36
+ }
37
+ function storeOf(ctx, scope) {
38
+ const key = runKey(ctx);
39
+ const byScope = stores.get(key) ?? new WeakMap();
40
+ stores.set(key, byScope);
41
+ const existing = byScope.get(scope);
42
+ if (existing) {
43
+ return existing;
44
+ }
45
+ const created = new Map();
46
+ byScope.set(scope, created);
47
+ return created;
48
+ }
49
+ //#endregion
50
+ //#region Public API
51
+ /**
52
+ * Marks a step so the interpreter records its output for `$steps` when it
53
+ * completes, in the store of the document `scope` stands for.
54
+ */
55
+ export function markRecorded(step, scope) {
56
+ recorded.set(step, scope);
57
+ }
58
+ /** The document scope a step's output is recorded under, when the interpreter records it for `$steps`. */
59
+ export function recordedScopeOf(step) {
60
+ return recorded.get(step);
61
+ }
62
+ /** Records a completed node's output under its id for later `$steps` reads in its document. A later run of the same id replaces it. */
63
+ export function recordStepOutput(ctx, node, output) {
64
+ storeOf(ctx, node.scope).set(node.id, output);
65
+ }
66
+ /** The `$steps` value for an expression of document `scope` evaluated in `ctx`: its recorded outputs, read by `readInput`. */
67
+ export function stepOutputsOf(ctx, scope) {
68
+ const store = stores.get(runKey(ctx))?.get(scope);
69
+ if (!store) {
70
+ return {};
71
+ }
72
+ const out = {};
73
+ for (const [id, output] of store) {
74
+ out[id] = readInput(output);
75
+ }
76
+ return out;
77
+ }
78
+ //#endregion
@@ -1,151 +1,13 @@
1
+ import type { ArtifactStore, ConnectionStatus } from '@noetic-tools/types';
1
2
  import { ItemSchemaRegistry } from '@noetic-tools/types';
2
3
  import { AcpSessionStore } from '../runtime/acp-session-store.js';
3
4
  import type { LayerStateStore, RecallCache } from './deps/context.js';
4
5
  import type { DetachedSpawnOverrides } from './deps/interpreter.js';
5
6
  import type { CheckpointStore, EventBroadcaster, RestoreCheckpointOptions, StepLedgerRetention, StepLedgerStore } from './deps/runtime.js';
6
7
  import { ChannelStore, Drains } from './deps/runtime.js';
7
- import type { AcpLiveSession, AcpSessionInfo, AgentConfig, AgentHarnessContract, AgentHooks, CallModelRequest, CancelOptions, Channel, ChannelHandle, Context, ContextCacheConfig, ContextCacheStore, ContextData, ContextLayer, CustomItem, CustomItemOf, CustomItemStreamEvent, CustomItemsBrand, CustomStreamingItem, CwdState, DecideRequest, DecideResponse, DecisionRecord, DeclaredItems, DeliveryMode, DetachedHandle, DrainReport, ExecuteInput, ExecuteOptions, ExecutionScope, ExecutionStatus, ExternalChannel, FsAdapter, HarnessResponse, HarnessStatus, Item, ItemSchemaConfig, LLMResponse, LlmProviderConfig, OnSteerParams, PendingSpend, ProjectionPolicy, RecallLayerOutput, RecallOptions, ReconcileSpendOptions, SessionScope, SessionUsage, ShellAdapter, Span, SpendSettlement, SteeringDecision, SteerVerdict, Step, StorageAdapter, StreamEvent, StreamingItem, SubprocessAdapter, Tool, ToolApprover, TraceExporter, WriteOffSpendOptions, ZodType } from './deps/types.js';
8
+ import type { AcpLiveSession, AcpSessionInfo, AgentConfig, AgentHarnessContract, CallModelRequest, CancelOptions, Channel, ChannelHandle, Context, ContextCacheStore, ContextData, ContextLayer, CustomItem, CustomItemOf, CustomItemStreamEvent, CustomStreamingItem, CwdState, DecideRequest, DecideResponse, DecisionRecord, DeclaredItems, DetachedHandle, DrainReport, ExecuteInput, ExecuteOptions, ExecutionScope, ExecutionStatus, ExternalChannel, FsAdapter, HarnessResponse, HarnessStatus, Item, LLMResponse, OnSteerParams, PendingSpend, RecallLayerOutput, RecallOptions, ReconcileSpendOptions, SessionScope, SessionUsage, ShellAdapter, Span, SpendSettlement, SteeringDecision, SteerVerdict, Step, StepLike, StepsInput, StepsOutput, StorageAdapter, StreamEvent, StreamingItem, SubprocessAdapter, TraceExporter, ValidStepChain, WriteOffSpendOptions } from './deps/types.js';
9
+ import type { AgentHarnessOpts } from './harness-options.js';
8
10
  import { Spend } from './spend.js';
9
- export { createStreamIdleWatchdog } from './model-call.js';
10
- /**
11
- * Storage-scoped environment configuration for `AgentHarness`.
12
- *
13
- * @public
14
- */
15
- export interface StorageEnvironmentConfig {
16
- /**
17
- * Key-value storage adapter backing context-layer persistence and the
18
- * step-completion ledger. Defaults to an in-memory adapter.
19
- */
20
- adapter?: StorageAdapter;
21
- /**
22
- * Checkpoint store used by `harness.checkpoint(ctx)` / `harness.restore()`.
23
- * Defaults to a store over `adapter` when one is given, so configuring durable
24
- * storage is enough for a later harness on the same storage to resume this one's
25
- * executions (see the harness `durability` option to turn that off). With no
26
- * adapter and no store, checkpoint/restore are no-ops — a zero-config harness keeps
27
- * its ephemeral semantics.
28
- */
29
- checkpointStore?: CheckpointStore;
30
- /** Layer-state store override. Defaults to an in-memory store. */
31
- layerStateStore?: LayerStateStore;
32
- /**
33
- * Bounds on the step-completion ledger that backs step-level resume. Only meaningful
34
- * when durability is on (a `checkpointStore`, given or defaulted). Defaults to `DEFAULT_STEP_LEDGER_RETENTION` — 128 KiB
35
- * per entry, 1000 entries per execution — so an unbounded run cannot grow an unbounded
36
- * ledger. Exceeding either cap costs resumability for the affected steps (they re-run),
37
- * never correctness.
38
- */
39
- stepLedgerRetention?: StepLedgerRetention;
40
- }
41
- /**
42
- * Execution-environment configuration for `AgentHarness`: the storage,
43
- * filesystem, shell, and subprocess surfaces the agent runs against.
44
- *
45
- * @public
46
- */
47
- export interface AgentEnvironmentConfig {
48
- /** Storage configuration: adapter, durability stores, ledger retention. */
49
- storage?: StorageEnvironmentConfig;
50
- /** Filesystem adapter. Defaults to an in-memory adapter. */
51
- fs?: FsAdapter;
52
- /** Shell adapter. Defaults to an in-memory adapter. */
53
- shell?: ShellAdapter;
54
- /** Subprocess adapter. Defaults to an in-memory, same-process adapter. */
55
- subprocess?: SubprocessAdapter;
56
- }
57
- interface AgentHarnessOpts<TParams extends Record<string, unknown> = Record<string, unknown>, TItem extends CustomItem = CustomItem> {
58
- name: string;
59
- /**
60
- * Root step tree executed for every turn submitted via `execute()`. The custom items
61
- * it declares (a `workflow()` step's brand) type `getItemStream`, `getFullStream`,
62
- * and `getAgentResponse` (spec 34).
63
- */
64
- agentGraph?: Step<ContextData, string, string> & CustomItemsBrand<TItem>;
65
- /** Default context layers applied to every context created via `createContext()` / `execute()`. */
66
- contextLayers?: ContextLayer[];
67
- /**
68
- * Whether runs and sessions are durable: checkpointed, recorded to the step ledger,
69
- * and resumable on a later harness over the same storage. Defaults to true whenever
70
- * `environment.storage` gives an adapter or a checkpoint store. `false` turns every
71
- * durability surface off even then — the adapter still backs context-layer
72
- * persistence.
73
- */
74
- durability?: boolean;
75
- hooks?: AgentHooks;
76
- /**
77
- * Harness-wide tool pool. Merged (identity-deduplicated) with tools
78
- * collected from `agentGraph` to form every context's `unifiedTools`.
79
- * Use this when the workflow step tree is static and tools are supplied
80
- * per harness instance rather than baked into individual `step.callModel` calls.
81
- */
82
- tools?: Tool[];
83
- params: TParams;
84
- paramsSchema?: ZodType<TParams>;
85
- /** Execution environment: storage, filesystem, shell, subprocess. */
86
- environment?: AgentEnvironmentConfig;
87
- /** Default provider configuration for model calls made through this harness. */
88
- callModelDefaults?: LlmProviderConfig;
89
- /** Harness-wide item schema extensions and validation strictness. */
90
- itemSchemas?: ItemSchemaConfig;
91
- /** Default projection policy for all LLM steps. Individual steps override via `step.projection`. */
92
- projection?: ProjectionPolicy;
93
- /** When true, every layer is recalled atomically regardless of its `recallMode`. */
94
- forceAtomicRecall?: boolean;
95
- /** Tuning for prompt-cache anchoring. See `ContextCacheConfig` for the defaults. */
96
- contextCache?: ContextCacheConfig;
97
- traceExporter?: TraceExporter;
98
- /** Default delivery mode for messages that don't specify one. Defaults to `next-turn`. */
99
- defaultDeliveryMode?: DeliveryMode;
100
- /**
101
- * Initial working directory for the harness. Used as the seed value for the
102
- * shared `cwdState.cwd` on every Context this harness creates, including
103
- * those produced by spawn/fork. Defaults to `process.cwd()`.
104
- */
105
- initialCwd?: string;
106
- /** Default model for `decide` steps. */
107
- decisionModel?: string;
108
- /**
109
- * Whether a resumed run streams again the items its replayed steps emitted
110
- * (`step.emitItems`), as `item_appended`. Defaults to `false`: a replay rebuilds the
111
- * log quietly. Set it when a client that reconnects to a resumed run should see
112
- * the progress it missed.
113
- */
114
- emitItemsOnReplay?: boolean;
115
- /**
116
- * Approves or refuses calls to tools that declare `needsApproval`, after the
117
- * `beforeToolCall` layers allow them. Without one, those calls run
118
- * unapproved and the harness warns once per tool name.
119
- */
120
- approveToolCall?: ToolApprover;
121
- /** @internal Test-only escape hatch to inject a mock callModel implementation. */
122
- _testCallModel?: (request: CallModelRequest) => Promise<LLMResponse>;
123
- /** @internal Test-only escape hatch to inject a mock decide implementation. */
124
- _testDecide?: (request: DecideRequest) => Promise<DecideResponse>;
125
- }
126
- /** Env vars consulted when resolving the LLM client (read defensively so the
127
- * harness also works in runtimes without a `process` global, e.g. the browser). */
128
- interface LlmEnv {
129
- noeticApiKey?: string;
130
- noeticBaseUrl?: string;
131
- openrouterApiKey?: string;
132
- }
133
- /** @public Effective client options resolved from config + environment. */
134
- export interface ResolvedLlmClient {
135
- apiKey: string;
136
- /** Undefined means "use the SDK's default OpenRouter base URL". */
137
- serverURL?: string;
138
- cache: boolean;
139
- }
140
- /**
141
- * Resolve the effective LLM client options from the provider config + environment.
142
- * Defaults to the Noetic platform (`provider: 'noetic'`): the `'noetic'` provider
143
- * authenticates with `NOETIC_API_KEY` and targets the Noetic platform base URL,
144
- * while `'openrouter'` authenticates with `OPENROUTER_API_KEY` and uses the SDK's
145
- * default OpenRouter endpoint. Returns undefined when no API key is available.
146
- * Exported for testing.
147
- */
148
- export declare function resolveLlmClient(config: LlmProviderConfig | undefined, env: LlmEnv): ResolvedLlmClient | undefined;
149
11
  /**
150
12
  * Default agent harness for executing agent steps with built-in channel, context, and trace support.
151
13
  * Provides channel store, context layer lifecycle, and trace export with no external dependencies.
@@ -157,6 +19,7 @@ export declare function resolveLlmClient(config: LlmProviderConfig | undefined,
157
19
  * @public
158
20
  */
159
21
  export declare class AgentHarness<TParams extends Record<string, unknown> = Record<string, unknown>, TItem extends CustomItem = never> implements AgentHarnessContract<TParams> {
22
+ #private;
160
23
  readonly config: AgentConfig<TParams>;
161
24
  readonly fs: FsAdapter;
162
25
  readonly shell: ShellAdapter;
@@ -187,20 +50,13 @@ export declare class AgentHarness<TParams extends Record<string, unknown> = Reco
187
50
  * so free functions in `runtime/durable/` (checkpoint/restore) can read it
188
51
  * without friend-class gymnastics. Do not access from outside core. */
189
52
  readonly _contextLayers?: ContextLayer[];
190
- private readonly client?;
191
- /**
192
- * SDK 1.x client for the endpoints the agent's client predates: decisions, model
193
- * prices, and generation lookups.
194
- */
195
- private readonly sdkClient?;
53
+ /** Provider clients and the model / decision calls made through them. */
54
+ private readonly llm;
196
55
  /**
197
56
  * Paid dispatch records, present exactly when durability is on.
198
57
  * @internal
199
58
  */
200
59
  readonly spend?: Spend;
201
- private readonly decideOverride?;
202
- /** Model id → whether it answers natively as a decision model. */
203
- private readonly decisionModels;
204
60
  /** @internal Channel state; read by the checkpoint functions. */
205
61
  readonly channelStore: ChannelStore;
206
62
  /**
@@ -212,7 +68,6 @@ export declare class AgentHarness<TParams extends Record<string, unknown> = Reco
212
68
  private readonly sessionStore?;
213
69
  /** Checkpoint capture in flight per execution id — see `saveCheckpoint`. */
214
70
  private readonly pendingCheckpoints;
215
- private readonly callModelOverride?;
216
71
  private readonly defaultDeliveryMode;
217
72
  private readonly sessions;
218
73
  /**
@@ -223,6 +78,8 @@ export declare class AgentHarness<TParams extends Record<string, unknown> = Reco
223
78
  readonly acpSessions: AcpSessionStore;
224
79
  /** @internal Graceful stops in progress; the interpreter and model loop hold on them. */
225
80
  readonly drains: Drains;
81
+ /** Where binary content is stored: `environment.artifacts`, else an in-memory store. */
82
+ readonly artifacts: ArtifactStore;
226
83
  /**
227
84
  * Snapshot of every live ACP sub-agent, for a UI that wants to show what is
228
85
  * running and let a user act on it. Read-only: a session's turns are driven
@@ -284,6 +141,27 @@ export declare class AgentHarness<TParams extends Record<string, unknown> = Reco
284
141
  * access from outside core. */
285
142
  readonly itemSchemas: ItemSchemaRegistry;
286
143
  constructor(opts: AgentHarnessOpts<TParams, TItem>);
144
+ /**
145
+ * Connects every connection provider and starts triggers. The first `execute()`
146
+ * or `run()` calls it; call it yourself for a harness that only reacts to
147
+ * triggers. Idempotent.
148
+ * @public
149
+ */
150
+ start(): Promise<void>;
151
+ /**
152
+ * Each connection's state, identity and pool usage; one entry for `name`, or all.
153
+ * @public
154
+ */
155
+ getConnectionStatus(name?: string): ReadonlyArray<ConnectionStatus>;
156
+ /**
157
+ * Shuts down everything the harness holds open: stops triggers, releases
158
+ * every connection and pool lease, and closes every ACP session. Call it when
159
+ * the host is done with the harness; anything left open can keep the process
160
+ * alive. Everything is closed even when one part throws; the first failure is
161
+ * then rethrown. Idempotent.
162
+ * @public
163
+ */
164
+ close(): Promise<void>;
287
165
  /**
288
166
  * Update the harness-wide root cwd. The TUI calls this in response to a
289
167
  * user-issued `! cd`, so the next root Context (and any tool inspecting
@@ -321,14 +199,24 @@ export declare class AgentHarness<TParams extends Record<string, unknown> = Reco
321
199
  callModel(request: CallModelRequest): Promise<LLMResponse>;
322
200
  decide(request: DecideRequest): Promise<DecideResponse>;
323
201
  notifyDecision(layers: ContextLayer[], record: DecisionRecord, ctx: Context): Promise<void>;
324
- run<I, O>(s: Step<ContextData, I, O>, input: I, ctx: Context): Promise<O>;
325
202
  /**
326
- * Whether `step` calls a model this harness has no credentials for. Checked
327
- * before any step runs so a missing provider fails fast instead of after
328
- * earlier steps' side effects. Steps the walk cannot see (dynamic branches)
329
- * still hit the same error lazily at their model call.
203
+ * Runs a step — or an array of steps in sequence, each output the next one's
204
+ * input. Every link of an array is type-checked (`ValidStepChain`).
205
+ */
206
+ run<I, O>(step: Step<ContextData, I, O>, input: I, ctx: Context): Promise<O>;
207
+ run<const T extends StepLike | ReadonlyArray<StepLike>>(steps: T & ValidStepChain<T>, input: StepsInput<T>, ctx: Context): Promise<StepsOutput<T>>;
208
+ /**
209
+ * Everything `run()` does before the root executes: fail fast on a missing
210
+ * model provider, connect, negotiate the root, wire the tool pool and run the
211
+ * layers' `init` hooks.
330
212
  */
331
- private lacksModelFor;
213
+ private prepareRun;
214
+ /**
215
+ * Runs `prepare`, ending any rerun allowance `ctx` carries from its restore
216
+ * when it throws: a run that fails before executing still ends the restore's
217
+ * allowance, as one that executes does.
218
+ */
219
+ private dropRerunsOnFailure;
332
220
  /** Run all layer `init` hooks before the first step executes. Per spec 11,
333
221
  * init MUST complete before any recall fires so layer state is populated. */
334
222
  private initAndRun;
@@ -351,6 +239,14 @@ export declare class AgentHarness<TParams extends Record<string, unknown> = Reco
351
239
  * the execution would, not from what the failed attempt left in memory.
352
240
  */
353
241
  private beginDurableRun;
242
+ /**
243
+ * Before a resumed run replays anything, checks the connections its ledger and
244
+ * pending entries were recorded against, discarding the ledger from the first
245
+ * entry whose connection was replaced (spec 35 § Durability).
246
+ *
247
+ * @throws NoeticErrorImpl `connection_resume_refused` when a replaced connection is unsafe to drive again.
248
+ */
249
+ private reconcileConnections;
354
250
  /**
355
251
  * Stand `ctx` at its stored baseline and give it the stored ledger. Without a
356
252
  * snapshot (its save failed), the baseline the context fixed in memory when the run
@@ -372,7 +268,12 @@ export declare class AgentHarness<TParams extends Record<string, unknown> = Reco
372
268
  * clobber accumulated in-memory state.
373
269
  */
374
270
  private ensureLayersInit;
375
- detachedSpawn<I, O>(s: Step<ContextData, I, O>, input: I, parentCtx: Context, overrides?: DetachedSpawnOverrides): DetachedHandle<O>;
271
+ /**
272
+ * Launches a step — or an array of steps, run in sequence as one background
273
+ * execution — in a fresh child context.
274
+ */
275
+ detachedSpawn<I, O>(step: Step<ContextData, I, O>, input: I, parentCtx: Context, overrides?: DetachedSpawnOverrides): DetachedHandle<O>;
276
+ detachedSpawn<const T extends StepLike | ReadonlyArray<StepLike>>(steps: T & ValidStepChain<T>, input: StepsInput<T>, parentCtx: Context, overrides?: DetachedSpawnOverrides): DetachedHandle<StepsOutput<T>>;
376
277
  createContext(opts?: {
377
278
  parent?: Context;
378
279
  /** Charge this context's usage to `parent` as it is spent. Default `true`. */
@@ -475,7 +376,15 @@ export declare class AgentHarness<TParams extends Record<string, unknown> = Reco
475
376
  * Paid calls the interrupted run left with no settled bill are held on the
476
377
  * returned context (`heldCost`) and reconciled in the background.
477
378
  */
478
- restore(executionId: string, opts?: RestoreCheckpointOptions): Promise<Context | null>;
379
+ restore(executionId: string, opts?: RestoreCheckpointOptions & {
380
+ /**
381
+ * Connections the restored run may drive again live although they were
382
+ * replaced since it stopped — the way past `connection_resume_refused` for
383
+ * a connection whose determinism is `unsafe` (spec 35 § Durability).
384
+ * Applies to this restore only; it ends when the run does.
385
+ */
386
+ readonly rerun?: ReadonlyArray<string>;
387
+ }): Promise<Context | null>;
479
388
  /**
480
389
  * Discard everything `restore(executionId)` would have used — the snapshot *and* the
481
390
  * step-completion ledger — so the next run of that execution starts clean.
@@ -553,13 +462,7 @@ export declare class AgentHarness<TParams extends Record<string, unknown> = Reco
553
462
  * (spec 09, Cancellation item 6).
554
463
  */
555
464
  private teardownCancelledContext;
556
- /**
557
- * Channel state is shared by every root on this harness, so a channel
558
- * warning is recorded as a `channel.warning` event on each live root's
559
- * span (spec 10). A root span counts only if it will reach the trace
560
- * exporter — a harness span (`SpanImpl`) with a real exporter configured.
561
- * With no such span the warning goes to the console, so it is never lost.
562
- */
465
+ /** Records a channel warning on every live root's span (see `recordChannelWarning`). */
563
466
  private recordChannelWarning;
564
467
  createSpan(name: string, parent: Span | null): Span;
565
468
  getLayerState<T>(executionId: string, layerId: string): T | undefined;