@noetic-tools/core 6.0.0 → 6.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
- import type { AnsweredAll, CaseKeyOf, Context, ContextData, DecideQuestions, DecideStep, DecideView, Lazy, ProjectionPolicy, Step, StepConditional, StepReplay } from '@noetic-tools/types';
1
+ import type { AnsweredAll, CaseKeyOf, Context, ContextData, DecideAnswers, DecideQuestions, DecideStep, DecideView, Lazy, ProjectionPolicy, Step, StepConditional, StepEmitItems, StepReplay } from '@noetic-tools/types';
2
2
  /** @public Options for `decide()`. */
3
- export interface StepDecideOpts<TContext, Q extends DecideQuestions, I = unknown> extends StepReplay<TContext, I> {
3
+ export interface StepDecideOpts<TContext, Q extends DecideQuestions, I = unknown> extends StepReplay<TContext, I>, StepEmitItems<TContext, DecideAnswers<Q>> {
4
4
  id: string;
5
5
  /** Decision model id. Falls back to `harness.config.decisionModel`. */
6
6
  model?: Lazy<string, TContext>;
@@ -40,6 +40,8 @@ A WorkflowNode is one of:
40
40
 
41
41
  Every entry of a callModel node's "tools" is an OBJECT, never a bare string. Use { "type": "<tool-name>" } to let the model call one of the tools listed below. Two provider-executed tools are also available without being listed: { "type": "openrouter:web_search" } and { "type": "openrouter:web_fetch" }, each accepting an optional "parameters" object.
42
42
 
43
+ Any node may carry "emitItems": true to show its output to the user as an assistant message the moment it finishes, or "emitItems": { "expr": "<JSONata expression on the output, e.g. 'Done ' & n & ' items'>" } to show computed text (no value shows nothing). Add "as": "items" to emit conversation items instead (the expression, or the output itself, must give an object with a string "type", or a list of them; only use custom "prefix:name" types the task says are registered). Use it for progress inside loops: only the workflow's final output is shown otherwise.
44
+
43
45
  An acp-agent node delegates a turn to an external coding agent over the Agent Client Protocol; only emit one if a matching agent adapter is registered for the workflow.
44
46
 
45
47
  An UntilPredicate (the "until" field of a loop) is one of:
@@ -1,6 +1,6 @@
1
1
  import type { ContextConfig, ContextData, ContextLayer } from '@noetic-tools/context';
2
- import type { Step, StepReplay, StepWithContext } from '@noetic-tools/types';
3
- export interface WithContextOpts<TContext, I, O> extends StepReplay<TContext, I> {
2
+ import type { Step, StepEmitItems, StepReplay, StepWithContext } from '@noetic-tools/types';
3
+ export interface WithContextOpts<TContext, I, O> extends StepReplay<TContext, I>, StepEmitItems<TContext, O> {
4
4
  id: string;
5
5
  child: Step<TContext, I, O>;
6
6
  context: ContextConfig | ContextLayer[];
@@ -1,11 +1,11 @@
1
1
  import type { ContextConfig, ContextData, ContextLayer } from '@noetic-tools/context';
2
- import type { Step, StepReplay, StepSpawn, SubprocessAdapter } from '@noetic-tools/types';
2
+ import type { Step, StepEmitItems, StepReplay, StepSpawn, SubprocessAdapter } from '@noetic-tools/types';
3
3
  /**
4
4
  * Options for {@link spawn}.
5
5
  *
6
6
  * @public
7
7
  */
8
- export interface SpawnOpts<TContext = ContextData, I = unknown, O = unknown> extends StepReplay<TContext, I> {
8
+ export interface SpawnOpts<TContext = ContextData, I = unknown, O = unknown> extends StepReplay<TContext, I>, StepEmitItems<TContext, O> {
9
9
  id: string;
10
10
  child: Step<TContext, I, O>;
11
11
  context?: ContextConfig | ContextLayer[];
@@ -1,6 +1,6 @@
1
1
  import type { ContextData } from '@noetic-tools/context';
2
- import type { AcpAgent, AcpClientCapabilityConfig, AcpContentBlock, AcpMcpServer, AcpPermissionHandler, AcpPermissionPolicy, AcpSessionPolicy, Context, Lazy, ModelParams, OutputCodec, RetryPolicy, ServerToolSpec, StandardSchemaV1, StepAcpAgent, StepCallModel, StepInvokeTool, StepReplay, StepRunCode, SubprocessAdapter, Tool, ToolChoice } from '@noetic-tools/types';
3
- export interface RunCodeOpts<TContext, I, O> extends StepReplay<TContext, I> {
2
+ import type { AcpAgent, AcpClientCapabilityConfig, AcpContentBlock, AcpMcpServer, AcpPermissionHandler, AcpPermissionPolicy, AcpSessionPolicy, Context, Lazy, ModelParams, OutputCodec, RetryPolicy, ServerToolSpec, StandardSchemaV1, StepAcpAgent, StepCallModel, StepEmitItems, StepInvokeTool, StepReplay, StepRunCode, SubprocessAdapter, Tool, ToolChoice } from '@noetic-tools/types';
3
+ export interface RunCodeOpts<TContext, I, O> extends StepReplay<TContext, I>, StepEmitItems<TContext, O> {
4
4
  id: string;
5
5
  execute: (input: I, ctx: Context<TContext>) => Promise<O>;
6
6
  retry?: RetryPolicy;
@@ -11,7 +11,7 @@ export interface RunCodeOpts<TContext, I, O> extends StepReplay<TContext, I> {
11
11
  */
12
12
  subprocess?: SubprocessAdapter;
13
13
  }
14
- export interface CallModelOpts<TContext, O, I = unknown> extends StepReplay<TContext, I> {
14
+ export interface CallModelOpts<TContext, O, I = unknown> extends StepReplay<TContext, I>, StepEmitItems<TContext, O> {
15
15
  id: string;
16
16
  /** Model id. Eager string or `(ctx) => string` getter (resolved at step execution). */
17
17
  model: Lazy<string, TContext>;
@@ -38,12 +38,12 @@ export interface CallModelOpts<TContext, O, I = unknown> extends StepReplay<TCon
38
38
  params?: ModelParams;
39
39
  emit?: boolean | ((eventType: string, data: Record<string, unknown>) => boolean);
40
40
  }
41
- export interface InvokeToolOpts<I, O, TContext = ContextData> extends StepReplay<TContext, I> {
41
+ export interface InvokeToolOpts<I, O, TContext = ContextData> extends StepReplay<TContext, I>, StepEmitItems<TContext, O> {
42
42
  id: string;
43
43
  tool: Tool<StandardSchemaV1<unknown, I>, StandardSchemaV1<unknown, O>>;
44
44
  args?: Partial<I>;
45
45
  }
46
- export interface StepAcpAgentOpts<TContext, O, I = unknown> extends StepReplay<TContext, I> {
46
+ export interface StepAcpAgentOpts<TContext, O, I = unknown> extends StepReplay<TContext, I>, StepEmitItems<TContext, O> {
47
47
  id: string;
48
48
  /** An ACP agent adapter, e.g. `claudeCode()` from `@noetic-tools/acp`. Eager or `(ctx) => AcpAgent`. */
49
49
  agent: Lazy<AcpAgent, TContext>;
@@ -66,7 +66,7 @@ export interface HydrationContext {
66
66
  * @throws `NoeticConfigError` with code `UNKNOWN_WORKFLOW_REFERENCE` (at execution time) if a subflow ref names no registered workflow.
67
67
  * @throws `NoeticConfigError` with code `WORKFLOW_RECURSION_LIMIT` (at execution time) if named sub-workflow refs nest deeper than `maxRecursionDepth`.
68
68
  * @throws `NoeticConfigError` with code `INVALID_MAX_RECURSION_DEPTH` (at execution time) when a named ref resolves under a `maxRecursionDepth` that is not a positive integer or `Infinity`.
69
- * @throws `NoeticConfigError` with code `WORKFLOW_VALIDATION_FAILED` if a `compute` expression, a conditional route's `expr`, or an `expr` until predicate does not parse.
69
+ * @throws `NoeticConfigError` with code `WORKFLOW_VALIDATION_FAILED` if a `compute` expression, a conditional route's `expr`, an `expr` until predicate, or an `emitItems` expression does not parse.
70
70
  * @throws `NoeticConfigError` with code `INVALID_EXPRESSION_LIMITS` if an expression compiles under `expressionLimits` holding a value that is not a positive integer or `Infinity`.
71
71
  * @throws `NoeticConfigError` with code `EXPRESSION_FAILED` or `EXPRESSION_LIMIT_EXCEEDED` (at execution time) if an expression fails or exceeds its limits.
72
72
  */
@@ -5,8 +5,8 @@
5
5
  * `loop`, etc.) so hydrated steps are indistinguishable from programmatic
6
6
  * ones — they register in the step registry, carry retry policies, etc.
7
7
  */
8
- import { frameworkCast, isServerToolSpec, NoeticConfigError } from '@noetic-tools/types';
9
- import { compileExpression, compute, passes, readInput } from '../expression/jsonata.js';
8
+ import { frameworkCast, ItemSchema, isServerToolSpec, NoeticConfigError, } from '@noetic-tools/types';
9
+ import { compileExpression, compute, computeMaybe, passes, readInput } from '../expression/jsonata.js';
10
10
  import { all, any } from '../until/combinators.js';
11
11
  import { until } from '../until/predicates.js';
12
12
  import { DetachedHandleImpl } from '../util/detached-handle.js';
@@ -650,6 +650,53 @@ function parseJsonObject(text) {
650
650
  return text;
651
651
  }
652
652
  }
653
+ /**
654
+ * The object form of a node's `emitItems` builds an emit function: the value is the
655
+ * `expr` result, or the output itself read as JSON, and no value emits nothing, so one
656
+ * node can emit on some iterations of a loop and stay quiet on others.
657
+ */
658
+ function workflowEmitItems(nodeId, option, ctx) {
659
+ if (typeof option === 'boolean') {
660
+ return option;
661
+ }
662
+ const where = `emitItems of node '${nodeId}'`;
663
+ const expr = option.expr === undefined
664
+ ? undefined
665
+ : compileExpression(option.expr, where, ctx.expressionLimits);
666
+ const asItems = option.as === 'items';
667
+ if (!expr && !asItems) {
668
+ return true;
669
+ }
670
+ return async (output) => {
671
+ const value = expr ? await computeMaybe(expr, readInput(output)) : readInput(output);
672
+ if (value === undefined) {
673
+ return undefined;
674
+ }
675
+ return asItems ? itemList(value, where) : stringifyResult(value);
676
+ };
677
+ }
678
+ /**
679
+ * Reads a value as items: one object or a list of them, each with a string `type`.
680
+ * Whether a type is allowed is the item log's call, against the harness's item schemas.
681
+ *
682
+ * @throws `NoeticConfigError` with code `INVALID_EMIT_ITEMS` when the value is not an
683
+ * item or a list of items.
684
+ */
685
+ function itemList(value, where) {
686
+ const list = Array.isArray(value)
687
+ ? value
688
+ : [
689
+ value,
690
+ ];
691
+ if (!list.every((entry) => ItemSchema.safeParse(entry).success)) {
692
+ throw new NoeticConfigError({
693
+ code: 'INVALID_EMIT_ITEMS',
694
+ message: `The ${where} gave ${JSON.stringify(value)}, which is not an item or a list of items.`,
695
+ hint: 'With "as": "items", give an object with a string "type" (e.g. { "type": "message", "role": "assistant", ... } or a registered custom type like "myapp:progress"), or a list of them.',
696
+ });
697
+ }
698
+ return frameworkCast(list);
699
+ }
653
700
  function stringifyResult(value) {
654
701
  if (typeof value === 'string') {
655
702
  return value;
@@ -815,7 +862,7 @@ async function runCodeViaSubprocess(opts) {
815
862
  * @throws `NoeticConfigError` with code `UNKNOWN_WORKFLOW_REFERENCE` (at execution time) if a subflow ref names no registered workflow.
816
863
  * @throws `NoeticConfigError` with code `WORKFLOW_RECURSION_LIMIT` (at execution time) if named sub-workflow refs nest deeper than `maxRecursionDepth`.
817
864
  * @throws `NoeticConfigError` with code `INVALID_MAX_RECURSION_DEPTH` (at execution time) when a named ref resolves under a `maxRecursionDepth` that is not a positive integer or `Infinity`.
818
- * @throws `NoeticConfigError` with code `WORKFLOW_VALIDATION_FAILED` if a `compute` expression, a conditional route's `expr`, or an `expr` until predicate does not parse.
865
+ * @throws `NoeticConfigError` with code `WORKFLOW_VALIDATION_FAILED` if a `compute` expression, a conditional route's `expr`, an `expr` until predicate, or an `emitItems` expression does not parse.
819
866
  * @throws `NoeticConfigError` with code `INVALID_EXPRESSION_LIMITS` if an expression compiles under `expressionLimits` holding a value that is not a positive integer or `Infinity`.
820
867
  * @throws `NoeticConfigError` with code `EXPRESSION_FAILED` or `EXPRESSION_LIMIT_EXCEEDED` (at execution time) if an expression fails or exceeds its limits.
821
868
  */
@@ -836,6 +883,9 @@ export function hydrateNode(node, ctx) {
836
883
  if (node.replayKey !== undefined) {
837
884
  hydrated.replayKey = workflowReplayKey(node.id, node.replayKey);
838
885
  }
886
+ if (node.emitItems !== undefined) {
887
+ hydrated.emitItems = workflowEmitItems(node.id, node.emitItems, ctx);
888
+ }
839
889
  return hydrated;
840
890
  }
841
891
  /**
@@ -26,6 +26,20 @@ export function expressionErrors(root) {
26
26
  //#endregion
27
27
  //#region Helpers
28
28
  function expressionsOf(node) {
29
+ const emitted = typeof node.emitItems === 'object' && node.emitItems.expr !== undefined
30
+ ? [
31
+ {
32
+ where: `emitItems of node '${node.id}'`,
33
+ source: node.emitItems.expr,
34
+ },
35
+ ]
36
+ : [];
37
+ return [
38
+ ...emitted,
39
+ ...kindExpressionsOf(node),
40
+ ];
41
+ }
42
+ function kindExpressionsOf(node) {
29
43
  if (node.kind === 'compute') {
30
44
  return [
31
45
  {
@@ -49,6 +49,13 @@ export declare function syntaxError(source: string): string | undefined;
49
49
  * @throws `NoeticConfigError` with code `EXPRESSION_FAILED` or `EXPRESSION_LIMIT_EXCEEDED`.
50
50
  */
51
51
  export declare function compute(expr: CompiledExpression, input: unknown): Promise<unknown>;
52
+ /**
53
+ * Evaluates like `compute`, except that "no value" resolves to `undefined`
54
+ * instead of failing, for callers where nothing is a valid answer.
55
+ *
56
+ * @throws `NoeticConfigError` with code `EXPRESSION_FAILED` or `EXPRESSION_LIMIT_EXCEEDED`.
57
+ */
58
+ export declare function computeMaybe(expr: CompiledExpression, input: unknown): Promise<unknown>;
52
59
  /**
53
60
  * Evaluates an `expr` test. `true` passes; `false` and JSONata's "no value"
54
61
  * (`undefined`, e.g. a path that matched nothing) do not; anything else fails.
@@ -89,10 +89,20 @@ export function syntaxError(source) {
89
89
  * @throws `NoeticConfigError` with code `EXPRESSION_FAILED` or `EXPRESSION_LIMIT_EXCEEDED`.
90
90
  */
91
91
  export async function compute(expr, input) {
92
- const result = await expr.run(input);
92
+ const result = await computeMaybe(expr, input);
93
93
  if (result === undefined) {
94
94
  throw failed(expr.where, 'the expression gave no value; check the paths it reads.');
95
95
  }
96
+ return result;
97
+ }
98
+ /**
99
+ * Evaluates like `compute`, except that "no value" resolves to `undefined`
100
+ * instead of failing, for callers where nothing is a valid answer.
101
+ *
102
+ * @throws `NoeticConfigError` with code `EXPRESSION_FAILED` or `EXPRESSION_LIMIT_EXCEEDED`.
103
+ */
104
+ export async function computeMaybe(expr, input) {
105
+ const result = await expr.run(input);
96
106
  if (holdsFunction(result)) {
97
107
  throw failed(expr.where, 'the expression gave a function, which has no JSON form.');
98
108
  }
@@ -100,6 +100,13 @@ interface AgentHarnessOpts<TParams extends Record<string, unknown> = Record<stri
100
100
  initialCwd?: string;
101
101
  /** Default model for `decide` steps. */
102
102
  decisionModel?: string;
103
+ /**
104
+ * Whether a resumed run streams again the items its replayed steps emitted
105
+ * (`step.emitItems`), as `item_appended`. Defaults to `false`: a replay rebuilds the
106
+ * log quietly. Set it when a client that reconnects to a resumed run should see
107
+ * the progress it missed.
108
+ */
109
+ emitItemsOnReplay?: boolean;
103
110
  /**
104
111
  * Approves or refuses calls to tools that declare `needsApproval`, after the
105
112
  * `beforeToolCall` layers allow them. Without one, those calls run
@@ -330,6 +330,7 @@ export class AgentHarness {
330
330
  forceAtomicRecall: opts.forceAtomicRecall,
331
331
  contextCache: opts.contextCache,
332
332
  decisionModel: opts.decisionModel,
333
+ emitItemsOnReplay: opts.emitItemsOnReplay,
333
334
  approveToolCall: opts.approveToolCall,
334
335
  };
335
336
  this.fs = environment?.fs ?? createInMemoryFsAdapter();
package/dist/index.d.ts CHANGED
@@ -119,7 +119,7 @@ export type { Expression } from '@noetic-tools/types';
119
119
  /** @public */
120
120
  export { defaultItemSchemaRegistry, ExpressionSchema, ItemSchema, ItemSchemaRegistry, } from '@noetic-tools/types';
121
121
  /** @public */
122
- export type { AcpAgentWorkflowNode, CallModelWorkflowNode, ComputeWorkflowNode, ConditionalRoute, ConditionalWorkflowNode, DecideWorkflowNode, InParallelWorkflowNode, InvokeToolWorkflowNode, LoopWorkflowNode, MergeStrategy, RouteSwitchWorkflowNode, ScheduleWorkflowNode, SequenceWorkflowNode, SpawnWorkflowNode, SubflowWorkflowNode, UntilPredicate, WithContextWorkflowNode, WorkflowDocument, WorkflowNode, } from './schemas/workflow.js';
122
+ export type { AcpAgentWorkflowNode, CallModelWorkflowNode, ComputeWorkflowNode, ConditionalRoute, ConditionalWorkflowNode, DecideWorkflowNode, InParallelWorkflowNode, InvokeToolWorkflowNode, LoopWorkflowNode, MergeStrategy, RouteSwitchWorkflowNode, ScheduleWorkflowNode, SequenceWorkflowNode, SpawnWorkflowNode, SubflowWorkflowNode, UntilPredicate, WithContextWorkflowNode, WorkflowDocument, WorkflowEmitItems, WorkflowNode, } from './schemas/workflow.js';
123
123
  /** @public */
124
124
  export { MergeStrategySchema, UntilPredicateSchema, validateWorkflow, WorkflowDocumentSchema, WorkflowNodeSchema, walkWorkflow, workflowDepth, } from './schemas/workflow.js';
125
125
  /** @public */
@@ -166,7 +166,7 @@ export type { AfterModelCallParams, AfterModelCallResult, ApproveToolCallParams,
166
166
  /** @public */
167
167
  export { LedgerEntryKind, SteeringAction } from '@noetic-tools/types';
168
168
  /** @public */
169
- export type { ExecuteStepFn, MergeFn, SettleResult, Snapshot, Step, StepAcpAgent, StepCallModel, StepConditional, StepInParallel, StepInParallelAll, StepInParallelRace, StepInParallelSettle, StepInvokeTool, StepLoop, StepReplay, StepRunCode, StepSpawn, StepWithContext, Until, UntilRun, Verdict, } from '@noetic-tools/types';
169
+ export type { ExecuteStepFn, MergeFn, SettleResult, Snapshot, Step, StepAcpAgent, StepCallModel, StepConditional, StepEmitItems, StepEmitItemsFn, StepEmitItemsOption, StepEmitItemsResult, StepInParallel, StepInParallelAll, StepInParallelRace, StepInParallelSettle, StepInvokeTool, StepLoop, StepReplay, StepRunCode, StepSpawn, StepWithContext, Until, UntilRun, Verdict, } from '@noetic-tools/types';
170
170
  /** @public */
171
171
  export type { AnsweredAll, AnswerFor, BooleanAnswer, BooleanQuestion, CaseKeyOf, ChoiceAnswer, ChoiceQuestion, ChoiceValues, DecideAnswer, DecideAnswers, DecideQuestion, DecideQuestions, DecideRequest, DecideResponse, DecideStatePart, DecideStep, DecideView, DecisionMeta, DecisionRecord, DecisionSource, LevelLabels, OnDecisionParams, RecallOptions, ScoreAnswer, ScoreLevel, ScoreQuestion, StepDecide, } from '@noetic-tools/types';
172
172
  /** @public */
@@ -0,0 +1,19 @@
1
+ import type { Context, Item, Step } from '@noetic-tools/types';
2
+ /**
3
+ * Emits what a finished step asks to (`step.emitItems`): appends the items to the item
4
+ * log and streams each as `item_appended` at once, so they reach `getItemStream` while
5
+ * the rest of the workflow still runs. Like the SDK item events, it ignores
6
+ * `step.emit` filtering. Each item is marked in the step's lane record, so the ledger
7
+ * entry that holds it can stream it again on replay.
8
+ *
9
+ * @throws `NoeticError` with kind `item_schema_mismatch` when an item's type is not
10
+ * one the context's item schemas accept.
11
+ */
12
+ export declare function emitStepItems<TContext, I, O>(step: Step<TContext, I, O>, output: O, ctx: Context<TContext>): Promise<void>;
13
+ /**
14
+ * Puts a replayed entry's items back on the log. The ones at `emitted` (the entry's
15
+ * `streamed` indices) keep their mark, so a parent that records on this resumed run
16
+ * carries it on, and stream again as `item_appended` when the harness sets
17
+ * `emitItemsOnReplay`. The rest go back quietly, as all of them do by default.
18
+ */
19
+ export declare function appendReplayed<TContext>(ctx: Context<TContext>, items: ReadonlyArray<Item>, emitted: ReadonlyArray<number>): void;
@@ -0,0 +1,106 @@
1
+ import { frameworkCast } from '@noetic-tools/types';
2
+ import { emitFrameworkEvent, getBroadcaster } from '../runtime/broadcaster-utils.js';
3
+ import { ContextImpl } from '../runtime/context-impl.js';
4
+ //#region Public API
5
+ /**
6
+ * Emits what a finished step asks to (`step.emitItems`): appends the items to the item
7
+ * log and streams each as `item_appended` at once, so they reach `getItemStream` while
8
+ * the rest of the workflow still runs. Like the SDK item events, it ignores
9
+ * `step.emit` filtering. Each item is marked in the step's lane record, so the ledger
10
+ * entry that holds it can stream it again on replay.
11
+ *
12
+ * @throws `NoeticError` with kind `item_schema_mismatch` when an item's type is not
13
+ * one the context's item schemas accept.
14
+ */
15
+ export async function emitStepItems(step, output, ctx) {
16
+ const option = step.emitItems;
17
+ if (!option) {
18
+ return;
19
+ }
20
+ const items = toItems(option === true ? outputText(output) : await option(output, ctx));
21
+ for (const item of items) {
22
+ appendEmitted(ctx, item);
23
+ streamItem(ctx, item);
24
+ }
25
+ }
26
+ /**
27
+ * Puts a replayed entry's items back on the log. The ones at `emitted` (the entry's
28
+ * `streamed` indices) keep their mark, so a parent that records on this resumed run
29
+ * carries it on, and stream again as `item_appended` when the harness sets
30
+ * `emitItemsOnReplay`. The rest go back quietly, as all of them do by default.
31
+ */
32
+ export function appendReplayed(ctx, items, emitted) {
33
+ const marked = new Set(emitted);
34
+ const stream = ctx.harness.config.emitItemsOnReplay === true;
35
+ items.forEach((item, i) => {
36
+ if (!marked.has(i)) {
37
+ ctx.itemLog.append(item);
38
+ return;
39
+ }
40
+ appendEmitted(ctx, item);
41
+ if (stream) {
42
+ streamItem(ctx, item);
43
+ }
44
+ });
45
+ }
46
+ //#endregion
47
+ //#region Helpers
48
+ function appendEmitted(ctx, item) {
49
+ if (ctx instanceof ContextImpl) {
50
+ ctx.appendEmitted(item);
51
+ return;
52
+ }
53
+ ctx.itemLog.append(item);
54
+ }
55
+ function streamItem(ctx, item) {
56
+ emitFrameworkEvent({
57
+ broadcaster: getBroadcaster(frameworkCast(ctx)),
58
+ agentName: ctx.harness.config.name,
59
+ eventType: 'item_appended',
60
+ data: {
61
+ item,
62
+ },
63
+ });
64
+ }
65
+ function outputText(output) {
66
+ if (typeof output === 'string') {
67
+ return output;
68
+ }
69
+ return output === undefined || output === null ? undefined : JSON.stringify(output);
70
+ }
71
+ function toItems(result) {
72
+ if (result === undefined || result === '') {
73
+ return [];
74
+ }
75
+ if (typeof result === 'string') {
76
+ return [
77
+ assistantMessage(result),
78
+ ];
79
+ }
80
+ return isItemList(result)
81
+ ? [
82
+ ...result,
83
+ ]
84
+ : [
85
+ result,
86
+ ];
87
+ }
88
+ function isItemList(result) {
89
+ return Array.isArray(result);
90
+ }
91
+ function assistantMessage(text) {
92
+ return {
93
+ id: `emitted-${crypto.randomUUID()}`,
94
+ type: 'message',
95
+ role: 'assistant',
96
+ status: 'completed',
97
+ content: [
98
+ {
99
+ type: 'output_text',
100
+ text,
101
+ annotations: [],
102
+ },
103
+ ],
104
+ };
105
+ }
106
+ //#endregion
@@ -3,6 +3,7 @@ import { emitFrameworkEvent, getBroadcaster, shouldEmit } from '../runtime/broad
3
3
  import { ContextImpl } from '../runtime/context-impl.js';
4
4
  import { REPLAY_KEY_PREFIX } from '../runtime/durable/step-ledger.js';
5
5
  import { DetachedHandleImpl } from '../util/detached-handle.js';
6
+ import { appendReplayed, emitStepItems } from './emit-items.js';
6
7
  import { executeAcpAgent } from './execute-acp-agent.js';
7
8
  import { executeCallModel, executeInvokeTool, executeRunCode, executeSpawn, executeWithContext, } from './execute-action.js';
8
9
  import { executeConditional, executeInParallel, executeLoop, executeSchedule, } from './execute-control.js';
@@ -175,9 +176,7 @@ function replayFromLedger(opts) {
175
176
  hit: false,
176
177
  };
177
178
  }
178
- for (const item of items) {
179
- stepCtx.itemLog.append(item);
180
- }
179
+ appendReplayed(stepCtx, items, replayed.streamed ?? []);
181
180
  emitFrameworkEvent({
182
181
  broadcaster,
183
182
  agentName,
@@ -220,6 +219,7 @@ async function recordToLedger(opts) {
220
219
  return;
221
220
  }
222
221
  const items = lane?.appendedItems() ?? [];
222
+ const streamed = lane?.emittedIndices() ?? [];
223
223
  await ledger.record({
224
224
  path: ledgerKey,
225
225
  stepId: step.id,
@@ -231,6 +231,11 @@ async function recordToLedger(opts) {
231
231
  items,
232
232
  }
233
233
  : {}),
234
+ ...(streamed.length > 0
235
+ ? {
236
+ streamed,
237
+ }
238
+ : {}),
234
239
  completedAt: new Date().toISOString(),
235
240
  });
236
241
  }
@@ -379,6 +384,9 @@ export async function execute(step, input, ctx) {
379
384
  });
380
385
  }
381
386
  }
387
+ // Inside the try, so an item the schemas refuse fails the dispatch like any other
388
+ // error; before the ledger record, so the entry holds the items and replays them.
389
+ await emitStepItems(step, result, stepCtx);
382
390
  }
383
391
  catch (error) {
384
392
  lane?.releaseDispatch();
@@ -228,6 +228,19 @@ export declare class ContextImpl implements Context<ContextData> {
228
228
  * dispatched on the same context. Empty on the context itself.
229
229
  */
230
230
  appendedItems(): Item[];
231
+ /**
232
+ * @internal
233
+ * Indices into `appendedItems()` of the items appended through `appendEmitted`, which
234
+ * a replay streams again under the harness's `emitItemsOnReplay`.
235
+ */
236
+ emittedIndices(): number[];
237
+ /**
238
+ * @internal
239
+ * Append an item a step emitted (`step.emitItems`), marking it in this lane's record
240
+ * and every record above it, so the ledger entry that holds it knows to stream it
241
+ * again on replay.
242
+ */
243
+ appendEmitted(item: Item): void;
231
244
  /**
232
245
  * @internal
233
246
  * Drop `frame` from the in-flight set. Called when its step resolves, success or
@@ -380,6 +380,33 @@ export class ContextImpl {
380
380
  ...(this._lane?.appended.items ?? []),
381
381
  ];
382
382
  }
383
+ /**
384
+ * @internal
385
+ * Indices into `appendedItems()` of the items appended through `appendEmitted`, which
386
+ * a replay streams again under the harness's `emitItemsOnReplay`.
387
+ */
388
+ emittedIndices() {
389
+ const record = this._lane?.appended;
390
+ if (!record) {
391
+ return [];
392
+ }
393
+ return record.items.flatMap((item, i) => record.emitted.has(item)
394
+ ? [
395
+ i,
396
+ ]
397
+ : []);
398
+ }
399
+ /**
400
+ * @internal
401
+ * Append an item a step emitted (`step.emitItems`), marking it in this lane's record
402
+ * and every record above it, so the ledger entry that holds it knows to stream it
403
+ * again on replay.
404
+ */
405
+ appendEmitted(item) {
406
+ this.itemLog.append(item);
407
+ const items = this.itemLog.items;
408
+ this._lane?.appended.markEmitted(items[items.length - 1]);
409
+ }
383
410
  /**
384
411
  * @internal
385
412
  * Drop `frame` from the in-flight set. Called when its step resolves, success or
@@ -492,6 +519,8 @@ export class ContextImpl {
492
519
  class AppendRecord {
493
520
  parent;
494
521
  items = [];
522
+ /** The items among `items` a step emitted through `emitItems`. */
523
+ emitted = new Set();
495
524
  constructor(parent) {
496
525
  this.parent = parent;
497
526
  }
@@ -499,6 +528,10 @@ class AppendRecord {
499
528
  this.items.push(item);
500
529
  this.parent?.add(item);
501
530
  }
531
+ markEmitted(item) {
532
+ this.emitted.add(item);
533
+ this.parent?.markEmitted(item);
534
+ }
502
535
  }
503
536
  /** The context each lane views, so `laneOf` never stacks a proxy on a proxy. */
504
537
  const laneTargets = new WeakMap();
@@ -43,6 +43,7 @@ export declare const StepLedgerEntrySchema: z.ZodObject<{
43
43
  output: z.ZodUnknown;
44
44
  inputHash: z.ZodOptional<z.ZodString>;
45
45
  items: z.ZodOptional<z.ZodArray<z.ZodUnknown>>;
46
+ streamed: z.ZodOptional<z.ZodArray<z.ZodNumber>>;
46
47
  completedAt: z.ZodString;
47
48
  }, z.core.$strip>;
48
49
  /** @public A completed step recorded for replay. */
@@ -55,6 +55,11 @@ export const StepLedgerEntrySchema = z.object({
55
55
  inputHash: z.string().optional(),
56
56
  /** Items the step appended to its context's item log, re-appended on replay. */
57
57
  items: z.array(z.unknown()).optional(),
58
+ /**
59
+ * Indices into `items` of those `step.emitItems` emitted (spec 01 § Emitting items),
60
+ * streamed again on replay when the harness sets `emitItemsOnReplay`.
61
+ */
62
+ streamed: z.array(z.number().int().nonnegative()).optional(),
58
63
  completedAt: z.string(),
59
64
  });
60
65
  /** @public Retention applied when a harness does not configure `stepLedgerRetention`. */
@@ -3,5 +3,5 @@
3
3
  * consumers can validate workflow documents without importing core.
4
4
  * This barrel keeps core's public and intra-core import paths unchanged.
5
5
  */
6
- export type { AcpAgentWorkflowNode, CallModelWorkflowNode, ComputeWorkflowNode, ConditionalRoute, ConditionalWorkflowNode, DecideWorkflowNode, InParallelWorkflowNode, InvokeToolWorkflowNode, LoopWorkflowNode, OutputCodecRef, RouteSwitchWorkflowNode, RunCodeWorkflowNode, ScheduleWorkflowNode, SequenceWorkflowNode, SpawnWorkflowNode, SubflowWorkflowNode, UntilPredicate, WithContextWorkflowNode, WorkflowDocument, WorkflowGraph, WorkflowNode, WorkflowReplayKey, } from '@noetic-tools/types';
6
+ export type { AcpAgentWorkflowNode, CallModelWorkflowNode, ComputeWorkflowNode, ConditionalRoute, ConditionalWorkflowNode, DecideWorkflowNode, InParallelWorkflowNode, InvokeToolWorkflowNode, LoopWorkflowNode, OutputCodecRef, RouteSwitchWorkflowNode, RunCodeWorkflowNode, ScheduleWorkflowNode, SequenceWorkflowNode, SpawnWorkflowNode, SubflowWorkflowNode, UntilPredicate, WithContextWorkflowNode, WorkflowDocument, WorkflowEmitItems, WorkflowGraph, WorkflowNode, WorkflowReplayKey, } from '@noetic-tools/types';
7
7
  export { MergeStrategy, MergeStrategySchema, UntilPredicateSchema, validateWorkflow, WorkflowDocumentSchema, WorkflowNodeSchema, walkWorkflow, workflowDepth, workflowGraph, } from '@noetic-tools/types';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@noetic-tools/core",
3
- "version": "6.0.0",
3
+ "version": "6.1.0",
4
4
  "type": "module",
5
5
  "description": "Step primitives, interpreter, runtime, and context layer contract for Noetic agents.",
6
6
  "license": "Apache-2.0",
@@ -69,7 +69,7 @@
69
69
  },
70
70
  "dependencies": {
71
71
  "@noetic-tools/context": "^1.9.0",
72
- "@noetic-tools/types": "^4.0.0",
72
+ "@noetic-tools/types": "^4.1.0",
73
73
  "@openrouter/agent": "^0.11.0",
74
74
  "@openrouter/sdk": "1.4.25",
75
75
  "jsonata": "2.2.2",
@@ -60,6 +60,29 @@
60
60
  }
61
61
  ]
62
62
  },
63
+ "emitItems": {
64
+ "anyOf": [
65
+ {
66
+ "type": "boolean"
67
+ },
68
+ {
69
+ "type": "object",
70
+ "properties": {
71
+ "expr": {
72
+ "$ref": "#/$defs/Expression"
73
+ },
74
+ "as": {
75
+ "type": "string",
76
+ "enum": [
77
+ "text",
78
+ "items"
79
+ ]
80
+ }
81
+ },
82
+ "additionalProperties": false
83
+ }
84
+ ]
85
+ },
63
86
  "model": {
64
87
  "type": "string"
65
88
  },
@@ -217,6 +240,29 @@
217
240
  }
218
241
  ]
219
242
  },
243
+ "emitItems": {
244
+ "anyOf": [
245
+ {
246
+ "type": "boolean"
247
+ },
248
+ {
249
+ "type": "object",
250
+ "properties": {
251
+ "expr": {
252
+ "$ref": "#/$defs/Expression"
253
+ },
254
+ "as": {
255
+ "type": "string",
256
+ "enum": [
257
+ "text",
258
+ "items"
259
+ ]
260
+ }
261
+ },
262
+ "additionalProperties": false
263
+ }
264
+ ]
265
+ },
220
266
  "toolName": {
221
267
  "type": "string",
222
268
  "minLength": 1
@@ -275,6 +321,29 @@
275
321
  }
276
322
  ]
277
323
  },
324
+ "emitItems": {
325
+ "anyOf": [
326
+ {
327
+ "type": "boolean"
328
+ },
329
+ {
330
+ "type": "object",
331
+ "properties": {
332
+ "expr": {
333
+ "$ref": "#/$defs/Expression"
334
+ },
335
+ "as": {
336
+ "type": "string",
337
+ "enum": [
338
+ "text",
339
+ "items"
340
+ ]
341
+ }
342
+ },
343
+ "additionalProperties": false
344
+ }
345
+ ]
346
+ },
278
347
  "execute": {
279
348
  "type": "string",
280
349
  "minLength": 1
@@ -362,6 +431,29 @@
362
431
  }
363
432
  ]
364
433
  },
434
+ "emitItems": {
435
+ "anyOf": [
436
+ {
437
+ "type": "boolean"
438
+ },
439
+ {
440
+ "type": "object",
441
+ "properties": {
442
+ "expr": {
443
+ "$ref": "#/$defs/Expression"
444
+ },
445
+ "as": {
446
+ "type": "string",
447
+ "enum": [
448
+ "text",
449
+ "items"
450
+ ]
451
+ }
452
+ },
453
+ "additionalProperties": false
454
+ }
455
+ ]
456
+ },
365
457
  "expr": {
366
458
  "$ref": "#/$defs/Expression"
367
459
  }
@@ -412,6 +504,29 @@
412
504
  }
413
505
  ]
