@noetic-tools/core 5.22.0-next.1 → 5.22.0-next.3
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/in-memory-subprocess-adapter.js +4 -2
- package/dist/adapters/openrouter.d.ts +6 -1
- package/dist/adapters/openrouter.js +10 -0
- package/dist/builders/custom-item.d.ts +1 -1
- package/dist/builders/custom-item.js +14 -3
- 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/connections/pool.d.ts +18 -0
- package/dist/connections/pool.js +54 -9
- package/dist/connections/registry.js +11 -0
- package/dist/harness/agent-harness.d.ts +130 -3
- package/dist/harness/agent-harness.js +337 -22
- package/dist/harness/decide-call.d.ts +15 -0
- package/dist/harness/decide-call.js +57 -7
- package/dist/harness/deps/types.d.ts +1 -1
- package/dist/harness/forget.d.ts +57 -0
- package/dist/harness/forget.js +496 -0
- package/dist/harness/harness-options.d.ts +24 -1
- package/dist/harness/llm-client.d.ts +2 -0
- package/dist/harness/llm-client.js +9 -5
- package/dist/harness/model-rounds.d.ts +6 -0
- package/dist/harness/model-rounds.js +7 -3
- package/dist/harness/model-tool-round.js +67 -8
- package/dist/harness/recorded-tool-calls.d.ts +16 -0
- package/dist/harness/recorded-tool-calls.js +106 -0
- package/dist/harness/spend.d.ts +13 -1
- package/dist/harness/spend.js +82 -1
- package/dist/harness/steer-inbox.js +9 -5
- package/dist/harness/thread-record.d.ts +12 -1
- package/dist/harness/thread-record.js +63 -19
- package/dist/index.d.ts +9 -6
- package/dist/index.js +4 -3
- package/dist/interpreter/acp-tools.js +21 -4
- package/dist/interpreter/execute-action.js +7 -1
- package/dist/interpreter/execute-decide.js +5 -0
- package/dist/interpreter/execute.js +55 -3
- package/dist/interpreter/step-dispatcher.js +17 -1
- package/dist/interpreter/step-kind-dispatch.js +9 -1
- package/dist/portable/runtime.d.ts +4 -0
- package/dist/portable/runtime.js +2 -0
- package/dist/runtime/durable/child-links.d.ts +61 -0
- package/dist/runtime/durable/child-links.js +127 -0
- package/dist/runtime/durable/session-store.d.ts +6 -0
- package/dist/runtime/durable/session-store.js +16 -2
- package/dist/runtime/durable/turn-lease.d.ts +10 -0
- package/dist/runtime/durable/turn-lease.js +10 -2
- package/dist/runtime/event-broadcaster.d.ts +9 -1
- package/dist/runtime/event-broadcaster.js +16 -1
- package/dist/runtime/held-calls.d.ts +65 -6
- package/dist/runtime/held-calls.js +257 -5
- package/dist/runtime/output-store.d.ts +90 -0
- package/dist/runtime/output-store.js +243 -0
- package/dist/runtime/session-streams.d.ts +28 -7
- package/dist/runtime/session-streams.js +112 -67
- package/dist/runtime/tool-approval.d.ts +1 -3
- package/dist/runtime/tool-approval.js +1 -1
- package/package.json +2 -2
- package/schema/noetic-workflow.schema.json +27 -0
|
@@ -30,8 +30,12 @@ import { isFunctionCall } from '../interpreter/typeguards.js';
|
|
|
30
30
|
import { hashStepInput } from '../runtime/durable/step-ledger.js';
|
|
31
31
|
import { ContextImpl } from './deps/runtime.js';
|
|
32
32
|
//#region Types
|
|
33
|
-
|
|
34
|
-
const
|
|
33
|
+
/** Ledger kind of a model-loop round's record. */
|
|
34
|
+
export const ROUND_KIND = 'callModel:round';
|
|
35
|
+
/** Ledger kind of one tool call's record within a round. */
|
|
36
|
+
export const CALL_KIND = 'callModel:call';
|
|
37
|
+
/** What follows a round's key in the key of a call recorded beneath it. */
|
|
38
|
+
export const CALL_SEGMENT = '/call:';
|
|
35
39
|
/** What a recorded tool call left: the result the round went on with. */
|
|
36
40
|
const CallOutputSchema = z.object({
|
|
37
41
|
output: z.string(),
|
|
@@ -193,7 +197,7 @@ export class RoundLedger {
|
|
|
193
197
|
calls(round) {
|
|
194
198
|
const ledger = this.ctx.ledger;
|
|
195
199
|
const stepId = this.dispatch.stepId;
|
|
196
|
-
const keyOf = (call) => `${this.key(round)}
|
|
200
|
+
const keyOf = (call) => `${this.key(round)}${CALL_SEGMENT}${call.callId}`;
|
|
197
201
|
// A call is the same call only with the same name and arguments, asked for by
|
|
198
202
|
// the same step input: a provider that numbers its calls from one each time
|
|
199
203
|
// would otherwise hand a call the result of another conversation's.
|
|
@@ -3,11 +3,11 @@
|
|
|
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
|
-
import { heldCallsOf, heldScopeOf, mayWriteHolds, waitOnHeldCalls } from '../runtime/held-calls.js';
|
|
10
|
+
import { heldCallsOf, heldScopeOf, mayWriteHolds, noticeHeld, waitOnHeldCalls, } from '../runtime/held-calls.js';
|
|
11
11
|
import { createToolResultItem, executeToolCall } from '../runtime/tool-call.js';
|
|
12
12
|
import { emitToolUi } from '../runtime/tool-ui.js';
|
|
13
13
|
import { findTool } from './model-request.js';
|
|
@@ -64,6 +64,8 @@ async function executeToolRound(scope, params) {
|
|
|
64
64
|
});
|
|
65
65
|
}
|
|
66
66
|
const heldCalls = [];
|
|
67
|
+
/** What each held call was last announced as held for. */
|
|
68
|
+
const announcedAs = new Map();
|
|
67
69
|
for (const [index, fc] of functionCalls.entries()) {
|
|
68
70
|
await drainsOf(request.ctx)?.hold(request.ctx);
|
|
69
71
|
if (request.signal?.aborted) {
|
|
@@ -100,6 +102,7 @@ async function executeToolRound(scope, params) {
|
|
|
100
102
|
});
|
|
101
103
|
if (call.held) {
|
|
102
104
|
heldCalls.push(fc);
|
|
105
|
+
announcedAs.set(fc.callId, call.held);
|
|
103
106
|
continue;
|
|
104
107
|
}
|
|
105
108
|
spans.recordToolSpan(modelSpan, fc.name, toolForCall?.needsApproval ?? false, call.approval);
|
|
@@ -142,10 +145,11 @@ async function executeToolRound(scope, params) {
|
|
|
142
145
|
conversationInput,
|
|
143
146
|
emitIfAllowed: params.emitIfAllowed,
|
|
144
147
|
calls: params.calls,
|
|
145
|
-
announced:
|
|
148
|
+
announced: announcedAs.get(fc.callId),
|
|
146
149
|
});
|
|
147
150
|
if (call.held) {
|
|
148
151
|
heldCalls.push(fc);
|
|
152
|
+
announcedAs.set(fc.callId, call.held);
|
|
149
153
|
continue;
|
|
150
154
|
}
|
|
151
155
|
spans.recordToolSpan(modelSpan, fc.name, toolForCall?.needsApproval ?? false, call.approval);
|
|
@@ -208,13 +212,23 @@ async function executeFunctionCall(scope, params) {
|
|
|
208
212
|
}));
|
|
209
213
|
// Held: it has no result yet. Nothing goes into the conversation for it.
|
|
210
214
|
if (toolResult.held) {
|
|
211
|
-
if (
|
|
215
|
+
if (params.announced !== toolResult.held.reason) {
|
|
212
216
|
params.emitIfAllowed('tool_call_held', {
|
|
213
217
|
...toolResult.held,
|
|
214
218
|
});
|
|
219
|
+
if (request.ctx) {
|
|
220
|
+
noticeHeld({
|
|
221
|
+
harness: scope.harness,
|
|
222
|
+
ctx: request.ctx,
|
|
223
|
+
held: toolResult.held,
|
|
224
|
+
emit: (settled) => params.emitIfAllowed('tool_call_settled', {
|
|
225
|
+
...settled,
|
|
226
|
+
}),
|
|
227
|
+
});
|
|
228
|
+
}
|
|
215
229
|
}
|
|
216
230
|
return {
|
|
217
|
-
held:
|
|
231
|
+
held: toolResult.held.reason,
|
|
218
232
|
};
|
|
219
233
|
}
|
|
220
234
|
// A replayed call appends the item it appended before, under the same id.
|
|
@@ -266,7 +280,13 @@ async function executeFunctionCall(scope, params) {
|
|
|
266
280
|
conversationInput.push({
|
|
267
281
|
type: 'function_call_output',
|
|
268
282
|
callId: fc.callId,
|
|
269
|
-
output:
|
|
283
|
+
output: await modelOutputOf({
|
|
284
|
+
tool: toolForCall,
|
|
285
|
+
toolResult,
|
|
286
|
+
args: parsedArgs,
|
|
287
|
+
emitIfAllowed: params.emitIfAllowed,
|
|
288
|
+
callId: fc.callId,
|
|
289
|
+
}),
|
|
270
290
|
});
|
|
271
291
|
scope.emitItemAppended(request.ctx, outputItem);
|
|
272
292
|
params.emitIfAllowed('tool_call_completed', {
|
|
@@ -284,6 +304,45 @@ async function executeFunctionCall(scope, params) {
|
|
|
284
304
|
approval: toolResult.approval,
|
|
285
305
|
};
|
|
286
306
|
}
|
|
307
|
+
/**
|
|
308
|
+
* What the model is given as a call's result: the tool's `toModelOutput` value for
|
|
309
|
+
* a call that did not fail, else the output text. The result item, the completed
|
|
310
|
+
* event and the call's record keep the text whatever this returns, so a replayed
|
|
311
|
+
* call lands here again with its recorded result.
|
|
312
|
+
*
|
|
313
|
+
* Live and on replay alike, `toModelOutput` reads the result as its JSON round
|
|
314
|
+
* trip, which is what a call record keeps, and the arguments as the tool's input
|
|
315
|
+
* schema reads them, defaults included: a replay must give the model what the
|
|
316
|
+
* live call gave it.
|
|
317
|
+
*/
|
|
318
|
+
async function modelOutputOf(params) {
|
|
319
|
+
const { tool, toolResult } = params;
|
|
320
|
+
if (toolResult.error || !tool?.toModelOutput) {
|
|
321
|
+
return toolResult.output;
|
|
322
|
+
}
|
|
323
|
+
try {
|
|
324
|
+
const args = await validateSchema(tool.input, params.args);
|
|
325
|
+
if (!args.success) {
|
|
326
|
+
throw args.zodError;
|
|
327
|
+
}
|
|
328
|
+
return toolModelOutputToProvider(tool.toModelOutput(asRecorded(toolResult.result), args.value));
|
|
329
|
+
}
|
|
330
|
+
catch (error) {
|
|
331
|
+
// The call is done and on record: a throw here would fail it again on every
|
|
332
|
+
// resume. The model gets the JSON output, and the event says why.
|
|
333
|
+
params.emitIfAllowed('tool_model_output_failed', {
|
|
334
|
+
name: tool.name,
|
|
335
|
+
callId: params.callId,
|
|
336
|
+
error: error instanceof Error ? error.message : String(error),
|
|
337
|
+
});
|
|
338
|
+
return toolResult.output;
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
/** `result` as a call record gives it back: its JSON round trip. */
|
|
342
|
+
function asRecorded(result) {
|
|
343
|
+
const json = result === undefined ? undefined : JSON.stringify(result);
|
|
344
|
+
return json === undefined ? result : JSON.parse(json);
|
|
345
|
+
}
|
|
287
346
|
/** Drop what a finished call may have left in storage: its intent, its answered hold. */
|
|
288
347
|
async function tidyFinishedCall(scope, ctx, callId) {
|
|
289
348
|
const holds = heldCallsOf(scope.harness);
|
|
@@ -335,7 +394,7 @@ async function dropHolds(scope, request, calls) {
|
|
|
335
394
|
const executionId = heldScopeOf(request.ctx);
|
|
336
395
|
for (const call of calls) {
|
|
337
396
|
if (await holds.load(executionId, call.callId)) {
|
|
338
|
-
await holds.close(executionId, call.callId);
|
|
397
|
+
await holds.close(executionId, call.callId, 'skipped');
|
|
339
398
|
}
|
|
340
399
|
}
|
|
341
400
|
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The tool calls an execution's step ledger holds (spec 23a § Tool calls in a round).
|
|
3
|
+
*
|
|
4
|
+
* A resumed run replays what its ledger recorded: completed steps with the items they
|
|
5
|
+
* appended, the rounds of an unfinished model loop with theirs, and the calls a cut-off
|
|
6
|
+
* round finished. A host that keeps its own record of tool traffic reads this list to
|
|
7
|
+
* know which calls the resume brings back on its own, so it never adds them twice.
|
|
8
|
+
*/
|
|
9
|
+
import type { RecordedToolCall } from '@noetic-tools/types';
|
|
10
|
+
import type { StepLedgerWindow } from '../runtime/durable/step-ledger.js';
|
|
11
|
+
/**
|
|
12
|
+
* The tool calls a recovered ledger window holds, in the order they were recorded.
|
|
13
|
+
* A call is `settled` when its result is on record too, in the same entry or as a
|
|
14
|
+
* call record beneath its round.
|
|
15
|
+
*/
|
|
16
|
+
export declare function recordedToolCalls(window: StepLedgerWindow): RecordedToolCall[];
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The tool calls an execution's step ledger holds (spec 23a § Tool calls in a round).
|
|
3
|
+
*
|
|
4
|
+
* A resumed run replays what its ledger recorded: completed steps with the items they
|
|
5
|
+
* appended, the rounds of an unfinished model loop with theirs, and the calls a cut-off
|
|
6
|
+
* round finished. A host that keeps its own record of tool traffic reads this list to
|
|
7
|
+
* know which calls the resume brings back on its own, so it never adds them twice.
|
|
8
|
+
*/
|
|
9
|
+
import { z } from 'zod';
|
|
10
|
+
import { CALL_KIND, CALL_SEGMENT, ROUND_KIND } from './model-rounds.js';
|
|
11
|
+
//#region Types
|
|
12
|
+
const FunctionCallSchema = z.object({
|
|
13
|
+
type: z.literal('function_call'),
|
|
14
|
+
callId: z.string(),
|
|
15
|
+
name: z.string(),
|
|
16
|
+
});
|
|
17
|
+
const FunctionCallOutputSchema = z.object({
|
|
18
|
+
type: z.literal('function_call_output'),
|
|
19
|
+
callId: z.string(),
|
|
20
|
+
});
|
|
21
|
+
const RoundOutputItemsSchema = z.object({
|
|
22
|
+
items: z.array(z.unknown()),
|
|
23
|
+
});
|
|
24
|
+
//#endregion
|
|
25
|
+
//#region Helpers
|
|
26
|
+
/** Every item an entry replays: those it appended, and a round's own output items. */
|
|
27
|
+
function itemsOf(entry) {
|
|
28
|
+
const appended = entry.items ?? [];
|
|
29
|
+
if (entry.kind !== ROUND_KIND) {
|
|
30
|
+
return appended;
|
|
31
|
+
}
|
|
32
|
+
const round = RoundOutputItemsSchema.safeParse(entry.output);
|
|
33
|
+
return round.success
|
|
34
|
+
? [
|
|
35
|
+
...round.data.items,
|
|
36
|
+
...appended,
|
|
37
|
+
]
|
|
38
|
+
: appended;
|
|
39
|
+
}
|
|
40
|
+
/** `scope|callId`: a call id is unique only within the entry that asked for it. */
|
|
41
|
+
function keyOf(scope, callId) {
|
|
42
|
+
return `${scope}|${callId}`;
|
|
43
|
+
}
|
|
44
|
+
/** The round a call record sits beneath and the call's id, from the record's path. */
|
|
45
|
+
function splitCallPath(path) {
|
|
46
|
+
const at = path.lastIndexOf(CALL_SEGMENT);
|
|
47
|
+
if (at < 0) {
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
return {
|
|
51
|
+
scope: path.slice(0, at),
|
|
52
|
+
callId: path.slice(at + CALL_SEGMENT.length),
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
/** Note the requests and results one entry holds. */
|
|
56
|
+
function collectEntry(entry, requests, settled) {
|
|
57
|
+
if (entry.kind === CALL_KIND) {
|
|
58
|
+
const call = splitCallPath(entry.path);
|
|
59
|
+
if (call) {
|
|
60
|
+
settled.add(keyOf(call.scope, call.callId));
|
|
61
|
+
}
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
for (const item of itemsOf(entry)) {
|
|
65
|
+
const request = FunctionCallSchema.safeParse(item);
|
|
66
|
+
if (request.success) {
|
|
67
|
+
const key = keyOf(entry.path, request.data.callId);
|
|
68
|
+
if (!requests.has(key)) {
|
|
69
|
+
requests.set(key, {
|
|
70
|
+
callId: request.data.callId,
|
|
71
|
+
name: request.data.name,
|
|
72
|
+
path: entry.path,
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
const result = FunctionCallOutputSchema.safeParse(item);
|
|
78
|
+
if (result.success) {
|
|
79
|
+
settled.add(keyOf(entry.path, result.data.callId));
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
//#endregion
|
|
84
|
+
//#region Public API
|
|
85
|
+
/**
|
|
86
|
+
* The tool calls a recovered ledger window holds, in the order they were recorded.
|
|
87
|
+
* A call is `settled` when its result is on record too, in the same entry or as a
|
|
88
|
+
* call record beneath its round.
|
|
89
|
+
*/
|
|
90
|
+
export function recordedToolCalls(window) {
|
|
91
|
+
const requests = new Map();
|
|
92
|
+
const settled = new Set();
|
|
93
|
+
const ordered = [
|
|
94
|
+
...window.entries.values(),
|
|
95
|
+
].sort((a, b) => (window.seqs.get(a.path) ?? 0) - (window.seqs.get(b.path) ?? 0));
|
|
96
|
+
for (const entry of ordered) {
|
|
97
|
+
collectEntry(entry, requests, settled);
|
|
98
|
+
}
|
|
99
|
+
return [
|
|
100
|
+
...requests.entries(),
|
|
101
|
+
].map(([key, request]) => ({
|
|
102
|
+
...request,
|
|
103
|
+
settled: settled.has(key),
|
|
104
|
+
}));
|
|
105
|
+
}
|
|
106
|
+
//#endregion
|
package/dist/harness/spend.d.ts
CHANGED
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
import type { Context, PendingSpend, ReconcileSpendOptions, SpendSettlement, UsageCharge, WriteOffSpendOptions } from '@noetic-tools/types';
|
|
12
12
|
import { SpendKind } from '@noetic-tools/types';
|
|
13
13
|
import type { OpenRouter } from '@openrouter/sdk';
|
|
14
|
-
import type { DispatchRecord, SpendLog } from '../runtime/durable/spend-log.js';
|
|
14
|
+
import type { DispatchRecord, SpendLog, SpendRecord } from '../runtime/durable/spend-log.js';
|
|
15
15
|
import type { EventBroadcaster } from './deps/runtime.js';
|
|
16
16
|
import { ContextImpl } from './deps/runtime.js';
|
|
17
17
|
/** @internal Request header that ties a response back to its dispatch. */
|
|
@@ -77,6 +77,18 @@ export declare class Spend {
|
|
|
77
77
|
reconcile(opts?: ReconcileSpendOptions): Promise<SpendSettlement[]>;
|
|
78
78
|
/** Settle one pending dispatch at an amount the host asserts. */
|
|
79
79
|
writeOff(id: string, opts: WriteOffSpendOptions): Promise<SpendSettlement | undefined>;
|
|
80
|
+
/**
|
|
81
|
+
* Settle every pending dispatch `owns` picks, for a forget (spec 23 § Forgetting):
|
|
82
|
+
* price each through the provider, waiting no longer than `patienceMs` even for a
|
|
83
|
+
* lookup already running, then write off the rest at their ceiling, or at 0 flagged
|
|
84
|
+
* `unbounded` when nothing bounds them. Priced settlements come first.
|
|
85
|
+
*
|
|
86
|
+
* @throws NoeticError `ledger_write_failed` when a dispatch's record could not be
|
|
87
|
+
* deleted, so its bill is not lost with what the forget deletes next.
|
|
88
|
+
*/
|
|
89
|
+
close(owns: (record: SpendRecord) => boolean, patienceMs?: number): Promise<SpendSettlement[]>;
|
|
90
|
+
/** Write a held dispatch off at its ceiling, or at 0 flagged `unbounded` when it has none. */
|
|
91
|
+
private writeOffAtCeiling;
|
|
80
92
|
/** USD held for a thread's pending dispatches. */
|
|
81
93
|
heldFor(threadId: string): number;
|
|
82
94
|
/** A live dispatch ended. Called by `Dispatch` only. */
|
package/dist/harness/spend.js
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
* leaves the record behind. It is then *pending*: held at its ceiling, and priced
|
|
9
9
|
* through the provider's generation lookup once the provider has billed it.
|
|
10
10
|
*/
|
|
11
|
-
import { recordUsage, SpendKind } from '@noetic-tools/types';
|
|
11
|
+
import { NoeticErrorImpl, recordUsage, SpendKind } from '@noetic-tools/types';
|
|
12
12
|
import { emitFrameworkEvent, getBroadcaster } from '../runtime/broadcaster-utils.js';
|
|
13
13
|
import { isUnreadable } from '../runtime/durable/spend-log.js';
|
|
14
14
|
import { hashText } from '../runtime/durable/step-ledger.js';
|
|
@@ -24,6 +24,24 @@ export const GENERATION_HEADER = 'x-generation-id';
|
|
|
24
24
|
const DEFAULT_PATIENCE_MS = 60e3;
|
|
25
25
|
const FIRST_POLL_MS = 1e3;
|
|
26
26
|
const MAX_POLL_MS = 10e3;
|
|
27
|
+
/** `promise`, or undefined once `ms` pass first. The timer never keeps a process alive. */
|
|
28
|
+
function within(ms, promise) {
|
|
29
|
+
let timer;
|
|
30
|
+
const timeout = new Promise((resolve) => {
|
|
31
|
+
timer = setTimeout(() => resolve(undefined), Math.max(0, ms));
|
|
32
|
+
unrefTimer(timer);
|
|
33
|
+
});
|
|
34
|
+
return Promise.race([
|
|
35
|
+
promise,
|
|
36
|
+
timeout,
|
|
37
|
+
]).finally(() => clearTimeout(timer));
|
|
38
|
+
}
|
|
39
|
+
/** Let a timer not hold the process open, where the runtime allows it. */
|
|
40
|
+
function unrefTimer(timer) {
|
|
41
|
+
if (typeof timer === 'object' && timer !== null && 'unref' in timer) {
|
|
42
|
+
timer.unref();
|
|
43
|
+
}
|
|
44
|
+
}
|
|
27
45
|
//#endregion
|
|
28
46
|
//#region Spend
|
|
29
47
|
/**
|
|
@@ -160,6 +178,58 @@ export class Spend {
|
|
|
160
178
|
outputTokens: 0,
|
|
161
179
|
}, true);
|
|
162
180
|
}
|
|
181
|
+
/**
|
|
182
|
+
* Settle every pending dispatch `owns` picks, for a forget (spec 23 § Forgetting):
|
|
183
|
+
* price each through the provider, waiting no longer than `patienceMs` even for a
|
|
184
|
+
* lookup already running, then write off the rest at their ceiling, or at 0 flagged
|
|
185
|
+
* `unbounded` when nothing bounds them. Priced settlements come first.
|
|
186
|
+
*
|
|
187
|
+
* @throws NoeticError `ledger_write_failed` when a dispatch's record could not be
|
|
188
|
+
* deleted, so its bill is not lost with what the forget deletes next.
|
|
189
|
+
*/
|
|
190
|
+
async close(owns, patienceMs = DEFAULT_PATIENCE_MS) {
|
|
191
|
+
const records = (await this.unsettled(undefined)).filter(owns);
|
|
192
|
+
await Promise.all(records.map((record) => this.hold(record)));
|
|
193
|
+
// A lookup started earlier keeps its own patience: wait for it no longer than ours.
|
|
194
|
+
const priced = await Promise.all(records.map((record) => this.lookups.has(record.id)
|
|
195
|
+
? within(patienceMs, this.lookup(record, patienceMs))
|
|
196
|
+
: this.lookup(record, patienceMs)));
|
|
197
|
+
const settled = priced.filter((settlement) => settlement !== undefined);
|
|
198
|
+
const done = new Set(settled.map((settlement) => settlement.id));
|
|
199
|
+
for (const record of records) {
|
|
200
|
+
if (done.has(record.id)) {
|
|
201
|
+
continue;
|
|
202
|
+
}
|
|
203
|
+
const writeOff = await this.writeOffAtCeiling(record.id);
|
|
204
|
+
if (writeOff) {
|
|
205
|
+
settled.push(writeOff);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
const left = (await this.unsettled(undefined)).find((record) => owns(record) && records.some((known) => known.id === record.id));
|
|
209
|
+
if (left) {
|
|
210
|
+
throw new NoeticErrorImpl({
|
|
211
|
+
kind: 'ledger_write_failed',
|
|
212
|
+
executionId: left.executionId ?? '',
|
|
213
|
+
path: `spend:${left.id}`,
|
|
214
|
+
cause: new Error(`the spend record of dispatch "${left.id}" could not be settled`),
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
return settled;
|
|
218
|
+
}
|
|
219
|
+
/** Write a held dispatch off at its ceiling, or at 0 flagged `unbounded` when it has none. */
|
|
220
|
+
async writeOffAtCeiling(id) {
|
|
221
|
+
const ceiling = this.holds.get(id)?.ceiling;
|
|
222
|
+
const settlement = await this.writeOff(id, {
|
|
223
|
+
assumedCost: ceiling ?? 0,
|
|
224
|
+
});
|
|
225
|
+
if (!settlement || ceiling !== undefined) {
|
|
226
|
+
return settlement;
|
|
227
|
+
}
|
|
228
|
+
return {
|
|
229
|
+
...settlement,
|
|
230
|
+
unbounded: true,
|
|
231
|
+
};
|
|
232
|
+
}
|
|
163
233
|
/** USD held for a thread's pending dispatches. */
|
|
164
234
|
heldFor(threadId) {
|
|
165
235
|
let held = 0;
|
|
@@ -329,6 +399,7 @@ export class Spend {
|
|
|
329
399
|
}
|
|
330
400
|
await this.charge(hold, bill);
|
|
331
401
|
const { executionId, threadId } = hold.record;
|
|
402
|
+
const { model, path } = isUnreadable(hold.record) ? {} : hold.record;
|
|
332
403
|
this.emit(hold, 'spend_settled', {
|
|
333
404
|
id,
|
|
334
405
|
cost: bill.cost,
|
|
@@ -351,6 +422,16 @@ export class Spend {
|
|
|
351
422
|
}
|
|
352
423
|
: {}),
|
|
353
424
|
...bill,
|
|
425
|
+
...(model !== undefined
|
|
426
|
+
? {
|
|
427
|
+
model,
|
|
428
|
+
}
|
|
429
|
+
: {}),
|
|
430
|
+
...(path !== undefined
|
|
431
|
+
? {
|
|
432
|
+
path,
|
|
433
|
+
}
|
|
434
|
+
: {}),
|
|
354
435
|
...(writtenOff
|
|
355
436
|
? {
|
|
356
437
|
writtenOff: true,
|
|
@@ -96,7 +96,7 @@ export class SteerInbox {
|
|
|
96
96
|
items.every((item) => 'id' in item && item.id !== undefined && this.opts.inConversation(item.id)));
|
|
97
97
|
}
|
|
98
98
|
async judge(message, items, point, pendingCalls) {
|
|
99
|
-
const action = defaultAction(point, message.deliveryMode);
|
|
99
|
+
const action = defaultAction(point, message.deliveryMode, this.opts.harness.config.steerWhileHeld);
|
|
100
100
|
const { harness, layers } = this.opts;
|
|
101
101
|
if (!harness.onSteer || !layers.some((layer) => layer.hooks.onSteer)) {
|
|
102
102
|
return {
|
|
@@ -177,10 +177,14 @@ function findSessionQueue(ctx) {
|
|
|
177
177
|
return undefined;
|
|
178
178
|
}
|
|
179
179
|
/** What each delivery mode does at each point before any layer has a say. */
|
|
180
|
-
function defaultAction(point, mode) {
|
|
181
|
-
// At a round
|
|
182
|
-
//
|
|
183
|
-
if (point === SteerPoint.
|
|
180
|
+
function defaultAction(point, mode, whileHeld = 'apply') {
|
|
181
|
+
// At a round stuck on held calls there is no boundary to reach: the harness says
|
|
182
|
+
// whether a steer skips them or waits behind them.
|
|
183
|
+
if (point === SteerPoint.Held) {
|
|
184
|
+
return whileHeld === 'defer' ? SteerAction.Defer : SteerAction.Apply;
|
|
185
|
+
}
|
|
186
|
+
// At a round boundary a steer lands.
|
|
187
|
+
if (point === SteerPoint.BeforeRound) {
|
|
184
188
|
return SteerAction.Apply;
|
|
185
189
|
}
|
|
186
190
|
if (point === SteerPoint.ItemDone && mode === 'next-item') {
|
|
@@ -19,6 +19,8 @@ export interface ThreadRecordHost {
|
|
|
19
19
|
restore(executionId: string, opts: RestoreCheckpointOptions): Promise<Context | null>;
|
|
20
20
|
clearCheckpoint(executionId: string): Promise<void>;
|
|
21
21
|
parseItems(raw: unknown[]): Item[];
|
|
22
|
+
/** Ids of the context layers this harness keeps durable state for. */
|
|
23
|
+
layerIds?(): ReadonlyArray<string>;
|
|
22
24
|
}
|
|
23
25
|
/**
|
|
24
26
|
* @internal
|
|
@@ -107,7 +109,7 @@ export declare class ThreadRecord {
|
|
|
107
109
|
* thread's recent turns delivered it.
|
|
108
110
|
*/
|
|
109
111
|
answerFor(messageId: string): Promise<string | undefined>;
|
|
110
|
-
/** The executions of the thread
|
|
112
|
+
/** The executions of every turn the thread began, oldest first, the one in flight last. */
|
|
111
113
|
executions(): Promise<string[]>;
|
|
112
114
|
/** The turn in flight, cut off or parked, when one is recorded. */
|
|
113
115
|
turn(): Promise<SessionRecord['turn']>;
|
|
@@ -137,6 +139,15 @@ export declare class ThreadRecord {
|
|
|
137
139
|
*/
|
|
138
140
|
private commit;
|
|
139
141
|
private parseInput;
|
|
142
|
+
/** `layers` with the ids of the layers this harness keeps durable state for, when it has any new ones. */
|
|
143
|
+
private withLayers;
|
|
140
144
|
private load;
|
|
141
145
|
private run;
|
|
142
146
|
}
|
|
147
|
+
/**
|
|
148
|
+
* @internal
|
|
149
|
+
* Every execution a stored record names, oldest first, without repeats: those it
|
|
150
|
+
* began, then remembered finished turns from records written before `executions`
|
|
151
|
+
* was kept, then the turn in flight.
|
|
152
|
+
*/
|
|
153
|
+
export declare function executionsOf(record: SessionRecord | undefined): string[];
|
|
@@ -151,6 +151,8 @@ export class ThreadRecord {
|
|
|
151
151
|
return this.updateHeld(ctx, (record) => ({
|
|
152
152
|
...record,
|
|
153
153
|
steers: record.steers?.filter((steer) => !messageIds.includes(steer.id)),
|
|
154
|
+
executions: withExecution(record.executions, ctx.id),
|
|
155
|
+
...this.withLayers(record),
|
|
154
156
|
turn: {
|
|
155
157
|
executionId: ctx.id,
|
|
156
158
|
messageIds: [
|
|
@@ -286,22 +288,9 @@ export class ThreadRecord {
|
|
|
286
288
|
return done.findLast((turn) => turn.messageIds.includes(messageId))?.text;
|
|
287
289
|
});
|
|
288
290
|
}
|
|
289
|
-
/** The executions of the thread
|
|
291
|
+
/** The executions of every turn the thread began, oldest first, the one in flight last. */
|
|
290
292
|
executions() {
|
|
291
|
-
return this.run(async () =>
|
|
292
|
-
const record = await this.load();
|
|
293
|
-
const ids = (record?.done ?? []).flatMap((turn) => turn.executionId === undefined
|
|
294
|
-
? []
|
|
295
|
-
: [
|
|
296
|
-
turn.executionId,
|
|
297
|
-
]);
|
|
298
|
-
return record?.turn
|
|
299
|
-
? [
|
|
300
|
-
...ids,
|
|
301
|
-
record.turn.executionId,
|
|
302
|
-
]
|
|
303
|
-
: ids;
|
|
304
|
-
});
|
|
293
|
+
return this.run(async () => executionsOf(await this.load()));
|
|
305
294
|
}
|
|
306
295
|
/** The turn in flight, cut off or parked, when one is recorded. */
|
|
307
296
|
turn() {
|
|
@@ -314,6 +303,7 @@ export class ThreadRecord {
|
|
|
314
303
|
async end(ctx, history, queuedIds) {
|
|
315
304
|
await this.updateHeld(ctx, (record) => ({
|
|
316
305
|
...withoutTurn(record),
|
|
306
|
+
...this.withLayers(record),
|
|
317
307
|
steers: record.steers?.filter((steer) => queuedIds.includes(steer.id)),
|
|
318
308
|
items: [
|
|
319
309
|
...history,
|
|
@@ -325,10 +315,13 @@ export class ThreadRecord {
|
|
|
325
315
|
addUsage(spent) {
|
|
326
316
|
return this.run(async () => {
|
|
327
317
|
const usage = addUsage((await this.load())?.usage ?? EMPTY_USAGE, spent);
|
|
318
|
+
// A record a forget deleted meanwhile stays deleted: a late bill does not bring it back.
|
|
328
319
|
await this.write((record) => ({
|
|
329
320
|
...record,
|
|
330
321
|
usage,
|
|
331
|
-
})
|
|
322
|
+
}), {
|
|
323
|
+
onlyIfStored: true,
|
|
324
|
+
});
|
|
332
325
|
return usage;
|
|
333
326
|
});
|
|
334
327
|
}
|
|
@@ -377,9 +370,9 @@ export class ThreadRecord {
|
|
|
377
370
|
});
|
|
378
371
|
}
|
|
379
372
|
/** Read-modify-write the stored record, best-effort. Call only from inside `run`. */
|
|
380
|
-
async write(change) {
|
|
373
|
+
async write(change, opts) {
|
|
381
374
|
try {
|
|
382
|
-
await this.commit(change);
|
|
375
|
+
await this.commit(change, opts);
|
|
383
376
|
}
|
|
384
377
|
catch (error) {
|
|
385
378
|
// Same rule as checkpoints: losing the record costs resumability, not the turn.
|
|
@@ -391,10 +384,13 @@ export class ThreadRecord {
|
|
|
391
384
|
* the write lands only if nothing else wrote meanwhile, and is tried again on what
|
|
392
385
|
* the other writer left, so two harnesses never overwrite each other's fields.
|
|
393
386
|
*/
|
|
394
|
-
async commit(change) {
|
|
387
|
+
async commit(change, opts) {
|
|
395
388
|
const store = this.host.store;
|
|
396
389
|
for (let attempt = 0; attempt < COMMIT_ATTEMPTS; attempt += 1) {
|
|
397
390
|
const stored = await store.read(this.threadId);
|
|
391
|
+
if (opts?.onlyIfStored && stored.raw === null) {
|
|
392
|
+
return;
|
|
393
|
+
}
|
|
398
394
|
const next = change(stored.record ?? {
|
|
399
395
|
items: [],
|
|
400
396
|
});
|
|
@@ -418,6 +414,21 @@ export class ThreadRecord {
|
|
|
418
414
|
input,
|
|
419
415
|
]);
|
|
420
416
|
}
|
|
417
|
+
/** `layers` with the ids of the layers this harness keeps durable state for, when it has any new ones. */
|
|
418
|
+
withLayers(record) {
|
|
419
|
+
const known = this.host.layerIds?.() ?? [];
|
|
420
|
+
const layers = new Set(record.layers);
|
|
421
|
+
for (const id of known) {
|
|
422
|
+
layers.add(id);
|
|
423
|
+
}
|
|
424
|
+
return layers.size === 0
|
|
425
|
+
? {}
|
|
426
|
+
: {
|
|
427
|
+
layers: [
|
|
428
|
+
...layers,
|
|
429
|
+
],
|
|
430
|
+
};
|
|
431
|
+
}
|
|
421
432
|
load() {
|
|
422
433
|
return this.host.store.load(this.threadId);
|
|
423
434
|
}
|
|
@@ -466,3 +477,36 @@ function addUsage(total, spent) {
|
|
|
466
477
|
};
|
|
467
478
|
}
|
|
468
479
|
//#endregion
|
|
480
|
+
//#region Executions
|
|
481
|
+
/** `executions` with `executionId` added at the end, unless it is already there. */
|
|
482
|
+
function withExecution(executions, executionId) {
|
|
483
|
+
const known = executions ?? [];
|
|
484
|
+
return known.includes(executionId)
|
|
485
|
+
? known
|
|
486
|
+
: [
|
|
487
|
+
...known,
|
|
488
|
+
executionId,
|
|
489
|
+
];
|
|
490
|
+
}
|
|
491
|
+
/**
|
|
492
|
+
* @internal
|
|
493
|
+
* Every execution a stored record names, oldest first, without repeats: those it
|
|
494
|
+
* began, then remembered finished turns from records written before `executions`
|
|
495
|
+
* was kept, then the turn in flight.
|
|
496
|
+
*/
|
|
497
|
+
export function executionsOf(record) {
|
|
498
|
+
const ids = new Set(record?.executions);
|
|
499
|
+
for (const turn of record?.done ?? []) {
|
|
500
|
+
if (turn.executionId !== undefined) {
|
|
501
|
+
ids.add(turn.executionId);
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
if (record?.turn) {
|
|
505
|
+
ids.delete(record.turn.executionId);
|
|
506
|
+
ids.add(record.turn.executionId);
|
|
507
|
+
}
|
|
508
|
+
return [
|
|
509
|
+
...ids,
|
|
510
|
+
];
|
|
511
|
+
}
|
|
512
|
+
//#endregion
|