@noetic-tools/core 5.22.0-next.2 → 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/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 +76 -3
- package/dist/harness/agent-harness.js +229 -21
- 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 +15 -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/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 +4 -5
- 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 +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/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/tool-approval.d.ts +1 -3
- package/dist/runtime/tool-approval.js +1 -1
- package/package.json +2 -2
|
@@ -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
|
package/dist/index.d.ts
CHANGED
|
@@ -67,8 +67,7 @@ export { aiCondition, allCondition, anyCondition, embeddingMatch, otherwise, sem
|
|
|
67
67
|
/** @public */
|
|
68
68
|
export { cosineSimilarity } from './conditions/cosine-similarity.js';
|
|
69
69
|
/** @public */
|
|
70
|
-
|
|
71
|
-
export { DECISION_ITEM_TYPE, isDecisionItem, isNoeticConfigError, isNoeticError, NoeticConfigError, NoeticErrorImpl, } from '@noetic-tools/types';
|
|
70
|
+
export { DECISION_ITEM_TYPE, failureCause, HeldCallSchema, HeldCallSettledSchema, isDecisionItem, isNoeticConfigError, isNoeticError, NoeticConfigError, NoeticErrorImpl, readHeldCallEvent, } from '@noetic-tools/types';
|
|
72
71
|
/** @public */
|
|
73
72
|
export type { AskUserAnnotation, AskUserInput, AskUserOption, AskUserOutput, AskUserQuestion, } from './types/ask-user-types.js';
|
|
74
73
|
/** @public */
|
|
@@ -182,11 +181,11 @@ export type { LayerTraceSpan, Span, TraceExporter } from '@noetic-tools/types';
|
|
|
182
181
|
/** @public */
|
|
183
182
|
export type { FrameworkStreamEvent, HarnessResponse, SdkStreamEvent, StreamEvent, StreamingItem, } from '@noetic-tools/types';
|
|
184
183
|
/** @public */
|
|
185
|
-
export type { AgentConfig, AgentHarnessContract, AgentHooks, CallModelRequest, CancelOptions, ContextCacheConfig, ContextCacheStore, ContextEpoch, DeliveryMode, DrainCall, DrainReport, ExecuteOptions, ExecutionScope, ExecutionStatus, HarnessJudgmentContract, HarnessStatus, HeldCall, HeldResolution, ItemSchemaConfig, ReanchorReason, RecallLayerOutput, SessionScope, SessionUsage, StuckTurn, ToolHold, TrailMark, } from '@noetic-tools/types';
|
|
184
|
+
export type { AgentConfig, AgentHarnessContract, AgentHooks, CallModelRequest, CancelOptions, ContextCacheConfig, ContextCacheStore, ContextEpoch, DeliveryMode, DrainCall, DrainReport, ExecuteOptions, ExecutionScope, ExecutionStatus, HarnessJudgmentContract, HarnessStatus, HeldCall, HeldCallContext, HeldCallEvent, HeldCallHandler, HeldCallSettled, HeldResolution, HeldSteerPolicy, ItemSchemaConfig, ReanchorReason, RecallLayerOutput, RecordedToolCall, SessionScope, SessionUsage, StuckTurn, ToolHold, TrailMark, } from '@noetic-tools/types';
|
|
186
185
|
/** @public */
|
|
187
|
-
export type { PendingSpend, ReconcileSpendOptions, SpendSettlement, WriteOffSpendOptions, } from '@noetic-tools/types';
|
|
186
|
+
export type { ForgetOptions, ForgetReport, ListStoredOptions, PendingSpend, ReconcileSpendOptions, SpendSettlement, StoredExecution, WriteOffSpendOptions, } from '@noetic-tools/types';
|
|
188
187
|
/** @public */
|
|
189
|
-
export { SpendKind } from '@noetic-tools/types';
|
|
188
|
+
export { ExecutionPart, SpendKind } from '@noetic-tools/types';
|
|
190
189
|
/** @public */
|
|
191
190
|
export type { AfterModelCallParams, AfterModelCallResult, ApproveRequest, ApproveToolCallParams, BeforeToolCallParams, BeforeToolCallResult, LedgerEntry, OnSteerParams, OnSteerResult, Steer, SteeringConfig, SteeringDecision, SteeringRule, SteeringState, SteerVerdict, ToolApprover, } from '@noetic-tools/types';
|
|
192
191
|
/** @public */
|
package/dist/index.js
CHANGED
|
@@ -50,8 +50,7 @@ export { cosineSimilarity } from './conditions/cosine-similarity.js';
|
|
|
50
50
|
//#endregion
|
|
51
51
|
//#region Errors
|
|
52
52
|
/** @public */
|
|
53
|
-
|
|
54
|
-
export { DECISION_ITEM_TYPE, isDecisionItem, isNoeticConfigError, isNoeticError, NoeticConfigError, NoeticErrorImpl, } from '@noetic-tools/types';
|
|
53
|
+
export { DECISION_ITEM_TYPE, failureCause, HeldCallSchema, HeldCallSettledSchema, isDecisionItem, isNoeticConfigError, isNoeticError, NoeticConfigError, NoeticErrorImpl, readHeldCallEvent, } from '@noetic-tools/types';
|
|
55
54
|
/** @public */
|
|
56
55
|
export { AskUserAnnotationSchema, AskUserInputSchema, AskUserOptionSchema, AskUserOutputSchema, AskUserQuestionSchema, } from './types/ask-user-types.js';
|
|
57
56
|
//#endregion
|
|
@@ -121,7 +120,7 @@ export { ChannelSnapshotSchema, CheckpointSchemaVersion, CheckpointSnapshotSchem
|
|
|
121
120
|
/** @public */
|
|
122
121
|
export { Slot } from '@noetic-tools/context';
|
|
123
122
|
/** @public */
|
|
124
|
-
export { SpendKind } from '@noetic-tools/types';
|
|
123
|
+
export { ExecutionPart, SpendKind } from '@noetic-tools/types';
|
|
125
124
|
/** @public */
|
|
126
125
|
export { LedgerEntryKind, SteerAction, SteeringAction, SteerPoint } from '@noetic-tools/types';
|
|
127
126
|
/** @public */
|
|
@@ -13,7 +13,7 @@ import { orderedCallId } from '../connections/durability.js';
|
|
|
13
13
|
import { offeredTools, stepConnectionsOf } from '../connections/step-tools.js';
|
|
14
14
|
import { ToolAttr } from '../observability/genai-attributes.js';
|
|
15
15
|
import { drainsOf } from '../runtime/drain.js';
|
|
16
|
-
import { heldCallsOf, heldScopeOf, mayWriteHolds, waitOnHeldCalls } from '../runtime/held-calls.js';
|
|
16
|
+
import { heldCallsOf, heldScopeOf, mayWriteHolds, noticeHeld, waitOnHeldCalls, } from '../runtime/held-calls.js';
|
|
17
17
|
import { createToolResultItem, executeToolCall, resolveWireJsonSchema } from '../runtime/tool-call.js';
|
|
18
18
|
import { sanitizeToolNameForWire } from '../util/tool-name.js';
|
|
19
19
|
import { BridgedCallRecords } from './acp-resume.js';
|
|
@@ -373,8 +373,20 @@ export class AcpToolRunner {
|
|
|
373
373
|
callId: params.callId ?? held.callId,
|
|
374
374
|
heldAs: held.callId,
|
|
375
375
|
});
|
|
376
|
+
noticeHeld({
|
|
377
|
+
harness: ctx.harness,
|
|
378
|
+
ctx,
|
|
379
|
+
held,
|
|
380
|
+
emit: (settled) => binding.events.toolEvent('tool_call_settled', {
|
|
381
|
+
...settled,
|
|
382
|
+
callId: params.callId ?? settled.callId,
|
|
383
|
+
heldAs: settled.callId,
|
|
384
|
+
}),
|
|
385
|
+
});
|
|
376
386
|
}
|
|
377
|
-
|
|
387
|
+
// The wait throws `cancelled` when the agent's signal ends it, as it does for
|
|
388
|
+
// the turn's own abort: only the latter is the turn's to handle.
|
|
389
|
+
const gaveUp = await waitOnHeldCalls({
|
|
378
390
|
harness: ctx.harness,
|
|
379
391
|
ctx,
|
|
380
392
|
callIds: [
|
|
@@ -382,11 +394,16 @@ export class AcpToolRunner {
|
|
|
382
394
|
],
|
|
383
395
|
signal,
|
|
384
396
|
park: false,
|
|
397
|
+
}).then(() => signal.aborted, (error) => {
|
|
398
|
+
if (signal.aborted) {
|
|
399
|
+
return true;
|
|
400
|
+
}
|
|
401
|
+
throw error;
|
|
385
402
|
});
|
|
386
403
|
// The agent stopped waiting for this call: nobody is left to give an answer to.
|
|
387
|
-
if (
|
|
404
|
+
if (gaveUp) {
|
|
388
405
|
if (mayWriteHolds(ctx)) {
|
|
389
|
-
await heldCallsOf(ctx.harness).close(heldScopeOf(ctx), held.callId);
|
|
406
|
+
await heldCallsOf(ctx.harness).close(heldScopeOf(ctx), held.callId, 'cancelled');
|
|
390
407
|
}
|
|
391
408
|
return {
|
|
392
409
|
output: CANCELLED_OUTPUT,
|
|
@@ -46,7 +46,13 @@ export async function executeRunCode(step, input, ctx) {
|
|
|
46
46
|
if (ending) {
|
|
47
47
|
throw ending;
|
|
48
48
|
}
|
|
49
|
-
|
|
49
|
+
// A thrown non-Error keeps the value itself as the wrapper's cause.
|
|
50
|
+
lastError =
|
|
51
|
+
e instanceof Error
|
|
52
|
+
? e
|
|
53
|
+
: new Error(String(e), {
|
|
54
|
+
cause: e,
|
|
55
|
+
});
|
|
50
56
|
if (attempt < maxAttempts - 1 && retry) {
|
|
51
57
|
const delay = computeDelay(retry, attempt);
|
|
52
58
|
await new Promise((r) => setTimeout(r, delay));
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { frameworkCast, NoeticErrorImpl } from '@noetic-tools/types';
|
|
1
|
+
import { frameworkCast, isNoeticConfigError, isNoeticError, NoeticErrorImpl, } from '@noetic-tools/types';
|
|
2
2
|
import { recordedScopeOf, recordStepOutput } from '../expression/step-outputs.js';
|
|
3
3
|
import { emitFrameworkEvent, getBroadcaster, shouldEmit } from '../runtime/broadcaster-utils.js';
|
|
4
4
|
import { ContextImpl } from '../runtime/context-impl.js';
|
|
@@ -144,13 +144,13 @@ function parseRecordedItems(ctx, raw) {
|
|
|
144
144
|
* runs again on resume.
|
|
145
145
|
*/
|
|
146
146
|
async function recordToLedger(opts) {
|
|
147
|
-
const { ledger, ledgerKey, inputHash, lane, step, output } = opts;
|
|
147
|
+
const { ledger, ledgerKey, inputHash, lane, positionalPath, step, output } = opts;
|
|
148
148
|
if (!ledger || ledgerKey === undefined) {
|
|
149
149
|
return;
|
|
150
150
|
}
|
|
151
151
|
const items = lane?.appendedItems() ?? [];
|
|
152
152
|
const streamed = lane?.emittedIndices() ?? [];
|
|
153
|
-
await ledger.record({
|
|
153
|
+
const stored = await ledger.record({
|
|
154
154
|
path: ledgerKey,
|
|
155
155
|
stepId: step.id,
|
|
156
156
|
kind: step.kind,
|
|
@@ -168,6 +168,42 @@ async function recordToLedger(opts) {
|
|
|
168
168
|
: {}),
|
|
169
169
|
completedAt: new Date().toISOString(),
|
|
170
170
|
});
|
|
171
|
+
/* A positional record prunes what recorded beneath it. A `key:` record sits at no
|
|
172
|
+
* position, so the rounds and child steps that recorded under this dispatch's path
|
|
173
|
+
* are dropped here: the step now replays from its key, and nothing reads them. */
|
|
174
|
+
if (stored && ledgerKey.startsWith(REPLAY_KEY_PREFIX) && positionalPath) {
|
|
175
|
+
await ledger.dropWithin(positionalPath);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* Run one of the harness's step hooks (spec 08 § Step hooks). A hook that throws fails
|
|
180
|
+
* the step it ran for: a Noetic error passes through as is, anything else becomes
|
|
181
|
+
* `step_failed` with the hook's error as its cause.
|
|
182
|
+
*/
|
|
183
|
+
async function runStepHook(stepId, hook) {
|
|
184
|
+
try {
|
|
185
|
+
await hook();
|
|
186
|
+
}
|
|
187
|
+
catch (error) {
|
|
188
|
+
if (isNoeticError(error) || isNoeticConfigError(error)) {
|
|
189
|
+
throw error;
|
|
190
|
+
}
|
|
191
|
+
throw new NoeticErrorImpl({
|
|
192
|
+
kind: 'step_failed',
|
|
193
|
+
stepId,
|
|
194
|
+
cause: error instanceof Error
|
|
195
|
+
? error
|
|
196
|
+
: new Error(String(error), {
|
|
197
|
+
cause: error,
|
|
198
|
+
}),
|
|
199
|
+
retriesExhausted: false,
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
/** The step hooks a context's harness was configured with, when it has any. */
|
|
204
|
+
function stepHooksOf(ctx) {
|
|
205
|
+
const hooks = ctx.harness.config.hooks;
|
|
206
|
+
return hooks?.beforeStep || hooks?.afterStep ? hooks : undefined;
|
|
171
207
|
}
|
|
172
208
|
//#endregion
|
|
173
209
|
/**
|
|
@@ -267,6 +303,7 @@ async function executeStep(step, input, ctx) {
|
|
|
267
303
|
lane?.skipLedger();
|
|
268
304
|
}
|
|
269
305
|
const inputHash = ledgerKey === undefined ? undefined : lane?.currentDispatch()?.inputHash;
|
|
306
|
+
const positionalPath = lane?.currentDispatch()?.path;
|
|
270
307
|
const ledger = impl?.ledger;
|
|
271
308
|
const replay = replayFromLedger({
|
|
272
309
|
ledger,
|
|
@@ -290,8 +327,15 @@ async function executeStep(step, input, ctx) {
|
|
|
290
327
|
}
|
|
291
328
|
// Parking needs to know which steps are in flight (spec 23 § Parked turns).
|
|
292
329
|
const leaveParking = ledger?.parking.enter(lane?.currentDispatch()?.path);
|
|
330
|
+
const hooks = stepHooksOf(baseCtx);
|
|
331
|
+
const hookStep = frameworkCast(step);
|
|
332
|
+
const hookCtx = frameworkCast(stepCtx);
|
|
293
333
|
let result;
|
|
294
334
|
try {
|
|
335
|
+
const before = hooks?.beforeStep;
|
|
336
|
+
if (before) {
|
|
337
|
+
await runStepHook(step.id, () => before(hookStep, hookCtx));
|
|
338
|
+
}
|
|
295
339
|
await beginEmitItems(step, input, stepCtx);
|
|
296
340
|
result = await dispatchStepKind(step, input, {
|
|
297
341
|
stepCtx,
|
|
@@ -302,6 +346,13 @@ async function executeStep(step, input, ctx) {
|
|
|
302
346
|
// Inside the try, so an item the schemas refuse fails the dispatch like any other
|
|
303
347
|
// error; before the ledger record, so the entry holds the items and replays them.
|
|
304
348
|
await emitStepItems(step, result, stepCtx);
|
|
349
|
+
// The step completes only once afterStep returns: one that throws fails it, and
|
|
350
|
+
// the step is not recorded, so a resume runs it again.
|
|
351
|
+
const after = hooks?.afterStep;
|
|
352
|
+
if (after) {
|
|
353
|
+
const output = result;
|
|
354
|
+
await runStepHook(step.id, () => after(hookStep, output, hookCtx));
|
|
355
|
+
}
|
|
305
356
|
// A JSON workflow node's output is readable as `$steps.<id>` from here on (spec 33).
|
|
306
357
|
const outputScope = recordedScopeOf(step);
|
|
307
358
|
if (outputScope) {
|
|
@@ -341,6 +392,7 @@ async function executeStep(step, input, ctx) {
|
|
|
341
392
|
ledgerKey,
|
|
342
393
|
inputHash,
|
|
343
394
|
lane,
|
|
395
|
+
positionalPath,
|
|
344
396
|
step,
|
|
345
397
|
output: result,
|
|
346
398
|
});
|