414
506
  },
507
+ "emitItems": {
508
+ "anyOf": [
509
+ {
510
+ "type": "boolean"
511
+ },
512
+ {
513
+ "type": "object",
514
+ "properties": {
515
+ "expr": {
516
+ "$ref": "#/$defs/Expression"
517
+ },
518
+ "as": {
519
+ "type": "string",
520
+ "enum": [
521
+ "text",
522
+ "items"
523
+ ]
524
+ }
525
+ },
526
+ "additionalProperties": false
527
+ }
528
+ ]
529
+ },
415
530
  "routes": {
416
531
  "minItems": 1,
417
532
  "type": "array",
@@ -485,6 +600,29 @@
485
600
  }
486
601
  ]
487
602
  },
603
+ "emitItems": {
604
+ "anyOf": [
605
+ {
606
+ "type": "boolean"
607
+ },
608
+ {
609
+ "type": "object",
610
+ "properties": {
611
+ "expr": {
612
+ "$ref": "#/$defs/Expression"
613
+ },
614
+ "as": {
615
+ "type": "string",
616
+ "enum": [
617
+ "text",
618
+ "items"
619
+ ]
620
+ }
621
+ },
622
+ "additionalProperties": false
623
+ }
624
+ ]
625
+ },
488
626
  "model": {
489
627
  "type": "string",
490
628
  "minLength": 1
@@ -689,6 +827,29 @@
689
827
  }
