@noetic-tools/core 5.16.0 → 5.17.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.
@@ -6,8 +6,8 @@ import { AcpSessionStore } from '../runtime/acp-session-store.js';
6
6
  import { callDecide } from './decide-call.js';
7
7
  import { createInMemoryFsAdapter, createInMemoryShellAdapter, createInMemorySubprocessAdapter, OpenRouter, OpenRouterSdk, } from './deps/adapters.js';
8
8
  import { afterModelCallLayers, allocateBudgets, assembleView, beforeToolCallLayers, completeLayers, contextToExecCtx, createContextCacheStore, createLayerStateStore, createRecallCache, DEFAULT_PROJECTION, disposeLayers, executeRerender, initLayers, notifyDecision, onSteerLayers, projectHistoryLayers, recallLayers, recallLayersAtomic, recallLayersEventual, resolveLayerTools, runAppendPipeline, storeLayers, } from './deps/context.js';
9
- import { collectAllTools, collectCustomItems, customItemGates, deduplicateTools, dispatchStepThroughAdapter, execute, prepareBandedView, someStep, } from './deps/interpreter.js';
10
- import { buildItemStream, ChannelStore, ContextImpl, captureCheckpoint, clearCheckpoint, collectContextTree, createCheckpointStore, createInMemoryStorage, createSessionStore, createStepLedgerStore, filterReasoningStream, filterTextStream, INTERRUPT_REASON, resolveStepLedgerRetention, restoreFromCheckpoint, rootIdOf, SessionRunner, StepLedger, snapshotCwdState, warnToConsole, } from './deps/runtime.js';
9
+ import { collectAllTools, collectCustomItems, deduplicateTools, dispatchStepThroughAdapter, execute, prepareBandedView, someStep, } from './deps/interpreter.js';
10
+ import { buildItemStream, ChannelStore, ContextImpl, captureCheckpoint, clearCheckpoint, collectContextTree, createCheckpointStore, createInMemoryStorage, createSessionStore, createStepLedgerStore, customItemGates, filterReasoningStream, filterTextStream, INTERRUPT_REASON, isSteer, resolveStepLedgerRetention, restoreFromCheckpoint, rootIdOf, SessionRunner, StepLedger, snapshotCwdState, warnToConsole, } from './deps/runtime.js';
11
11
  import { SteeringAction } from './deps/types.js';
12
12
  import { AgentHarnessModelCaller, noLlmProviderError } from './model-call.js';
13
13
  import { ThreadRecord } from './thread-record.js';
@@ -374,7 +374,7 @@ export class AgentHarness {
374
374
  strictUnknownExtensions: opts.itemSchemas?.strict ?? true,
375
375
  }).extend({
376
376
  items: opts.agentGraph
377
- ? customItemGates(collectCustomItems(frameworkCast(opts.agentGraph)))
377
+ ? customItemGates(collectCustomItems(frameworkCast(opts.agentGraph)).map((item) => item.type))
378
378
  : [],
379
379
  });
380
380
  this.rootCwdState = {
@@ -422,7 +422,11 @@ export class AgentHarness {
422
422
  void session.runner.abort(INTERRUPT_REASON);
423
423
  return Promise.resolve();
424
424
  }
425
+ const steersRunningTurn = session.runner.getStatus().kind === 'generating' && isSteer(message);
425
426
  session.runner.enqueue(message);
427
+ if (steersRunningTurn) {
428
+ void session.record?.keepSteer(message);
429
+ }
426
430
  return Promise.resolve();
427
431
  }
428
432
  /** The turn's response. `items` holds final items: standard ones and the graph's declared custom items. */
@@ -505,7 +509,7 @@ export class AgentHarness {
505
509
  // Save a turn's items as the thread's history for the next turn.
506
510
  const keepHistory = async (ctx) => {
507
511
  if (record) {
508
- await record.end(ctx, ctx.itemLog.items);
512
+ await record.end(ctx, ctx.itemLog.items, session.runner.queue.peekAll().map((message) => message.id));
509
513
  return;
510
514
  }
511
515
  session.accumulatedItems = [
@@ -554,6 +558,14 @@ export class AgentHarness {
554
558
  ...this.harnessTools,
555
559
  ]);
556
560
  }
561
+ // Steers the last harness accepted but never applied go back in the queue;
562
+ // ones already in the conversation are skipped when offered.
563
+ for (const steer of (await record?.steers()) ?? []) {
564
+ const queued = session.runner.queue.peekAll().some((m) => m.id === steer.id);
565
+ if (!queued && !messageIds.includes(steer.id)) {
566
+ session.runner.queue.enqueue(steer);
567
+ }
568
+ }
557
569
  await record?.begin(ctx, messageIds);
558
570
  return ctx;
559
571
  },
