@noetic-tools/core 5.13.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.
Files changed (42) hide show
  1. package/dist/builders/decide-builders.d.ts +2 -2
  2. package/dist/builders/dynamic-workflow.js +2 -0
  3. package/dist/builders/provide-builder.d.ts +2 -2
  4. package/dist/builders/spawn-builder.d.ts +2 -2
  5. package/dist/builders/step-builders.d.ts +5 -5
  6. package/dist/builders/workflow-hydrator.d.ts +1 -1
  7. package/dist/builders/workflow-hydrator.js +53 -3
  8. package/dist/expression/check.js +14 -0
  9. package/dist/expression/jsonata.d.ts +7 -0
  10. package/dist/expression/jsonata.js +11 -1
  11. package/dist/harness/agent-harness.d.ts +59 -5
  12. package/dist/harness/agent-harness.js +176 -25
  13. package/dist/harness/deps/runtime.d.ts +4 -0
  14. package/dist/harness/deps/runtime.js +2 -0
  15. package/dist/harness/model-call.js +69 -0
  16. package/dist/harness/model-rounds.d.ts +52 -0
  17. package/dist/harness/model-rounds.js +115 -0
  18. package/dist/harness/thread-record.d.ts +54 -0
  19. package/dist/harness/thread-record.js +159 -0
  20. package/dist/index.d.ts +2 -2
  21. package/dist/interpreter/emit-items.d.ts +19 -0
  22. package/dist/interpreter/emit-items.js +106 -0
  23. package/dist/interpreter/execute-action.js +3 -0
  24. package/dist/interpreter/execute-control.js +3 -0
  25. package/dist/interpreter/execute.js +66 -9
  26. package/dist/runtime/context-impl.d.ts +106 -4
  27. package/dist/runtime/context-impl.js +224 -14
  28. package/dist/runtime/durable/harness-checkpoints.d.ts +13 -3
  29. package/dist/runtime/durable/harness-checkpoints.js +66 -7
  30. package/dist/runtime/durable/session-store.d.ts +37 -0
  31. package/dist/runtime/durable/session-store.js +58 -0
  32. package/dist/runtime/durable/step-ledger.d.ts +77 -40
  33. package/dist/runtime/durable/step-ledger.js +193 -73
  34. package/dist/runtime/item-log-impl.d.ts +6 -0
  35. package/dist/runtime/item-log-impl.js +12 -0
  36. package/dist/runtime/session-runner.d.ts +25 -1
  37. package/dist/runtime/session-runner.js +83 -11
  38. package/dist/schemas/workflow.d.ts +1 -1
  39. package/dist/types/checkpoint.d.ts +21 -4
  40. package/dist/types/checkpoint.js +33 -3
  41. package/package.json +2 -2
  42. package/schema/noetic-workflow.schema.json +391 -0
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Durable sessions: what lets a new harness pick up a thread that `execute()` drove on
3
+ * an earlier one. See `runtime/durable/session-store` for the stored shape.
4
+ *
5
+ * Storage is the only record. Nothing here is cached between calls: every turn reads
6
+ * the thread's history and in-flight turn from the store, and every change is a
7
+ * read-modify-write of the stored record, so a harness that served the last turn and
8
+ * a harness built a moment ago behave the same.
9
+ */
10
+ import type { Context, Item, SessionUsage } from '@noetic-tools/types';
11
+ import type { RestoreCheckpointOptions, SessionStore, TurnUsage } from './deps/runtime.js';
12
+ /** @internal The harness surface a thread record needs. */
13
+ export interface ThreadRecordHost {
14
+ readonly store: SessionStore;
15
+ restore(executionId: string, opts: RestoreCheckpointOptions): Promise<Context | null>;
16
+ clearCheckpoint(executionId: string): Promise<void>;
17
+ parseItems(raw: unknown[]): Item[];
18
+ }
19
+ /**
20
+ * @internal
21
+ * One thread's stored session. Turns call `history` → `resume` → `begin` → `end`; a
22
+ * turn that throws never reaches `end`, so its record stays for a re-delivery of the
23
+ * same messages to resume. Operations run one at a time, in call order, so a read
24
+ * never overtakes a write issued before it.
25
+ */
26
+ export declare class ThreadRecord {
27
+ private readonly host;
28
+ private readonly threadId;
29
+ private queue;
30
+ constructor(host: ThreadRecordHost, threadId: string);
31
+ /** The history the thread's next turn builds on: what storage holds, or none. */
32
+ history(): Promise<Item[]>;
33
+ /** Replace the stored history (`seedSessionHistory`). */
34
+ seed(items: ReadonlyArray<Item>): Promise<void>;
35
+ /**
36
+ * The context of the cut-off turn, when `messageIds` re-deliver exactly its
37
+ * messages. A cut-off turn that is not re-delivered is abandoned: its record is
38
+ * dropped, its checkpoint cleared, and the new messages start a fresh turn.
39
+ */
40
+ resume(messageIds: ReadonlyArray<string>, opts: RestoreCheckpointOptions): Promise<Context | undefined>;
41
+ /** Record the turn about to run on `ctx`, before any of it runs. */
42
+ begin(ctx: Context, messageIds: ReadonlyArray<string>): Promise<void>;
43
+ /** The turn on `ctx` finished: store the history it left and drop its checkpoint. */
44
+ end(ctx: Context, history: ReadonlyArray<Item>): Promise<void>;
45
+ /** Add one turn's spend to the stored totals, and return the totals now stored. */
46
+ addUsage(spent: TurnUsage): Promise<SessionUsage>;
47
+ /** The stored totals. */
48
+ usage(): Promise<SessionUsage>;
49
+ private update;
50
+ /** Read-modify-write the stored record. Call only from inside `run`. */
51
+ private write;
52
+ private load;
53
+ private run;
54
+ }
@@ -0,0 +1,159 @@
1
+ /**
2
+ * Durable sessions: what lets a new harness pick up a thread that `execute()` drove on
3
+ * an earlier one. See `runtime/durable/session-store` for the stored shape.
4
+ *
5
+ * Storage is the only record. Nothing here is cached between calls: every turn reads
6
+ * the thread's history and in-flight turn from the store, and every change is a
7
+ * read-modify-write of the stored record, so a harness that served the last turn and
8
+ * a harness built a moment ago behave the same.
9
+ */
10
+ const EMPTY_USAGE = {
11
+ inputTokens: 0,
12
+ outputTokens: 0,
13
+ };
14
+ //#endregion
15
+ //#region ThreadRecord
16
+ /**
17
+ * @internal
18
+ * One thread's stored session. Turns call `history` → `resume` → `begin` → `end`; a
19
+ * turn that throws never reaches `end`, so its record stays for a re-delivery of the
20
+ * same messages to resume. Operations run one at a time, in call order, so a read
21
+ * never overtakes a write issued before it.
22
+ */
23
+ export class ThreadRecord {
24
+ host;
25
+ threadId;
26
+ queue = Promise.resolve();
27
+ constructor(host, threadId) {
28
+ this.host = host;
29
+ this.threadId = threadId;
30
+ }
31
+ /** The history the thread's next turn builds on: what storage holds, or none. */
32
+ history() {
33
+ return this.run(async () => this.host.parseItems((await this.load())?.items ?? []));
34
+ }
35
+ /** Replace the stored history (`seedSessionHistory`). */
36
+ seed(items) {
37
+ return this.update((record) => ({
38
+ ...record,
39
+ items: [
40
+ ...items,
41
+ ],
42
+ }));
43
+ }
44
+ /**
45
+ * The context of the cut-off turn, when `messageIds` re-deliver exactly its
46
+ * messages. A cut-off turn that is not re-delivered is abandoned: its record is
47
+ * dropped, its checkpoint cleared, and the new messages start a fresh turn.
48
+ */
49
+ resume(messageIds, opts) {
50
+ return this.run(async () => {
51
+ const turn = (await this.load())?.turn;
52
+ if (!turn) {
53
+ return undefined;
54
+ }
55
+ if (sameIds(turn.messageIds, messageIds)) {
56
+ return (await this.host.restore(turn.executionId, opts)) ?? undefined;
57
+ }
58
+ await this.write(withoutTurn);
59
+ await this.host.clearCheckpoint(turn.executionId);
60
+ return undefined;
61
+ });
62
+ }
63
+ /** Record the turn about to run on `ctx`, before any of it runs. */
64
+ begin(ctx, messageIds) {
65
+ return this.update((record) => ({
66
+ ...record,
67
+ turn: {
68
+ executionId: ctx.id,
69
+ messageIds: [
70
+ ...messageIds,
71
+ ],
72
+ },
73
+ }));
74
+ }
75
+ /** The turn on `ctx` finished: store the history it left and drop its checkpoint. */
76
+ async end(ctx, history) {
77
+ await this.update((record) => ({
78
+ ...withoutTurn(record),
79
+ items: [
80
+ ...history,
81
+ ],
82
+ }));
83
+ await this.host.clearCheckpoint(ctx.id);
84
+ }
85
+ /** Add one turn's spend to the stored totals, and return the totals now stored. */
86
+ addUsage(spent) {
87
+ return this.run(async () => {
88
+ const usage = addUsage((await this.load())?.usage ?? EMPTY_USAGE, spent);
89
+ await this.write((record) => ({
90
+ ...record,
91
+ usage,
92
+ }));
93
+ return usage;
94
+ });
95
+ }
96
+ /** The stored totals. */
97
+ usage() {
98
+ return this.run(async () => (await this.load())?.usage ?? EMPTY_USAGE);
99
+ }
100
+ update(change) {
101
+ return this.run(() => this.write(change));
102
+ }
103
+ /** Read-modify-write the stored record. Call only from inside `run`. */
104
+ async write(change) {
105
+ const record = change((await this.load()) ?? {
106
+ items: [],
107
+ });
108
+ try {
109
+ await this.host.store.save(this.threadId, record);
110
+ }
111
+ catch (error) {
112
+ // Same rule as checkpoints: losing the record costs resumability, not the turn.
113
+ console.warn(`AgentHarness: failed to persist session "${this.threadId}":`, error instanceof Error ? error.message : String(error));
114
+ }
115
+ }
116
+ load() {
117
+ return this.host.store.load(this.threadId);
118
+ }
119
+ run(op) {
120
+ const next = this.queue.then(op);
121
+ this.queue = next.catch(() => { });
122
+ return next;
123
+ }
124
+ }
125
+ function withoutTurn(record) {
126
+ const { turn, ...rest } = record;
127
+ void turn;
128
+ return rest;
129
+ }
130
+ function sameIds(a, b) {
131
+ return a.length === b.length && a.every((id, i) => id === b[i]);
132
+ }
133
+ function addUsage(total, spent) {
134
+ const cost = (total.cost ?? 0) + spent.cost;
135
+ const billedCost = (total.billedCost ?? 0) + spent.billedCost;
136
+ const cachedTokens = spent.cachedTokens === undefined
137
+ ? total.cachedTokens
138
+ : (total.cachedTokens ?? 0) + spent.cachedTokens;
139
+ return {
140
+ inputTokens: total.inputTokens + spent.inputTokens,
141
+ outputTokens: total.outputTokens + spent.outputTokens,
142
+ ...(cachedTokens !== undefined
143
+ ? {
144
+ cachedTokens,
145
+ }
146
+ : {}),
147
+ ...(cost > 0
148
+ ? {
149
+ cost,
150
+ }
151
+ : {}),
152
+ ...(billedCost > 0
153
+ ? {
154
+ billedCost,
155
+ }
156
+ : {}),
157
+ };
158
+ }
159
+ //#endregion
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
@@ -439,6 +439,7 @@ function recordTurnOutcome(params) {
439
439
  toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
440
440
  usage: response.usage,
441
441
  cost: response.cost,
442
+ billedCost: response.billedCost,
442
443
  serviceTier: response.serviceTier,
443
444
  responseItems: response.items,
444
445
  };