690
828
  ]
691
829
  },
830
+ "emitItems": {
831
+ "anyOf": [
832
+ {
833
+ "type": "boolean"
834
+ },
835
+ {
836
+ "type": "object",
837
+ "properties": {
838
+ "expr": {
839
+ "$ref": "#/$defs/Expression"
840
+ },
841
+ "as": {
842
+ "type": "string",
843
+ "enum": [
844
+ "text",
845
+ "items"
846
+ ]
847
+ }
848
+ },
849
+ "additionalProperties": false
850
+ }
851
+ ]
852
+ },
692
853
  "decide": {
693
854
  "type": "object",
694
855
  "properties": {
@@ -728,6 +889,29 @@
728
889
  }
729
890
  ]
730
891
  },
892
+ "emitItems": {
893
+ "anyOf": [
894
+ {
895
+ "type": "boolean"
896
+ },
897
+ {
898
+ "type": "object",
899
+ "properties": {
900
+ "expr": {
901
+ "$ref": "#/$defs/Expression"
902
+ },
903
+ "as": {
904
+ "type": "string",
905
+ "enum": [
906
+ "text",
907
+ "items"
908
+ ]
909
+ }
910
+ },
911
+ "additionalProperties": false
912
+ }
913
+ ]
914
+ },
731
915
  "model": {
732
916
  "type": "string",
733
917
  "minLength": 1
@@ -965,6 +1149,29 @@
965
1149
  }
