@noetic-tools/core 5.14.1 → 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.
- package/dist/builders/spawn-builder.d.ts +7 -0
- package/dist/builders/spawn-builder.js +2 -0
- package/dist/builders/workflow-hydrator.js +1 -0
- package/dist/harness/agent-harness.d.ts +2 -1
- package/dist/harness/agent-harness.js +32 -17
- package/dist/harness/deps/context.d.ts +1 -1
- package/dist/harness/deps/context.js +1 -1
- package/dist/harness/deps/runtime.d.ts +2 -1
- package/dist/harness/deps/runtime.js +1 -0
- package/dist/harness/deps/types.d.ts +1 -1
- package/dist/harness/model-call.d.ts +12 -12
- package/dist/harness/model-call.js +191 -116
- package/dist/harness/model-rounds.d.ts +1 -1
- package/dist/harness/model-rounds.js +1 -1
- package/dist/harness/steer-inbox.d.ts +51 -0
- package/dist/harness/steer-inbox.js +149 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/interpreter/action-deps.d.ts +2 -0
- package/dist/interpreter/action-deps.js +1 -0
- package/dist/interpreter/action-types.d.ts +1 -1
- package/dist/interpreter/execute-action.js +44 -1
- package/dist/runtime/message-queue.d.ts +15 -1
- package/dist/runtime/message-queue.js +54 -0
- package/dist/runtime/session-runner.d.ts +3 -0
- package/dist/runtime/session-runner.js +18 -29
- package/package.json +3 -3
- package/schema/noetic-workflow.schema.json +7 -0
|
@@ -10,6 +10,12 @@ export interface SpawnOpts<TContext = ContextData, I = unknown, O = unknown> ext
|
|
|
10
10
|
child: Step<TContext, I, O>;
|
|
11
11
|
context?: ContextConfig | ContextLayer[];
|
|
12
12
|
timeout?: number;
|
|
13
|
+
/**
|
|
14
|
+
* Whether the child takes steers sent to the session while it runs.
|
|
15
|
+
* `'hold'` (default) keeps them queued until control returns to the parent;
|
|
16
|
+
* `'forward'` lets the child's model calls apply them.
|
|
17
|
+
*/
|
|
18
|
+
steers?: 'forward' | 'hold';
|
|
13
19
|
/**
|
|
14
20
|
* Optional per-step subprocess adapter override. The interpreter routes
|
|
15
21
|
* this spawn through the given adapter instead of the harness default.
|
|
@@ -25,6 +31,7 @@ export interface SpawnOpts<TContext = ContextData, I = unknown, O = unknown> ext
|
|
|
25
31
|
* @param opts.child - Step to execute in the isolated child context.
|
|
26
32
|
* @param opts.context - Optional context config or layers for the child context (replaces parent layers entirely).
|
|
27
33
|
* @param opts.timeout - Optional execution timeout in ms; the child is aborted if it exceeds this.
|
|
34
|
+
* @param opts.steers - `'forward'` lets the child apply steers sent while it runs; default `'hold'`.
|
|
28
35
|
* @param opts.subprocess - Optional per-step subprocess adapter override.
|
|
29
36
|
* @returns A `StepSpawn` step. The spawn step and its `child` step are both
|
|
30
37
|
* auto-registered in the shared step registry so the subprocess adapter
|
|
@@ -10,6 +10,7 @@ import { getDefaultRegistrar } from '../types/step-registrar.js';
|
|
|
10
10
|
* @param opts.child - Step to execute in the isolated child context.
|
|
11
11
|
* @param opts.context - Optional context config or layers for the child context (replaces parent layers entirely).
|
|
12
12
|
* @param opts.timeout - Optional execution timeout in ms; the child is aborted if it exceeds this.
|
|
13
|
+
* @param opts.steers - `'forward'` lets the child apply steers sent while it runs; default `'hold'`.
|
|
13
14
|
* @param opts.subprocess - Optional per-step subprocess adapter override.
|
|
14
15
|
* @returns A `StepSpawn` step. The spawn step and its `child` step are both
|
|
15
16
|
* auto-registered in the shared step registry so the subprocess adapter
|
|
@@ -38,6 +39,7 @@ export function spawn(opts) {
|
|
|
38
39
|
child: opts.child,
|
|
39
40
|
context: opts.context,
|
|
40
41
|
timeout: opts.timeout,
|
|
42
|
+
steers: opts.steers,
|
|
41
43
|
subprocess: opts.subprocess,
|
|
42
44
|
durable: opts.durable,
|
|
43
45
|
replayKey: opts.replayKey,
|
|
@@ -4,7 +4,7 @@ import type { LayerStateStore, RecallCache } from './deps/context.js';
|
|
|
4
4
|
import type { DetachedSpawnOverrides } from './deps/interpreter.js';
|
|
5
5
|
import type { CheckpointStore, EventBroadcaster, RestoreCheckpointOptions, StepLedgerRetention, StepLedgerStore } from './deps/runtime.js';
|
|
6
6
|
import { ChannelStore } from './deps/runtime.js';
|
|
7
|
-
import type { AcpLiveSession, AcpSessionInfo, AgentConfig, AgentHarnessContract, AgentHooks, CallModelRequest, Channel, ChannelHandle, Context, ContextCacheConfig, ContextCacheStore, ContextData, ContextLayer, CwdState, DecideRequest, DecideResponse, DecisionRecord, DeliveryMode, DetachedHandle, ExecuteInput, ExecuteOptions, ExternalChannel, FsAdapter, HarnessResponse, HarnessStatus, Item, ItemSchemaConfig, LLMResponse, LlmProviderConfig, ProjectionPolicy, RecallLayerOutput, RecallOptions, SessionScope, SessionUsage, ShellAdapter, Span, SteeringDecision, Step, StorageAdapter, StreamEvent, StreamingItem, SubprocessAdapter, Tool, ToolApprover, TraceExporter, ZodType } from './deps/types.js';
|
|
7
|
+
import type { AcpLiveSession, AcpSessionInfo, AgentConfig, AgentHarnessContract, AgentHooks, CallModelRequest, Channel, ChannelHandle, Context, ContextCacheConfig, ContextCacheStore, ContextData, ContextLayer, CwdState, DecideRequest, DecideResponse, DecisionRecord, DeliveryMode, DetachedHandle, ExecuteInput, ExecuteOptions, ExternalChannel, FsAdapter, HarnessResponse, HarnessStatus, Item, ItemSchemaConfig, LLMResponse, LlmProviderConfig, OnSteerParams, ProjectionPolicy, RecallLayerOutput, RecallOptions, SessionScope, SessionUsage, ShellAdapter, Span, SteeringDecision, SteerVerdict, Step, StorageAdapter, StreamEvent, StreamingItem, SubprocessAdapter, Tool, ToolApprover, TraceExporter, ZodType } from './deps/types.js';
|
|
8
8
|
export { createStreamIdleWatchdog } from './model-call.js';
|
|
9
9
|
/**
|
|
10
10
|
* Storage-scoped environment configuration for `AgentHarness`.
|
|
@@ -502,6 +502,7 @@ export declare class AgentHarness<TParams extends Record<string, unknown> = Reco
|
|
|
502
502
|
setLayerState<T>(executionId: string, layerId: string, state: T): void;
|
|
503
503
|
beforeToolCall(layers: ContextLayer[], toolName: string, toolArgs: unknown, ctx: Context, callId?: string): Promise<SteeringDecision>;
|
|
504
504
|
afterModelCall(layers: ContextLayer[], response: LLMResponse, ctx: Context): Promise<SteeringDecision>;
|
|
505
|
+
onSteer(layers: ContextLayer[], params: Pick<OnSteerParams, 'steer' | 'point' | 'action' | 'pendingCalls'>, ctx: Context): Promise<SteerVerdict>;
|
|
505
506
|
/** Record `hook` as running on `ctx` until it settles (see `runningHooks`). */
|
|
506
507
|
private trackHook;
|
|
507
508
|
projectHistory(layers: ContextLayer[], items: ReadonlyArray<Item>, ctx: Context): Promise<ReadonlyArray<Item>>;
|
|
@@ -5,9 +5,9 @@ import { NoopExporter } from '../observability/trace-exporter.js';
|
|
|
5
5
|
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
|
-
import { afterModelCallLayers, allocateBudgets, assembleView, beforeToolCallLayers, completeLayers, contextToExecCtx, createContextCacheStore, createLayerStateStore, createRecallCache, DEFAULT_PROJECTION, disposeLayers, executeRerender, initLayers, notifyDecision, projectHistoryLayers, recallLayers, recallLayersAtomic, recallLayersEventual, resolveLayerTools, runAppendPipeline, storeLayers, } from './deps/context.js';
|
|
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, deduplicateTools, dispatchStepThroughAdapter, execute, prepareBandedView, someStep, } from './deps/interpreter.js';
|
|
10
|
-
import { buildItemStream, ChannelStore, ContextImpl, captureCheckpoint, clearCheckpoint, collectContextTree, createCheckpointStore, createInMemoryStorage, createSessionStore, createStepLedgerStore, filterReasoningStream, filterTextStream, resolveStepLedgerRetention, restoreFromCheckpoint, rootIdOf, SessionRunner, StepLedger, snapshotCwdState, warnToConsole, } from './deps/runtime.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';
|
|
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';
|
|
@@ -414,10 +414,10 @@ export class AgentHarness {
|
|
|
414
414
|
if (deliveryMode === 'interrupt' && session.runner.getStatus().kind === 'generating') {
|
|
415
415
|
session.runner.queue.prepend(message);
|
|
416
416
|
// Abort kicks the runner via queue subscription after the in-flight turn settles.
|
|
417
|
-
void session.runner.abort(
|
|
417
|
+
void session.runner.abort(INTERRUPT_REASON);
|
|
418
418
|
return Promise.resolve();
|
|
419
419
|
}
|
|
420
|
-
session.runner.
|
|
420
|
+
session.runner.enqueue(message);
|
|
421
421
|
return Promise.resolve();
|
|
422
422
|
}
|
|
423
423
|
getAgentResponse(scope) {
|
|
@@ -491,6 +491,16 @@ export class AgentHarness {
|
|
|
491
491
|
return existing;
|
|
492
492
|
}
|
|
493
493
|
const record = this.threadRecord(threadId);
|
|
494
|
+
// Save a turn's items as the thread's history for the next turn.
|
|
495
|
+
const keepHistory = async (ctx) => {
|
|
496
|
+
if (record) {
|
|
497
|
+
await record.end(ctx, ctx.itemLog.items);
|
|
498
|
+
return;
|
|
499
|
+
}
|
|
500
|
+
session.accumulatedItems = [
|
|
501
|
+
...ctx.itemLog.items,
|
|
502
|
+
];
|
|
503
|
+
};
|
|
494
504
|
const session = {
|
|
495
505
|
accumulatedItems: [],
|
|
496
506
|
record,
|
|
@@ -525,10 +535,7 @@ export class AgentHarness {
|
|
|
525
535
|
extraContextLayers: perTurnOptions.extraContextLayers,
|
|
526
536
|
_broadcaster: session.runner.broadcaster,
|
|
527
537
|
});
|
|
528
|
-
|
|
529
|
-
ext._sessionQueue = session.runner.queue;
|
|
530
|
-
ext._sessionBetweenRounds = true;
|
|
531
|
-
ext._sessionRunnerAgentName = this.config.name;
|
|
538
|
+
frameworkCast(ctx)._sessionQueue = session.runner.queue;
|
|
532
539
|
if (this.agentGraph || this.harnessTools.length > 0) {
|
|
533
540
|
const stepTools = this.agentGraph ? collectAllTools(this.agentGraph) : [];
|
|
534
541
|
this.setUnifiedTools(ctx, [
|
|
@@ -558,15 +565,15 @@ export class AgentHarness {
|
|
|
558
565
|
once: true,
|
|
559
566
|
});
|
|
560
567
|
}
|
|
561
|
-
const result = await this.initAndRun(this.agentGraph, '', ctx)
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
568
|
+
const result = await this.initAndRun(this.agentGraph, '', ctx).catch(async (error) => {
|
|
569
|
+
// An interrupted turn restarts from what it finished, so the
|
|
570
|
+
// interrupting message lands after the work it interrupted.
|
|
571
|
+
if (ctx.abortReason === INTERRUPT_REASON) {
|
|
572
|
+
await keepHistory(ctx);
|
|
573
|
+
}
|
|
574
|
+
throw error;
|
|
575
|
+
});
|
|
576
|
+
await keepHistory(ctx);
|
|
570
577
|
return result;
|
|
571
578
|
},
|
|
572
579
|
// Stored totals are the session's usage; the runner only mirrors them.
|
|
@@ -1261,6 +1268,14 @@ export class AgentHarness {
|
|
|
1261
1268
|
store: this.layerStateStore,
|
|
1262
1269
|
}));
|
|
1263
1270
|
}
|
|
1271
|
+
async onSteer(layers, params, ctx) {
|
|
1272
|
+
return this.trackHook(ctx, onSteerLayers({
|
|
1273
|
+
layers,
|
|
1274
|
+
...params,
|
|
1275
|
+
ctx: this.toExecCtx(ctx),
|
|
1276
|
+
store: this.layerStateStore,
|
|
1277
|
+
}));
|
|
1278
|
+
}
|
|
1264
1279
|
/** Record `hook` as running on `ctx` until it settles (see `runningHooks`). */
|
|
1265
1280
|
trackHook(ctx, hook) {
|
|
1266
1281
|
let running = this.runningHooks.get(ctx);
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
export type { LayerStateStore, RecallCache } from '@noetic-tools/context';
|
|
2
|
-
export { afterModelCallLayers, allocateBudgets, assembleView, beforeToolCallLayers, completeLayers, contextToExecCtx, createContextCacheStore, createLayerStateStore, createRecallCache, DEFAULT_PROJECTION, disposeLayers, executeRerender, exportSpans, initLayers, notifyDecision, projectHistoryLayers, recallLayers, recallLayersAtomic, recallLayersEventual, resolveLayerTools, runAppendPipeline, storeLayers, } from '@noetic-tools/context';
|
|
2
|
+
export { afterModelCallLayers, allocateBudgets, assembleView, beforeToolCallLayers, completeLayers, contextToExecCtx, createContextCacheStore, createLayerStateStore, createRecallCache, DEFAULT_PROJECTION, disposeLayers, executeRerender, exportSpans, initLayers, notifyDecision, onSteerLayers, projectHistoryLayers, recallLayers, recallLayersAtomic, recallLayersEventual, resolveLayerTools, runAppendPipeline, storeLayers, } from '@noetic-tools/context';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export { afterModelCallLayers, allocateBudgets, assembleView, beforeToolCallLayers, completeLayers, contextToExecCtx, createContextCacheStore, createLayerStateStore, createRecallCache, DEFAULT_PROJECTION, disposeLayers, executeRerender, exportSpans, initLayers, notifyDecision, projectHistoryLayers, recallLayers, recallLayersAtomic, recallLayersEventual, resolveLayerTools, runAppendPipeline, storeLayers, } from '@noetic-tools/context';
|
|
1
|
+
export { afterModelCallLayers, allocateBudgets, assembleView, beforeToolCallLayers, completeLayers, contextToExecCtx, createContextCacheStore, createLayerStateStore, createRecallCache, DEFAULT_PROJECTION, disposeLayers, executeRerender, exportSpans, initLayers, notifyDecision, onSteerLayers, projectHistoryLayers, recallLayers, recallLayersAtomic, recallLayersEventual, resolveLayerTools, runAppendPipeline, storeLayers, } from '@noetic-tools/context';
|
|
@@ -12,7 +12,8 @@ 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 type { QueuedMessage } from '../../runtime/message-queue.js';
|
|
15
|
+
export type { QueuedMessage, SessionCtxExtension } from '../../runtime/message-queue.js';
|
|
16
|
+
export { INTERRUPT_REASON } from '../../runtime/message-queue.js';
|
|
16
17
|
export type { TurnUsage } from '../../runtime/session-runner.js';
|
|
17
18
|
export { SessionRunner } from '../../runtime/session-runner.js';
|
|
18
19
|
export { buildItemStream, filterReasoningStream, filterTextStream, } from '../../runtime/session-streams.js';
|
|
@@ -6,5 +6,6 @@ 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
10
|
export { SessionRunner } from '../../runtime/session-runner.js';
|
|
10
11
|
export { buildItemStream, filterReasoningStream, filterTextStream, } from '../../runtime/session-streams.js';
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
export type { ContextCacheConfig, ContextCacheStore, ContextData, ContextLayer, ExecutionContext, ProjectionPolicy, StorageAdapter, } from '@noetic-tools/context';
|
|
2
|
-
export type { AcpKeepAlive, AcpLiveSession, AcpSessionInfo, AgentConfig, AgentHarnessContract, AgentHooks, CallModelRequest, Channel, ChannelHandle, Context, CwdState, DecideRequest, DecideResponse, DecisionRecord, DeliveryMode, DetachedHandle, ExecuteInput, ExecuteOptions, ExternalChannel, FsAdapter, HarnessResponse, HarnessStatus, Item, ItemSchemaConfig, ItemSchemaExtensions, LLMResponse, LlmProviderConfig, RecallLayerOutput, RecallOptions, SessionScope, SessionUsage, ShellAdapter, Span, SteeringDecision, Step, StreamEvent, StreamingItem, SubprocessAdapter, Tool, ToolApprover, TraceExporter, } from '@noetic-tools/types';
|
|
2
|
+
export type { AcpKeepAlive, AcpLiveSession, AcpSessionInfo, AgentConfig, AgentHarnessContract, AgentHooks, CallModelRequest, Channel, ChannelHandle, Context, CwdState, DecideRequest, DecideResponse, DecisionRecord, DeliveryMode, DetachedHandle, ExecuteInput, ExecuteOptions, ExternalChannel, FsAdapter, HarnessResponse, HarnessStatus, Item, ItemSchemaConfig, ItemSchemaExtensions, LLMResponse, LlmProviderConfig, OnSteerParams, RecallLayerOutput, RecallOptions, SessionScope, SessionUsage, ShellAdapter, Span, SteeringDecision, SteerVerdict, Step, StreamEvent, StreamingItem, SubprocessAdapter, Tool, ToolApprover, TraceExporter, } from '@noetic-tools/types';
|
|
3
3
|
export { SteeringAction } from '@noetic-tools/types';
|
|
4
4
|
export type { ZodType } from 'zod';
|
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import type { AgentHarnessContract, CallModelRequest, ItemSchemaRegistry, LLMResponse, TraceExporter } from '@noetic-tools/types';
|
|
2
2
|
import { NoeticConfigError } from '@noetic-tools/types';
|
|
3
3
|
import type { OpenRouter } from '@openrouter/agent';
|
|
4
|
-
import type { MessageQueue } from '../runtime/message-queue.js';
|
|
5
4
|
interface StreamIdleWatchdog {
|
|
6
5
|
/** Bump the deadline because a stream event just arrived. */
|
|
7
6
|
reset: () => void;
|
|
@@ -17,13 +16,6 @@ export declare function noLlmProviderError(): NoeticConfigError;
|
|
|
17
16
|
* `.stop()` in a `finally`. `onTimeout` runs before the abort so observers can
|
|
18
17
|
* emit a framework event with the original cause. Exported only for unit tests. */
|
|
19
18
|
export declare function createStreamIdleWatchdog(timeoutMs: number, controller: AbortController, onTimeout?: () => void): StreamIdleWatchdog;
|
|
20
|
-
/** @internal Context carries the session queue reference so callModel can
|
|
21
|
-
* inject between-rounds messages into the current tool-round loop. */
|
|
22
|
-
export interface SessionCtxExtension {
|
|
23
|
-
_sessionQueue?: MessageQueue;
|
|
24
|
-
_sessionBetweenRounds?: boolean;
|
|
25
|
-
_sessionRunnerAgentName?: string;
|
|
26
|
-
}
|
|
27
19
|
interface AgentHarnessModelCallerOpts {
|
|
28
20
|
agentName: string;
|
|
29
21
|
itemSchemas: ItemSchemaRegistry;
|
|
@@ -48,14 +40,22 @@ export declare class AgentHarnessModelCaller {
|
|
|
48
40
|
private requireModelClient;
|
|
49
41
|
callModel(request: CallModelRequest): Promise<LLMResponse>;
|
|
50
42
|
private runModelLoop;
|
|
51
|
-
|
|
43
|
+
/**
|
|
44
|
+
* Offer queued steers before a model call and add the applied ones to the
|
|
45
|
+
* conversation. They join `allItems` rather than the log so the log keeps
|
|
46
|
+
* them in the order the model saw them.
|
|
47
|
+
*/
|
|
48
|
+
private applySteers;
|
|
49
|
+
private parseRoundItems;
|
|
50
|
+
/** Run the round's function calls. Returns `false` when there were none to run. */
|
|
51
|
+
private runToolRound;
|
|
52
52
|
private handleModelRecovery;
|
|
53
53
|
private handleEmptyOutputRecovery;
|
|
54
54
|
private executeToolRound;
|
|
55
55
|
private executeFunctionCall;
|
|
56
|
-
private
|
|
56
|
+
private recordSkippedToolCall;
|
|
57
|
+
/** Answer a call that never ran, so every call in the history has an output. */
|
|
58
|
+
private recordUnrunToolCall;
|
|
57
59
|
private handleToolRoundLimit;
|
|
58
|
-
/** @internal Drain only messages tagged `between-rounds` from the queue. */
|
|
59
|
-
private drainBetweenRoundsMessages;
|
|
60
60
|
}
|
|
61
61
|
export {};
|
|
@@ -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 (
|
|
549
|
-
this.
|
|
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
|
-
|
|
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
|
|
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
|
|
686
|
-
|
|
687
|
-
break;
|
|
688
|
-
}
|
|
689
|
-
await this.executeToolRound({
|
|
690
|
-
functionCalls,
|
|
768
|
+
const ranTools = await this.runToolRound({
|
|
769
|
+
roundItems,
|
|
691
770
|
request,
|
|
692
|
-
|
|
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
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
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
|
-
|
|
745
|
-
|
|
746
|
-
|
|
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
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
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
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
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.
|
|
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
|
-
|
|
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:
|
|
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:
|
|
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:
|
|
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
|
|
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
|
|
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 {};
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import { frameworkCast, SteerAction, SteerPoint } from '@noetic-tools/types';
|
|
2
|
+
import { inputToItems, isSteer } from '../runtime/message-queue.js';
|
|
3
|
+
//#endregion
|
|
4
|
+
//#region Public API
|
|
5
|
+
/**
|
|
6
|
+
* @internal Open the steer inbox for a model call, or `undefined` when the call
|
|
7
|
+
* runs outside a session. A context inherits its parent's session only when it
|
|
8
|
+
* was spawned with `steers: 'forward'`; parallel paths and other spawns hold
|
|
9
|
+
* steers until control returns to the session's own context.
|
|
10
|
+
*/
|
|
11
|
+
export function openSteerInbox(opts) {
|
|
12
|
+
const { ctx } = opts;
|
|
13
|
+
if (!ctx) {
|
|
14
|
+
return undefined;
|
|
15
|
+
}
|
|
16
|
+
const queue = findSessionQueue(ctx);
|
|
17
|
+
if (!queue) {
|
|
18
|
+
return undefined;
|
|
19
|
+
}
|
|
20
|
+
return new SteerInbox({
|
|
21
|
+
...opts,
|
|
22
|
+
ctx,
|
|
23
|
+
queue,
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* @internal The steers a running model call can take. The call offers queued
|
|
28
|
+
* steers to the context layers at each steer point; those the layers apply are
|
|
29
|
+
* staged and handed over before the next model call.
|
|
30
|
+
*/
|
|
31
|
+
export class SteerInbox {
|
|
32
|
+
opts;
|
|
33
|
+
staged = {
|
|
34
|
+
messageIds: [],
|
|
35
|
+
items: [],
|
|
36
|
+
};
|
|
37
|
+
/** Steers already reported as waiting on tool calls, so each is reported once. */
|
|
38
|
+
reportedPending = new Set();
|
|
39
|
+
constructor(opts) {
|
|
40
|
+
this.opts = opts;
|
|
41
|
+
}
|
|
42
|
+
hasQueued() {
|
|
43
|
+
return this.opts.queue.peekAll().some(isSteer);
|
|
44
|
+
}
|
|
45
|
+
hasStaged() {
|
|
46
|
+
return this.staged.messageIds.length > 0;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Offer every queued steer at `point`. Returns `true` when at least one was
|
|
50
|
+
* staged by this offer.
|
|
51
|
+
*/
|
|
52
|
+
async offer(point, pendingCalls = []) {
|
|
53
|
+
let stagedAny = false;
|
|
54
|
+
for (const message of this.opts.queue.peekAll().filter(isSteer)) {
|
|
55
|
+
const verdict = await this.judge(message, point, pendingCalls);
|
|
56
|
+
if (verdict.action === SteerAction.Defer) {
|
|
57
|
+
this.reportPending(message, point, pendingCalls);
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
// A sibling call may have taken it while the layers were judging.
|
|
61
|
+
if (this.opts.queue.take((queued) => queued === message).length === 0) {
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
if (verdict.action === SteerAction.Drop) {
|
|
65
|
+
this.opts.emit('steer_dropped', {
|
|
66
|
+
messageId: message.id,
|
|
67
|
+
point,
|
|
68
|
+
});
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
await this.stage(message.id, verdict.items);
|
|
72
|
+
stagedAny = true;
|
|
73
|
+
}
|
|
74
|
+
return stagedAny;
|
|
75
|
+
}
|
|
76
|
+
/** Hand over the staged steers and clear them. */
|
|
77
|
+
takeStaged() {
|
|
78
|
+
const staged = this.staged;
|
|
79
|
+
this.staged = {
|
|
80
|
+
messageIds: [],
|
|
81
|
+
items: [],
|
|
82
|
+
};
|
|
83
|
+
return staged;
|
|
84
|
+
}
|
|
85
|
+
async judge(message, point, pendingCalls) {
|
|
86
|
+
const action = defaultAction(point, message.deliveryMode);
|
|
87
|
+
const items = inputToItems(message.input);
|
|
88
|
+
const { harness, layers } = this.opts;
|
|
89
|
+
if (!harness.onSteer || !layers.some((layer) => layer.hooks.onSteer)) {
|
|
90
|
+
return {
|
|
91
|
+
action,
|
|
92
|
+
items,
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
return harness.onSteer(layers, {
|
|
96
|
+
steer: {
|
|
97
|
+
id: message.id,
|
|
98
|
+
items,
|
|
99
|
+
},
|
|
100
|
+
point,
|
|
101
|
+
action,
|
|
102
|
+
pendingCalls,
|
|
103
|
+
}, this.opts.ctx);
|
|
104
|
+
}
|
|
105
|
+
/** Steers are user input, so they pass through `onItemAppend` like any other.
|
|
106
|
+
* Re-render requests are ignored: recall does not run again mid-call. */
|
|
107
|
+
async stage(messageId, items) {
|
|
108
|
+
const piped = this.opts.layers.length > 0
|
|
109
|
+
? (await this.opts.harness.runAppendPipeline(this.opts.layers, items, this.opts.ctx)).items
|
|
110
|
+
: items;
|
|
111
|
+
this.staged.messageIds.push(messageId);
|
|
112
|
+
this.staged.items.push(...piped);
|
|
113
|
+
}
|
|
114
|
+
reportPending(message, point, pendingCalls) {
|
|
115
|
+
if (point !== SteerPoint.BeforeToolCall || this.reportedPending.has(message.id)) {
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
this.reportedPending.add(message.id);
|
|
119
|
+
this.opts.emit('steer_pending', {
|
|
120
|
+
messageId: message.id,
|
|
121
|
+
waitingOn: pendingCalls.map((call) => call.callId),
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
//#endregion
|
|
126
|
+
//#region Helpers
|
|
127
|
+
function findSessionQueue(ctx) {
|
|
128
|
+
for (let current = ctx; current; current = current.parent) {
|
|
129
|
+
const ext = frameworkCast(current);
|
|
130
|
+
if (ext._sessionQueue) {
|
|
131
|
+
return ext._sessionQueue;
|
|
132
|
+
}
|
|
133
|
+
if (!ext._forwardSteers) {
|
|
134
|
+
return undefined;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
return undefined;
|
|
138
|
+
}
|
|
139
|
+
/** What each delivery mode does at each point before any layer has a say. */
|
|
140
|
+
function defaultAction(point, mode) {
|
|
141
|
+
if (point === SteerPoint.BeforeRound) {
|
|
142
|
+
return SteerAction.Apply;
|
|
143
|
+
}
|
|
144
|
+
if (point === SteerPoint.ItemDone && mode === 'next-item') {
|
|
145
|
+
return SteerAction.Apply;
|
|
146
|
+
}
|
|
147
|
+
return SteerAction.Defer;
|
|
148
|
+
}
|
|
149
|
+
//#endregion
|
package/dist/index.d.ts
CHANGED
|
@@ -162,9 +162,9 @@ export type { FrameworkStreamEvent, HarnessResponse, SdkStreamEvent, StreamEvent
|
|
|
162
162
|
/** @public */
|
|
163
163
|
export type { AgentConfig, AgentHarnessContract, AgentHooks, CallModelRequest, ContextCacheConfig, ContextCacheStore, ContextEpoch, DeliveryMode, ExecuteOptions, HarnessJudgmentContract, HarnessStatus, ItemSchemaConfig, ReanchorReason, RecallLayerOutput, SessionScope, SessionUsage, } from '@noetic-tools/types';
|
|
164
164
|
/** @public */
|
|
165
|
-
export type { AfterModelCallParams, AfterModelCallResult, ApproveToolCallParams, BeforeToolCallParams, BeforeToolCallResult, LedgerEntry, SteeringConfig, SteeringDecision, SteeringRule, SteeringState, ToolApprover, } from '@noetic-tools/types';
|
|
165
|
+
export type { AfterModelCallParams, AfterModelCallResult, ApproveToolCallParams, BeforeToolCallParams, BeforeToolCallResult, LedgerEntry, OnSteerParams, OnSteerResult, Steer, SteeringConfig, SteeringDecision, SteeringRule, SteeringState, SteerVerdict, ToolApprover, } from '@noetic-tools/types';
|
|
166
166
|
/** @public */
|
|
167
|
-
export { LedgerEntryKind, SteeringAction } from '@noetic-tools/types';
|
|
167
|
+
export { LedgerEntryKind, SteerAction, SteeringAction, SteerPoint } from '@noetic-tools/types';
|
|
168
168
|
/** @public */
|
|
169
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 */
|
package/dist/index.js
CHANGED
|
@@ -101,7 +101,7 @@ export { ChannelSnapshotSchema, CheckpointSchemaVersion, CheckpointSnapshotSchem
|
|
|
101
101
|
/** @public */
|
|
102
102
|
export { Slot } from '@noetic-tools/context';
|
|
103
103
|
/** @public */
|
|
104
|
-
export { LedgerEntryKind, SteeringAction } from '@noetic-tools/types';
|
|
104
|
+
export { LedgerEntryKind, SteerAction, SteeringAction, SteerPoint } from '@noetic-tools/types';
|
|
105
105
|
/** @public */
|
|
106
106
|
export { BooleanQuestionSchema, ChoiceQuestionSchema, choiceValues, DECIDE_LIMITS, DecideOutputError, DecideQuestionSchema, DecideQuestionsSchema, routeOutcomes, ScoreQuestionSchema, scoreLevels, } from '@noetic-tools/types';
|
|
107
107
|
/** @public */
|
|
@@ -5,4 +5,6 @@ export { defaultItemSchemaRegistry } from '@noetic-tools/types';
|
|
|
5
5
|
export { emitFrameworkEvent, getBroadcaster, shouldEmit } from '../runtime/broadcaster-utils.js';
|
|
6
6
|
export { ContextImpl, laneBase } from '../runtime/context-impl.js';
|
|
7
7
|
export { snapshotCwdState } from '../runtime/cwd-helpers.js';
|
|
8
|
+
export type { SessionCtxExtension } from '../runtime/message-queue.js';
|
|
9
|
+
export { INTERRUPT_REASON } from '../runtime/message-queue.js';
|
|
8
10
|
export { buildToolExecutionContext } from '../runtime/tool-context.js';
|
|
@@ -3,4 +3,5 @@ export { defaultItemSchemaRegistry } from '@noetic-tools/types';
|
|
|
3
3
|
export { emitFrameworkEvent, getBroadcaster, shouldEmit } from '../runtime/broadcaster-utils.js';
|
|
4
4
|
export { ContextImpl, laneBase } from '../runtime/context-impl.js';
|
|
5
5
|
export { snapshotCwdState } from '../runtime/cwd-helpers.js';
|
|
6
|
+
export { INTERRUPT_REASON } from '../runtime/message-queue.js';
|
|
6
7
|
export { buildToolExecutionContext } from '../runtime/tool-context.js';
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
export type { ContextConfig, ContextData, ContextLayer, ExecutionContext, } from '@noetic-tools/context';
|
|
2
|
-
export type { AgentHarnessContract, CallModelRequest, Context, ContextRerenderRequest, ExecuteStepFn, FunctionCallItem, InputMessageItem, Item, LLMResponse, ProjectionPolicy, RecallLayerOutput, RetryPolicy, ServerToolSpec, StepCallModel, StepDecide, StepInvokeTool, StepMeta, StepRunCode, StepSpawn, StepWithContext, StorageAdapter, Tool, } from '@noetic-tools/types';
|
|
2
|
+
export type { AgentHarnessContract, CallModelRequest, Context, ContextRerenderRequest, ExecuteStepFn, FunctionCallItem, FunctionCallOutputItem, InputMessageItem, Item, LLMResponse, ProjectionPolicy, RecallLayerOutput, RetryPolicy, ServerToolSpec, StepCallModel, StepDecide, StepInvokeTool, StepMeta, StepRunCode, StepSpawn, StepWithContext, StorageAdapter, Tool, } from '@noetic-tools/types';
|
|
3
3
|
export { isServerToolSpec, SteeringAction } from '@noetic-tools/types';
|
|
@@ -5,7 +5,7 @@ import { createMessage, estimateTokens, extractAssistantText, frameworkCast, isN
|
|
|
5
5
|
import { ToolAttr } from '../observability/genai-attributes.js';
|
|
6
6
|
import { askApproval } from '../runtime/tool-approval.js';
|
|
7
7
|
import { emitToolUi } from '../runtime/tool-ui.js';
|
|
8
|
-
import { allocateBudgets, assembleView, buildToolExecutionContext, ContextImpl, commitLayerUsage, computeLayerUsage, contextToExecCtx, createContextCacheStore, DEFAULT_PROJECTION, defaultItemSchemaRegistry, disposeLayers, emitFrameworkEvent, getBroadcaster, initLayers, lineageKey, noteCacheOutcome, resolveCacheConfig, resolveLayerTools, returnLayers, shouldEmit, snapshotCwdState, spawnLayers, unpinLayers, } from './action-deps.js';
|
|
8
|
+
import { allocateBudgets, assembleView, buildToolExecutionContext, ContextImpl, commitLayerUsage, computeLayerUsage, contextToExecCtx, createContextCacheStore, DEFAULT_PROJECTION, defaultItemSchemaRegistry, disposeLayers, emitFrameworkEvent, getBroadcaster, INTERRUPT_REASON, initLayers, lineageKey, noteCacheOutcome, resolveCacheConfig, resolveLayerTools, returnLayers, shouldEmit, snapshotCwdState, spawnLayers, unpinLayers, } from './action-deps.js';
|
|
9
9
|
import { isServerToolSpec, SteeringAction } from './action-types.js';
|
|
10
10
|
import { openChildSpan, traceChild } from './child-span.js';
|
|
11
11
|
import { cloneWithGuard } from './clone-guard.js';
|
|
@@ -420,6 +420,42 @@ function buildModelRequest(params) {
|
|
|
420
420
|
}
|
|
421
421
|
return base;
|
|
422
422
|
}
|
|
423
|
+
/**
|
|
424
|
+
* Keep what an interrupted call finished, so the restarted turn knows what
|
|
425
|
+
* already ran. A call cut off mid-round leaves tool calls with no output,
|
|
426
|
+
* which no provider accepts in history, so each gets one.
|
|
427
|
+
*/
|
|
428
|
+
function keepFinishedItems(ctx, items) {
|
|
429
|
+
const answered = new Set(items
|
|
430
|
+
.filter((item) => item.type === 'function_call_output')
|
|
431
|
+
.map((item) => item.callId));
|
|
432
|
+
for (const item of items) {
|
|
433
|
+
ctx.itemLog.append(item);
|
|
434
|
+
}
|
|
435
|
+
for (const call of items.filter(isFunctionCall)) {
|
|
436
|
+
if (answered.has(call.callId)) {
|
|
437
|
+
continue;
|
|
438
|
+
}
|
|
439
|
+
ctx.itemLog.append({
|
|
440
|
+
id: `cancelled-${call.callId}`,
|
|
441
|
+
type: 'function_call_output',
|
|
442
|
+
status: 'incomplete',
|
|
443
|
+
callId: call.callId,
|
|
444
|
+
output: 'Cancelled before it ran.',
|
|
445
|
+
});
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
/**
|
|
449
|
+
* A guardrail retry throws the response away, but steers in it came from the
|
|
450
|
+
* user, not the model. Log them so the retry still sees them.
|
|
451
|
+
*/
|
|
452
|
+
function keepSteers(ctx, items) {
|
|
453
|
+
for (const item of items) {
|
|
454
|
+
if (item.type === 'message' && item.role !== 'assistant') {
|
|
455
|
+
ctx.itemLog.append(item);
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
}
|
|
423
459
|
/**
|
|
424
460
|
* Records a finished model response on the context: appends response items to
|
|
425
461
|
* the log, publishes `lastStepMeta`, and commits the per-layer usage breakdown
|
|
@@ -587,6 +623,9 @@ export async function executeCallModel(step, input, ctx, layers) {
|
|
|
587
623
|
// the signal fired. The spend is charged above, but a truncated generation
|
|
588
624
|
// is not this step's output — surface cancellation instead.
|
|
589
625
|
if (baseCtx.aborted) {
|
|
626
|
+
if (baseCtx.abortReason === INTERRUPT_REASON) {
|
|
627
|
+
keepFinishedItems(baseCtx, response.items);
|
|
628
|
+
}
|
|
590
629
|
throw new NoeticErrorImpl({
|
|
591
630
|
kind: 'cancelled',
|
|
592
631
|
reason: baseCtx.abortReason ?? 'context aborted',
|
|
@@ -606,6 +645,7 @@ export async function executeCallModel(step, input, ctx, layers) {
|
|
|
606
645
|
// so the retry's view ends on the correction rather than burying it
|
|
607
646
|
// ahead of the live band. Assembly drops it from history to avoid
|
|
608
647
|
// showing it twice.
|
|
648
|
+
keepSteers(baseCtx, response.items);
|
|
609
649
|
baseCtx.itemLog.append(guidance);
|
|
610
650
|
steeringTail = [
|
|
611
651
|
...steeringTail,
|
|
@@ -740,6 +780,9 @@ export async function executeSpawn(step, input, ctx, executeStep, opts) {
|
|
|
740
780
|
// The child's steps checkpoint the root, as an inParallel path's do.
|
|
741
781
|
checkpointFn: () => baseCtx.checkpoint(),
|
|
742
782
|
});
|
|
783
|
+
if (step.steers === 'forward') {
|
|
784
|
+
frameworkCast(childCtx)._forwardSteers = true;
|
|
785
|
+
}
|
|
743
786
|
// `childExecutionCtx` predates the spawn span; the child's hooks trace onto that span.
|
|
744
787
|
const childTracedCtx = {
|
|
745
788
|
...childExecutionCtx,
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { DeliveryMode, ExecuteInput, ExecuteOptions } from '@noetic-tools/types';
|
|
1
|
+
import type { DeliveryMode, ExecuteInput, ExecuteOptions, Item } from '@noetic-tools/types';
|
|
2
2
|
/** @internal A message accepted by `AgentHarness.execute()` and held until the
|
|
3
3
|
* session runner processes it. The effective `DeliveryMode` is resolved at
|
|
4
4
|
* enqueue time so the runner never has to look at harness defaults again. */
|
|
@@ -9,8 +9,20 @@ export interface QueuedMessage {
|
|
|
9
9
|
readonly options: ExecuteOptions;
|
|
10
10
|
readonly enqueuedAt: number;
|
|
11
11
|
}
|
|
12
|
+
/** @internal Context fields that let a model call find its session's steers. */
|
|
13
|
+
export interface SessionCtxExtension {
|
|
14
|
+
_sessionQueue?: MessageQueue;
|
|
15
|
+
/** Set on a spawned child that takes its parent's steers. */
|
|
16
|
+
_forwardSteers?: boolean;
|
|
17
|
+
}
|
|
12
18
|
/** @internal Subscription callback fired after any mutation. */
|
|
13
19
|
export type QueueChangeListener = (size: number) => void;
|
|
20
|
+
/** @internal Convert `execute()` input to log items. An empty string is no input. */
|
|
21
|
+
export declare function inputToItems(input: ExecuteInput): Item[];
|
|
22
|
+
/** @internal The abort reason a `deliveryMode: 'interrupt'` message cancels its turn with. */
|
|
23
|
+
export declare const INTERRUPT_REASON = "interrupt";
|
|
24
|
+
/** @internal Whether a queued message is a steer: one meant for the running turn. */
|
|
25
|
+
export declare function isSteer(message: QueuedMessage): boolean;
|
|
14
26
|
/** @internal Per-thread FIFO of inbox messages with prepend + subscription.
|
|
15
27
|
*
|
|
16
28
|
* `prepend` is used when an in-flight turn is aborted — the aborting message
|
|
@@ -22,6 +34,8 @@ export declare class MessageQueue {
|
|
|
22
34
|
enqueue(message: QueuedMessage): void;
|
|
23
35
|
prepend(message: QueuedMessage): void;
|
|
24
36
|
drainAll(): QueuedMessage[];
|
|
37
|
+
/** Remove and return the messages `match` accepts, keeping the rest in order. */
|
|
38
|
+
take(match: (message: QueuedMessage) => boolean): QueuedMessage[];
|
|
25
39
|
peekAll(): ReadonlyArray<QueuedMessage>;
|
|
26
40
|
get size(): number;
|
|
27
41
|
subscribe(listener: QueueChangeListener): () => void;
|
|
@@ -1,4 +1,41 @@
|
|
|
1
1
|
//#endregion
|
|
2
|
+
//#region Input conversion
|
|
3
|
+
/** @internal Convert `execute()` input to log items. An empty string is no input. */
|
|
4
|
+
export function inputToItems(input) {
|
|
5
|
+
if (typeof input === 'string') {
|
|
6
|
+
if (input.length === 0) {
|
|
7
|
+
return [];
|
|
8
|
+
}
|
|
9
|
+
const item = {
|
|
10
|
+
id: `user-${crypto.randomUUID()}`,
|
|
11
|
+
type: 'message',
|
|
12
|
+
role: 'user',
|
|
13
|
+
status: 'completed',
|
|
14
|
+
content: [
|
|
15
|
+
{
|
|
16
|
+
type: 'input_text',
|
|
17
|
+
text: input,
|
|
18
|
+
},
|
|
19
|
+
],
|
|
20
|
+
};
|
|
21
|
+
return [
|
|
22
|
+
item,
|
|
23
|
+
];
|
|
24
|
+
}
|
|
25
|
+
if (Array.isArray(input)) {
|
|
26
|
+
return input;
|
|
27
|
+
}
|
|
28
|
+
return [
|
|
29
|
+
input,
|
|
30
|
+
];
|
|
31
|
+
}
|
|
32
|
+
/** @internal The abort reason a `deliveryMode: 'interrupt'` message cancels its turn with. */
|
|
33
|
+
export const INTERRUPT_REASON = 'interrupt';
|
|
34
|
+
/** @internal Whether a queued message is a steer: one meant for the running turn. */
|
|
35
|
+
export function isSteer(message) {
|
|
36
|
+
return message.deliveryMode === 'between-rounds' || message.deliveryMode === 'next-item';
|
|
37
|
+
}
|
|
38
|
+
//#endregion
|
|
2
39
|
//#region MessageQueue
|
|
3
40
|
/** @internal Per-thread FIFO of inbox messages with prepend + subscription.
|
|
4
41
|
*
|
|
@@ -24,6 +61,23 @@ export class MessageQueue {
|
|
|
24
61
|
this.notify();
|
|
25
62
|
return drained;
|
|
26
63
|
}
|
|
64
|
+
/** Remove and return the messages `match` accepts, keeping the rest in order. */
|
|
65
|
+
take(match) {
|
|
66
|
+
const taken = [];
|
|
67
|
+
for (let i = 0; i < this.items.length;) {
|
|
68
|
+
const message = this.items[i];
|
|
69
|
+
if (message && match(message)) {
|
|
70
|
+
taken.push(message);
|
|
71
|
+
this.items.splice(i, 1);
|
|
72
|
+
continue;
|
|
73
|
+
}
|
|
74
|
+
i++;
|
|
75
|
+
}
|
|
76
|
+
if (taken.length > 0) {
|
|
77
|
+
this.notify();
|
|
78
|
+
}
|
|
79
|
+
return taken;
|
|
80
|
+
}
|
|
27
81
|
peekAll() {
|
|
28
82
|
return this.items;
|
|
29
83
|
}
|
|
@@ -78,6 +78,9 @@ export declare class SessionRunner {
|
|
|
78
78
|
private readonly responseWaiters;
|
|
79
79
|
constructor(opts: SessionRunnerOpts);
|
|
80
80
|
getStatus(): HarnessStatus;
|
|
81
|
+
/** Queue a message. A steer that arrives mid-turn is announced first, so
|
|
82
|
+
* `steer_accepted` always precedes the `inbox_injected` that applies it. */
|
|
83
|
+
enqueue(message: QueuedMessage): void;
|
|
81
84
|
/** Cumulative token usage and cost across all turns this session has run. */
|
|
82
85
|
getUsage(): SessionUsage;
|
|
83
86
|
/** Replace the totals with ones a durable host read back from storage. */
|
|
@@ -1,37 +1,9 @@
|
|
|
1
1
|
import { isNoeticError } from '@noetic-tools/types';
|
|
2
2
|
import { emitFrameworkEvent } from './broadcaster-utils.js';
|
|
3
3
|
import { EventBroadcaster } from './event-broadcaster.js';
|
|
4
|
-
import { MessageQueue } from './message-queue.js';
|
|
4
|
+
import { inputToItems, isSteer, MessageQueue } from './message-queue.js';
|
|
5
5
|
//#endregion
|
|
6
6
|
//#region Helpers
|
|
7
|
-
function inputToItems(input) {
|
|
8
|
-
if (typeof input === 'string') {
|
|
9
|
-
if (input.length === 0) {
|
|
10
|
-
return [];
|
|
11
|
-
}
|
|
12
|
-
const item = {
|
|
13
|
-
id: `user-${crypto.randomUUID()}`,
|
|
14
|
-
type: 'message',
|
|
15
|
-
role: 'user',
|
|
16
|
-
status: 'completed',
|
|
17
|
-
content: [
|
|
18
|
-
{
|
|
19
|
-
type: 'input_text',
|
|
20
|
-
text: input,
|
|
21
|
-
},
|
|
22
|
-
],
|
|
23
|
-
};
|
|
24
|
-
return [
|
|
25
|
-
item,
|
|
26
|
-
];
|
|
27
|
-
}
|
|
28
|
-
if (Array.isArray(input)) {
|
|
29
|
-
return input;
|
|
30
|
-
}
|
|
31
|
-
return [
|
|
32
|
-
input,
|
|
33
|
-
];
|
|
34
|
-
}
|
|
35
7
|
function mergeInputsToItems(messages) {
|
|
36
8
|
const items = [];
|
|
37
9
|
for (const msg of messages) {
|
|
@@ -95,6 +67,23 @@ export class SessionRunner {
|
|
|
95
67
|
getStatus() {
|
|
96
68
|
return this.status;
|
|
97
69
|
}
|
|
70
|
+
/** Queue a message. A steer that arrives mid-turn is announced first, so
|
|
71
|
+
* `steer_accepted` always precedes the `inbox_injected` that applies it. */
|
|
72
|
+
enqueue(message) {
|
|
73
|
+
if (this.status.kind === 'generating' && isSteer(message)) {
|
|
74
|
+
emitFrameworkEvent({
|
|
75
|
+
broadcaster: this.broadcaster,
|
|
76
|
+
agentName: this.agentName,
|
|
77
|
+
eventType: 'steer_accepted',
|
|
78
|
+
data: {
|
|
79
|
+
messageId: message.id,
|
|
80
|
+
turnId: this.status.turnId,
|
|
81
|
+
deliveryMode: message.deliveryMode,
|
|
82
|
+
},
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
this.queue.enqueue(message);
|
|
86
|
+
}
|
|
98
87
|
/** Cumulative token usage and cost across all turns this session has run. */
|
|
99
88
|
getUsage() {
|
|
100
89
|
return {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@noetic-tools/core",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.15.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.
|
|
72
|
-
"@noetic-tools/types": "^3.
|
|
71
|
+
"@noetic-tools/context": "^1.10.0",
|
|
72
|
+
"@noetic-tools/types": "^3.13.0",
|
|
73
73
|
"@openrouter/agent": "^0.11.0",
|
|
74
74
|
"@openrouter/sdk": "1.4.25",
|
|
75
75
|
"jsonata": "2.2.2",
|