@noetic-tools/core 5.18.0 → 5.19.1-next.1
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 +7 -0
- package/dist/adapters/openrouter.js +23 -0
- package/dist/conditions/conditions.js +2 -0
- package/dist/harness/agent-harness.d.ts +16 -7
- package/dist/harness/agent-harness.js +64 -21
- package/dist/harness/call-spend.d.ts +34 -0
- package/dist/harness/call-spend.js +125 -0
- package/dist/harness/decide-call.js +8 -2
- package/dist/harness/deps/types.d.ts +1 -1
- package/dist/harness/model-call.js +51 -64
- package/dist/harness/model-price.d.ts +20 -4
- package/dist/harness/model-price.js +94 -17
- package/dist/harness/model-rounds.d.ts +11 -0
- package/dist/harness/model-rounds.js +37 -1
- package/dist/harness/spend.d.ts +9 -3
- package/dist/harness/spend.js +59 -19
- package/dist/index.d.ts +1 -1
- package/dist/interpreter/execute-action.js +2 -0
- package/dist/interpreter/execute-decide.js +26 -2
- package/dist/runtime/drain.d.ts +13 -22
- package/dist/runtime/drain.js +17 -5
- package/dist/runtime/durable/spend-log.d.ts +23 -3
- package/dist/runtime/durable/spend-log.js +79 -11
- package/dist/runtime/durable/step-ledger.d.ts +3 -2
- package/dist/runtime/durable/step-ledger.js +6 -4
- package/dist/util/spent.d.ts +14 -0
- package/dist/util/spent.js +67 -0
- package/package.json +3 -3
|
@@ -54,6 +54,13 @@ export declare function resolveWireJsonSchema(params: {
|
|
|
54
54
|
}): Record<string, unknown>;
|
|
55
55
|
/** @internal */
|
|
56
56
|
export declare function convertTools({ tools }: ConvertToolsParams): SdkTool[];
|
|
57
|
+
/**
|
|
58
|
+
* @internal
|
|
59
|
+
* Tools as the wire carries them, for sizing a request. The agent turns each live
|
|
60
|
+
* Zod input schema into JSON Schema only when it sends, so serializing `convertTools`
|
|
61
|
+
* output would drop every description and constraint the provider bills for.
|
|
62
|
+
*/
|
|
63
|
+
export declare function toolsOnWire(tools: ReadonlyArray<SdkTool>): unknown[];
|
|
57
64
|
/** @internal */
|
|
58
65
|
export interface ExecuteToolCallParams {
|
|
59
66
|
toolName: string;
|
|
@@ -288,6 +288,29 @@ export function convertTools({ tools }) {
|
|
|
288
288
|
},
|
|
289
289
|
}));
|
|
290
290
|
}
|
|
291
|
+
/**
|
|
292
|
+
* @internal
|
|
293
|
+
* Tools as the wire carries them, for sizing a request. The agent turns each live
|
|
294
|
+
* Zod input schema into JSON Schema only when it sends, so serializing `convertTools`
|
|
295
|
+
* output would drop every description and constraint the provider bills for.
|
|
296
|
+
*/
|
|
297
|
+
export function toolsOnWire(tools) {
|
|
298
|
+
return tools.map((tool) => {
|
|
299
|
+
if (!('function' in tool) || !isZodSchema(tool.function.inputSchema)) {
|
|
300
|
+
return tool;
|
|
301
|
+
}
|
|
302
|
+
return {
|
|
303
|
+
...tool,
|
|
304
|
+
function: {
|
|
305
|
+
...tool.function,
|
|
306
|
+
inputSchema: z.toJSONSchema(tool.function.inputSchema, {
|
|
307
|
+
target: 'draft-07',
|
|
308
|
+
unrepresentable: 'any',
|
|
309
|
+
}),
|
|
310
|
+
},
|
|
311
|
+
};
|
|
312
|
+
});
|
|
313
|
+
}
|
|
291
314
|
function isAsyncGenerator(value) {
|
|
292
315
|
if (typeof value !== 'object' || value === null) {
|
|
293
316
|
return false;
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { storageGetMany } from '@noetic-tools/context';
|
|
2
2
|
import { DecideOutputError, isNoeticError, NoeticErrorImpl, trackUsage } from '@noetic-tools/types';
|
|
3
3
|
import { z } from 'zod';
|
|
4
|
+
import { chargeSpent } from '../util/spent.js';
|
|
4
5
|
import { cosineSimilarity } from './cosine-similarity.js';
|
|
5
6
|
//#endregion
|
|
6
7
|
//#region Helpers
|
|
@@ -293,6 +294,7 @@ async function askDecide(ctx, request) {
|
|
|
293
294
|
return await ctx.harness.decide(request);
|
|
294
295
|
}
|
|
295
296
|
catch (e) {
|
|
297
|
+
chargeSpent(ctx, e);
|
|
296
298
|
if (isNoeticError(e)) {
|
|
297
299
|
throw e;
|
|
298
300
|
}
|
|
@@ -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, Drains } from './deps/runtime.js';
|
|
7
|
-
import type { AcpLiveSession, AcpSessionInfo, AgentConfig, AgentHarnessContract, AgentHooks, CallModelRequest, CancelOptions, Channel, ChannelHandle, Context, ContextCacheConfig, ContextCacheStore, ContextData, ContextLayer, CustomItem, CustomItemOf, CustomItemStreamEvent, CustomItemsBrand, CustomStreamingItem, CwdState, DecideRequest, DecideResponse, DecisionRecord, DeclaredItems, DeliveryMode, DetachedHandle, ExecuteInput, ExecuteOptions, ExternalChannel, FsAdapter, HarnessResponse, HarnessStatus, Item, ItemSchemaConfig, LLMResponse, LlmProviderConfig, OnSteerParams, PendingSpend, ProjectionPolicy, RecallLayerOutput, RecallOptions, ReconcileSpendOptions, SessionScope, SessionUsage, ShellAdapter, Span, SpendSettlement, SteeringDecision, SteerVerdict, Step, StorageAdapter, StreamEvent, StreamingItem, SubprocessAdapter, Tool, ToolApprover, TraceExporter, WriteOffSpendOptions, ZodType } from './deps/types.js';
|
|
7
|
+
import type { AcpLiveSession, AcpSessionInfo, AgentConfig, AgentHarnessContract, AgentHooks, CallModelRequest, CancelOptions, Channel, ChannelHandle, Context, ContextCacheConfig, ContextCacheStore, ContextData, ContextLayer, CustomItem, CustomItemOf, CustomItemStreamEvent, CustomItemsBrand, CustomStreamingItem, CwdState, DecideRequest, DecideResponse, DecisionRecord, DeclaredItems, DeliveryMode, DetachedHandle, DrainReport, ExecuteInput, ExecuteOptions, ExecutionScope, ExecutionStatus, ExternalChannel, FsAdapter, HarnessResponse, HarnessStatus, Item, ItemSchemaConfig, LLMResponse, LlmProviderConfig, OnSteerParams, PendingSpend, ProjectionPolicy, RecallLayerOutput, RecallOptions, ReconcileSpendOptions, SessionScope, SessionUsage, ShellAdapter, Span, SpendSettlement, SteeringDecision, SteerVerdict, Step, StorageAdapter, StreamEvent, StreamingItem, SubprocessAdapter, Tool, ToolApprover, TraceExporter, WriteOffSpendOptions, ZodType } from './deps/types.js';
|
|
8
8
|
import { Spend } from './spend.js';
|
|
9
9
|
export { createStreamIdleWatchdog } from './model-call.js';
|
|
10
10
|
/**
|
|
@@ -303,8 +303,14 @@ export declare class AgentHarness<TParams extends Record<string, unknown> = Reco
|
|
|
303
303
|
getReasoningStream(scope?: SessionScope): AsyncIterable<string>;
|
|
304
304
|
/** Every event raw, including each declared custom item's `custom_item_event`. */
|
|
305
305
|
getFullStream(scope?: SessionScope): AsyncIterable<StreamEvent | CustomItemStreamEvent<DeclaredItems<TItem>>>;
|
|
306
|
-
abort(scope?: SessionScope & CancelOptions): Promise<
|
|
306
|
+
abort(scope?: SessionScope & CancelOptions): Promise<DrainReport | undefined>;
|
|
307
|
+
getStatus(scope: ExecutionScope): ExecutionStatus;
|
|
307
308
|
getStatus(scope?: SessionScope): HarnessStatus;
|
|
309
|
+
/**
|
|
310
|
+
* A `run()` execution's state, read from its live root context. Only a root
|
|
311
|
+
* context's outermost run registers, so a context nothing runs on reads idle.
|
|
312
|
+
*/
|
|
313
|
+
private executionStatus;
|
|
308
314
|
getQueueSize(scope?: SessionScope): number;
|
|
309
315
|
getUsage(scope?: SessionScope): SessionUsage;
|
|
310
316
|
seedSessionHistory(threadId: string, items: ReadonlyArray<Item>): void;
|
|
@@ -487,8 +493,9 @@ export declare class AgentHarness<TParams extends Record<string, unknown> = Reco
|
|
|
487
493
|
/**
|
|
488
494
|
* Paid provider calls with no settled bill — cut off by a crash, a cancel, a steer,
|
|
489
495
|
* or a dropped connection — all of them or one execution's, each with its ceiling.
|
|
490
|
-
* A
|
|
491
|
-
*
|
|
496
|
+
* A record that no longer reads is listed as `unreadable`, with no ceiling, until
|
|
497
|
+
* written off. A call still in flight in this harness is not listed. Empty without
|
|
498
|
+
* durable storage. See spec 23 § Paid dispatches.
|
|
492
499
|
* @public
|
|
493
500
|
*/
|
|
494
501
|
pendingSpend(executionId?: string): Promise<PendingSpend[]>;
|
|
@@ -502,8 +509,8 @@ export declare class AgentHarness<TParams extends Record<string, unknown> = Reco
|
|
|
502
509
|
*/
|
|
503
510
|
reconcileSpend(opts?: ReconcileSpendOptions): Promise<SpendSettlement[]>;
|
|
504
511
|
/**
|
|
505
|
-
* Settle one pending dispatch at `assumedCost`, for a call that can never be priced
|
|
506
|
-
* Resolves `undefined` when no pending dispatch has that id.
|
|
512
|
+
* Settle one pending dispatch at `assumedCost`, for a call that can never be priced,
|
|
513
|
+
* unreadable ones included. Resolves `undefined` when no pending dispatch has that id.
|
|
507
514
|
* @public
|
|
508
515
|
*/
|
|
509
516
|
writeOffSpend(id: string, opts: WriteOffSpendOptions): Promise<SpendSettlement | undefined>;
|
|
@@ -533,8 +540,10 @@ export declare class AgentHarness<TParams extends Record<string, unknown> = Reco
|
|
|
533
540
|
* `ctx`, model calls in flight get up to `drainMs` to finish and be charged,
|
|
534
541
|
* and `{name}:drain_started` / `{name}:drain_finished` report which finished
|
|
535
542
|
* and which were cut off. A second `cancel` during the drain cancels at once.
|
|
543
|
+
* Either call resolves with the drain's report, the same data as
|
|
544
|
+
* `drain_finished`; a cancel with no drain resolves `undefined`.
|
|
536
545
|
*/
|
|
537
|
-
cancel(ctx: Context, options?: string | CancelOptions): Promise<
|
|
546
|
+
cancel(ctx: Context, options?: string | CancelOptions): Promise<DrainReport | undefined>;
|
|
538
547
|
/** Abort `ctx`'s tree and tear its layers down. The abort happens before the first `await`. */
|
|
539
548
|
private cancelNow;
|
|
540
549
|
/**
|
|
@@ -117,7 +117,7 @@ async function addCacheBreakpoint(request) {
|
|
|
117
117
|
}),
|
|
118
118
|
});
|
|
119
119
|
}
|
|
120
|
-
function createClient(config, contextCache,
|
|
120
|
+
function createClient(config, contextCache, http) {
|
|
121
121
|
const resolved = resolveLlmClient(config, readLlmEnv());
|
|
122
122
|
if (!resolved) {
|
|
123
123
|
return undefined;
|
|
@@ -128,8 +128,10 @@ function createClient(config, contextCache, spend) {
|
|
|
128
128
|
if (resolved.serverURL) {
|
|
129
129
|
options.serverURL = resolved.serverURL;
|
|
130
130
|
}
|
|
131
|
-
if (
|
|
132
|
-
|
|
131
|
+
if (http) {
|
|
132
|
+
// The agent bundles an older SDK whose `HTTPClient` class is nominally different;
|
|
133
|
+
// the agent calls only `request()` on it, which both versions share.
|
|
134
|
+
options.httpClient = frameworkCast(http);
|
|
133
135
|
}
|
|
134
136
|
// A cache write costs more than a plain read, so the breakpoint only pays off
|
|
135
137
|
// when something is holding the prefix still — which is what anchoring does.
|
|
@@ -153,14 +155,12 @@ function createClient(config, contextCache, spend) {
|
|
|
153
155
|
}
|
|
154
156
|
/**
|
|
155
157
|
* An HTTP client that saves a paid call's generation id the moment its headers
|
|
156
|
-
* arrive. The SDK awaits the hook before it reads the body, so a
|
|
157
|
-
*
|
|
158
|
-
*
|
|
159
|
-
* The agent bundles an older SDK whose `HTTPClient` class is nominally different;
|
|
160
|
-
* the agent calls only `request()` on it, which both versions share.
|
|
158
|
+
* arrive. The SDK awaits the hook before it reads the body, so a call cut off after
|
|
159
|
+
* its headers can still be priced. Both the model client and the decisions client
|
|
160
|
+
* send through it; requests without a dispatch header pass untouched.
|
|
161
161
|
*/
|
|
162
162
|
function generationHook(spend) {
|
|
163
|
-
|
|
163
|
+
return new HTTPClient().addHook('response', async (res, req) => {
|
|
164
164
|
const dispatchId = req.headers.get(DISPATCH_HEADER);
|
|
165
165
|
const generationId = res.headers.get(GENERATION_HEADER);
|
|
166
166
|
// An error response is retried or refused; only a success carries the call's id.
|
|
@@ -168,9 +168,8 @@ function generationHook(spend) {
|
|
|
168
168
|
await spend.noteGeneration(dispatchId, generationId);
|
|
169
169
|
}
|
|
170
170
|
});
|
|
171
|
-
return frameworkCast(http);
|
|
172
171
|
}
|
|
173
|
-
function createSdkClient(config) {
|
|
172
|
+
function createSdkClient(config, http) {
|
|
174
173
|
const resolved = resolveLlmClient(config, readLlmEnv());
|
|
175
174
|
if (!resolved) {
|
|
176
175
|
return undefined;
|
|
@@ -178,6 +177,11 @@ function createSdkClient(config) {
|
|
|
178
177
|
return new OpenRouterSdk({
|
|
179
178
|
apiKey: resolved.apiKey,
|
|
180
179
|
serverURL: resolved.serverURL,
|
|
180
|
+
...(http
|
|
181
|
+
? {
|
|
182
|
+
httpClient: http,
|
|
183
|
+
}
|
|
184
|
+
: {}),
|
|
181
185
|
});
|
|
182
186
|
}
|
|
183
187
|
/**
|
|
@@ -386,11 +390,14 @@ export class AgentHarness {
|
|
|
386
390
|
this.harnessTools = opts.tools ?? [];
|
|
387
391
|
this._contextLayers = opts.contextLayers;
|
|
388
392
|
this.callModelOverride = opts._testCallModel;
|
|
393
|
+
const http = this.spend ? generationHook(this.spend) : undefined;
|
|
389
394
|
this.client = opts._testCallModel
|
|
390
395
|
? undefined
|
|
391
|
-
: createClient(opts.callModelDefaults, opts.contextCache,
|
|
396
|
+
: createClient(opts.callModelDefaults, opts.contextCache, http);
|
|
392
397
|
this.decideOverride = opts._testDecide;
|
|
393
|
-
this.sdkClient = opts._testCallModel
|
|
398
|
+
this.sdkClient = opts._testCallModel
|
|
399
|
+
? undefined
|
|
400
|
+
: createSdkClient(opts.callModelDefaults, http);
|
|
394
401
|
this.channelStore = new ChannelStore({
|
|
395
402
|
onWarning: (warning) => this.recordChannelWarning(warning),
|
|
396
403
|
});
|
|
@@ -493,13 +500,13 @@ export class AgentHarness {
|
|
|
493
500
|
const threadId = scope?.threadId ?? DEFAULT_THREAD_ID;
|
|
494
501
|
const session = this.sessions.get(threadId);
|
|
495
502
|
if (!session) {
|
|
496
|
-
return;
|
|
503
|
+
return undefined;
|
|
497
504
|
}
|
|
498
505
|
const { runner } = session;
|
|
499
506
|
const ctx = runner.context;
|
|
500
507
|
if (!ctx) {
|
|
501
508
|
await runner.abort(scope?.reason);
|
|
502
|
-
return;
|
|
509
|
+
return undefined;
|
|
503
510
|
}
|
|
504
511
|
const draining = this.drains.stop(ctx);
|
|
505
512
|
if (draining) {
|
|
@@ -507,7 +514,7 @@ export class AgentHarness {
|
|
|
507
514
|
}
|
|
508
515
|
if (!scope?.drainMs) {
|
|
509
516
|
await runner.abort(scope?.reason);
|
|
510
|
-
return;
|
|
517
|
+
return undefined;
|
|
511
518
|
}
|
|
512
519
|
// The drained turn may end on its own; then the runner has moved on and
|
|
513
520
|
// there is nothing left to abort.
|
|
@@ -518,6 +525,9 @@ export class AgentHarness {
|
|
|
518
525
|
});
|
|
519
526
|
}
|
|
520
527
|
getStatus(scope) {
|
|
528
|
+
if (scope && 'executionId' in scope) {
|
|
529
|
+
return this.executionStatus(scope.executionId);
|
|
530
|
+
}
|
|
521
531
|
const threadId = scope?.threadId ?? DEFAULT_THREAD_ID;
|
|
522
532
|
const session = this.sessions.get(threadId);
|
|
523
533
|
if (!session) {
|
|
@@ -537,6 +547,34 @@ export class AgentHarness {
|
|
|
537
547
|
deadline: drain.deadline,
|
|
538
548
|
};
|
|
539
549
|
}
|
|
550
|
+
/**
|
|
551
|
+
* A `run()` execution's state, read from its live root context. Only a root
|
|
552
|
+
* context's outermost run registers, so a context nothing runs on reads idle.
|
|
553
|
+
*/
|
|
554
|
+
executionStatus(executionId) {
|
|
555
|
+
const live = this.liveRoots.get(executionId);
|
|
556
|
+
if (!live) {
|
|
557
|
+
return {
|
|
558
|
+
kind: 'idle',
|
|
559
|
+
};
|
|
560
|
+
}
|
|
561
|
+
if (live.ctx.aborted) {
|
|
562
|
+
return {
|
|
563
|
+
kind: 'aborting',
|
|
564
|
+
};
|
|
565
|
+
}
|
|
566
|
+
const drain = this.drains.covering(live.ctx);
|
|
567
|
+
if (drain) {
|
|
568
|
+
return {
|
|
569
|
+
kind: 'draining',
|
|
570
|
+
deadline: drain.deadline,
|
|
571
|
+
};
|
|
572
|
+
}
|
|
573
|
+
return {
|
|
574
|
+
kind: 'generating',
|
|
575
|
+
startedAt: live.startedAt,
|
|
576
|
+
};
|
|
577
|
+
}
|
|
540
578
|
getQueueSize(scope) {
|
|
541
579
|
const threadId = scope?.threadId ?? DEFAULT_THREAD_ID;
|
|
542
580
|
const session = this.sessions.get(threadId);
|
|
@@ -793,6 +831,7 @@ export class AgentHarness {
|
|
|
793
831
|
const entry = live ?? {
|
|
794
832
|
ctx,
|
|
795
833
|
depth: 0,
|
|
834
|
+
startedAt: Date.now(),
|
|
796
835
|
failed: false,
|
|
797
836
|
ready: Promise.resolve(),
|
|
798
837
|
};
|
|
@@ -1247,8 +1286,9 @@ export class AgentHarness {
|
|
|
1247
1286
|
/**
|
|
1248
1287
|
* Paid provider calls with no settled bill — cut off by a crash, a cancel, a steer,
|
|
1249
1288
|
* or a dropped connection — all of them or one execution's, each with its ceiling.
|
|
1250
|
-
* A
|
|
1251
|
-
*
|
|
1289
|
+
* A record that no longer reads is listed as `unreadable`, with no ceiling, until
|
|
1290
|
+
* written off. A call still in flight in this harness is not listed. Empty without
|
|
1291
|
+
* durable storage. See spec 23 § Paid dispatches.
|
|
1252
1292
|
* @public
|
|
1253
1293
|
*/
|
|
1254
1294
|
async pendingSpend(executionId) {
|
|
@@ -1266,8 +1306,8 @@ export class AgentHarness {
|
|
|
1266
1306
|
return (await this.spend?.reconcile(opts)) ?? [];
|
|
1267
1307
|
}
|
|
1268
1308
|
/**
|
|
1269
|
-
* Settle one pending dispatch at `assumedCost`, for a call that can never be priced
|
|
1270
|
-
* Resolves `undefined` when no pending dispatch has that id.
|
|
1309
|
+
* Settle one pending dispatch at `assumedCost`, for a call that can never be priced,
|
|
1310
|
+
* unreadable ones included. Resolves `undefined` when no pending dispatch has that id.
|
|
1271
1311
|
* @public
|
|
1272
1312
|
*/
|
|
1273
1313
|
async writeOffSpend(id, opts) {
|
|
@@ -1326,6 +1366,8 @@ export class AgentHarness {
|
|
|
1326
1366
|
* `ctx`, model calls in flight get up to `drainMs` to finish and be charged,
|
|
1327
1367
|
* and `{name}:drain_started` / `{name}:drain_finished` report which finished
|
|
1328
1368
|
* and which were cut off. A second `cancel` during the drain cancels at once.
|
|
1369
|
+
* Either call resolves with the drain's report, the same data as
|
|
1370
|
+
* `drain_finished`; a cancel with no drain resolves `undefined`.
|
|
1329
1371
|
*/
|
|
1330
1372
|
async cancel(ctx, options) {
|
|
1331
1373
|
const { reason, drainMs } = typeof options === 'string'
|
|
@@ -1338,12 +1380,13 @@ export class AgentHarness {
|
|
|
1338
1380
|
return draining;
|
|
1339
1381
|
}
|
|
1340
1382
|
if (ctx.aborted) {
|
|
1341
|
-
return;
|
|
1383
|
+
return undefined;
|
|
1342
1384
|
}
|
|
1343
1385
|
if (drainMs) {
|
|
1344
1386
|
return this.drains.run(ctx, drainMs, () => this.cancelNow(ctx, reason));
|
|
1345
1387
|
}
|
|
1346
1388
|
await this.cancelNow(ctx, reason);
|
|
1389
|
+
return undefined;
|
|
1347
1390
|
}
|
|
1348
1391
|
/** Abort `ctx`'s tree and tear its layers down. The abort happens before the first `await`. */
|
|
1349
1392
|
async cancelNow(ctx, reason) {
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { LLMResponse, RoundUsage, UsageCharge } from '@noetic-tools/types';
|
|
2
|
+
/** What one round used and cost. */
|
|
3
|
+
export interface Bill {
|
|
4
|
+
usage: RoundUsage;
|
|
5
|
+
cost: number;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* What one model call's rounds used and cost. Every round the provider answered
|
|
9
|
+
* counts, including one the loop rejected and asked again: the provider billed it.
|
|
10
|
+
* A rejected round's bill is held and folded into the round the loop goes on from,
|
|
11
|
+
* so `rounds` lists the rounds the conversation kept, and `rounds[0]` still reports
|
|
12
|
+
* on the first view the model answered.
|
|
13
|
+
*/
|
|
14
|
+
export declare class CallSpend {
|
|
15
|
+
private readonly rounds;
|
|
16
|
+
/** Bills counted since the last round the loop went on from. */
|
|
17
|
+
private held;
|
|
18
|
+
/** Count a round the provider answered, whether or not the loop keeps it. */
|
|
19
|
+
count(usage: RoundUsage, cost: number): void;
|
|
20
|
+
/**
|
|
21
|
+
* The loop goes on from the round just counted, or from a steered round that has
|
|
22
|
+
* no bill of its own. Returns its bill, held rejected rounds included, for the
|
|
23
|
+
* round ledger to record.
|
|
24
|
+
*/
|
|
25
|
+
keep(): Bill;
|
|
26
|
+
/** Count a round replayed from the round ledger. */
|
|
27
|
+
replay({ usage, cost }: Bill): void;
|
|
28
|
+
totals(): Pick<LLMResponse, 'usage' | 'rounds' | 'cost' | 'billedCost'>;
|
|
29
|
+
/**
|
|
30
|
+
* What a call that throws must charge: every round paid for now. A replayed round
|
|
31
|
+
* was charged by the attempt that paid for it.
|
|
32
|
+
*/
|
|
33
|
+
charge(): UsageCharge;
|
|
34
|
+
}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What one model call's rounds used and cost. Every round the provider answered
|
|
3
|
+
* counts, including one the loop rejected and asked again: the provider billed it.
|
|
4
|
+
* A rejected round's bill is held and folded into the round the loop goes on from,
|
|
5
|
+
* so `rounds` lists the rounds the conversation kept, and `rounds[0]` still reports
|
|
6
|
+
* on the first view the model answered.
|
|
7
|
+
*/
|
|
8
|
+
export class CallSpend {
|
|
9
|
+
rounds = [];
|
|
10
|
+
/** Bills counted since the last round the loop went on from. */
|
|
11
|
+
held;
|
|
12
|
+
/** Count a round the provider answered, whether or not the loop keeps it. */
|
|
13
|
+
count(usage, cost) {
|
|
14
|
+
this.held = addBills(this.held, {
|
|
15
|
+
usage,
|
|
16
|
+
cost,
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* The loop goes on from the round just counted, or from a steered round that has
|
|
21
|
+
* no bill of its own. Returns its bill, held rejected rounds included, for the
|
|
22
|
+
* round ledger to record.
|
|
23
|
+
*/
|
|
24
|
+
keep() {
|
|
25
|
+
const bill = this.held ?? {
|
|
26
|
+
usage: {
|
|
27
|
+
inputTokens: 0,
|
|
28
|
+
outputTokens: 0,
|
|
29
|
+
},
|
|
30
|
+
cost: 0,
|
|
31
|
+
};
|
|
32
|
+
if (this.held) {
|
|
33
|
+
this.rounds.push({
|
|
34
|
+
...this.held,
|
|
35
|
+
replayed: false,
|
|
36
|
+
});
|
|
37
|
+
this.held = undefined;
|
|
38
|
+
}
|
|
39
|
+
return bill;
|
|
40
|
+
}
|
|
41
|
+
/** Count a round replayed from the round ledger. */
|
|
42
|
+
replay({ usage, cost }) {
|
|
43
|
+
this.rounds.push({
|
|
44
|
+
usage,
|
|
45
|
+
cost,
|
|
46
|
+
replayed: true,
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
totals() {
|
|
50
|
+
const bills = this.held
|
|
51
|
+
? [
|
|
52
|
+
...this.rounds,
|
|
53
|
+
this.held,
|
|
54
|
+
]
|
|
55
|
+
: this.rounds;
|
|
56
|
+
const usage = sumUsage(bills.map((bill) => bill.usage));
|
|
57
|
+
const cost = sum(bills.map((bill) => bill.cost));
|
|
58
|
+
const replayed = this.rounds.filter((round) => round.replayed);
|
|
59
|
+
return {
|
|
60
|
+
usage: {
|
|
61
|
+
inputTokens: usage.inputTokens,
|
|
62
|
+
outputTokens: usage.outputTokens,
|
|
63
|
+
cachedTokens: usage.cachedTokens,
|
|
64
|
+
},
|
|
65
|
+
rounds: bills.map((bill) => bill.usage),
|
|
66
|
+
cost: cost > 0 ? cost : undefined,
|
|
67
|
+
...(replayed.length > 0
|
|
68
|
+
? {
|
|
69
|
+
billedCost: cost - sum(replayed.map((round) => round.cost)),
|
|
70
|
+
}
|
|
71
|
+
: {}),
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* What a call that throws must charge: every round paid for now. A replayed round
|
|
76
|
+
* was charged by the attempt that paid for it.
|
|
77
|
+
*/
|
|
78
|
+
charge() {
|
|
79
|
+
const paid = this.rounds.filter((round) => !round.replayed);
|
|
80
|
+
const bill = addBills(this.held, ...paid) ?? {
|
|
81
|
+
usage: {
|
|
82
|
+
inputTokens: 0,
|
|
83
|
+
outputTokens: 0,
|
|
84
|
+
},
|
|
85
|
+
cost: 0,
|
|
86
|
+
};
|
|
87
|
+
return {
|
|
88
|
+
...bill.usage,
|
|
89
|
+
cost: bill.cost,
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
function addBills(...bills) {
|
|
94
|
+
const present = bills.filter((bill) => bill !== undefined);
|
|
95
|
+
if (present.length === 0) {
|
|
96
|
+
return undefined;
|
|
97
|
+
}
|
|
98
|
+
return {
|
|
99
|
+
usage: sumUsage(present.map((bill) => bill.usage)),
|
|
100
|
+
cost: sum(present.map((bill) => bill.cost)),
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
function sum(values) {
|
|
104
|
+
return values.reduce((total, value) => total + value, 0);
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Add rounds' usage. A cache figure stays `undefined` when no round reported one, so
|
|
108
|
+
* callers can tell "this provider says nothing about caching" from "nothing was cached".
|
|
109
|
+
*/
|
|
110
|
+
function sumUsage(rounds) {
|
|
111
|
+
const [only] = rounds;
|
|
112
|
+
if (rounds.length === 1 && only) {
|
|
113
|
+
return only;
|
|
114
|
+
}
|
|
115
|
+
return {
|
|
116
|
+
inputTokens: sum(rounds.map((r) => r.inputTokens)),
|
|
117
|
+
outputTokens: sum(rounds.map((r) => r.outputTokens)),
|
|
118
|
+
cachedTokens: sumReported(rounds.map((r) => r.cachedTokens)),
|
|
119
|
+
cacheWriteTokens: sumReported(rounds.map((r) => r.cacheWriteTokens)),
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
function sumReported(values) {
|
|
123
|
+
const reported = values.filter((value) => value !== undefined);
|
|
124
|
+
return reported.length > 0 ? sum(reported) : undefined;
|
|
125
|
+
}
|
|
@@ -89,8 +89,9 @@ async function callNative(request, client, spend) {
|
|
|
89
89
|
};
|
|
90
90
|
}
|
|
91
91
|
/**
|
|
92
|
-
* Send one native call under a dispatch record. The
|
|
93
|
-
*
|
|
92
|
+
* Send one native call under a dispatch record. The dispatch header lets the client's
|
|
93
|
+
* response hook save the generation id when the headers arrive, so a call cut off
|
|
94
|
+
* before its body finishes can still be priced.
|
|
94
95
|
*/
|
|
95
96
|
async function sendNative({ client, decisionsRequest, request, spend, }) {
|
|
96
97
|
const dispatch = await spend?.open({
|
|
@@ -104,6 +105,11 @@ async function sendNative({ client, decisionsRequest, request, spend, }) {
|
|
|
104
105
|
decisionsRequest,
|
|
105
106
|
}, {
|
|
106
107
|
signal: request.signal,
|
|
108
|
+
...(dispatch
|
|
109
|
+
? {
|
|
110
|
+
headers: dispatch.headers,
|
|
111
|
+
}
|
|
112
|
+
: {}),
|
|
107
113
|
});
|
|
108
114
|
await dispatch?.settle();
|
|
109
115
|
return response;
|
|
@@ -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, CancelOptions, Channel, ChannelHandle, Context, CustomItem, CustomItemOf, CustomItemStreamEvent, CustomItemsBrand, CustomStreamingItem, CwdState, DecideRequest, DecideResponse, DecisionRecord, DeclaredItems, DeliveryMode, DetachedHandle, ExecuteInput, ExecuteOptions, ExternalChannel, FsAdapter, HarnessResponse, HarnessStatus, Item, ItemSchemaConfig, ItemSchemaExtensions, LLMResponse, LlmProviderConfig, OnSteerParams, PendingSpend, RecallLayerOutput, RecallOptions, ReconcileSpendOptions, SessionScope, SessionUsage, ShellAdapter, Span, SpendSettlement, SteeringDecision, SteerVerdict, Step, StreamEvent, StreamingItem, SubprocessAdapter, Tool, ToolApprover, TraceExporter, UsageCharge, WriteOffSpendOptions, } from '@noetic-tools/types';
|
|
2
|
+
export type { AcpKeepAlive, AcpLiveSession, AcpSessionInfo, AgentConfig, AgentHarnessContract, AgentHooks, CallModelRequest, CancelOptions, Channel, ChannelHandle, Context, CustomItem, CustomItemOf, CustomItemStreamEvent, CustomItemsBrand, CustomStreamingItem, CwdState, DecideRequest, DecideResponse, DecisionRecord, DeclaredItems, DeliveryMode, DetachedHandle, DrainReport, ExecuteInput, ExecuteOptions, ExecutionScope, ExecutionStatus, ExternalChannel, FsAdapter, HarnessResponse, HarnessStatus, Item, ItemSchemaConfig, ItemSchemaExtensions, LLMResponse, LlmProviderConfig, OnSteerParams, PendingSpend, RecallLayerOutput, RecallOptions, ReconcileSpendOptions, SessionScope, SessionUsage, ShellAdapter, Span, SpendSettlement, SteeringDecision, SteerVerdict, Step, StreamEvent, StreamingItem, SubprocessAdapter, Tool, ToolApprover, TraceExporter, UsageCharge, WriteOffSpendOptions, } from '@noetic-tools/types';
|
|
3
3
|
export { SteeringAction } from '@noetic-tools/types';
|
|
4
4
|
export type { ZodType } from 'zod';
|