966
1150
  ]
967
1151
  },
1152
+ "emitItems": {
1153
+ "anyOf": [
1154
+ {
1155
+ "type": "boolean"
1156
+ },
1157
+ {
1158
+ "type": "object",
1159
+ "properties": {
1160
+ "expr": {
1161
+ "$ref": "#/$defs/Expression"
1162
+ },
1163
+ "as": {
1164
+ "type": "string",
1165
+ "enum": [
1166
+ "text",
1167
+ "items"
1168
+ ]
1169
+ }
1170
+ },
1171
+ "additionalProperties": false
1172
+ }
1173
+ ]
1174
+ },
968
1175
  "mode": {
969
1176
  "type": "string",
970
1177
  "enum": [
@@ -1047,6 +1254,29 @@
1047
1254
  }
1048
1255
  ]
1049
1256
  },
1257
+ "emitItems": {
1258
+ "anyOf": [
1259
+ {
1260
+ "type": "boolean"
1261
+ },
1262
+ {
1263
+ "type": "object",
1264
+ "properties": {
1265
+ "expr": {
1266
+ "$ref": "#/$defs/Expression"
1267
+ },
1268
+ "as": {
1269
+ "type": "string",
1270
+ "enum": [
1271
+ "text",
1272
+ "items"
1273
+ ]
1274
+ }
1275
+ },
1276
+ "additionalProperties": false
1277
+ }
1278
+ ]
1279
+ },
1050
1280
  "child": {
1051
1281
  "$ref": "#/$defs/WorkflowNode"
1052
1282
  },