@@ -770,9 +782,11 @@ export class AgentHarness {
770
782
  async rebuildFromStorage(ctx) {
771
783
  await this.pendingCheckpoints.get(ctx.id);
772
784
  const snapshot = await this.checkpointStore?.load(ctx.id).catch(() => null);
785
+ ctx.allowItemTypes(snapshot?.customItemTypes ?? []);
786
+ const itemSchemas = ctx.itemSchemas ?? this.itemSchemas;
773
787
  ctx.rebase(snapshot
774
788
  ? {
775
- items: this.itemSchemas.parseMany(snapshot.itemLog.items),
789
+ items: itemSchemas.parseMany(snapshot.itemLog.items),
776
790
  occurrences: snapshot.occurrences,
777
791
  }
778
792
  : ctx.runBaseline());
@@ -1,6 +1,6 @@
1
1
  export { collectAllTools, deduplicateTools } from '../../interpreter/collect-tools.js';
2
2
  export { prepareBandedView } from '../../interpreter/context-assembly.js';
3
- export { collectCustomItems, customItemGates } from '../../interpreter/emit-items.js';
3
+ export { collectCustomItems } from '../../interpreter/emit-items.js';
4
4
  export { execute } from '../../interpreter/execute.js';
5
5
  export type { DetachedSpawnOverrides } from '../../interpreter/step-dispatcher.js';
6
6
  export { dispatchStepThroughAdapter } from '../../interpreter/step-dispatcher.js';
@@ -1,6 +1,6 @@
1
1
  export { collectAllTools, deduplicateTools } from '../../interpreter/collect-tools.js';
2
2
  export { prepareBandedView } from '../../interpreter/context-assembly.js';
3
- export { collectCustomItems, customItemGates } from '../../interpreter/emit-items.js';
3
+ export { collectCustomItems } from '../../interpreter/emit-items.js';
4
4
  export { execute } from '../../interpreter/execute.js';
5
5
  export { dispatchStepThroughAdapter } from '../../interpreter/step-dispatcher.js';
6
6
  export { someStep } from '../../interpreter/step-walk.js';
@@ -12,8 +12,9 @@ export type { StepLedgerEntry, StepLedgerRetention, StepLedgerStore, } from '../
12
12
  export { createStepLedgerStore, resolveStepLedgerRetention, StepLedger, } from '../../runtime/durable/step-ledger.js';
13
13
  export type { EventBroadcaster } from '../../runtime/event-broadcaster.js';
14
14
  export { createInMemoryStorage } from '../../runtime/in-memory-storage.js';
15
+ export { customItemGates } from '../../runtime/item-gates.js';
15
16
  export type { QueuedMessage, SessionCtxExtension } from '../../runtime/message-queue.js';
16
- export { INTERRUPT_REASON } from '../../runtime/message-queue.js';
17
+ export { INTERRUPT_REASON, isSteer } from '../../runtime/message-queue.js';
17
18
  export type { TurnUsage } from '../../runtime/session-runner.js';
18
19
  export { SessionRunner } from '../../runtime/session-runner.js';
19
20
  export { buildItemStream, filterReasoningStream, filterTextStream, } from '../../runtime/session-streams.js';
@@ -6,6 +6,7 @@ export { captureCheckpoint, clearCheckpoint, restoreFromCheckpoint, } from '../.
6
6
  export { createSessionStore } from '../../runtime/durable/session-store.js';
7
7
  export { createStepLedgerStore, resolveStepLedgerRetention, StepLedger, } from '../../runtime/durable/step-ledger.js';
8
8
  export { createInMemoryStorage } from '../../runtime/in-memory-storage.js';
9
- export { INTERRUPT_REASON } from '../../runtime/message-queue.js';
9
+ export { customItemGates } from '../../runtime/item-gates.js';
10
+ export { INTERRUPT_REASON, isSteer } from '../../runtime/message-queue.js';
10
11
  export { SessionRunner } from '../../runtime/session-runner.js';
11
12
  export { buildItemStream, filterReasoningStream, filterTextStream, } from '../../runtime/session-streams.js';
@@ -43,7 +43,8 @@ export declare class AgentHarnessModelCaller {
43
43
  /**
44
44
  * Offer queued steers before a model call and add the applied ones to the
45
45
  * conversation. They join `allItems` rather than the log so the log keeps
46
- * them in the order the model saw them.
46
+ * them in the order the model saw them. Returns whether a layer asked for
47
+ * recall to run again before the call goes on.
47
48
  */
48
49
  private applySteers;
49
50
  private parseRoundItems;
@@ -66,6 +66,9 @@ function providerTerminalError(response) {
66
66
  function replayOutput(input, roundItems) {
67
67
  input.push(...itemsToInput(roundItems.filter((item) => !isFunctionCall(item))));
68
68
  }
69
+ function hasItem(items, id) {
70
+ return items.some((item) => 'id' in item && item.id === id);
71
+ }
69
72
  function hasUsableResponseOutput(response, items) {
70
73
  if (items.length > 0) {
71
74
  return true;
@@ -529,11 +532,13 @@ export class AgentHarnessModelCaller {
529
532
  cost,
530
533
  });
531
534
  };
535
+ let stoppedForRecall = false;
532
536
  const steers = openSteerInbox({
533
537
  ctx: request.ctx,
534
538
  layers: request.layers ?? [],
535
539
  harness: this.opts.harness,
536
540
  emit: prepared.emitIfAllowed,
541
+ inConversation: (itemId) => hasItem(allItems, itemId) || hasItem(request.ctx?.itemLog.items ?? [], itemId),
537
542
  });
538
543
  while (!request.signal?.aborted) {
539
544
  const replayed = roundLedger?.take(round, replaySchemas);
@@ -575,7 +580,7 @@ export class AgentHarnessModelCaller {
575
580
  const recoveryContinuation = useEphemeralContinue;
576
581
  useEphemeralContinue = false;
577
582
  if (steers) {
578
- await this.applySteers({
583
+ const recall = await this.applySteers({
579
584
  steers,
580
585
  ctx: request.ctx,
581
586
  conversationInput,
@@ -583,6 +588,10 @@ export class AgentHarnessModelCaller {
583
588
  round,
584
589
  emitIfAllowed: prepared.emitIfAllowed,
585
590
  });
591
+ if (recall) {
592
+ stoppedForRecall = true;
593
+ break;
594
+ }
586
595
  }
587
596
  const roundController = new AbortController();
588
597
  const roundSignal = request.signal
@@ -809,6 +818,11 @@ export class AgentHarnessModelCaller {
809
818
  },
810
819
  rounds,
811
820
  cost: totalCost > 0 ? totalCost : undefined,
821
+ ...(stoppedForRecall
822
+ ? {
823
+ recall: true,
824
+ }
825
+ : {}),
812
826
  ...(replayedCost !== undefined
813
827
  ? {
814
828
  billedCost: totalCost - replayedCost,
@@ -824,14 +838,15 @@ export class AgentHarnessModelCaller {
824
838
  /**
825
839
  * Offer queued steers before a model call and add the applied ones to the
826
840
  * conversation. They join `allItems` rather than the log so the log keeps
827
- * them in the order the model saw them.
841
+ * them in the order the model saw them. Returns whether a layer asked for
842
+ * recall to run again before the call goes on.
828
843
  */
829
844
  async applySteers(params) {
830
845
  const { steers, ctx, conversationInput, allItems } = params;
831
846
  await steers.offer(SteerPoint.BeforeRound);
832
- const { messageIds, items } = steers.takeStaged();
847
+ const { messageIds, items, recall } = steers.takeStaged();
833
848
  if (messageIds.length === 0) {
834
- return;
849
+ return false;
835
850
  }
836
851
  conversationInput.push(...itemsToInput(items));
837
852
  for (const item of items) {
@@ -843,6 +858,7 @@ export class AgentHarnessModelCaller {
843
858
  count: messageIds.length,
844
859
  messageIds,
845
860
  });
861
+ return recall;
846
862
  }
847
863
  parseRoundItems(request, items) {
848
864
  const roundItemSchemas = buildItemSchemaRegistry({
@@ -5,6 +5,8 @@ import type { MessageQueue } from '../runtime/message-queue.js';
5
5
  export interface StagedSteers {
6
6
  messageIds: string[];
7
7
  items: Item[];
8
+ /** A layer asked for recall to run again once these are applied. */
9
+ recall: boolean;
8
10
  }
9
11
  interface SteerInboxOpts {
10
12
  queue: MessageQueue;
@@ -12,6 +14,8 @@ interface SteerInboxOpts {
12
14
  layers: ContextLayer[];
13
15
  harness: AgentHarnessContract;
14
16
  emit: (eventType: string, data: Record<string, unknown>) => void;
17
+ /** Whether an item with this id is already in the conversation. */
18
+ inConversation: (itemId: string) => boolean;
15
19
  }
16
20
  /**
17
21
  * @internal Open the steer inbox for a model call, or `undefined` when the call
@@ -42,6 +46,7 @@ export declare class SteerInbox {
42
46
  offer(point: SteerPoint, pendingCalls?: ReadonlyArray<FunctionCallItem>): Promise<boolean>;
43
47
  /** Hand over the staged steers and clear them. */
44
48
  takeStaged(): StagedSteers;
49
+ private alreadyApplied;
45
50
  private judge;
46
51
  /** Steers are user input, so they pass through `onItemAppend` like any other.
47
52
  * Re-render requests are ignored: recall does not run again mid-call. */
@@ -33,6 +33,7 @@ export class SteerInbox {
33
33
  staged = {
34
34
  messageIds: [],
35
35
  items: [],
36
+ recall: false,
36
37
  };
37
38
  /** Steers already reported as waiting on tool calls, so each is reported once. */
38
39
  reportedPending = new Set();
@@ -52,7 +53,14 @@ export class SteerInbox {
52
53
  async offer(point, pendingCalls = []) {
53
54
  let stagedAny = false;
54
55
  for (const message of this.opts.queue.peekAll().filter(isSteer)) {
55
- const verdict = await this.judge(message, point, pendingCalls);
56
+ const items = steerItems(message);
57
+ // A resumed turn re-queues the steers its last run kept; the ones that run
58
+ // already applied come back with the replayed rounds and steps.
59
+ if (this.alreadyApplied(items)) {
60
+ this.opts.queue.take((queued) => queued === message);
61
+ continue;
62
+ }
63
+ const verdict = await this.judge(message, items, point, pendingCalls);
56
64
  if (verdict.action === SteerAction.Defer) {
57
65
  this.reportPending(message, point, pendingCalls);
58
66
  continue;
@@ -68,7 +76,7 @@ export class SteerInbox {
68
76
  });
69
77
  continue;
70
78
  }
71
- await this.stage(message.id, verdict.items);
79
+ await this.stage(message.id, verdict.items, verdict.recall === true);
72
80
  stagedAny = true;
73
81
  }
74
82
  return stagedAny;
@@ -79,12 +87,16 @@ export class SteerInbox {
79
87
  this.staged = {
80
88
  messageIds: [],
81
89
  items: [],
90
+ recall: false,
82
91
  };
83
92
  return staged;
84
93
  }
85
- async judge(message, point, pendingCalls) {
94
+ alreadyApplied(items) {
95
+ return (items.length > 0 &&
96
+ items.every((item) => 'id' in item && item.id !== undefined && this.opts.inConversation(item.id)));
97
+ }
98
+ async judge(message, items, point, pendingCalls) {
86
99
  const action = defaultAction(point, message.deliveryMode);
87
- const items = inputToItems(message.input);
88
100
  const { harness, layers } = this.opts;
89
101
  if (!harness.onSteer || !layers.some((layer) => layer.hooks.onSteer)) {
90
102
  return {
@@ -104,12 +116,13 @@ export class SteerInbox {
104
116
  }
105
117
  /** Steers are user input, so they pass through `onItemAppend` like any other.
106
118
  * Re-render requests are ignored: recall does not run again mid-call. */
107
- async stage(messageId, items) {
119
+ async stage(messageId, items, recall) {
108
120
  const piped = this.opts.layers.length > 0
109
121
  ? (await this.opts.harness.runAppendPipeline(this.opts.layers, items, this.opts.ctx)).items
110
122
  : items;
111
123
  this.staged.messageIds.push(messageId);
112
124
  this.staged.items.push(...piped);
125
+ this.staged.recall ||= recall;
113
126
  }
114
127
  reportPending(message, point, pendingCalls) {
115
128
  if (point !== SteerPoint.BeforeToolCall || this.reportedPending.has(message.id)) {
@@ -124,6 +137,33 @@ export class SteerInbox {
124
137
  }
125
138
  //#endregion
126
139
  //#region Helpers
140
+ /**
141
+ * A steer's items. Text gets an id from the message id rather than a random one,
142
+ * so a resumed turn can tell the steer is already in the conversation.
143
+ */
144
+ function steerItems(message) {
145
+ if (typeof message.input !== 'string') {
146
+ return inputToItems(message.input);
147
+ }
148
+ if (message.input.length === 0) {
149
+ return [];
150
+ }
151
+ const item = {
152
+ id: `steer-${message.id}`,
153
+ type: 'message',
154
+ role: 'user',
155
+ status: 'completed',
156
+ content: [
157
+ {
158
+ type: 'input_text',
159
+ text: message.input,
160
+ },
161
+ ],
162
+ };
163
+ return [
164
+ item,
165
+ ];
166
+ }
127
167
  function findSessionQueue(ctx) {
128
168
  for (let current = ctx; current; current = current.parent) {
129
169
  const ext = frameworkCast(current);
@@ -8,7 +8,7 @@
8
8
  * a harness built a moment ago behave the same.
9
9
  */
10
10
  import type { Context, Item, SessionUsage } from '@noetic-tools/types';
11
- import type { RestoreCheckpointOptions, SessionStore, TurnUsage } from './deps/runtime.js';
11
+ import type { QueuedMessage, RestoreCheckpointOptions, SessionStore, TurnUsage } from './deps/runtime.js';
12
12
  /** @internal The harness surface a thread record needs. */
13
13
  export interface ThreadRecordHost {
14
14
  readonly store: SessionStore;
@@ -20,7 +20,8 @@ export interface ThreadRecordHost {
20
20
  * @internal
21
21
  * One thread's stored session. Turns call `history` → `resume` → `begin` → `end`; a
22
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
23
+ * same messages to resume. Steers sent into a running turn are kept with `keepSteer`
24
+ * until `end`. Operations run one at a time, in call order, so a read
24
25
  * never overtakes a write issued before it.
25
26
  */
26
27
  export declare class ThreadRecord {
@@ -38,10 +39,20 @@ export declare class ThreadRecord {
38
39
  * dropped, its checkpoint cleared, and the new messages start a fresh turn.
39
40
  */
40
41
  resume(messageIds: ReadonlyArray<string>, opts: RestoreCheckpointOptions): Promise<Context | undefined>;
41
- /** Record the turn about to run on `ctx`, before any of it runs. */
42
+ /** Keep a steer sent into the running turn, so a resumed turn still applies it. */
43
+ keepSteer(message: QueuedMessage): Promise<void>;
44
+ /** The steers kept for the turn in flight, as queue messages. */
45
+ steers(): Promise<QueuedMessage[]>;
46
+ /**
47
+ * Record the turn about to run on `ctx`, before any of it runs. Kept steers it
48
+ * delivers as input stop being steers: re-delivering the turn re-sends them.
49
+ */
42
50
  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>;
51
+ /**
52
+ * The turn on `ctx` finished: store the history it left and drop its checkpoint.
53
+ * Only steers still queued are kept; the rest were applied or dropped.
54
+ */
55
+ end(ctx: Context, history: ReadonlyArray<Item>, queuedIds: ReadonlyArray<string>): Promise<void>;
45
56
  /** Add one turn's spend to the stored totals, and return the totals now stored. */
46
57
  addUsage(spent: TurnUsage): Promise<SessionUsage>;
47
58
  /** The stored totals. */
@@ -49,6 +60,7 @@ export declare class ThreadRecord {
49
60
  private update;
50
61
  /** Read-modify-write the stored record. Call only from inside `run`. */
51
62
  private write;
63
+ private parseInput;
52
64
  private load;
53
65
  private run;
54
66
  }
@@ -17,7 +17,8 @@ const EMPTY_USAGE = {
17
17
  * @internal
18
18
  * One thread's stored session. Turns call `history` → `resume` → `begin` → `end`; a
19
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
20
+ * same messages to resume. Steers sent into a running turn are kept with `keepSteer`
21
+ * until `end`. Operations run one at a time, in call order, so a read
21
22
  * never overtakes a write issued before it.
22
23
  */
23
24
  export class ThreadRecord {
@@ -60,10 +61,45 @@ export class ThreadRecord {
60
61
  return undefined;
61
62
  });
62
63
  }
63
- /** Record the turn about to run on `ctx`, before any of it runs. */
64
+ /** Keep a steer sent into the running turn, so a resumed turn still applies it. */
65
+ keepSteer(message) {
66
+ if (message.deliveryMode !== 'between-rounds' && message.deliveryMode !== 'next-item') {
67
+ return Promise.resolve();
68
+ }
69
+ const steer = {
70
+ id: message.id,
71
+ input: message.input,
72
+ deliveryMode: message.deliveryMode,
73
+ enqueuedAt: message.enqueuedAt,
74
+ };
75
+ return this.update((record) => ({
76
+ ...record,
77
+ steers: [
78
+ ...(record.steers ?? []).filter((kept) => kept.id !== steer.id),
79
+ steer,
80
+ ],
81
+ }));
82
+ }
83
+ /** The steers kept for the turn in flight, as queue messages. */
84
+ steers() {
85
+ return this.run(async () => ((await this.load())?.steers ?? []).map((steer) => ({
86
+ id: steer.id,
87
+ input: this.parseInput(steer.input),
88
+ deliveryMode: steer.deliveryMode,
89
+ // Options carry live objects (layers, state) that storage cannot hold; a
90
+ // steer applied mid-turn never reads them.
91
+ options: {},
92
+ enqueuedAt: steer.enqueuedAt,
93
+ })));
94
+ }
95
+ /**
96
+ * Record the turn about to run on `ctx`, before any of it runs. Kept steers it
97
+ * delivers as input stop being steers: re-delivering the turn re-sends them.
98
+ */
64
99
  begin(ctx, messageIds) {
65
100
  return this.update((record) => ({
66
101
  ...record,
102
+ steers: record.steers?.filter((steer) => !messageIds.includes(steer.id)),
67
103
  turn: {
68
104
  executionId: ctx.id,
69
105
  messageIds: [
@@ -72,10 +108,14 @@ export class ThreadRecord {
72
108
  },
73
109
  }));
74
110
  }
75
- /** The turn on `ctx` finished: store the history it left and drop its checkpoint. */
76
- async end(ctx, history) {
111
+ /**
112
+ * The turn on `ctx` finished: store the history it left and drop its checkpoint.
113
+ * Only steers still queued are kept; the rest were applied or dropped.
114
+ */
115
+ async end(ctx, history, queuedIds) {
77
116
  await this.update((record) => ({
78
117
  ...withoutTurn(record),
118
+ steers: record.steers?.filter((steer) => queuedIds.includes(steer.id)),
79
119
  items: [
80
120
  ...history,
81
121
  ],
@@ -113,6 +153,16 @@ export class ThreadRecord {
113
153
  console.warn(`AgentHarness: failed to persist session "${this.threadId}":`, error instanceof Error ? error.message : String(error));
114
154
  }
115
155
  }
156
+ parseInput(input) {
157
+ if (typeof input === 'string') {
158
+ return input;
159
+ }
160
+ return this.host.parseItems(Array.isArray(input)
161
+ ? input
162
+ : [
163
+ input,
164
+ ]);
165
+ }
116
166
  load() {
117
167
  return this.host.store.load(this.threadId);
118
168
  }
@@ -1,5 +1,4 @@
1
1
  import type { Context, CustomItem, Item, Step } from '@noetic-tools/types';
2
- import type { ZodTypeAny } from 'zod';
3
2
  /**
4
3
  * Starts what a step emits (spec 34 § Emitting): opens the dispatch's custom item, if
5
4
  * `emitItems` names one, and runs `onStart` with the step's input. Events stream at
@@ -41,11 +40,6 @@ export declare function allowCustomItems<TContext, I, O>(step: Step<TContext, I,
41
40
  * before it rebuilds or restores a log that may hold them.
42
41
  */
43
42
  export declare function collectCustomItems(step: Step): CustomItem[];
44
- /**
45
- * Schemas that let a context's item log accept these items' final forms. They gate on
46
- * `type` and `id` only: the emitter has already checked the fields against `output`.
47
- */
48
- export declare function customItemGates(items: ReadonlyArray<CustomItem>): ZodTypeAny[];
49
43
  /**
50
44
  * Puts a replayed entry's items back on the log. The ones at `emitted` (the entry's
51
45
  * `streamed` indices) keep their mark, so a parent that records on this resumed run
@@ -1,5 +1,4 @@
1
1
  import { frameworkCast, NoeticConfigError, validateSchema } from '@noetic-tools/types';
2
- import { z } from 'zod';
3
2
  import { emitFrameworkEvent, getBroadcaster } from '../runtime/broadcaster-utils.js';
4
3
  import { ContextImpl } from '../runtime/context-impl.js';
5
4
  import { stepChildren } from './step-walk.js';
@@ -98,7 +97,7 @@ export function allowCustomItems(step, ctx) {
98
97
  if (items.length === 0 || !(ctx instanceof ContextImpl)) {
99
98
  return;
100
99
  }
101
- ctx.allowItems(customItemGates(items));
100
+ ctx.allowItemTypes(items.map((item) => item.type));
102
101
  }
103
102
  /**
104
103
  * Every custom item declared anywhere in `step`'s static tree, for a harness to accept
@@ -110,18 +109,6 @@ export function collectCustomItems(step) {
110
109
  ...stepChildren(step).flatMap(collectCustomItems),
111
110
  ];
112
111
  }
113
- /**
114
- * Schemas that let a context's item log accept these items' final forms. They gate on
115
- * `type` and `id` only: the emitter has already checked the fields against `output`.
116
- */
117
- export function customItemGates(items) {
118
- return [
119
- ...new Set(items.map((item) => item.type)),
120
- ].map((type) => z.looseObject({
121
- type: z.literal(type),
122
- id: z.string(),
123
- }));
124
- }
125
112
  /**
126
113
  * Puts a replayed entry's items back on the log. The ones at `emitted` (the entry's
127
114
  * `streamed` indices) keep their mark, so a parent that records on this resumed run
@@ -496,7 +496,6 @@ function recordTurnOutcome(params) {
496
496
  }
497
497
  export async function executeCallModel(step, input, ctx, layers) {
498
498
  const baseCtx = frameworkCast(ctx);
499
- const hasLayers = layers !== undefined && layers.length > 0;
500
499
  // Resolve lazy step fields up-front. Function-form getters run once per
501
500
  // step execution with the live context, so `ctx.harness.config.params`,
502
501
  // `ctx.unifiedTools`, and context layer state are all visible at resolution.
@@ -534,7 +533,47 @@ export async function executeCallModel(step, input, ctx, layers) {
534
533
  policy,
535
534
  systemPromptTokens,
536
535
  });
537
- const recallQuery = typeof input === 'string' ? input : '';
536
+ const scope = {
537
+ step,
538
+ ctx: baseCtx,
539
+ layers,
540
+ resolvedModel,
541
+ resolvedInstructions,
542
+ resolvedTools,
543
+ allowedToolNames,
544
+ outputSchema,
545
+ serverToolSpecs,
546
+ viewPolicy,
547
+ budgetMap,
548
+ systemPromptTokens,
549
+ };
550
+ let recallQuery = typeof input === 'string' ? input : '';
551
+ let rerender = rerenderRequests;
552
+ // A steer whose layers asked for recall ends the call early. Recall runs again over
553
+ // the conversation the steer joined, and the call goes on from there.
554
+ for (;;) {
555
+ const response = await callOnFreshView(scope, recallQuery, rerender);
556
+ if (!response.recall) {
557
+ return finalizeStepOutput({
558
+ stepId: step.id,
559
+ emit: step.emit,
560
+ outputCodec,
561
+ outputSchema,
562
+ lastText: extractAssistantText(response.items),
563
+ ctx: baseCtx,
564
+ });
565
+ }
566
+ recallQuery = lastInputText(response.items) ?? recallQuery;
567
+ rerender = [];
568
+ }
569
+ }
570
+ /**
571
+ * Recall, build the view, and call the model on it, retrying on steering guidance.
572
+ * Returns the response once it is recorded on the context and stored by the layers.
573
+ */
574
+ async function callOnFreshView(scope, recallQuery, rerenderRequests) {
575
+ const { step, ctx: baseCtx, layers, resolvedModel, resolvedInstructions, resolvedTools, allowedToolNames, outputSchema, serverToolSpecs, viewPolicy, budgetMap, systemPromptTokens, } = scope;
576
+ const hasLayers = layers !== undefined && layers.length > 0;
538
577
  const slotOf = new Map((layers ?? []).map((l) => [
539
578
  l.id,
540
579
  l.slot,
@@ -668,15 +707,7 @@ export async function executeCallModel(step, input, ctx, layers) {
668
707
  if (hasLayers) {
669
708
  await baseCtx.harness.storeLayers(layers, response, baseCtx);
670
709
  }
671
- const lastText = extractAssistantText(response.items);
672
- return finalizeStepOutput({
673
- stepId: step.id,
674
- emit: step.emit,
675
- outputCodec,
676
- outputSchema,
677
- lastText,
678
- ctx: baseCtx,
679
- });
710
+ return response;
680
711
  }
681
712
  // Safety net: the loop above always returns or throws within the body.
682
713
  // This throw is unreachable but protects against future refactors that
@@ -688,6 +719,24 @@ export async function executeCallModel(step, input, ctx, layers) {
688
719
  retriesExhausted: true,
689
720
  });
690
721
  }
722
+ /** The text of the last input message — the steer that asked for recall. */
723
+ function lastInputText(items) {
724
+ for (const item of [
725
+ ...items,
726
+ ].reverse()) {
727
+ if (item.type !== 'message' || item.role === 'assistant') {
728
+ continue;
729
+ }
730
+ const text = item.content
731
+ .map((part) => ('text' in part && typeof part.text === 'string' ? part.text : ''))
732
+ .join('\n')
733
+ .trim();
734
+ if (text.length > 0) {
735
+ return text;
736
+ }
737
+ }
738
+ return undefined;
739
+ }
691
740
  function isContextConfig(value) {
692
741
  return typeof value === 'object' && value !== null && 'layers' in value;
693
742
  }
@@ -1,4 +1,3 @@
1
- import type { ZodTypeAny } from 'zod';
2
1
  import type { AgentHarnessContract, Channel, ChannelStore, Context, ContextData, ContextLayer, CwdState, EventBroadcaster, FrontierFrame, FsAdapter, Item, ItemLog, ItemSchemaRegistry, LastLayerUsage, Span, StepMeta, TokenUsage, Tool } from './context-deps.js';
3
2
  import type { StepLedger } from './durable/step-ledger.js';
4
3
  /**
@@ -30,6 +29,8 @@ export declare class ContextImpl implements Context<ContextData> {
30
29
  readonly itemLog: ItemLog;
31
30
  /** The same log, typed for `rebase`. */
32
31
  private readonly log;
32
+ /** Custom item types `allowItemTypes` has accepted. Shared by every lane. */
33
+ private readonly _customItemTypes;
33
34
  lastStepMeta: StepMeta | null;
34
35
  lastLayerUsage: LastLayerUsage | undefined;
35
36
  readonly harness: AgentHarnessContract;
@@ -252,11 +253,14 @@ export declare class ContextImpl implements Context<ContextData> {
252
253
  emittedIndices(): number[];
253
254
  /**
254
255
  * @internal
255
- * Accept items matching `schemas` in this context's log from now on, as a step's
256
- * custom items need. Contexts created from this one afterwards inherit the wider
257
- * registry; a lane widens the context it views.
258
- */
259
- allowItems(schemas: ReadonlyArray<ZodTypeAny>): void;
256
+ * Accept the final items of these custom item types in this context's log from now
257
+ * on (spec 34). Contexts created from this one afterwards inherit the wider registry,
258
+ * and a lane widens the context it views. A checkpoint records the types, so a
259
+ * restore can accept a stored log that holds them before any step runs.
260
+ */
261
+ allowItemTypes(types: ReadonlyArray<string>): void;
262
+ /** @internal The custom item types this context accepts, for a checkpoint to record. */
263
+ customItemTypes(): string[];
260
264
  /**
261
265
  * @internal
262
266
  * Append an item a step emitted (`step.emitItems`), marking it in this lane's record
@@ -1,5 +1,6 @@
1
1
  import { buildContextData, defaultItemSchemaRegistry } from './context-deps.js';
2
2
  import { hashStepInput } from './durable/step-ledger.js';
3
+ import { customItemGates } from './item-gates.js';
3
4
  import { ItemLogImpl } from './item-log-impl.js';
4
5
  const EMPTY_CONTEXT = Object.freeze({});
5
6
  class NoopSpan {
@@ -60,6 +61,8 @@ export class ContextImpl {
60
61
  itemLog;
61
62
  /** The same log, typed for `rebase`. */
62
63
  log;
64
+ /** Custom item types `allowItemTypes` has accepted. Shared by every lane. */
65
+ _customItemTypes = new Set();
63
66
  lastStepMeta = null;
64
67
  lastLayerUsage = undefined;
65
68
  harness;
@@ -416,17 +419,31 @@ export class ContextImpl {
416
419
  }
417
420
  /**
418
421
  * @internal
419
- * Accept items matching `schemas` in this context's log from now on, as a step's
420
- * custom items need. Contexts created from this one afterwards inherit the wider
421
- * registry; a lane widens the context it views.
422
- */
423
- allowItems(schemas) {
422
+ * Accept the final items of these custom item types in this context's log from now
423
+ * on (spec 34). Contexts created from this one afterwards inherit the wider registry,
424
+ * and a lane widens the context it views. A checkpoint records the types, so a
425
+ * restore can accept a stored log that holds them before any step runs.
426
+ */
427
+ allowItemTypes(types) {
428
+ const added = types.filter((type) => !this._customItemTypes.has(type));
429
+ if (added.length === 0) {
430
+ return;
431
+ }
432
+ for (const type of added) {
433
+ this._customItemTypes.add(type);
434
+ }
424
435
  const registry = (this.itemSchemas ?? defaultItemSchemaRegistry).extend({
425
- items: schemas,
436
+ items: customItemGates(added),
426
437
  });
427
438
  this.itemSchemas = registry;
428
439
  this.log.useSchemas(registry);
429
440
  }
441
+ /** @internal The custom item types this context accepts, for a checkpoint to record. */
442
+ customItemTypes() {
443
+ return [
444
+ ...this._customItemTypes,
445
+ ];
446
+ }
430
447
  /**
431
448
  * @internal
432
449
  * Append an item a step emitted (`step.emitItems`), marking it in this lane's record
@@ -1,5 +1,6 @@
1
1
  import { CheckpointSchemaVersion } from '../../types/checkpoint.js';
2
2
  import { ContextImpl, rootIdOf } from '../context-impl.js';
3
+ import { customItemGates } from '../item-gates.js';
3
4
  import { StepLedger } from './step-ledger.js';
4
5
  //#endregion
5
6
  //#region captureCheckpoint
@@ -58,6 +59,11 @@ export async function captureCheckpoint(h, ctx) {
58
59
  items: baseline.items,
59
60
  },
60
61
  occurrences: baseline.occurrences,
62
+ ...(impl && impl.customItemTypes().length > 0
63
+ ? {
64
+ customItemTypes: impl.customItemTypes(),
65
+ }
66
+ : {}),
61
67
  ...(state.ok
62
68
  ? {
63
69
  state: state.value,
@@ -165,14 +171,28 @@ function contextFromSnapshot(h, snapshot, opts) {
165
171
  /* Caller wiring first, snapshot second: a host may legitimately swap the context
166
172
  * layers or hang the restored execution under a new parent, but it must never be
167
173
  * able to override the identity/history the snapshot is the record of. */
174
+ const customItemTypes = snapshot.customItemTypes ?? [];
175
+ const items = h.itemSchemas
176
+ .extend({
177
+ items: customItemGates(customItemTypes),
178
+ })
179
+ .parseMany(snapshot.itemLog.items);
168
180
  const ctx = h.createContext({
169
181
  ...opts,
170
182
  state: opts?.state ?? snapshot.state,
171
- items: h.itemSchemas.parseMany(snapshot.itemLog.items),
183
+ items: [],
172
184
  threadId: snapshot.threadId,
173
185
  resourceId: snapshot.resourceId,
174
186
  cwdInit: snapshot.cwd?.current ?? undefined,
175
187
  });
188
+ /* The log goes in after the context accepts the recorded custom item types:
189
+ * seeded at creation, it would be checked against the harness's schemas alone. */
190
+ if (ctx instanceof ContextImpl) {
191
+ ctx.allowItemTypes(customItemTypes);
192
+ }
193
+ for (const item of items) {
194
+ ctx.itemLog.append(item);
195
+ }
176
196
  if (ctx instanceof ContextImpl) {
177
197
  ctx.restoreOccurrences(snapshot.occurrences);
178
198
  if (snapshot.usage) {
@@ -7,6 +7,9 @@
7
7
  * arrive again — a host with at-least-once delivery re-sends what it never saw
8
8
  * answered — the turn resumes on its recorded execution: finished steps replay and
9
9
  * the turn continues from the step that was cut off.
10
+ *
11
+ * Steers sent into a running turn are kept too, until the turn ends, so a turn that
12
+ * resumes on a new harness still applies the steers it had not applied yet.
10
13
  */
11
14
  import type { StorageAdapter } from '@noetic-tools/context';
12
15
  import { z } from 'zod';
@@ -23,6 +26,15 @@ declare const SessionRecordSchema: z.ZodObject<{
23
26
  executionId: z.ZodString;
24
27
  messageIds: z.ZodArray<z.ZodString>;
25
28
  }, z.core.$strip>>;
29
+ steers: z.ZodOptional<z.ZodArray<z.ZodObject<{
30
+ id: z.ZodString;
31
+ input: z.ZodUnknown;
32
+ deliveryMode: z.ZodEnum<{
33
+ "between-rounds": "between-rounds";
34
+ "next-item": "next-item";
35
+ }>;
36
+ enqueuedAt: z.ZodNumber;
37
+ }, z.core.$strip>>>;
26
38
  }, z.core.$strip>;
27
39
  /** @internal One thread's stored session. */
28
40
  export type SessionRecord = z.infer<typeof SessionRecordSchema>;
@@ -7,6 +7,9 @@
7
7
  * arrive again — a host with at-least-once delivery re-sends what it never saw
8
8
  * answered — the turn resumes on its recorded execution: finished steps replay and
9
9
  * the turn continues from the step that was cut off.
10
+ *
11
+ * Steers sent into a running turn are kept too, until the turn ends, so a turn that
12
+ * resumes on a new harness still applies the steers it had not applied yet.
10
13
  */
11
14
  import { z } from 'zod';
12
15
  //#region Schema
@@ -31,6 +34,19 @@ const SessionRecordSchema = z.object({
31
34
  messageIds: z.array(z.string()),
32
35
  })
33
36
  .optional(),
37
+ /** Steers sent into the turn in flight, in arrival order. */
38
+ steers: z
39
+ .array(z.object({
40
+ id: z.string(),
41
+ /** The `execute()` input: a string, an item, or items. */
42
+ input: z.unknown(),
43
+ deliveryMode: z.enum([
44
+ 'between-rounds',
45
+ 'next-item',
46
+ ]),
47
+ enqueuedAt: z.number(),
48
+ }))
49
+ .optional(),
34
50
  });
35
51
  /** @internal */
36
52
  export function createSessionStore(storage) {
@@ -0,0 +1,8 @@
1
+ import type { ZodTypeAny } from 'zod';
2
+ /**
3
+ * Item schemas that let a log accept the final items of these custom item types
4
+ * (spec 34). They gate on `type` and `id` only: an emitter checks an item's fields
5
+ * against its declared `output` before appending it, and a restore reads back items
6
+ * that were checked when they were emitted.
7
+ */
8
+ export declare function customItemGates(types: Iterable<string>): ZodTypeAny[];
@@ -0,0 +1,15 @@
1
+ import { z } from 'zod';
2
+ /**
3
+ * Item schemas that let a log accept the final items of these custom item types
4
+ * (spec 34). They gate on `type` and `id` only: an emitter checks an item's fields
5
+ * against its declared `output` before appending it, and a restore reads back items
6
+ * that were checked when they were emitted.
7
+ */
8
+ export function customItemGates(types) {
9
+ return [
10
+ ...new Set(types),
11
+ ].map((type) => z.looseObject({
12
+ type: z.literal(type),
13
+ id: z.string(),
14
+ }));
15
+ }
@@ -128,6 +128,7 @@ export declare const CheckpointSnapshotSchema: z.ZodObject<{
128
128
  items: z.ZodArray<z.ZodUnknown>;
129
129
  }, z.core.$strip>;
130
130
  occurrences: z.ZodRecord<z.ZodString, z.ZodNumber>;
131
+ customItemTypes: z.ZodOptional<z.ZodArray<z.ZodString>>;
131
132
  state: z.ZodOptional<z.ZodUnknown>;
132
133
  usage: z.ZodOptional<z.ZodObject<{
133
134
  tokens: z.ZodObject<{
@@ -120,6 +120,11 @@ export const CheckpointSnapshotSchema = z.object({
120
120
  * on the same execution does not land on an earlier run's paths.
121
121
  */
122
122
  occurrences: z.record(z.string(), z.number()),
123
+ /**
124
+ * Custom item types the context accepted (spec 34), so a restore can parse an
125
+ * `itemLog` that holds them before the steps that declare them run again.
126
+ */
127
+ customItemTypes: z.array(z.string()).optional(),
123
128
  /**
124
129
  * The execution's `ctx.state` at capture time. Absent when the state does not survive
125
130
  * JSON encoding, in which case restore keeps whatever state the host passes.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@noetic-tools/core",
3
- "version": "5.16.0",
3
+ "version": "5.17.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",
@@ -68,8 +68,8 @@
68
68
  }
69
69
  },
70
70
  "dependencies": {
71
- "@noetic-tools/context": "^1.10.0",
72
- "@noetic-tools/types": "^3.14.0",
71
+ "@noetic-tools/context": "^1.11.0",
72
+ "@noetic-tools/types": "^3.15.0",
73
73
  "@openrouter/agent": "^0.11.0",
74
74
  "@openrouter/sdk": "1.4.25",
75
75
  "jsonata": "2.2.2",