@noetic-tools/core 5.16.1 → 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.
@@ -7,7 +7,7 @@ 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
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, resolveStepLedgerRetention, restoreFromCheckpoint, rootIdOf, SessionRunner, StepLedger, snapshotCwdState, warnToConsole, } from './deps/runtime.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';
@@ -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
  },
@@ -14,7 +14,7 @@ export type { EventBroadcaster } from '../../runtime/event-broadcaster.js';
14
14
  export { createInMemoryStorage } from '../../runtime/in-memory-storage.js';
15
15
  export { customItemGates } from '../../runtime/item-gates.js';
16
16
  export type { QueuedMessage, SessionCtxExtension } from '../../runtime/message-queue.js';
17
- export { INTERRUPT_REASON } from '../../runtime/message-queue.js';
17
+ export { INTERRUPT_REASON, isSteer } from '../../runtime/message-queue.js';
18
18
  export type { TurnUsage } from '../../runtime/session-runner.js';
19
19
  export { SessionRunner } from '../../runtime/session-runner.js';
20
20
  export { buildItemStream, filterReasoningStream, filterTextStream, } from '../../runtime/session-streams.js';
@@ -7,6 +7,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
9
  export { customItemGates } from '../../runtime/item-gates.js';
10
- export { INTERRUPT_REASON } from '../../runtime/message-queue.js';
10
+ export { INTERRUPT_REASON, isSteer } from '../../runtime/message-queue.js';
11
11
  export { SessionRunner } from '../../runtime/session-runner.js';
12
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
  }
@@ -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
  }
@@ -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) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@noetic-tools/core",
3
- "version": "5.16.1",
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",