@@ -736,6 +737,8 @@ export async function executeSpawn(step, input, ctx, executeStep, opts) {
736
737
  // with the ones recorded inside the same spawn rather than at the root.
737
738
  pathPrefix: baseCtx instanceof ContextImpl ? baseCtx.currentPath() : '',
738
739
  ledger: baseCtx instanceof ContextImpl ? baseCtx.ledger : undefined,
740
+ // The child's steps checkpoint the root, as an inParallel path's do.
741
+ checkpointFn: () => baseCtx.checkpoint(),
739
742
  });
740
743
  // `childExecutionCtx` predates the spawn span; the child's hooks trace onto that span.
741
744
  const childTracedCtx = {
@@ -42,6 +42,9 @@ function createChildContexts(ctx, paths, stepId) {
42
42
  * restart at the root and collide with its siblings. */
43
43
  pathPrefix: `${parentPath}[${index}]`,
44
44
  ledger: parentLedger,
45
+ // A path's steps checkpoint the root: its usage, state, and layer folds roll
46
+ // into what a resumed root restores.
47
+ checkpointFn: () => ctx.checkpoint(),
45
48
  items: [
46
49
  ...ctx.itemLog.items,
47
50
  ],
@@ -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';
@@ -144,13 +145,16 @@ export function resolveLedgerKey(step, input, ctx) {
144
145
  }
145
146
  }
146
147
  /**
147
- * Resume path: when a previous run recorded this exact step at `ledgerKey`,
148
- * replay its output instead of re-running, and emit `step_replayed`. Returns
149
- * `{ hit: false }` when there is nothing to replay so the caller dispatches the
150
- * step normally.
148
+ * Resume path: when a previous run recorded this exact step at `ledgerKey` on the same
149
+ * input, replay its output instead of re-running, put the items it appended back on
150
+ * `stepCtx`'s item log, and emit `step_replayed`. Returns `{ hit: false }` when there
151
+ * is nothing to replay so the caller dispatches the step normally.
152
+ *
153
+ * The items go back through `stepCtx` so the lanes above it note them too: a parent
154
+ * that completes on this resumed run records everything beneath it, replayed or not.
151
155
  */
152
156
  function replayFromLedger(opts) {
153
- const { ledger, ledgerKey, step, broadcaster, agentName } = opts;
157
+ const { ledger, ledgerKey, inputHash, step, stepCtx, broadcaster, agentName } = opts;
154
158
  if (!ledger || ledgerKey === undefined || ledger.isEmpty) {
155
159
  return {
156
160
  hit: false,
@@ -159,12 +163,20 @@ function replayFromLedger(opts) {
159
163
  const replayed = ledger.take(ledgerKey, {
160
164
  id: step.id,
161
165
  kind: step.kind,
166
+ inputHash,
162
167
  });
163
168
  if (!replayed) {
164
169
  return {
165
170
  hit: false,
166
171
  };
167
172
  }
173
+ const items = parseRecordedItems(stepCtx, replayed.items ?? []);
174
+ if (!items) {
175
+ return {
176
+ hit: false,
177
+ };
178
+ }
179
+ appendReplayed(stepCtx, items, replayed.streamed ?? []);
168
180
  emitFrameworkEvent({
169
181
  broadcaster,
170
182
  agentName,
@@ -180,20 +192,50 @@ function replayFromLedger(opts) {
180
192
  };
181
193
  }
182
194
  /**
183
- * Record a completed step's output so a resumed run replays it rather than
184
- * re-executing. A no-op without a ledger or ledger key. Only successes reach
185
- * here — a step that threw skips this call in `execute` and runs again on resume.
195
+ * Recorded items, parsed through the context's item schemas, or null when one no longer
196
+ * parses — a registry that changed since the run was recorded. The step then runs fresh
197
+ * rather than half-replaying its history.
198
+ */
199
+ function parseRecordedItems(ctx, raw) {
200
+ if (raw.length === 0) {
201
+ return [];
202
+ }
203
+ try {
204
+ return frameworkCast(ctx).itemSchemas?.parseMany(raw) ?? frameworkCast(raw);
205
+ }
206
+ catch {
207
+ return null;
208
+ }
209
+ }
210
+ /**
211
+ * Record a completed step's output, input hash, and the items it appended, so a resumed
212
+ * run replays this step rather than re-executing it. A no-op without a ledger or ledger
213
+ * key. Only successes reach here — a step that threw skips this call in `execute` and
214
+ * runs again on resume.
186
215
  */
187
216
  async function recordToLedger(opts) {
188
- const { ledger, ledgerKey, step, output } = opts;
217
+ const { ledger, ledgerKey, inputHash, lane, step, output } = opts;
189
218
  if (!ledger || ledgerKey === undefined) {
190
219
  return;
191
220
  }
221
+ const items = lane?.appendedItems() ?? [];
222
+ const streamed = lane?.emittedIndices() ?? [];
192
223
  await ledger.record({
193
224
  path: ledgerKey,
194
225
  stepId: step.id,
195
226
  kind: step.kind,
196
227
  output,
228
+ inputHash,
229
+ ...(items.length > 0
230
+ ? {
231
+ items,
232
+ }
233
+ : {}),
234
+ ...(streamed.length > 0
235
+ ? {
236
+ streamed,
237
+ }
238
+ : {}),
197
239
  completedAt: new Date().toISOString(),
198
240
  });
199
241
  }
@@ -263,11 +305,17 @@ export async function execute(step, input, ctx) {
263
305
  * output instead of re-running it. `ledgerKey`/`ledger` are captured before
264
306
  * dispatch and reused by the record below. */
265
307
  const ledgerKey = resolveLedgerKey(step, input, stepCtx);
308
+ if (ledgerKey === undefined) {
309
+ lane?.skipLedger();
310
+ }
311
+ const inputHash = ledgerKey === undefined ? undefined : lane?.currentDispatch()?.inputHash;
266
312
  const ledger = impl?.ledger;
267
313
  const replay = replayFromLedger({
268
314
  ledger,
269
315
  ledgerKey,
316
+ inputHash,
270
317
  step,
318
+ stepCtx,
271
319
  broadcaster,
272
320
  agentName,
273
321
  });
@@ -336,6 +384,13 @@ export async function execute(step, input, ctx) {
336
384
  });
337
385
  }
338
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);
390
+ }
391
+ catch (error) {
392
+ lane?.releaseDispatch();
393
+ throw error;
339
394
  }
340
395
  finally {
341
396
  lane?.leaveStep(frame);
@@ -359,6 +414,8 @@ export async function execute(step, input, ctx) {
359
414
  await recordToLedger({
360
415
  ledger,
361
416
  ledgerKey,
417
+ inputHash,
418
+ lane,
362
419
  step,
363
420
  output: result,
364
421
  });