@noetic-tools/core 5.22.0-next.1 → 5.22.0-next.2
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/adapters/openrouter.d.ts +6 -1
- package/dist/adapters/openrouter.js +10 -0
- package/dist/builders/decide-builders.d.ts +7 -0
- package/dist/builders/tool-builder.d.ts +5 -1
- package/dist/builders/tool-builder.js +2 -0
- package/dist/builders/workflow-control-nodes.js +1 -0
- package/dist/harness/agent-harness.d.ts +54 -0
- package/dist/harness/agent-harness.js +108 -1
- package/dist/harness/decide-call.d.ts +15 -0
- package/dist/harness/decide-call.js +57 -7
- package/dist/harness/harness-options.d.ts +9 -0
- package/dist/harness/llm-client.d.ts +2 -0
- package/dist/harness/llm-client.js +9 -5
- package/dist/harness/model-tool-round.js +48 -3
- package/dist/index.d.ts +5 -1
- package/dist/index.js +2 -0
- package/dist/interpreter/execute-decide.js +5 -0
- package/dist/portable/runtime.d.ts +4 -0
- package/dist/portable/runtime.js +2 -0
- package/dist/runtime/event-broadcaster.d.ts +9 -1
- package/dist/runtime/event-broadcaster.js +16 -1
- package/dist/runtime/output-store.d.ts +88 -0
- package/dist/runtime/output-store.js +241 -0
- package/dist/runtime/session-streams.d.ts +28 -7
- package/dist/runtime/session-streams.js +112 -67
- package/package.json +1 -1
- package/schema/noetic-workflow.schema.json +27 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { Item, LLMResponse, Tool } from '@noetic-tools/types';
|
|
1
|
+
import type { Item, LLMResponse, Tool, ToolModelOutput } from '@noetic-tools/types';
|
|
2
2
|
import type * as OpenRouterAgent from '@openrouter/agent';
|
|
3
3
|
import type { EmbedFn } from '../types/embed.js';
|
|
4
4
|
type ProviderOutputItem = OpenRouterAgent.OpenResponsesResult['output'][number];
|
|
@@ -9,6 +9,11 @@ export type SdkTool = OpenRouterAgent.Tool;
|
|
|
9
9
|
export interface ConvertToolsParams {
|
|
10
10
|
tools: ReadonlyArray<Tool>;
|
|
11
11
|
}
|
|
12
|
+
/**
|
|
13
|
+
* @internal What a `function_call_output` carries for a tool's `toModelOutput`
|
|
14
|
+
* value: text as it is, content parts in the provider's shape.
|
|
15
|
+
*/
|
|
16
|
+
export declare function toolModelOutputToProvider(output: ToolModelOutput): OpenRouterAgent.FunctionCallOutputItem['output'];
|
|
12
17
|
/** @internal Extracts system messages from items and returns them as a single instructions string. */
|
|
13
18
|
export declare function extractSystemInstruction(items: ReadonlyArray<Item>): {
|
|
14
19
|
instructions: string | undefined;
|
|
@@ -57,6 +57,16 @@ function contentPartsToProviderContent(parts) {
|
|
|
57
57
|
}
|
|
58
58
|
return frameworkCast(parts).map(inputContentPartToProvider);
|
|
59
59
|
}
|
|
60
|
+
/**
|
|
61
|
+
* @internal What a `function_call_output` carries for a tool's `toModelOutput`
|
|
62
|
+
* value: text as it is, content parts in the provider's shape.
|
|
63
|
+
*/
|
|
64
|
+
export function toolModelOutputToProvider(output) {
|
|
65
|
+
if (typeof output === 'string') {
|
|
66
|
+
return output;
|
|
67
|
+
}
|
|
68
|
+
return frameworkCast(output.map(inputContentPartToProvider));
|
|
69
|
+
}
|
|
60
70
|
//#endregion
|
|
61
71
|
//#region Item → OpenRouter Input Conversion
|
|
62
72
|
/** @internal Extracts system messages from items and returns them as a single instructions string. */
|
|
@@ -18,6 +18,13 @@ export interface StepDecideOpts<TContext, Q extends DecideQuestions, I = unknown
|
|
|
18
18
|
projection?: ProjectionPolicy;
|
|
19
19
|
/** Runs averaged on the estimated path. Ignored on the native path. Default 1. */
|
|
20
20
|
samples?: number;
|
|
21
|
+
/**
|
|
22
|
+
* Extra HTTP headers for the native request: how a host sets a provider's
|
|
23
|
+
* per-request option, e.g. `{ 'TypeSafe-Danger-Zone-Long-Context': 'true' }`
|
|
24
|
+
* for TypeSafe's long-context limits. Passed through unread and ignored on the
|
|
25
|
+
* estimated path. A step may be serialized, so keep credentials out of them.
|
|
26
|
+
*/
|
|
27
|
+
headers?: Readonly<Record<string, string>>;
|
|
21
28
|
emit?: boolean | ((eventType: string, data: Record<string, unknown>) => boolean);
|
|
22
29
|
}
|
|
23
30
|
/** An empty question map is a type error, not just a build-time one. */
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { FunctionCallItem, FunctionCallOutputItem, InferSchemaOutput, InputSchemaConfig, Item, ItemSchemaExtensions, StandardSchemaV1, Tool, ToolAcpDeclaration, ToolContextDeclaration, ToolExecutionContext, ToolResultExtensionItem, ToolUiDeclaration } from '@noetic-tools/types';
|
|
1
|
+
import type { FunctionCallItem, FunctionCallOutputItem, InferSchemaOutput, InputSchemaConfig, Item, ItemSchemaExtensions, StandardSchemaV1, Tool, ToolAcpDeclaration, ToolContextDeclaration, ToolExecutionContext, ToolModelOutput, ToolResultExtensionItem, ToolUiDeclaration } from '@noetic-tools/types';
|
|
2
2
|
type ToolConfig<I extends StandardSchemaV1, O extends StandardSchemaV1> = {
|
|
3
3
|
name: string;
|
|
4
4
|
description: string;
|
|
@@ -14,6 +14,8 @@ type ToolConfig<I extends StandardSchemaV1, O extends StandardSchemaV1> = {
|
|
|
14
14
|
error?: boolean;
|
|
15
15
|
}) => Item | ToolResultExtensionItem;
|
|
16
16
|
execute: (args: InferSchemaOutput<I>, toolCtx: ToolExecutionContext) => Promise<InferSchemaOutput<O>>;
|
|
17
|
+
/** See `Tool.toModelOutput`: what the model is given as the result, e.g. an image. */
|
|
18
|
+
toModelOutput?: (result: InferSchemaOutput<O>, args: InferSchemaOutput<I>) => ToolModelOutput;
|
|
17
19
|
needsApproval?: boolean;
|
|
18
20
|
/** See `Tool.durable`: `true` holds an interrupted call for a person, `false` records nothing. */
|
|
19
21
|
durable?: boolean;
|
|
@@ -40,6 +42,8 @@ type GeneratorToolConfig<I extends StandardSchemaV1, E extends StandardSchemaV1,
|
|
|
40
42
|
error?: boolean;
|
|
41
43
|
}) => Item | ToolResultExtensionItem;
|
|
42
44
|
execute: (args: InferSchemaOutput<I>, toolCtx: ToolExecutionContext) => AsyncGenerator<InferSchemaOutput<E>, InferSchemaOutput<O>>;
|
|
45
|
+
/** See `Tool.toModelOutput`: what the model is given as the result, e.g. an image. */
|
|
46
|
+
toModelOutput?: (result: InferSchemaOutput<O>, args: InferSchemaOutput<I>) => ToolModelOutput;
|
|
43
47
|
needsApproval?: boolean;
|
|
44
48
|
/** See `Tool.durable`: `true` holds an interrupted call for a person, `false` records nothing. */
|
|
45
49
|
durable?: boolean;
|
|
@@ -37,6 +37,7 @@ export function tool(config) {
|
|
|
37
37
|
inputJsonSchema: config.inputJsonSchema,
|
|
38
38
|
itemSchemas: config.itemSchemas,
|
|
39
39
|
decorateResultItem: config.decorateResultItem,
|
|
40
|
+
toModelOutput: config.toModelOutput,
|
|
40
41
|
execute: config.execute,
|
|
41
42
|
needsApproval: config.needsApproval,
|
|
42
43
|
durable: config.durable,
|
|
@@ -61,6 +62,7 @@ export function toolWithGenerator(config) {
|
|
|
61
62
|
inputJsonSchema: config.inputJsonSchema,
|
|
62
63
|
itemSchemas: config.itemSchemas,
|
|
63
64
|
decorateResultItem: config.decorateResultItem,
|
|
65
|
+
toModelOutput: config.toModelOutput,
|
|
64
66
|
execute: config.execute,
|
|
65
67
|
needsApproval: config.needsApproval,
|
|
66
68
|
durable: config.durable,
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { ApproveRequest, ArtifactStore, ConnectionStatus, ConnectionTrigger, ExecuteArgument, HeldCall, HeldResolution, StuckTurn, TrailMark } from '@noetic-tools/types';
|
|
2
2
|
import { ItemSchemaRegistry } from '@noetic-tools/types';
|
|
3
3
|
import { AcpSessionStore } from '../runtime/acp-session-store.js';
|
|
4
|
+
import type { OutputSnapshot } from '../runtime/output-store.js';
|
|
4
5
|
import type { LayerStateStore, RecallCache } from './deps/context.js';
|
|
5
6
|
import type { DetachedSpawnOverrides } from './deps/interpreter.js';
|
|
6
7
|
import type { CheckpointStore, EventBroadcaster, RestoreCheckpointOptions, StepLedgerRetention, StepLedgerStore } from './deps/runtime.js';
|
|
@@ -84,6 +85,16 @@ export declare class AgentHarness<TParams extends Record<string, unknown> = Reco
|
|
|
84
85
|
private readonly pendingCheckpoints;
|
|
85
86
|
private readonly defaultDeliveryMode;
|
|
86
87
|
private readonly sessions;
|
|
88
|
+
/** Whether threads keep their streamed output for display (`opts.interactive`). */
|
|
89
|
+
readonly interactive: boolean;
|
|
90
|
+
/** Where display output is kept: the harness's storage, or memory without one. */
|
|
91
|
+
private readonly outputStorage;
|
|
92
|
+
/** The display output each thread of an interactive harness records, by thread id. */
|
|
93
|
+
private readonly outputs;
|
|
94
|
+
/** Thread id → what stops recording it. */
|
|
95
|
+
private readonly stopRecording;
|
|
96
|
+
/** Threads named by a host-built context's own id, dropped when its run ends. */
|
|
97
|
+
private readonly ownThreads;
|
|
87
98
|
/**
|
|
88
99
|
* @internal Live ACP connections. Reached by the interpreter via
|
|
89
100
|
* `frameworkCast`; use {@link listAcpSessions}, {@link getAcpSession},
|
|
@@ -266,6 +277,31 @@ export declare class AgentHarness<TParams extends Record<string, unknown> = Reco
|
|
|
266
277
|
* each event in progress (`isComplete: false`), then its final item, under one `id`.
|
|
267
278
|
*/
|
|
268
279
|
getItemStream(scope?: SessionScope): AsyncIterable<StreamingItem | CustomStreamingItem<DeclaredItems<TItem>>>;
|
|
280
|
+
/**
|
|
281
|
+
* A thread's display output (spec 08 § Display output): the latest snapshot of
|
|
282
|
+
* every item it streamed, unfinished ones included, read from storage. An
|
|
283
|
+
* `interactive` harness records it; any harness over the same storage reads it.
|
|
284
|
+
* For showing a thread again, never for resuming one.
|
|
285
|
+
*
|
|
286
|
+
* @throws OutputStoreError when storage fails, or holds something else under the key.
|
|
287
|
+
* @public
|
|
288
|
+
*/
|
|
289
|
+
getSessionOutput(scope?: SessionScope): Promise<OutputSnapshot[]>;
|
|
290
|
+
/**
|
|
291
|
+
* Save display snapshots for a thread, each replacing the stored one with its
|
|
292
|
+
* id, and resolve the thread's whole display output. For a protocol adapter
|
|
293
|
+
* that shows a thread in its own item shapes. Model history is untouched.
|
|
294
|
+
*
|
|
295
|
+
* @throws OutputStoreError when `items` are not snapshots (objects with a string
|
|
296
|
+
* `type`), or storage fails.
|
|
297
|
+
* @public
|
|
298
|
+
*/
|
|
299
|
+
saveSessionOutput(items: ReadonlyArray<unknown>, scope: SessionScope): Promise<OutputSnapshot[]>;
|
|
300
|
+
/**
|
|
301
|
+
* The thread's one output store: every write for a thread goes through it, so
|
|
302
|
+
* this harness's writes queue behind each other instead of racing.
|
|
303
|
+
*/
|
|
304
|
+
private outputOf;
|
|
269
305
|
getTextStream(scope?: SessionScope): AsyncIterable<string>;
|
|
270
306
|
getReasoningStream(scope?: SessionScope): AsyncIterable<string>;
|
|
271
307
|
/** Every event raw, including each declared custom item's `custom_item_event`. */
|
|
@@ -496,6 +532,18 @@ export declare class AgentHarness<TParams extends Record<string, unknown> = Reco
|
|
|
496
532
|
* close anything.
|
|
497
533
|
*/
|
|
498
534
|
private executeClosingChannels;
|
|
535
|
+
/**
|
|
536
|
+
* Wait for what a run streamed to be saved. Display output never decides a run:
|
|
537
|
+
* a save that failed is logged, stays queued for the next flush, and the run's
|
|
538
|
+
* own result or error stands.
|
|
539
|
+
*/
|
|
540
|
+
private saveOutputOfRun;
|
|
541
|
+
/**
|
|
542
|
+
* A thread named by a host-built context's own id has no later turns: once its
|
|
543
|
+
* run ends, the harness drops its session and output store. What was saved stays
|
|
544
|
+
* in storage under `output:<ctx.id>`.
|
|
545
|
+
*/
|
|
546
|
+
private forgetOwnThread;
|
|
499
547
|
/**
|
|
500
548
|
* Fix the point a resume of this run starts from, and queue it for saving — so even
|
|
501
549
|
* a run whose first step dies leaves a snapshot to restore. The save is not awaited:
|
|
@@ -562,6 +610,12 @@ export declare class AgentHarness<TParams extends Record<string, unknown> = Reco
|
|
|
562
610
|
_connectionViews?: ContextLayer[];
|
|
563
611
|
_broadcaster?: EventBroadcaster;
|
|
564
612
|
}): Context;
|
|
613
|
+
/**
|
|
614
|
+
* On an interactive harness, a root context a host builds joins its thread: it
|
|
615
|
+
* gets the thread's broadcaster, so `run()` on it streams, and is recorded, like
|
|
616
|
+
* a session turn. A context with no `threadId` is its own thread, named by its id.
|
|
617
|
+
*/
|
|
618
|
+
private interactiveThread;
|
|
565
619
|
send<T>(channel: Channel<T>, value: NoInfer<T>, ctx: Context): Promise<void>;
|
|
566
620
|
recv<T>(channel: Channel<T>, ctx: Context, opts?: {
|
|
567
621
|
timeout?: number;
|
|
@@ -7,6 +7,7 @@ import { AcpSessionStore } from '../runtime/acp-session-store.js';
|
|
|
7
7
|
import { emitFrameworkEvent, getBroadcaster } from '../runtime/broadcaster-utils.js';
|
|
8
8
|
import { stubOf } from '../runtime/durable/step-ledger.js';
|
|
9
9
|
import { heldCallsOf, toHeldCall } from '../runtime/held-calls.js';
|
|
10
|
+
import { OutputStore } from '../runtime/output-store.js';
|
|
10
11
|
import { awaitApproval } from '../runtime/tool-approval.js';
|
|
11
12
|
import { ConnectionGate } from './connection-gate.js';
|
|
12
13
|
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';
|
|
@@ -195,6 +196,16 @@ export class AgentHarness {
|
|
|
195
196
|
pendingCheckpoints = new Map();
|
|
196
197
|
defaultDeliveryMode;
|
|
197
198
|
sessions = new Map();
|
|
199
|
+
/** Whether threads keep their streamed output for display (`opts.interactive`). */
|
|
200
|
+
interactive;
|
|
201
|
+
/** Where display output is kept: the harness's storage, or memory without one. */
|
|
202
|
+
outputStorage;
|
|
203
|
+
/** The display output each thread of an interactive harness records, by thread id. */
|
|
204
|
+
outputs = new Map();
|
|
205
|
+
/** Thread id → what stops recording it. */
|
|
206
|
+
stopRecording = new Map();
|
|
207
|
+
/** Threads named by a host-built context's own id, dropped when its run ends. */
|
|
208
|
+
ownThreads = new Set();
|
|
198
209
|
/**
|
|
199
210
|
* @internal Live ACP connections. Reached by the interpreter via
|
|
200
211
|
* `frameworkCast`; use {@link listAcpSessions}, {@link getAcpSession},
|
|
@@ -283,6 +294,7 @@ export class AgentHarness {
|
|
|
283
294
|
* access from outside core. */
|
|
284
295
|
itemSchemas;
|
|
285
296
|
constructor(opts) {
|
|
297
|
+
this.interactive = opts.interactive ?? false;
|
|
286
298
|
const validatedParams = opts.paramsSchema ? opts.paramsSchema.parse(opts.params) : opts.params;
|
|
287
299
|
const environment = opts.environment;
|
|
288
300
|
const storageEnv = environment?.storage;
|
|
@@ -300,6 +312,7 @@ export class AgentHarness {
|
|
|
300
312
|
approveToolCall: opts.approveToolCall,
|
|
301
313
|
now: opts.now,
|
|
302
314
|
};
|
|
315
|
+
this.outputStorage = this.config.storage ?? createInMemoryStorage();
|
|
303
316
|
const adapters = resolveEnvironmentAdapters(environment);
|
|
304
317
|
this.fs = adapters.fs;
|
|
305
318
|
this.shell = adapters.shell;
|
|
@@ -480,6 +493,9 @@ export class AgentHarness {
|
|
|
480
493
|
async close() {
|
|
481
494
|
this.parkWatchers?.stopAll();
|
|
482
495
|
await runEvery([
|
|
496
|
+
...[
|
|
497
|
+
...this.outputs.values(),
|
|
498
|
+
].map((output) => () => output.flush()),
|
|
483
499
|
() => this.#connections.close(),
|
|
484
500
|
() => this.closeAcpSessions(),
|
|
485
501
|
]);
|
|
@@ -677,6 +693,43 @@ export class AgentHarness {
|
|
|
677
693
|
const session = this.requireSession(scope);
|
|
678
694
|
return frameworkCast(buildItemStream(session.runner.broadcaster, this.itemSchemas));
|
|
679
695
|
}
|
|
696
|
+
/**
|
|
697
|
+
* A thread's display output (spec 08 § Display output): the latest snapshot of
|
|
698
|
+
* every item it streamed, unfinished ones included, read from storage. An
|
|
699
|
+
* `interactive` harness records it; any harness over the same storage reads it.
|
|
700
|
+
* For showing a thread again, never for resuming one.
|
|
701
|
+
*
|
|
702
|
+
* @throws OutputStoreError when storage fails, or holds something else under the key.
|
|
703
|
+
* @public
|
|
704
|
+
*/
|
|
705
|
+
getSessionOutput(scope) {
|
|
706
|
+
return this.outputOf(scope?.threadId ?? DEFAULT_THREAD_ID).read();
|
|
707
|
+
}
|
|
708
|
+
/**
|
|
709
|
+
* Save display snapshots for a thread, each replacing the stored one with its
|
|
710
|
+
* id, and resolve the thread's whole display output. For a protocol adapter
|
|
711
|
+
* that shows a thread in its own item shapes. Model history is untouched.
|
|
712
|
+
*
|
|
713
|
+
* @throws OutputStoreError when `items` are not snapshots (objects with a string
|
|
714
|
+
* `type`), or storage fails.
|
|
715
|
+
* @public
|
|
716
|
+
*/
|
|
717
|
+
saveSessionOutput(items, scope) {
|
|
718
|
+
return this.outputOf(scope.threadId ?? DEFAULT_THREAD_ID).write(items);
|
|
719
|
+
}
|
|
720
|
+
/**
|
|
721
|
+
* The thread's one output store: every write for a thread goes through it, so
|
|
722
|
+
* this harness's writes queue behind each other instead of racing.
|
|
723
|
+
*/
|
|
724
|
+
outputOf(threadId) {
|
|
725
|
+
const known = this.outputs.get(threadId);
|
|
726
|
+
if (known) {
|
|
727
|
+
return known;
|
|
728
|
+
}
|
|
729
|
+
const output = new OutputStore(this.outputStorage, threadId, this.itemSchemas);
|
|
730
|
+
this.outputs.set(threadId, output);
|
|
731
|
+
return output;
|
|
732
|
+
}
|
|
680
733
|
getTextStream(scope) {
|
|
681
734
|
const session = this.requireSession(scope);
|
|
682
735
|
return filterTextStream(session.runner.broadcaster);
|
|
@@ -1073,6 +1126,10 @@ export class AgentHarness {
|
|
|
1073
1126
|
await this.announceWakeTimeQuietly();
|
|
1074
1127
|
return result;
|
|
1075
1128
|
};
|
|
1129
|
+
if (this.interactive) {
|
|
1130
|
+
const output = this.outputOf(threadId);
|
|
1131
|
+
this.stopRecording.set(threadId, session.runner.broadcaster.observe((event) => output.record(event)));
|
|
1132
|
+
}
|
|
1076
1133
|
this.sessions.set(threadId, session);
|
|
1077
1134
|
if (record) {
|
|
1078
1135
|
void record.usage().then((usage) => session.runner.seedUsage(usage));
|
|
@@ -1838,7 +1895,8 @@ export class AgentHarness {
|
|
|
1838
1895
|
}
|
|
1839
1896
|
try {
|
|
1840
1897
|
await entry.ready;
|
|
1841
|
-
|
|
1898
|
+
const result = await execute(s, input, ctx);
|
|
1899
|
+
return result;
|
|
1842
1900
|
}
|
|
1843
1901
|
catch (error) {
|
|
1844
1902
|
entry.failed = true;
|
|
@@ -1862,9 +1920,39 @@ export class AgentHarness {
|
|
|
1862
1920
|
}
|
|
1863
1921
|
// The turn's own connections end with it; a resume attaches them again.
|
|
1864
1922
|
await this.#connections.release(ctx.id);
|
|
1923
|
+
await this.saveOutputOfRun(ctx.threadId);
|
|
1924
|
+
this.forgetOwnThread(ctx.threadId);
|
|
1865
1925
|
}
|
|
1866
1926
|
}
|
|
1867
1927
|
}
|
|
1928
|
+
/**
|
|
1929
|
+
* Wait for what a run streamed to be saved. Display output never decides a run:
|
|
1930
|
+
* a save that failed is logged, stays queued for the next flush, and the run's
|
|
1931
|
+
* own result or error stands.
|
|
1932
|
+
*/
|
|
1933
|
+
async saveOutputOfRun(threadId) {
|
|
1934
|
+
try {
|
|
1935
|
+
await this.outputs.get(threadId)?.flush();
|
|
1936
|
+
}
|
|
1937
|
+
catch (error) {
|
|
1938
|
+
console.warn('[noetic] could not save the display output of a run:', error);
|
|
1939
|
+
}
|
|
1940
|
+
}
|
|
1941
|
+
/**
|
|
1942
|
+
* A thread named by a host-built context's own id has no later turns: once its
|
|
1943
|
+
* run ends, the harness drops its session and output store. What was saved stays
|
|
1944
|
+
* in storage under `output:<ctx.id>`.
|
|
1945
|
+
*/
|
|
1946
|
+
forgetOwnThread(threadId) {
|
|
1947
|
+
// The thread is named by its context's id, so that context's root run is its only one.
|
|
1948
|
+
if (!this.ownThreads.delete(threadId) || this.liveRoots.has(threadId)) {
|
|
1949
|
+
return;
|
|
1950
|
+
}
|
|
1951
|
+
this.stopRecording.get(threadId)?.();
|
|
1952
|
+
this.stopRecording.delete(threadId);
|
|
1953
|
+
this.outputs.delete(threadId);
|
|
1954
|
+
this.sessions.delete(threadId);
|
|
1955
|
+
}
|
|
1868
1956
|
/**
|
|
1869
1957
|
* Fix the point a resume of this run starts from, and queue it for saving — so even
|
|
1870
1958
|
* a run whose first step dies leaves a snapshot to restore. The save is not awaited:
|
|
@@ -2007,6 +2095,7 @@ export class AgentHarness {
|
|
|
2007
2095
|
return new ContextImpl({
|
|
2008
2096
|
...rest,
|
|
2009
2097
|
id: executionId,
|
|
2098
|
+
...this.interactiveThread(resolved, executionId),
|
|
2010
2099
|
harness: this,
|
|
2011
2100
|
channelStore: this.channelStore,
|
|
2012
2101
|
layers: effectiveLayers,
|
|
@@ -2018,6 +2107,24 @@ export class AgentHarness {
|
|
|
2018
2107
|
ledger,
|
|
2019
2108
|
});
|
|
2020
2109
|
}
|
|
2110
|
+
/**
|
|
2111
|
+
* On an interactive harness, a root context a host builds joins its thread: it
|
|
2112
|
+
* gets the thread's broadcaster, so `run()` on it streams, and is recorded, like
|
|
2113
|
+
* a session turn. A context with no `threadId` is its own thread, named by its id.
|
|
2114
|
+
*/
|
|
2115
|
+
interactiveThread(opts, executionId) {
|
|
2116
|
+
if (!this.interactive || opts.parent || opts._broadcaster) {
|
|
2117
|
+
return {};
|
|
2118
|
+
}
|
|
2119
|
+
const threadId = opts.threadId ?? executionId;
|
|
2120
|
+
if (opts.threadId === undefined) {
|
|
2121
|
+
this.ownThreads.add(threadId);
|
|
2122
|
+
}
|
|
2123
|
+
return {
|
|
2124
|
+
threadId,
|
|
2125
|
+
_broadcaster: this.getOrCreateSession(threadId).runner.broadcaster,
|
|
2126
|
+
};
|
|
2127
|
+
}
|
|
2021
2128
|
send(channel, value, ctx) {
|
|
2022
2129
|
// Internal sender: back-pressured on full queue channels. The calling
|
|
2023
2130
|
// context's abort signal rejects a parked send with 'cancelled'.
|
|
@@ -6,12 +6,27 @@ export type DecisionsClient = Pick<OpenRouter, 'alpha' | 'models'>;
|
|
|
6
6
|
/** @internal */
|
|
7
7
|
export interface DecideCallerDeps {
|
|
8
8
|
client?: DecisionsClient;
|
|
9
|
+
/**
|
|
10
|
+
* Where native decisions are sent, when not to OpenRouter: the client's own base
|
|
11
|
+
* URL (see `decisionsServerUrl`). The SDK sends them to openrouter.ai whatever the
|
|
12
|
+
* client was built with, so without this a credential for another route would go there.
|
|
13
|
+
*/
|
|
14
|
+
serverUrl?: string;
|
|
9
15
|
callModel: (request: CallModelRequest) => Promise<LLMResponse>;
|
|
10
16
|
/** Per-harness cache: model id → whether it is a decision model (`undefined` while unknown). */
|
|
11
17
|
nativeModels: Map<string, Promise<boolean | undefined>>;
|
|
12
18
|
/** Records each native call before it is sent. Absent without durable storage. */
|
|
13
19
|
spend?: Spend;
|
|
14
20
|
}
|
|
21
|
+
/**
|
|
22
|
+
* The base URL native decisions are sent to, given the one the client was built
|
|
23
|
+
* with: that URL without trailing slashes, or undefined for OpenRouter's own (or
|
|
24
|
+
* none), whose decisions endpoint the SDK already knows. Any other base must
|
|
25
|
+
* serve `api/alpha/decisions` under its own path.
|
|
26
|
+
*
|
|
27
|
+
* @internal
|
|
28
|
+
*/
|
|
29
|
+
export declare function decisionsServerUrl(clientServerUrl: string | undefined): string | undefined;
|
|
15
30
|
/**
|
|
16
31
|
* Answer a decide request. Decision models (those whose OpenRouter output
|
|
17
32
|
* modality is `decisions`) answer natively with their own distributions; any
|
|
@@ -3,6 +3,33 @@ import { z } from 'zod';
|
|
|
3
3
|
import { isErrorStatus, statusOf } from '../util/status-code.js';
|
|
4
4
|
//#endregion
|
|
5
5
|
//#region Public API
|
|
6
|
+
const OPENROUTER_HOST = 'openrouter.ai';
|
|
7
|
+
/** Whether `url` is OpenRouter's own API, however its host and port are spelled. */
|
|
8
|
+
function isOpenRouter(url) {
|
|
9
|
+
let parsed;
|
|
10
|
+
try {
|
|
11
|
+
parsed = new URL(url);
|
|
12
|
+
}
|
|
13
|
+
catch {
|
|
14
|
+
return false;
|
|
15
|
+
}
|
|
16
|
+
// `URL` lower-cases the host and drops a scheme's default port.
|
|
17
|
+
return parsed.protocol === 'https:' && parsed.host === OPENROUTER_HOST;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* The base URL native decisions are sent to, given the one the client was built
|
|
21
|
+
* with: that URL without trailing slashes, or undefined for OpenRouter's own (or
|
|
22
|
+
* none), whose decisions endpoint the SDK already knows. Any other base must
|
|
23
|
+
* serve `api/alpha/decisions` under its own path.
|
|
24
|
+
*
|
|
25
|
+
* @internal
|
|
26
|
+
*/
|
|
27
|
+
export function decisionsServerUrl(clientServerUrl) {
|
|
28
|
+
if (!clientServerUrl || isOpenRouter(clientServerUrl)) {
|
|
29
|
+
return undefined;
|
|
30
|
+
}
|
|
31
|
+
return clientServerUrl.replace(/\/+$/, '');
|
|
32
|
+
}
|
|
6
33
|
/**
|
|
7
34
|
* Answer a decide request. Decision models (those whose OpenRouter output
|
|
8
35
|
* modality is `decisions`) answer natively with their own distributions; any
|
|
@@ -12,7 +39,11 @@ import { isErrorStatus, statusOf } from '../util/status-code.js';
|
|
|
12
39
|
*/
|
|
13
40
|
export async function callDecide(request, deps) {
|
|
14
41
|
if (deps.client && (await isDecisionModel(request.model, deps))) {
|
|
15
|
-
return callNative(request,
|
|
42
|
+
return callNative(request, {
|
|
43
|
+
client: deps.client,
|
|
44
|
+
serverUrl: deps.serverUrl,
|
|
45
|
+
spend: deps.spend,
|
|
46
|
+
});
|
|
16
47
|
}
|
|
17
48
|
return callEstimated(request, deps);
|
|
18
49
|
}
|
|
@@ -54,7 +85,7 @@ async function lookupDecisionModel(model, client) {
|
|
|
54
85
|
}
|
|
55
86
|
//#endregion
|
|
56
87
|
//#region Native path
|
|
57
|
-
async function callNative(request,
|
|
88
|
+
async function callNative(request, route) {
|
|
58
89
|
const questions = {};
|
|
59
90
|
for (const [id, question] of Object.entries(request.questions)) {
|
|
60
91
|
questions[id] = toNativeQuestion(question);
|
|
@@ -65,10 +96,9 @@ async function callNative(request, client, spend) {
|
|
|
65
96
|
questions,
|
|
66
97
|
};
|
|
67
98
|
const response = await sendNative({
|
|
68
|
-
|
|
99
|
+
...route,
|
|
69
100
|
decisionsRequest,
|
|
70
101
|
request,
|
|
71
|
-
spend,
|
|
72
102
|
});
|
|
73
103
|
const answers = {};
|
|
74
104
|
for (const [id, question] of Object.entries(request.questions)) {
|
|
@@ -93,7 +123,7 @@ async function callNative(request, client, spend) {
|
|
|
93
123
|
* response hook save the generation id when the headers arrive, so a call cut off
|
|
94
124
|
* before its body finishes can still be priced.
|
|
95
125
|
*/
|
|
96
|
-
async function sendNative({ client, decisionsRequest, request, spend, }) {
|
|
126
|
+
async function sendNative({ client, serverUrl, decisionsRequest, request, spend, }) {
|
|
97
127
|
const dispatch = await spend?.open({
|
|
98
128
|
ctx: request._billTo,
|
|
99
129
|
kind: SpendKind.Decide,
|
|
@@ -105,11 +135,12 @@ async function sendNative({ client, decisionsRequest, request, spend, }) {
|
|
|
105
135
|
decisionsRequest,
|
|
106
136
|
}, {
|
|
107
137
|
signal: request.signal,
|
|
108
|
-
...(
|
|
138
|
+
...(serverUrl
|
|
109
139
|
? {
|
|
110
|
-
|
|
140
|
+
serverURL: serverUrl,
|
|
111
141
|
}
|
|
112
142
|
: {}),
|
|
143
|
+
...nativeHeaders(dispatch?.headers, request),
|
|
113
144
|
});
|
|
114
145
|
await dispatch?.settle();
|
|
115
146
|
return response;
|
|
@@ -124,6 +155,25 @@ async function sendNative({ client, decisionsRequest, request, spend, }) {
|
|
|
124
155
|
dispatch?.end();
|
|
125
156
|
}
|
|
126
157
|
}
|
|
158
|
+
/**
|
|
159
|
+
* The request headers of a native call: the request's own, then the dispatch
|
|
160
|
+
* record's. Header names are not case-sensitive, so a request header that names a
|
|
161
|
+
* dispatch header in any case is dropped: sent beside it, the two values would be
|
|
162
|
+
* joined into one that names no record.
|
|
163
|
+
*/
|
|
164
|
+
function nativeHeaders(dispatchHeaders, request) {
|
|
165
|
+
if (!dispatchHeaders && !request.headers) {
|
|
166
|
+
return {};
|
|
167
|
+
}
|
|
168
|
+
const reserved = new Set(Object.keys(dispatchHeaders ?? {}).map((name) => name.toLowerCase()));
|
|
169
|
+
const own = Object.entries(request.headers ?? {}).filter(([name]) => !reserved.has(name.toLowerCase()));
|
|
170
|
+
return {
|
|
171
|
+
headers: {
|
|
172
|
+
...Object.fromEntries(own),
|
|
173
|
+
...dispatchHeaders,
|
|
174
|
+
},
|
|
175
|
+
};
|
|
176
|
+
}
|
|
127
177
|
/**
|
|
128
178
|
* The native APIs require `instructions` on every question, while Noetic lets a
|
|
129
179
|
* boolean question carry its meaning in `criteria` alone; and TypeSafe needs
|
|
@@ -123,6 +123,15 @@ export interface AgentEnvironmentConfig {
|
|
|
123
123
|
/** `AgentHarness` constructor options. */
|
|
124
124
|
export interface AgentHarnessOpts<TParams extends Record<string, unknown> = Record<string, unknown>, TItem extends CustomItem = CustomItem> {
|
|
125
125
|
name: string;
|
|
126
|
+
/**
|
|
127
|
+
* Keep each thread's streamed output for display (spec 08 § Display output):
|
|
128
|
+
* `getSessionOutput()` then returns every item the thread streamed, unfinished
|
|
129
|
+
* ones included, from this harness or a later one over the same storage. A root
|
|
130
|
+
* context from `createContext()` also joins its thread, so `run()` on it streams
|
|
131
|
+
* like a turn. Display output is kept apart from checkpoints and is never
|
|
132
|
+
* resumed from. Default false.
|
|
133
|
+
*/
|
|
134
|
+
interactive?: boolean;
|
|
126
135
|
/**
|
|
127
136
|
* Root step tree executed for every turn submitted via `execute()`. The custom items
|
|
128
137
|
* it declares (a `workflow()` step's brand) type `getItemStream`, `getFullStream`,
|
|
@@ -55,6 +55,8 @@ export declare class LlmGateway {
|
|
|
55
55
|
* prices, and generation lookups.
|
|
56
56
|
*/
|
|
57
57
|
readonly sdkClient?: OpenRouterSdk;
|
|
58
|
+
/** Where native decisions go when the provider's base URL is not OpenRouter's. */
|
|
59
|
+
private readonly decisionsServerUrl?;
|
|
58
60
|
/** Model id → whether it answers natively as a decision model. */
|
|
59
61
|
private readonly decisionModels;
|
|
60
62
|
constructor(options: LlmGatewayOptions);
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { frameworkCast } from '@noetic-tools/types';
|
|
2
|
-
import { callDecide } from './decide-call.js';
|
|
2
|
+
import { callDecide, decisionsServerUrl } from './decide-call.js';
|
|
3
3
|
import { HTTPClient, OpenRouter, OpenRouterSdk } from './deps/adapters.js';
|
|
4
4
|
import { someStep } from './deps/interpreter.js';
|
|
5
5
|
import { AgentHarnessModelCaller, noLlmProviderError } from './model-call.js';
|
|
@@ -134,8 +134,7 @@ function generationHook(spend) {
|
|
|
134
134
|
}
|
|
135
135
|
});
|
|
136
136
|
}
|
|
137
|
-
function createSdkClient(
|
|
138
|
-
const resolved = resolveLlmClient(config, readLlmEnv());
|
|
137
|
+
function createSdkClient(resolved, http) {
|
|
139
138
|
if (!resolved) {
|
|
140
139
|
return undefined;
|
|
141
140
|
}
|
|
@@ -164,6 +163,8 @@ export class LlmGateway {
|
|
|
164
163
|
* prices, and generation lookups.
|
|
165
164
|
*/
|
|
166
165
|
sdkClient;
|
|
166
|
+
/** Where native decisions go when the provider's base URL is not OpenRouter's. */
|
|
167
|
+
decisionsServerUrl;
|
|
167
168
|
/** Model id → whether it answers natively as a decision model. */
|
|
168
169
|
decisionModels = new Map();
|
|
169
170
|
constructor(options) {
|
|
@@ -172,9 +173,11 @@ export class LlmGateway {
|
|
|
172
173
|
this.client = options.callModelOverride
|
|
173
174
|
? undefined
|
|
174
175
|
: createClient(options.providerConfig, options.contextCache, http);
|
|
175
|
-
|
|
176
|
+
const resolved = options.callModelOverride
|
|
176
177
|
? undefined
|
|
177
|
-
:
|
|
178
|
+
: resolveLlmClient(options.providerConfig, readLlmEnv());
|
|
179
|
+
this.sdkClient = createSdkClient(resolved, http);
|
|
180
|
+
this.decisionsServerUrl = decisionsServerUrl(resolved?.serverURL);
|
|
178
181
|
}
|
|
179
182
|
callModel(request, host) {
|
|
180
183
|
return new AgentHarnessModelCaller({
|
|
@@ -194,6 +197,7 @@ export class LlmGateway {
|
|
|
194
197
|
}
|
|
195
198
|
return callDecide(request, {
|
|
196
199
|
client: this.sdkClient,
|
|
200
|
+
serverUrl: this.decisionsServerUrl,
|
|
197
201
|
callModel,
|
|
198
202
|
nativeModels: this.decisionModels,
|
|
199
203
|
spend: this.#options.spend,
|
|
@@ -3,8 +3,8 @@
|
|
|
3
3
|
* answer it unrun when a steer arrives first), append its result item to the
|
|
4
4
|
* conversation, and record the tool span.
|
|
5
5
|
*/
|
|
6
|
-
import { SteerPoint } from '@noetic-tools/types';
|
|
7
|
-
import { itemsToInput } from '../adapters/openrouter.js';
|
|
6
|
+
import { SteerPoint, validateSchema } from '@noetic-tools/types';
|
|
7
|
+
import { itemsToInput, toolModelOutputToProvider } from '../adapters/openrouter.js';
|
|
8
8
|
import { isFunctionCall } from '../interpreter/typeguards.js';
|
|
9
9
|
import { drainsOf } from '../runtime/drain.js';
|
|
10
10
|
import { heldCallsOf, heldScopeOf, mayWriteHolds, waitOnHeldCalls } from '../runtime/held-calls.js';
|
|
@@ -266,7 +266,13 @@ async function executeFunctionCall(scope, params) {
|
|
|
266
266
|
conversationInput.push({
|
|
267
267
|
type: 'function_call_output',
|
|
268
268
|
callId: fc.callId,
|
|
269
|
-
output:
|
|
269
|
+
output: await modelOutputOf({
|
|
270
|
+
tool: toolForCall,
|
|
271
|
+
toolResult,
|
|
272
|
+
args: parsedArgs,
|
|
273
|
+
emitIfAllowed: params.emitIfAllowed,
|
|
274
|
+
callId: fc.callId,
|
|
275
|
+
}),
|
|
270
276
|
});
|
|
271
277
|
scope.emitItemAppended(request.ctx, outputItem);
|
|
272
278
|
params.emitIfAllowed('tool_call_completed', {
|
|
@@ -284,6 +290,45 @@ async function executeFunctionCall(scope, params) {
|
|
|
284
290
|
approval: toolResult.approval,
|
|
285
291
|
};
|
|
286
292
|
}
|
|
293
|
+
/**
|
|
294
|
+
* What the model is given as a call's result: the tool's `toModelOutput` value for
|
|
295
|
+
* a call that did not fail, else the output text. The result item, the completed
|
|
296
|
+
* event and the call's record keep the text whatever this returns, so a replayed
|
|
297
|
+
* call lands here again with its recorded result.
|
|
298
|
+
*
|
|
299
|
+
* Live and on replay alike, `toModelOutput` reads the result as its JSON round
|
|
300
|
+
* trip, which is what a call record keeps, and the arguments as the tool's input
|
|
301
|
+
* schema reads them, defaults included: a replay must give the model what the
|
|
302
|
+
* live call gave it.
|
|
303
|
+
*/
|
|
304
|
+
async function modelOutputOf(params) {
|
|
305
|
+
const { tool, toolResult } = params;
|
|
306
|
+
if (toolResult.error || !tool?.toModelOutput) {
|
|
307
|
+
return toolResult.output;
|
|
308
|
+
}
|
|
309
|
+
try {
|
|
310
|
+
const args = await validateSchema(tool.input, params.args);
|
|
311
|
+
if (!args.success) {
|
|
312
|
+
throw args.zodError;
|
|
313
|
+
}
|
|
314
|
+
return toolModelOutputToProvider(tool.toModelOutput(asRecorded(toolResult.result), args.value));
|
|
315
|
+
}
|
|
316
|
+
catch (error) {
|
|
317
|
+
// The call is done and on record: a throw here would fail it again on every
|
|
318
|
+
// resume. The model gets the JSON output, and the event says why.
|
|
319
|
+
params.emitIfAllowed('tool_model_output_failed', {
|
|
320
|
+
name: tool.name,
|
|
321
|
+
callId: params.callId,
|
|
322
|
+
error: error instanceof Error ? error.message : String(error),
|
|
323
|
+
});
|
|
324
|
+
return toolResult.output;
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
/** `result` as a call record gives it back: its JSON round trip. */
|
|
328
|
+
function asRecorded(result) {
|
|
329
|
+
const json = result === undefined ? undefined : JSON.stringify(result);
|
|
330
|
+
return json === undefined ? result : JSON.parse(json);
|
|
331
|
+
}
|
|
287
332
|
/** Drop what a finished call may have left in storage: its intent, its answered hold. */
|
|
288
333
|
async function tidyFinishedCall(scope, ctx, callId) {
|
|
289
334
|
const holds = heldCallsOf(scope.harness);
|