@noetic-tools/core 5.14.0 → 5.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { frameworkCast, NoeticConfigError, ToolChoiceMode } from '@noetic-tools/types';
1
+ import { frameworkCast, NoeticConfigError, SteerPoint, ToolChoiceMode } from '@noetic-tools/types';
2
2
  import { serverTool } from '@openrouter/agent';
3
3
  import { convertTools, executeToolCall, extractOutputItems, extractSystemInstruction, extractUsage, itemsToInput, resolveWireJsonSchema, sanitizeToolNameForWire, } from '../adapters/openrouter.js';
4
4
  import { isFunctionCall } from '../interpreter/typeguards.js';
@@ -7,9 +7,11 @@ import { emitFrameworkEvent, getBroadcaster, shouldEmit } from '../runtime/broad
7
7
  import { exportSpans } from './deps/context.js';
8
8
  import { RoundLedger } from './model-rounds.js';
9
9
  import { buildItemSchemaRegistry, createToolResultItem } from './model-schema.js';
10
+ import { openSteerInbox } from './steer-inbox.js';
10
11
  const MAX_TOOL_ROUNDS = 32;
11
12
  const MAX_RECOVERY_CONTINUATIONS = 3;
12
13
  const EPHEMERAL_CONTINUE_INPUT = 'continue';
