@noetic-tools/core 5.22.0-next.2 → 5.22.0-next.4
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/builders/custom-item.d.ts +1 -1
- package/dist/builders/custom-item.js +14 -3
- 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 +110 -4
- package/dist/harness/agent-harness.js +394 -40
- 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 +40 -1
- package/dist/harness/model-rounds.d.ts +6 -0
- package/dist/harness/model-rounds.js +7 -3
- package/dist/harness/model-tool-round.js +19 -5
- package/dist/harness/park-watchers.d.ts +3 -2
- 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 +23 -1
- package/dist/harness/thread-record.js +98 -21
- package/dist/harness/turn-cuts.d.ts +50 -0
- package/dist/harness/turn-cuts.js +108 -0
- package/dist/index.d.ts +6 -7
- package/dist/index.js +2 -3
- package/dist/interpreter/acp-tools.js +21 -4
- package/dist/interpreter/execute-action.js +7 -1
- 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/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 +11 -0
- package/dist/runtime/durable/session-store.js +28 -2
- package/dist/runtime/durable/turn-lease.d.ts +10 -0
- package/dist/runtime/durable/turn-lease.js +10 -2
- package/dist/runtime/held-calls.d.ts +65 -6
- package/dist/runtime/held-calls.js +257 -5
- package/dist/runtime/output-store.d.ts +2 -0
- package/dist/runtime/output-store.js +3 -1
- package/dist/runtime/session-runner.d.ts +9 -1
- package/dist/runtime/session-runner.js +34 -0
- package/dist/runtime/tool-approval.d.ts +1 -3
- package/dist/runtime/tool-approval.js +1 -1
- package/package.json +2 -2
|
@@ -7,7 +7,7 @@ import { SteerPoint, validateSchema } from '@noetic-tools/types';
|
|
|
7
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.
|
|
@@ -380,7 +394,7 @@ async function dropHolds(scope, request, calls) {
|
|
|
380
394
|
const executionId = heldScopeOf(request.ctx);
|
|
381
395
|
for (const call of calls) {
|
|
382
396
|
if (await holds.load(executionId, call.callId)) {
|
|
383
|
-
await holds.close(executionId, call.callId);
|
|
397
|
+
await holds.close(executionId, call.callId, 'skipped');
|
|
384
398
|
}
|
|
385
399
|
}
|
|
386
400
|
}
|
|
@@ -40,7 +40,8 @@ export interface ParkWatcherHost {
|
|
|
40
40
|
/** The state of one of them now, or undefined when it cannot be read. */
|
|
41
41
|
taskState(task: ParkedTask, signal: AbortSignal): Promise<string | undefined>;
|
|
42
42
|
/** Resume the thread's turn. Resolves false when it could not be resumed just now. */
|
|
43
|
-
|
|
43
|
+
/** `options` undefined: the harness finds them (`turnOptions`). */
|
|
44
|
+
wake(threadId: string, options: ExecuteOptions | undefined): Promise<boolean>;
|
|
44
45
|
/** The execution of the turn the thread has parked now, or undefined when it has none. */
|
|
45
46
|
parked(threadId: string): Promise<string | undefined>;
|
|
46
47
|
now(): number;
|
|
@@ -51,7 +52,7 @@ export interface ParkedTurn {
|
|
|
51
52
|
/** When its earliest wait runs out, or undefined when none has a deadline. */
|
|
52
53
|
readonly until: number | undefined;
|
|
53
54
|
/** The `execute()` options the turn ran with, to resume it with. */
|
|
54
|
-
readonly options
|
|
55
|
+
readonly options?: ExecuteOptions;
|
|
55
56
|
}
|
|
56
57
|
/** @public How long auto-wake waits after an event before waking a turn, so a burst wakes it once. */
|
|
57
58
|
export declare const DEFAULT_WAKE_DEBOUNCE_MS = 250;
|
|
@@ -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
|
|
@@ -91,6 +93,17 @@ export declare class ThreadRecord {
|
|
|
91
93
|
* checkpoint and ledger stay, since they are what the woken turn resumes from.
|
|
92
94
|
*/
|
|
93
95
|
park(ctx: Context, until: number | undefined): Promise<void>;
|
|
96
|
+
/**
|
|
97
|
+
* The turn on `ctx` was cut (spec 23 § Cut turns): keep its record, marked with how
|
|
98
|
+
* often and when. Best-effort and unfenced: storage that just refused a write may
|
|
99
|
+
* refuse this one, and the harness keeps the mark in memory as well. Written only
|
|
100
|
+
* while the record still names the turn's execution.
|
|
101
|
+
*/
|
|
102
|
+
cut(ctx: Context, cut: {
|
|
103
|
+
reason: string;
|
|
104
|
+
count: number;
|
|
105
|
+
at: number;
|
|
106
|
+
}): Promise<void>;
|
|
94
107
|
/**
|
|
95
108
|
* The turn on `ctx` ended here without finishing. Best-effort: a turn whose mark
|
|
96
109
|
* does not land is simply taken for one that was cut off.
|
|
@@ -107,7 +120,7 @@ export declare class ThreadRecord {
|
|
|
107
120
|
* thread's recent turns delivered it.
|
|
108
121
|
*/
|
|
109
122
|
answerFor(messageId: string): Promise<string | undefined>;
|
|
110
|
-
/** The executions of the thread
|
|
123
|
+
/** The executions of every turn the thread began, oldest first, the one in flight last. */
|
|
111
124
|
executions(): Promise<string[]>;
|
|
112
125
|
/** The turn in flight, cut off or parked, when one is recorded. */
|
|
113
126
|
turn(): Promise<SessionRecord['turn']>;
|
|
@@ -137,6 +150,15 @@ export declare class ThreadRecord {
|
|
|
137
150
|
*/
|
|
138
151
|
private commit;
|
|
139
152
|
private parseInput;
|
|
153
|
+
/** `layers` with the ids of the layers this harness keeps durable state for, when it has any new ones. */
|
|
154
|
+
private withLayers;
|
|
140
155
|
private load;
|
|
141
156
|
private run;
|
|
142
157
|
}
|
|
158
|
+
/**
|
|
159
|
+
* @internal
|
|
160
|
+
* Every execution a stored record names, oldest first, without repeats: those it
|
|
161
|
+
* began, then remembered finished turns from records written before `executions`
|
|
162
|
+
* was kept, then the turn in flight.
|
|
163
|
+
*/
|
|
164
|
+
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: [
|
|
@@ -161,6 +163,14 @@ export class ThreadRecord {
|
|
|
161
163
|
: {
|
|
162
164
|
version: this.host.version,
|
|
163
165
|
}),
|
|
166
|
+
// Kept until the turn ends, even when it resumes under a new execution (its
|
|
167
|
+
// checkpoint was not written): how often it was cut counts toward giving up.
|
|
168
|
+
...(record.turn?.cut !== undefined &&
|
|
169
|
+
(record.turn.executionId === ctx.id || isSameList(record.turn.messageIds, messageIds))
|
|
170
|
+
? {
|
|
171
|
+
cut: record.turn.cut,
|
|
172
|
+
}
|
|
173
|
+
: {}),
|
|
164
174
|
// Kept until the turn ends: a host that dies part way through going on
|
|
165
175
|
// must not find the same step stuck again.
|
|
166
176
|
...(record.turn?.executionId === ctx.id && record.turn.accept !== undefined
|
|
@@ -224,7 +234,7 @@ export class ThreadRecord {
|
|
|
224
234
|
? {
|
|
225
235
|
...record,
|
|
226
236
|
turn: {
|
|
227
|
-
...record.turn,
|
|
237
|
+
...withoutCut(record.turn),
|
|
228
238
|
parked: until === undefined
|
|
229
239
|
? {}
|
|
230
240
|
: {
|
|
@@ -234,6 +244,23 @@ export class ThreadRecord {
|
|
|
234
244
|
}
|
|
235
245
|
: record);
|
|
236
246
|
}
|
|
247
|
+
/**
|
|
248
|
+
* The turn on `ctx` was cut (spec 23 § Cut turns): keep its record, marked with how
|
|
249
|
+
* often and when. Best-effort and unfenced: storage that just refused a write may
|
|
250
|
+
* refuse this one, and the harness keeps the mark in memory as well. Written only
|
|
251
|
+
* while the record still names the turn's execution.
|
|
252
|
+
*/
|
|
253
|
+
cut(ctx, cut) {
|
|
254
|
+
return this.update((record) => record.turn?.executionId === ctx.id
|
|
255
|
+
? {
|
|
256
|
+
...record,
|
|
257
|
+
turn: {
|
|
258
|
+
...record.turn,
|
|
259
|
+
cut,
|
|
260
|
+
},
|
|
261
|
+
}
|
|
262
|
+
: record);
|
|
263
|
+
}
|
|
237
264
|
/**
|
|
238
265
|
* The turn on `ctx` ended here without finishing. Best-effort: a turn whose mark
|
|
239
266
|
* does not land is simply taken for one that was cut off.
|
|
@@ -243,7 +270,7 @@ export class ThreadRecord {
|
|
|
243
270
|
? {
|
|
244
271
|
...record,
|
|
245
272
|
turn: {
|
|
246
|
-
...record.turn,
|
|
273
|
+
...withoutCut(record.turn),
|
|
247
274
|
stopped: {
|
|
248
275
|
at,
|
|
249
276
|
reason,
|
|
@@ -286,22 +313,9 @@ export class ThreadRecord {
|
|
|
286
313
|
return done.findLast((turn) => turn.messageIds.includes(messageId))?.text;
|
|
287
314
|
});
|
|
288
315
|
}
|
|
289
|
-
/** The executions of the thread
|
|
316
|
+
/** The executions of every turn the thread began, oldest first, the one in flight last. */
|
|
290
317
|
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
|
-
});
|
|
318
|
+
return this.run(async () => executionsOf(await this.load()));
|
|
305
319
|
}
|
|
306
320
|
/** The turn in flight, cut off or parked, when one is recorded. */
|
|
307
321
|
turn() {
|
|
@@ -314,6 +328,7 @@ export class ThreadRecord {
|
|
|
314
328
|
async end(ctx, history, queuedIds) {
|
|
315
329
|
await this.updateHeld(ctx, (record) => ({
|
|
316
330
|
...withoutTurn(record),
|
|
331
|
+
...this.withLayers(record),
|
|
317
332
|
steers: record.steers?.filter((steer) => queuedIds.includes(steer.id)),
|
|
318
333
|
items: [
|
|
319
334
|
...history,
|
|
@@ -325,10 +340,13 @@ export class ThreadRecord {
|
|
|
325
340
|
addUsage(spent) {
|
|
326
341
|
return this.run(async () => {
|
|
327
342
|
const usage = addUsage((await this.load())?.usage ?? EMPTY_USAGE, spent);
|
|
343
|
+
// A record a forget deleted meanwhile stays deleted: a late bill does not bring it back.
|
|
328
344
|
await this.write((record) => ({
|
|
329
345
|
...record,
|
|
330
346
|
usage,
|
|
331
|
-
})
|
|
347
|
+
}), {
|
|
348
|
+
onlyIfStored: true,
|
|
349
|
+
});
|
|
332
350
|
return usage;
|
|
333
351
|
});
|
|
334
352
|
}
|
|
@@ -377,9 +395,9 @@ export class ThreadRecord {
|
|
|
377
395
|
});
|
|
378
396
|
}
|
|
379
397
|
/** Read-modify-write the stored record, best-effort. Call only from inside `run`. */
|
|
380
|
-
async write(change) {
|
|
398
|
+
async write(change, opts) {
|
|
381
399
|
try {
|
|
382
|
-
await this.commit(change);
|
|
400
|
+
await this.commit(change, opts);
|
|
383
401
|
}
|
|
384
402
|
catch (error) {
|
|
385
403
|
// Same rule as checkpoints: losing the record costs resumability, not the turn.
|
|
@@ -391,10 +409,13 @@ export class ThreadRecord {
|
|
|
391
409
|
* the write lands only if nothing else wrote meanwhile, and is tried again on what
|
|
392
410
|
* the other writer left, so two harnesses never overwrite each other's fields.
|
|
393
411
|
*/
|
|
394
|
-
async commit(change) {
|
|
412
|
+
async commit(change, opts) {
|
|
395
413
|
const store = this.host.store;
|
|
396
414
|
for (let attempt = 0; attempt < COMMIT_ATTEMPTS; attempt += 1) {
|
|
397
415
|
const stored = await store.read(this.threadId);
|
|
416
|
+
if (opts?.onlyIfStored && stored.raw === null) {
|
|
417
|
+
return;
|
|
418
|
+
}
|
|
398
419
|
const next = change(stored.record ?? {
|
|
399
420
|
items: [],
|
|
400
421
|
});
|
|
@@ -418,6 +439,21 @@ export class ThreadRecord {
|
|
|
418
439
|
input,
|
|
419
440
|
]);
|
|
420
441
|
}
|
|
442
|
+
/** `layers` with the ids of the layers this harness keeps durable state for, when it has any new ones. */
|
|
443
|
+
withLayers(record) {
|
|
444
|
+
const known = this.host.layerIds?.() ?? [];
|
|
445
|
+
const layers = new Set(record.layers);
|
|
446
|
+
for (const id of known) {
|
|
447
|
+
layers.add(id);
|
|
448
|
+
}
|
|
449
|
+
return layers.size === 0
|
|
450
|
+
? {}
|
|
451
|
+
: {
|
|
452
|
+
layers: [
|
|
453
|
+
...layers,
|
|
454
|
+
],
|
|
455
|
+
};
|
|
456
|
+
}
|
|
421
457
|
load() {
|
|
422
458
|
return this.host.store.load(this.threadId);
|
|
423
459
|
}
|
|
@@ -427,6 +463,11 @@ export class ThreadRecord {
|
|
|
427
463
|
return next;
|
|
428
464
|
}
|
|
429
465
|
}
|
|
466
|
+
function withoutCut(turn) {
|
|
467
|
+
const { cut, ...rest } = turn;
|
|
468
|
+
void cut;
|
|
469
|
+
return rest;
|
|
470
|
+
}
|
|
430
471
|
function withoutTurn(record) {
|
|
431
472
|
const { turn, ...rest } = record;
|
|
432
473
|
void turn;
|
|
@@ -439,6 +480,9 @@ function withoutTurn(record) {
|
|
|
439
480
|
function isSameDelivery(turn, delivered) {
|
|
440
481
|
return delivered.length > 0 && delivered.every((id) => turn.includes(id));
|
|
441
482
|
}
|
|
483
|
+
function isSameList(a, b) {
|
|
484
|
+
return a.length === b.length && a.every((id, i) => id === b[i]);
|
|
485
|
+
}
|
|
442
486
|
function addUsage(total, spent) {
|
|
443
487
|
const cost = (total.cost ?? 0) + spent.cost;
|
|
444
488
|
const billedCost = (total.billedCost ?? 0) + spent.billedCost;
|
|
@@ -466,3 +510,36 @@ function addUsage(total, spent) {
|
|
|
466
510
|
};
|
|
467
511
|
}
|
|
468
512
|
//#endregion
|
|
513
|
+
//#region Executions
|
|
514
|
+
/** `executions` with `executionId` added at the end, unless it is already there. */
|
|
515
|
+
function withExecution(executions, executionId) {
|
|
516
|
+
const known = executions ?? [];
|
|
517
|
+
return known.includes(executionId)
|
|
518
|
+
? known
|
|
519
|
+
: [
|
|
520
|
+
...known,
|
|
521
|
+
executionId,
|
|
522
|
+
];
|
|
523
|
+
}
|
|
524
|
+
/**
|
|
525
|
+
* @internal
|
|
526
|
+
* Every execution a stored record names, oldest first, without repeats: those it
|
|
527
|
+
* began, then remembered finished turns from records written before `executions`
|
|
528
|
+
* was kept, then the turn in flight.
|
|
529
|
+
*/
|
|
530
|
+
export function executionsOf(record) {
|
|
531
|
+
const ids = new Set(record?.executions);
|
|
532
|
+
for (const turn of record?.done ?? []) {
|
|
533
|
+
if (turn.executionId !== undefined) {
|
|
534
|
+
ids.add(turn.executionId);
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
if (record?.turn) {
|
|
538
|
+
ids.delete(record.turn.executionId);
|
|
539
|
+
ids.add(record.turn.executionId);
|
|
540
|
+
}
|
|
541
|
+
return [
|
|
542
|
+
...ids,
|
|
543
|
+
];
|
|
544
|
+
}
|
|
545
|
+
//#endregion
|