@@ -1109,6 +1339,29 @@
1109
1339
  }
1110
1340
  ]
1111
1341
  },
1342
+ "emitItems": {
1343
+ "anyOf": [
1344
+ {
1345
+ "type": "boolean"
1346
+ },
1347
+ {
1348
+ "type": "object",
1349
+ "properties": {
1350
+ "expr": {
1351
+ "$ref": "#/$defs/Expression"
1352
+ },
1353
+ "as": {
1354
+ "type": "string",
1355
+ "enum": [
1356
+ "text",
1357
+ "items"
1358
+ ]
1359
+ }
1360
+ },
1361
+ "additionalProperties": false
1362
+ }
1363
+ ]
1364
+ },
1112
1365
  "child": {
1113
1366
  "$ref": "#/$defs/WorkflowNode"
1114
1367
  },
@@ -1168,6 +1421,29 @@
1168
1421
  }
1169
1422
  ]
1170
1423
  },
1424
+ "emitItems": {
1425
+ "anyOf": [
1426
+ {
1427
+ "type": "boolean"
1428
+ },
1429
+ {
1430
+ "type": "object",
1431
+ "properties": {
1432
+ "expr": {
1433
+ "$ref": "#/$defs/Expression"
1434
+ },
1435
+ "as": {
1436
+ "type": "string",
1437
+ "enum": [
1438
+ "text",
1439
+ "items"
1440
+ ]
1441
+ }
1442
+ },
1443
+ "additionalProperties": false
1444
+ }
1445
+ ]
1446
+ },
1171
1447
  "body": {
1172
1448
  "$ref": "#/$defs/WorkflowNode"
1173
1449
  },