14
+ const SKIPPED_FOR_STEER_OUTPUT = 'Skipped: a new message arrived before this tool call ran.';
13
15
  function buildTextFormat(schema, explicitJsonSchema) {
14
16
  const jsonSchema = resolveWireJsonSchema({
15
17
  schema,
@@ -56,6 +58,14 @@ function providerTerminalError(response) {
56
58
  message: `LLM response ended with status '${status}'`,
57
59
  };
58
60
  }
61
+ /**
62
+ * Tool rounds replay only their function calls. A round a steer follows must
63
+ * also replay what the model said, or the next round starts without it.
64
+ * Function calls are left to the tool round, which adds each with its output.
65
+ */
66
+ function replayOutput(input, roundItems) {
67
+ input.push(...itemsToInput(roundItems.filter((item) => !isFunctionCall(item))));
68
+ }
59
69
  function hasUsableResponseOutput(response, items) {
60
70
  if (items.length > 0) {
61
71
  return true;
@@ -102,7 +112,7 @@ function awaitWithAbort(p, signal) {
102
112
  });
103
113
  }
104
114
  async function pipeStreamEventsToBroadcaster(opts) {
105
- const { stream, broadcaster, agentName, signal, onEvent } = opts;
115
+ const { stream, broadcaster, agentName, signal, onEvent, onItemDone } = opts;
106
116
  try {
107
117
  for await (const event of stream) {
108
118
  if (signal?.aborted) {
@@ -119,9 +129,16 @@ async function pipeStreamEventsToBroadcaster(opts) {
119
129
  outputIndex: typeof event.outputIndex === 'number' ? event.outputIndex : undefined,
120
130
  contentIndex: typeof event.contentIndex === 'number' ? event.contentIndex : undefined,
121
131
  });
132
+ if (event.type === 'response.output_item.done' && onItemDone) {
133
+ await onItemDone(event.item);
134
+ }
122
135
  }
123
136
  }
124
137
  catch (err) {
138
+ // The stream ends badly when the round is aborted; that is not a pipe fault.
139
+ if (signal?.aborted) {
140
+ return;
141
+ }
125
142
  if (broadcaster) {
126
143
  emitFrameworkEvent({
127
144
  broadcaster,
@@ -186,12 +203,6 @@ export function createStreamIdleWatchdog(timeoutMs, controller, onTimeout) {
186
203
  },
187
204
  };
188
205
  }
189
- function hasSessionQueue(ctx) {
190
- const maybe = frameworkCast(ctx);
191
- return (maybe._sessionBetweenRounds === true &&
192
- maybe._sessionQueue !== undefined &&
193
- typeof maybe._sessionRunnerAgentName === 'string');
194
- }
195
206
  function prepareModelRequest(request, agentName) {
196
207
  const { instructions: extractedInstructions, remaining } = extractSystemInstruction(request.items);
197
208
  const instructions = [
@@ -506,6 +517,24 @@ export class AgentHarnessModelCaller {
506
517
  input: 0,
507
518
  items: 0,
508
519
  };
520
+ // Record a round the loop goes on from, so a resumed loop can replay it.
521
+ const recordRound = async (usage, cost) => {
522
+ if (request.signal?.aborted) {
523
+ return;
524
+ }
525
+ await roundLedger?.record(round, marks.log, {
526
+ items: allItems.slice(marks.items),
527
+ input: conversationInput.slice(marks.input),
528
+ usage,
529
+ cost,
530
+ });
531
+ };
532
+ const steers = openSteerInbox({
533
+ ctx: request.ctx,
534
+ layers: request.layers ?? [],
535
+ harness: this.opts.harness,
536
+ emit: prepared.emitIfAllowed,
537
+ });
509
538
  while (!request.signal?.aborted) {
510
539
  const replayed = roundLedger?.take(round, replaySchemas);
511
540
  if (replayed) {
@@ -545,8 +574,15 @@ export class AgentHarnessModelCaller {
545
574
  }
546
575
  const recoveryContinuation = useEphemeralContinue;
547
576
  useEphemeralContinue = false;
548
- if (round > 0 && request.ctx && hasSessionQueue(request.ctx)) {
549
- this.injectBetweenRoundMessages(request.ctx, conversationInput, round, prepared.emitIfAllowed);
577
+ if (steers) {
578
+ await this.applySteers({
579
+ steers,
580
+ ctx: request.ctx,
581
+ conversationInput,
582
+ allItems,
583
+ round,
584
+ emitIfAllowed: prepared.emitIfAllowed,
585
+ });
550
586
  }
551
587
  const roundController = new AbortController();
552
588
  const roundSignal = request.signal
@@ -594,6 +630,10 @@ export class AgentHarnessModelCaller {
594
630
  }, {
595
631
  signal: roundSignal,
596
632
  });
633
+ // Output items the stream has finished, kept so a steer can stop the
634
+ // round early without losing them.
635
+ const finishedItems = [];
636
+ let steered = false;
597
637
  const pipePromise = pipeStreamEventsToBroadcaster({
598
638
  stream: callResult.getFullResponsesStream(),
599
639
  broadcaster: prepared.broadcaster,
@@ -608,6 +648,14 @@ export class AgentHarnessModelCaller {
608
648
  });
609
649
  }
610
650
  },
651
+ onItemDone: async (item) => {
652
+ finishedItems.push(item);
653
+ if (!steers?.hasQueued() || !(await steers.offer(SteerPoint.ItemDone))) {
654
+ return;
655
+ }
656
+ steered = true;
657
+ roundController.abort(new Error('steered'));
658
+ },
611
659
  });
612
660
  // A dropped connection rejects the response and the event pipe together; the
613
661
  // response's rejection is the one that propagates. Unobserved, the pipe's would
@@ -628,7 +676,9 @@ export class AgentHarnessModelCaller {
628
676
  if (request.signal?.aborted) {
629
677
  break;
630
678
  }
631
- throw err;
679
+ if (!steered) {
680
+ throw err;
681
+ }
632
682
  }
633
683
  finally {
634
684
  watchdog.stop();
@@ -636,6 +686,44 @@ export class AgentHarnessModelCaller {
636
686
  if (request.signal?.aborted) {
637
687
  break;
638
688
  }
689
+ if (!sdkResponse) {
690
+ // A steer stopped the stream before the response finished. The provider
691
+ // never reports usage for a cut response, so this round adds none.
692
+ modelSpan.end();
693
+ const roundItems = this.parseRoundItems(request, frameworkCast(finishedItems));
694
+ prepared.emitIfAllowed('model_call_steered', {
695
+ round,
696
+ itemCount: roundItems.length,
697
+ });
698
+ allItems.push(...roundItems);
699
+ replayOutput(conversationInput, roundItems);
700
+ await this.runToolRound({
701
+ roundItems,
702
+ request,
703
+ prepared,
704
+ allItems,
705
+ conversationInput,
706
+ round,
707
+ spans,
708
+ modelSpan,
709
+ steers,
710
+ });
711
+ await recordRound({
712
+ inputTokens: 0,
713
+ outputTokens: 0,
714
+ }, 0);
715
+ round += 1;
716
+ const cutLimitRecovery = this.handleToolRoundLimit({
717
+ round,
718
+ toolLimitRecoveryContinuations,
719
+ emitIfAllowed: prepared.emitIfAllowed,
720
+ });
721
+ if (cutLimitRecovery.kind === 'continue') {
722
+ toolLimitRecoveryContinuations = cutLimitRecovery.toolLimitRecoveryContinuations;
723
+ useEphemeralContinue = true;
724
+ }
725
+ continue;
726
+ }
639
727
  const recovery = this.handleModelRecovery({
640
728
  sdkResponse,
641
729
  round,
@@ -648,12 +736,7 @@ export class AgentHarnessModelCaller {
648
736
  useEphemeralContinue = true;
649
737
  continue;
650
738
  }
651
- const roundItemSchemas = buildItemSchemaRegistry({
652
- base: this.opts.itemSchemas,
653
- layers: request.layers,
654
- tools: request.tools,
655
- });
656
- const roundItems = roundItemSchemas.parseMany(extractOutputItems(sdkResponse));
739
+ const roundItems = this.parseRoundItems(request, extractOutputItems(sdkResponse));
657
740
  const outputRecovery = this.handleEmptyOutputRecovery({
658
741
  sdkResponse,
659
742
  roundItems,
@@ -682,29 +765,26 @@ export class AgentHarnessModelCaller {
682
765
  totalCost += roundCost;
683
766
  servedTier = sdkResponse.serviceTier ?? undefined;
684
767
  allItems.push(...roundItems);
685
- const functionCalls = roundItems.filter(isFunctionCall);
686
- if (functionCalls.length === 0 || !request.tools) {
687
- break;
688
- }
689
- await this.executeToolRound({
690
- functionCalls,
768
+ const ranTools = await this.runToolRound({
769
+ roundItems,
691
770
  request,
692
- allowedTools: prepared.allowedTools,
771
+ prepared,
693
772
  allItems,
694
773
  conversationInput,
695
774
  round,
696
- emitIfAllowed: prepared.emitIfAllowed,
697
775
  spans,
698
776
  modelSpan,
777
+ steers,
699
778
  });
700
- if (!request.signal?.aborted) {
701
- await roundLedger?.record(round, marks.log, {
702
- items: allItems.slice(marks.items),
703
- input: conversationInput.slice(marks.input),
704
- usage: roundUsage,
705
- cost: roundCost,
706
- });
779
+ // A steer staged while the final answer streamed gets its own round, so
780
+ // the model answers it inside this call rather than in the next turn.
781
+ if (!ranTools && !steers?.hasStaged()) {
782
+ break;
707
783
  }
784
+ if (!ranTools) {
785
+ replayOutput(conversationInput, roundItems);
786
+ }
787
+ await recordRound(roundUsage, roundCost);
708
788
  round += 1;
709
789
  const limitRecovery = this.handleToolRoundLimit({
710
790
  round,
@@ -741,43 +821,56 @@ export class AgentHarnessModelCaller {
741
821
  : {}),
742
822
  };
743
823
  }
744
- injectBetweenRoundMessages(ctx, conversationInput, round, emitIfAllowed) {
745
- const injected = this.drainBetweenRoundsMessages(ctx._sessionQueue);
746
- if (injected.length === 0) {
824
+ /**
825
+ * Offer queued steers before a model call and add the applied ones to the
826
+ * conversation. They join `allItems` rather than the log so the log keeps
827
+ * them in the order the model saw them.
828
+ */
829
+ async applySteers(params) {
830
+ const { steers, ctx, conversationInput, allItems } = params;
831
+ await steers.offer(SteerPoint.BeforeRound);
832
+ const { messageIds, items } = steers.takeStaged();
833
+ if (messageIds.length === 0) {
747
834
  return;
748
835
  }
749
- for (const msg of injected) {
750
- const text = itemToText(msg);
751
- const userItem = {
752
- id: `user-${crypto.randomUUID()}`,
753
- type: 'message',
754
- role: 'user',
755
- status: 'completed',
756
- content: [
757
- {
758
- type: 'input_text',
759
- text,
760
- },
761
- ],
762
- };
763
- conversationInput.push({
764
- type: 'message',
765
- role: 'user',
766
- content: [
767
- {
768
- type: 'input_text',
769
- text,
770
- },
771
- ],
772
- });
773
- ctx.itemLog.append(userItem);
774
- this.emitItemAppended(ctx, userItem);
836
+ conversationInput.push(...itemsToInput(items));
837
+ for (const item of items) {
838
+ allItems.push(item);
839
+ this.emitItemAppended(ctx, item);
840
+ }
841
+ params.emitIfAllowed('inbox_injected', {
842
+ round: params.round,
843
+ count: messageIds.length,
844
+ messageIds,
845
+ });
846
+ }
847
+ parseRoundItems(request, items) {
848
+ const roundItemSchemas = buildItemSchemaRegistry({
849
+ base: this.opts.itemSchemas,
850
+ layers: request.layers,
851
+ tools: request.tools,
852
+ });
853
+ return roundItemSchemas.parseMany(items);
854
+ }
855
+ /** Run the round's function calls. Returns `false` when there were none to run. */
856
+ async runToolRound(params) {
857
+ const functionCalls = params.roundItems.filter(isFunctionCall);
858
+ if (functionCalls.length === 0 || !params.request.tools) {
859
+ return false;
775
860
  }
776
- emitIfAllowed('inbox_injected', {
777
- round,
778
- count: injected.length,
779
- messageIds: injected.map((i) => i.id),
861
+ await this.executeToolRound({
862
+ functionCalls,
863
+ request: params.request,
864
+ allowedTools: params.prepared.allowedTools,
865
+ allItems: params.allItems,
866
+ conversationInput: params.conversationInput,
867
+ round: params.round,
868
+ emitIfAllowed: params.prepared.emitIfAllowed,
869
+ spans: params.spans,
870
+ modelSpan: params.modelSpan,
871
+ steers: params.steers,
780
872
  });
873
+ return true;
781
874
  }
782
875
  handleModelRecovery(params) {
783
876
  const terminalError = providerTerminalError(params.sdkResponse);
@@ -836,7 +929,7 @@ export class AgentHarnessModelCaller {
836
929
  };
837
930
  }
838
931
  async executeToolRound(params) {
839
- const { functionCalls, request, allowedTools, allItems, conversationInput, spans, modelSpan } = params;
932
+ const { functionCalls, request, allowedTools, allItems, conversationInput, spans, modelSpan, steers, } = params;
840
933
  params.emitIfAllowed('tool_round_started', {
841
934
  round: params.round,
842
935
  toolCount: functionCalls.length,
@@ -850,10 +943,24 @@ export class AgentHarnessModelCaller {
850
943
  arguments: fc.arguments,
851
944
  });
852
945
  }
853
- for (const fc of functionCalls) {
946
+ for (const [index, fc] of functionCalls.entries()) {
854
947
  if (request.signal?.aborted) {
855
948
  break;
856
949
  }
950
+ const remaining = functionCalls.slice(index);
951
+ if (steers?.hasQueued() && (await steers.offer(SteerPoint.BeforeToolCall, remaining))) {
952
+ for (const skipped of remaining) {
953
+ this.recordSkippedToolCall({
954
+ fc: skipped,
955
+ request,
956
+ allowedTools,
957
+ allItems,
958
+ conversationInput,
959
+ emitIfAllowed: params.emitIfAllowed,
960
+ });
961
+ }
962
+ break;
963
+ }
857
964
  const toolForCall = findTool(allowedTools, fc.name);
858
965
  const approval = await this.executeFunctionCall({
859
966
  fc,
@@ -881,8 +988,9 @@ export class AgentHarnessModelCaller {
881
988
  parsedArgs = JSON.parse(fc.arguments);
882
989
  }
883
990
  catch {
884
- this.recordMalformedToolCall({
991
+ this.recordUnrunToolCall({
885
992
  fc,
993
+ output: `Error: malformed JSON in tool arguments: ${fc.arguments}`,
886
994
  request,
887
995
  allowedTools,
888
996
  allItems,
@@ -932,13 +1040,23 @@ export class AgentHarnessModelCaller {
932
1040
  });
933
1041
  return toolResult.approval;
934
1042
  }
935
- recordMalformedToolCall(params) {
1043
+ recordSkippedToolCall(params) {
1044
+ params.emitIfAllowed('tool_call_started', {
1045
+ name: params.fc.name,
1046
+ callId: params.fc.callId,
1047
+ });
1048
+ this.recordUnrunToolCall({
1049
+ ...params,
1050
+ output: SKIPPED_FOR_STEER_OUTPUT,
1051
+ });
1052
+ }
1053
+ /** Answer a call that never ran, so every call in the history has an output. */
1054
+ recordUnrunToolCall(params) {
936
1055
  const { fc, request, allowedTools, allItems, conversationInput } = params;
937
- const errorOutput = `Error: malformed JSON in tool arguments: ${fc.arguments}`;
938
1056
  const toolForCall = findTool(allowedTools, fc.name);
939
1057
  // Owner-scoped result validation (see executeFunctionCall).
940
1058
  const outputItem = createToolResultItem({
941
- output: errorOutput,
1059
+ output: params.output,
942
1060
  callId: fc.callId,
943
1061
  roundItemSchemas: this.opts.itemSchemas.extend(toolForCall?.itemSchemas),
944
1062
  tool: toolForCall,
@@ -949,14 +1067,14 @@ export class AgentHarnessModelCaller {
949
1067
  conversationInput.push({
950
1068
  type: 'function_call_output',
951
1069
  callId: fc.callId,
952
- output: errorOutput,
1070
+ output: params.output,
953
1071
  });
954
1072
  this.emitItemAppended(request.ctx, outputItem);
955
1073
  params.emitIfAllowed('tool_call_completed', {
956
1074
  name: fc.name,
957
1075
  callId: fc.callId,
958
1076
  error: true,
959
- output: errorOutput,
1077
+ output: params.output,
960
1078
  });
961
1079
  }
962
1080
  handleToolRoundLimit(params) {
@@ -978,47 +1096,4 @@ export class AgentHarnessModelCaller {
978
1096
  toolLimitRecoveryContinuations: params.toolLimitRecoveryContinuations + 1,
979
1097
  };
980
1098
  }
981
- /** @internal Drain only messages tagged `between-rounds` from the queue. */
982
- drainBetweenRoundsMessages(queue) {
983
- const pending = queue.peekAll();
984
- const toInject = [];
985
- const keep = [];
986
- for (const msg of pending) {
987
- if (msg.deliveryMode === 'between-rounds') {
988
- toInject.push(msg);
989
- continue;
990
- }
991
- keep.push(msg);
992
- }
993
- if (toInject.length === 0) {
994
- return [];
995
- }
996
- queue.drainAll();
997
- for (const msg of keep) {
998
- queue.enqueue(msg);
999
- }
1000
- return toInject;
1001
- }
1002
- }
1003
- function itemToText(msg) {
1004
- if (typeof msg.input === 'string') {
1005
- return msg.input;
1006
- }
1007
- const items = Array.isArray(msg.input)
1008
- ? msg.input
1009
- : [
1010
- msg.input,
1011
- ];
1012
- const texts = [];
1013
- for (const item of items) {
1014
- if (item.type !== 'message') {
1015
- continue;
1016
- }
1017
- for (const part of item.content) {
1018
- if (part.type === 'input_text' || part.type === 'output_text') {
1019
- texts.push(part.text);
1020
- }
1021
- }
1022
- }
1023
- return texts.join('\n');
1024
1099
  }
@@ -8,7 +8,7 @@
8
8
  *
9
9
  * Each finished round is recorded under `<step path>/round#<n>`, carrying what it
10
10
  * added to the loop: the model's output and tool results, the conversation input
11
- * those became, the items appended to the item log (messages injected between rounds),
11
+ * those became, the items appended to the item log,
12
12
  * and the round's usage. A resumed loop replays rounds in order and stops at the first
13
13
  * one it does not find; every round after that runs live, because a recorded round
14
14
  * belongs to the conversation the earlier recorded rounds built. When the step
@@ -8,7 +8,7 @@
8
8
  *
9
9
  * Each finished round is recorded under `<step path>/round#<n>`, carrying what it
10
10
  * added to the loop: the model's output and tool results, the conversation input
11
- * those became, the items appended to the item log (messages injected between rounds),
11
+ * those became, the items appended to the item log,
12
12
  * and the round's usage. A resumed loop replays rounds in order and stops at the first
13
13
  * one it does not find; every round after that runs live, because a recorded round
14
14
  * belongs to the conversation the earlier recorded rounds built. When the step
@@ -0,0 +1,51 @@
1
+ import type { AgentHarnessContract, Context, ContextLayer, FunctionCallItem, Item } from '@noetic-tools/types';
2
+ import { SteerPoint } from '@noetic-tools/types';
3
+ import type { MessageQueue } from '../runtime/message-queue.js';
4
+ /** @internal Steers taken off the queue, waiting for the next model call. */
5
+ export interface StagedSteers {
6
+ messageIds: string[];
7
+ items: Item[];
8
+ }
9
+ interface SteerInboxOpts {
10
+ queue: MessageQueue;
11
+ ctx: Context;
12
+ layers: ContextLayer[];
13
+ harness: AgentHarnessContract;
14
+ emit: (eventType: string, data: Record<string, unknown>) => void;
15
+ }
16
+ /**
17
+ * @internal Open the steer inbox for a model call, or `undefined` when the call
18
+ * runs outside a session. A context inherits its parent's session only when it
19
+ * was spawned with `steers: 'forward'`; parallel paths and other spawns hold
20
+ * steers until control returns to the session's own context.
21
+ */
22
+ export declare function openSteerInbox(opts: Omit<SteerInboxOpts, 'queue' | 'ctx'> & {
23
+ ctx: Context | undefined;
24
+ }): SteerInbox | undefined;
25
+ /**
26
+ * @internal The steers a running model call can take. The call offers queued
27
+ * steers to the context layers at each steer point; those the layers apply are
28
+ * staged and handed over before the next model call.
29
+ */
30
+ export declare class SteerInbox {
31
+ private readonly opts;
32
+ private staged;
33
+ /** Steers already reported as waiting on tool calls, so each is reported once. */
34
+ private readonly reportedPending;
35
+ constructor(opts: SteerInboxOpts);
36
+ hasQueued(): boolean;
37
+ hasStaged(): boolean;
38
+ /**
39
+ * Offer every queued steer at `point`. Returns `true` when at least one was
40
+ * staged by this offer.
41
+ */
42
+ offer(point: SteerPoint, pendingCalls?: ReadonlyArray<FunctionCallItem>): Promise<boolean>;
43
+ /** Hand over the staged steers and clear them. */
44
+ takeStaged(): StagedSteers;
45
+ private judge;
46
+ /** Steers are user input, so they pass through `onItemAppend` like any other.
47
+ * Re-render requests are ignored: recall does not run again mid-call. */
48
+ private stage;
49
+ private reportPending;
50
+ }
51
+ export {};