@@ -1235,6 +1511,29 @@
1235
1511
  }
1236
1512
  ]
1237
1513
  },
1514
+ "emitItems": {
1515
+ "anyOf": [
1516
+ {
1517
+ "type": "boolean"
1518
+ },
1519
+ {
1520
+ "type": "object",
1521
+ "properties": {
1522
+ "expr": {
1523
+ "$ref": "#/$defs/Expression"
1524
+ },
1525
+ "as": {
1526
+ "type": "string",
1527
+ "enum": [
1528
+ "text",
1529
+ "items"
1530
+ ]
1531
+ }
1532
+ },
1533
+ "additionalProperties": false
1534
+ }
1535
+ ]
1536
+ },
1238
1537
  "steps": {
1239
1538
  "minItems": 1,
1240
1539
  "type": "array",
@@ -1289,6 +1588,29 @@
1289
1588
  }
1290
1589
  ]
1291
1590
  },
1591
+ "emitItems": {
1592
+ "anyOf": [
1593
+ {
1594
+ "type": "boolean"
1595
+ },
1596
+ {
1597
+ "type": "object",
1598
+ "properties": {
1599
+ "expr": {
1600
+ "$ref": "#/$defs/Expression"
1601
+ },
1602
+ "as": {
1603
+ "type": "string",
1604
+ "enum": [
1605
+ "text",
1606
+ "items"
1607
+ ]
1608
+ }
1609
+ },
1610
+ "additionalProperties": false
1611
+ }
1612
+ ]
1613
+ },
1292
1614
  "step": {
1293
1615
  "$ref": "#/$defs/WorkflowNode"
1294
1616
  },
@@ -1351,6 +1673,29 @@
1351
1673
  }
1352
1674
  ]
1353
1675
  },
1676
+ "emitItems": {
1677
+ "anyOf": [
1678
+ {
1679
+ "type": "boolean"
1680
+ },
1681
+ {
1682
+ "type": "object",
1683
+ "properties": {
1684
+ "expr": {
1685
+ "$ref": "#/$defs/Expression"
1686
+ },
1687
+ "as": {
1688
+ "type": "string",
1689
+ "enum": [
1690
+ "text",
1691
+ "items"
1692
+ ]
1693
+ }
1694
+ },
1695
+ "additionalProperties": false
1696
+ }
1697
+ ]
1698
+ },
1354
1699
  "document": {
1355
1700
  "$ref": "#"
1356
1701
  },
@@ -1407,6 +1752,29 @@
1407
1752
  }
1408
1753
  ]
1409
1754
  },
1755
+ "emitItems": {
1756
+ "anyOf": [
1757
+ {
1758
+ "type": "boolean"
1759
+ },
1760
+ {
1761
+ "type": "object",
1762
+ "properties": {
1763
+ "expr": {
1764
+ "$ref": "#/$defs/Expression"
1765
+ },
1766
+ "as": {
1767
+ "type": "string",
1768
+ "enum": [
1769
+ "text",
1770
+ "items"
1771
+ ]
1772
+ }
1773
+ },
1774
+ "additionalProperties": false
1775
+ }
1776
+ ]
1777
+ },
1410
1778
  "agent": {
1411
1779
  "type": "string",
1412
1780
  "minLength": 1
@@ -1926,6 +2294,29 @@
1926
2294
  }
1927
2295
  ]
1928
2296
  },
2297
+ "emitItems": {
2298
+ "anyOf": [
2299
+ {
2300
+ "type": "boolean"
2301
+ },
2302
+ {
2303
+ "type": "object",
2304
+ "properties": {
2305
+ "expr": {
2306
+ "$ref": "#/$defs/Expression"
2307
+ },
2308
+ "as": {
2309
+ "type": "string",
2310
+ "enum": [
2311
+ "text",
2312
+ "items"
2313
+ ]
2314
+ }
2315
+ },
2316
+ "additionalProperties": false
2317
+ }
2318
+ ]
2319
+ },
1929
2320
  "model": {
1930
2321
  "type": "string",
1931
2322
  "minLength": 1