@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
|
@@ -4,7 +4,6 @@ import { runEvery } from '../connections/settle.js';
|
|
|
4
4
|
import { pendingTasksOf, resumableWaitsOf } from '../interpreter/connection-steps.js';
|
|
5
5
|
import { turnEndingIn } from '../interpreter/turn-ending.js';
|
|
6
6
|
import { AcpSessionStore } from '../runtime/acp-session-store.js';
|
|
7
|
-
import { emitFrameworkEvent, getBroadcaster } from '../runtime/broadcaster-utils.js';
|
|
8
7
|
import { stubOf } from '../runtime/durable/step-ledger.js';
|
|
9
8
|
import { heldCallsOf, toHeldCall } from '../runtime/held-calls.js';
|
|
10
9
|
import { OutputStore } from '../runtime/output-store.js';
|
|
@@ -15,14 +14,17 @@ import { clearPendingEntries, collectAllTools, collectCustomItems, deduplicateTo
|
|
|
15
14
|
import { buildItemStream, ChannelStore, ContextImpl, canSwap, captureCheckpoint, clearCheckpoint, collectContextTree, createInMemoryStorage, createSessionStore, createSpendLog, createStepLedgerStore, customItemGates, DEFAULT_LEASE_TTL_MS, DEFAULT_PARK_GRACE_MS, Drains, filterReasoningStream, filterTextStream, heldElsewhere, heldElsewhereUntil, INTERRUPT_REASON, isSteer, PARK_REASON, resolveStepLedgerRetention, restoreFromCheckpoint, rootIdOf, SessionRunner, StepLedger, snapshotCwdState, TurnLease, } from './deps/runtime.js';
|
|
16
15
|
import { SteeringAction } from './deps/types.js';
|
|
17
16
|
import { flowVersionOf } from './flow-version.js';
|
|
17
|
+
import { forgetExecution, forgetThread, listStoredExecutions, listStoredThreads } from './forget.js';
|
|
18
18
|
import { resolveCheckpointStore, resolveEnvironmentAdapters } from './harness-options.js';
|
|
19
19
|
import { createHarnessSpan, recordChannelWarning, resolveTraceExporter } from './harness-tracing.js';
|
|
20
20
|
import { LlmGateway } from './llm-client.js';
|
|
21
21
|
import { buildItemSchemaRegistry } from './model-schema.js';
|
|
22
22
|
import { DEFAULT_TASK_POLL_MS, DEFAULT_WAKE_DEBOUNCE_MS, ParkWatchers } from './park-watchers.js';
|
|
23
23
|
import { readDecision } from './read-decision.js';
|
|
24
|
+
import { recordedToolCalls } from './recorded-tool-calls.js';
|
|
24
25
|
import { Spend } from './spend.js';
|
|
25
26
|
import { ThreadRecord } from './thread-record.js';
|
|
27
|
+
import { TurnCuts } from './turn-cuts.js';
|
|
26
28
|
/** Keep `message` in storage for after the thread's parked turn, with its options. */
|
|
27
29
|
function keepForLater(session, record, message) {
|
|
28
30
|
session.keptOptions.set(message.id, message.options);
|
|
@@ -30,6 +32,28 @@ function keepForLater(session, record, message) {
|
|
|
30
32
|
}
|
|
31
33
|
//#endregion
|
|
32
34
|
const DEFAULT_THREAD_ID = '__default__';
|
|
35
|
+
/**
|
|
36
|
+
* `store`, noting in `ids` the id of every layer it keeps durable state for, so a
|
|
37
|
+
* forget knows which layers' storage to look in (spec 23 § Forgetting).
|
|
38
|
+
*/
|
|
39
|
+
function noteDurableLayers(store, ids) {
|
|
40
|
+
const register = store.registerDurable;
|
|
41
|
+
if (!register) {
|
|
42
|
+
return store;
|
|
43
|
+
}
|
|
44
|
+
return new Proxy(store, {
|
|
45
|
+
get(target, property) {
|
|
46
|
+
if (property === 'registerDurable') {
|
|
47
|
+
return (executionId, layerId, storage) => {
|
|
48
|
+
ids.add(layerId);
|
|
49
|
+
register.call(target, executionId, layerId, storage);
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
const value = Reflect.get(target, property, target);
|
|
53
|
+
return typeof value === 'function' ? value.bind(target) : value;
|
|
54
|
+
},
|
|
55
|
+
});
|
|
56
|
+
}
|
|
33
57
|
/** What a `turn_stuck` error says about where the turn stopped, or undefined for any other error. */
|
|
34
58
|
function stuckOf(error) {
|
|
35
59
|
const ending = turnEndingIn(error)?.noeticError;
|
|
@@ -54,6 +78,8 @@ function isLeaseLost(error) {
|
|
|
54
78
|
const LEASE_WAIT_MARGIN_MS = 1e3;
|
|
55
79
|
/** What a turn's run resolves to when it parked instead of finishing. */
|
|
56
80
|
const PARKED = Symbol('parked');
|
|
81
|
+
/** What a turn's run resolves to when it was cut instead of failing (spec 23 § Cut turns). */
|
|
82
|
+
const CUT = Symbol('cut');
|
|
57
83
|
/** When the turn on `ctx` parked until, or undefined when it did not park. */
|
|
58
84
|
function parkedUntil(ctx) {
|
|
59
85
|
if (ctx.abortReason !== PARK_REASON || !(ctx instanceof ContextImpl)) {
|
|
@@ -182,6 +208,12 @@ export class AgentHarness {
|
|
|
182
208
|
leaseOptions;
|
|
183
209
|
/** The flow version this harness runs, when the host names one. */
|
|
184
210
|
version;
|
|
211
|
+
/** Set with the lease: how cut turns are run again, and each thread's cut mark. */
|
|
212
|
+
cuts;
|
|
213
|
+
/** The cut each cut turn's context ended with, for its response. */
|
|
214
|
+
cutOfContext = new WeakMap();
|
|
215
|
+
/** The `execute()` options a stored turn is woken with when none are given. */
|
|
216
|
+
turnOptionsFor;
|
|
185
217
|
/** Set when turns park (`environment.storage.park`): the grace before one does. */
|
|
186
218
|
parkGraceMs;
|
|
187
219
|
/** Set when this harness wakes the turns it parked (`park.autoWake`). */
|
|
@@ -202,6 +234,10 @@ export class AgentHarness {
|
|
|
202
234
|
outputStorage;
|
|
203
235
|
/** The display output each thread of an interactive harness records, by thread id. */
|
|
204
236
|
outputs = new Map();
|
|
237
|
+
/** Forgets in progress, by thread id: a turn of the thread waits for its forget. */
|
|
238
|
+
forgetting = new Map();
|
|
239
|
+
/** Ids of the context layers whose state this harness has kept durably. */
|
|
240
|
+
durableLayerIds = new Set();
|
|
205
241
|
/** Thread id → what stops recording it. */
|
|
206
242
|
stopRecording = new Map();
|
|
207
243
|
/** Threads named by a host-built context's own id, dropped when its run ends. */
|
|
@@ -310,6 +346,8 @@ export class AgentHarness {
|
|
|
310
346
|
decisionModel: opts.decisionModel,
|
|
311
347
|
emitItemsOnReplay: opts.emitItemsOnReplay,
|
|
312
348
|
approveToolCall: opts.approveToolCall,
|
|
349
|
+
onHeld: opts.onHeld,
|
|
350
|
+
steerWhileHeld: opts.steerWhileHeld,
|
|
313
351
|
now: opts.now,
|
|
314
352
|
};
|
|
315
353
|
this.outputStorage = this.config.storage ?? createInMemoryStorage();
|
|
@@ -331,6 +369,8 @@ export class AgentHarness {
|
|
|
331
369
|
now: opts.now,
|
|
332
370
|
...storageEnv?.lease,
|
|
333
371
|
});
|
|
372
|
+
this.cuts = this.leaseOptions ? new TurnCuts(storageEnv?.lease?.cut) : undefined;
|
|
373
|
+
this.turnOptionsFor = opts.turnOptions;
|
|
334
374
|
this.parkGraceMs = resolveParkGrace(this.leaseOptions ? storageEnv?.park : undefined);
|
|
335
375
|
this.parkWatchers = this.createParkWatchers(storageEnv?.park);
|
|
336
376
|
this.spend = this.checkpointStore
|
|
@@ -353,11 +393,10 @@ export class AgentHarness {
|
|
|
353
393
|
onWarning: (warning) => this.recordChannelWarning(warning),
|
|
354
394
|
});
|
|
355
395
|
this.traceExporter = resolveTraceExporter(opts.traceExporter);
|
|
356
|
-
this.layerStateStore =
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
});
|
|
396
|
+
this.layerStateStore = noteDurableLayers(storageEnv?.layerStateStore ??
|
|
397
|
+
createLayerStateStore((layerId, hook, error) => {
|
|
398
|
+
console.warn(`[noetic] context layer '${layerId}' ${hook} error:`, error);
|
|
399
|
+
}), this.durableLayerIds);
|
|
361
400
|
this.recallCache = createRecallCache();
|
|
362
401
|
this.contextCache = createContextCacheStore();
|
|
363
402
|
this.defaultDeliveryMode = opts.defaultDeliveryMode ?? 'next-turn';
|
|
@@ -492,6 +531,7 @@ export class AgentHarness {
|
|
|
492
531
|
*/
|
|
493
532
|
async close() {
|
|
494
533
|
this.parkWatchers?.stopAll();
|
|
534
|
+
heldCallsOf(this).releaseWatches();
|
|
495
535
|
await runEvery([
|
|
496
536
|
...[
|
|
497
537
|
...this.outputs.values(),
|
|
@@ -630,6 +670,11 @@ export class AgentHarness {
|
|
|
630
670
|
return Promise.reject(missingModel);
|
|
631
671
|
}
|
|
632
672
|
const threadId = options?.threadId ?? DEFAULT_THREAD_ID;
|
|
673
|
+
const forgetting = this.forgetting.get(threadId);
|
|
674
|
+
if (forgetting) {
|
|
675
|
+
// A message for a thread being forgotten starts the thread afresh once the forget is done.
|
|
676
|
+
return forgetting.then(() => this.deliverInput(input, options));
|
|
677
|
+
}
|
|
633
678
|
const deliveryMode = options?.deliveryMode ?? this.defaultDeliveryMode;
|
|
634
679
|
const session = this.getOrCreateSession(threadId);
|
|
635
680
|
const message = {
|
|
@@ -653,9 +698,13 @@ export class AgentHarness {
|
|
|
653
698
|
* deliveries doing that at once would each miss the other.
|
|
654
699
|
*/
|
|
655
700
|
deliver(session, message) {
|
|
701
|
+
session.arriving = (session.arriving ?? 0) + 1;
|
|
656
702
|
const turn = (session.delivering ?? Promise.resolve())
|
|
657
703
|
.catch(() => undefined)
|
|
658
|
-
.then(() => this.deliverOne(session, message))
|
|
704
|
+
.then(() => this.deliverOne(session, message))
|
|
705
|
+
.finally(() => {
|
|
706
|
+
session.arriving = (session.arriving ?? 1) - 1;
|
|
707
|
+
});
|
|
659
708
|
session.delivering = turn;
|
|
660
709
|
return turn;
|
|
661
710
|
}
|
|
@@ -877,6 +926,7 @@ export class AgentHarness {
|
|
|
877
926
|
await record.answered(ctx, answer);
|
|
878
927
|
}
|
|
879
928
|
await record.end(ctx, ctx.itemLog.items, session.runner.queue.peekAll().map((message) => message.id));
|
|
929
|
+
this.cuts?.forget(threadId);
|
|
880
930
|
return;
|
|
881
931
|
}
|
|
882
932
|
session.accumulatedItems = [
|
|
@@ -933,6 +983,7 @@ export class AgentHarness {
|
|
|
933
983
|
}
|
|
934
984
|
}
|
|
935
985
|
},
|
|
986
|
+
cutOf: (ctx) => this.cutOfContext.get(ctx),
|
|
936
987
|
heldCalls: async (ctx) => (await heldCallsOf(this).list(rootIdOf(ctx)))
|
|
937
988
|
.filter((held) => held.resolution === undefined)
|
|
938
989
|
.map(toHeldCall),
|
|
@@ -950,6 +1001,7 @@ export class AgentHarness {
|
|
|
950
1001
|
session.turnOptions = perTurnOptions;
|
|
951
1002
|
this.parkWatchers?.stop(threadId);
|
|
952
1003
|
const messageIds = messages.map((m) => m.id);
|
|
1004
|
+
session.turnMessageIds = messageIds;
|
|
953
1005
|
const history = record ? await record.history() : session.accumulatedItems;
|
|
954
1006
|
const graph = this.agentGraph ? frameworkCast(this.agentGraph) : undefined;
|
|
955
1007
|
const views = this.#connections.turnViews(perTurnOptions.connections, graph);
|
|
@@ -993,14 +1045,7 @@ export class AgentHarness {
|
|
|
993
1045
|
frameworkCast(ctx)._sessionQueue = session.runner.queue;
|
|
994
1046
|
await this.start();
|
|
995
1047
|
const connectionTools = await this.#connections.openTurn(ctx, perTurnOptions.connections, graph);
|
|
996
|
-
|
|
997
|
-
const stepTools = this.agentGraph ? collectAllTools(this.agentGraph) : [];
|
|
998
|
-
this.setUnifiedTools(ctx, [
|
|
999
|
-
...stepTools,
|
|
1000
|
-
...this.harnessTools,
|
|
1001
|
-
...connectionTools,
|
|
1002
|
-
]);
|
|
1003
|
-
}
|
|
1048
|
+
this.setTurnTools(ctx, perTurnOptions.tools ?? [], connectionTools);
|
|
1004
1049
|
// Steers the last harness accepted but never applied go back in the queue;
|
|
1005
1050
|
// ones already in the conversation are skipped when offered.
|
|
1006
1051
|
for (const steer of (await record?.steers()) ?? []) {
|
|
@@ -1053,11 +1098,12 @@ export class AgentHarness {
|
|
|
1053
1098
|
}
|
|
1054
1099
|
const until = Number.isFinite(wakeAt) ? wakeAt : undefined;
|
|
1055
1100
|
await record.park(ctx, until);
|
|
1101
|
+
this.cuts?.forget(threadId);
|
|
1056
1102
|
await this.#connections.release(ctx.id);
|
|
1057
1103
|
this.parkWatchers?.watch(threadId, {
|
|
1058
1104
|
executionId: ctx.id,
|
|
1059
1105
|
until,
|
|
1060
|
-
options: session.turnOptions
|
|
1106
|
+
options: session.turnOptions,
|
|
1061
1107
|
});
|
|
1062
1108
|
// Before the turn answers as parked: whoever wakes it has to know when.
|
|
1063
1109
|
await this.announceWakeTime();
|
|
@@ -1094,6 +1140,11 @@ export class AgentHarness {
|
|
|
1094
1140
|
if (await closeOutPark(ctx)) {
|
|
1095
1141
|
return PARKED;
|
|
1096
1142
|
}
|
|
1143
|
+
// Cut short with everything before the stop on record: run again later.
|
|
1144
|
+
if (await this.closeOutCut(session, ctx, error)) {
|
|
1145
|
+
return CUT;
|
|
1146
|
+
}
|
|
1147
|
+
this.cuts?.forget(threadId);
|
|
1097
1148
|
// The turn ended here, in a live process. Say so, or a routine wake would
|
|
1098
1149
|
// take it for one cut off by a crash and run it again, every time.
|
|
1099
1150
|
// It stopped rather than redo a recorded effect under a newer flow version:
|
|
@@ -1107,7 +1158,9 @@ export class AgentHarness {
|
|
|
1107
1158
|
// A harness that was replaced says nothing about the turn: it is the new
|
|
1108
1159
|
// holder's now, and marking it stopped would keep a wake from resuming it.
|
|
1109
1160
|
const replaced = isLeaseLost(error) || session.lease?.lost === true;
|
|
1110
|
-
|
|
1161
|
+
// An interrupted turn answers its held calls "Cancelled before it ran." in
|
|
1162
|
+
// the history it restarts from: no answer could reach them any more.
|
|
1163
|
+
if (ctx.aborted && !replaced) {
|
|
1111
1164
|
await heldCallsOf(this).clear(ctx.id);
|
|
1112
1165
|
}
|
|
1113
1166
|
if (record && !replaced && ctx.abortReason !== INTERRUPT_REASON) {
|
|
@@ -1118,10 +1171,12 @@ export class AgentHarness {
|
|
|
1118
1171
|
});
|
|
1119
1172
|
// A flow that caught the wait's cancellation and returned is parked all the
|
|
1120
1173
|
// same: the wait it was in has not ended, and the woken turn goes back to it.
|
|
1121
|
-
if (result === PARKED || (await closeOutPark(ctx))) {
|
|
1174
|
+
if (result === CUT || result === PARKED || (await closeOutPark(ctx))) {
|
|
1175
|
+
return '';
|
|
1176
|
+
}
|
|
1177
|
+
if (await this.keepOrCut(session, ctx, () => keepHistory(ctx, result))) {
|
|
1122
1178
|
return '';
|
|
1123
1179
|
}
|
|
1124
|
-
await keepHistory(ctx, result);
|
|
1125
1180
|
this.parkWatchers?.forget(threadId, ctx.id);
|
|
1126
1181
|
await this.announceWakeTimeQuietly();
|
|
1127
1182
|
return result;
|
|
@@ -1145,8 +1200,11 @@ export class AgentHarness {
|
|
|
1145
1200
|
* it knows the event a parked turn waits for has arrived. A turn another harness
|
|
1146
1201
|
* holds, or one already running here, is left alone.
|
|
1147
1202
|
*
|
|
1203
|
+
* A turn that was cut (spec 23 § Cut turns) is due once its back-off is over.
|
|
1204
|
+
*
|
|
1148
1205
|
* A resumed turn replays what it finished and goes on. `options` are the
|
|
1149
|
-
* `execute()` options it runs with; a stored turn keeps none of its own
|
|
1206
|
+
* `execute()` options it runs with; a stored turn keeps none of its own, so
|
|
1207
|
+
* without them the harness asks `AgentHarnessOpts.turnOptions`.
|
|
1150
1208
|
*
|
|
1151
1209
|
* Resolves the ids of the threads it resumed. Durable sessions only.
|
|
1152
1210
|
* @public
|
|
@@ -1163,6 +1221,10 @@ export class AgentHarness {
|
|
|
1163
1221
|
: await this.sessionStore.threads();
|
|
1164
1222
|
const woken = [];
|
|
1165
1223
|
for (const threadId of threadIds) {
|
|
1224
|
+
// A thread being forgotten has no turn left to wake.
|
|
1225
|
+
if (this.forgetting.has(threadId)) {
|
|
1226
|
+
continue;
|
|
1227
|
+
}
|
|
1166
1228
|
// A turn asked for by name may be closing out its park this instant: its
|
|
1167
1229
|
// runner is busy, though nothing is running. Wait for it rather than skip.
|
|
1168
1230
|
const closing = scope?.threadId ? this.sessions.get(threadId)?.runner : undefined;
|
|
@@ -1177,14 +1239,16 @@ export class AgentHarness {
|
|
|
1177
1239
|
// A routine wake leaves alone a parked turn that is not due, one with no
|
|
1178
1240
|
// deadline at all (it waits for an answer, not for a time), and one that
|
|
1179
1241
|
// failed or was cancelled here: only a turn cut off by a crash resumes unasked.
|
|
1180
|
-
const
|
|
1242
|
+
const cut = turn.parked ? undefined : this.cuts?.markOf(threadId, turn);
|
|
1243
|
+
const notDue = (turn.parked && (turn.parked.until === undefined || turn.parked.until > now)) ||
|
|
1244
|
+
(cut !== undefined && this.cuts !== undefined && this.cuts.dueAt(cut) > now);
|
|
1181
1245
|
if (!scope?.threadId && (notDue || (turn.stopped && !turn.parked))) {
|
|
1182
1246
|
// A parked turn found in storage, as at boot, is watched over from here on.
|
|
1183
1247
|
if (turn.parked && this.parkWatchers && !this.parkWatchers.has(threadId)) {
|
|
1184
1248
|
this.parkWatchers.watch(threadId, {
|
|
1185
1249
|
executionId: turn.executionId,
|
|
1186
1250
|
until: turn.parked.until,
|
|
1187
|
-
options: scope?.options
|
|
1251
|
+
options: scope?.options,
|
|
1188
1252
|
});
|
|
1189
1253
|
}
|
|
1190
1254
|
continue;
|
|
@@ -1200,6 +1264,7 @@ export class AgentHarness {
|
|
|
1200
1264
|
if (held && !scope?.threadId) {
|
|
1201
1265
|
continue;
|
|
1202
1266
|
}
|
|
1267
|
+
const options = scope?.options ?? (await this.storedTurnOptions(threadId, turn, cut));
|
|
1203
1268
|
// Re-deliver the turn's own messages: the same ids resume it, and a resumed
|
|
1204
1269
|
// turn reads its input from its checkpoint, not from these. They go back as
|
|
1205
1270
|
// one arrival: handed over one at a time, the first would start a turn of
|
|
@@ -1208,13 +1273,124 @@ export class AgentHarness {
|
|
|
1208
1273
|
id,
|
|
1209
1274
|
input: [],
|
|
1210
1275
|
deliveryMode: 'next-turn',
|
|
1211
|
-
options
|
|
1276
|
+
options,
|
|
1212
1277
|
enqueuedAt: Date.now(),
|
|
1213
1278
|
})));
|
|
1214
1279
|
woken.push(threadId);
|
|
1215
1280
|
}
|
|
1216
1281
|
return woken;
|
|
1217
1282
|
}
|
|
1283
|
+
/**
|
|
1284
|
+
* A turn stopped by `lease_lost` or `ledger_write_failed` is cut, not failed
|
|
1285
|
+
* (spec 23 § Cut turns): its record stays, marked, and a wake runs it again once
|
|
1286
|
+
* its back-off is over. Resolves false when `error` does not cut the turn, or the
|
|
1287
|
+
* turn has been cut as often as it may be and fails instead.
|
|
1288
|
+
*/
|
|
1289
|
+
async closeOutCut(session, ctx, error) {
|
|
1290
|
+
const { record } = session;
|
|
1291
|
+
const { threadId } = session.runner;
|
|
1292
|
+
const reason = this.cuts?.reasonOf(error);
|
|
1293
|
+
if (!reason || !record || !this.cuts || !this.leaseOptions) {
|
|
1294
|
+
return false;
|
|
1295
|
+
}
|
|
1296
|
+
// The storage that refused a write may refuse this read: the mark in memory counts then.
|
|
1297
|
+
const stored = await record.turn().catch(() => undefined);
|
|
1298
|
+
if (reason === 'lease_lost') {
|
|
1299
|
+
return this.closeOutLostLease(threadId, ctx, stored);
|
|
1300
|
+
}
|
|
1301
|
+
const messageIds = stored?.executionId === ctx.id ? stored.messageIds : session.turnMessageIds;
|
|
1302
|
+
const mark = this.cuts.cut(threadId, {
|
|
1303
|
+
messageIds: messageIds ?? [],
|
|
1304
|
+
cut: stored?.executionId === ctx.id ? stored.cut : undefined,
|
|
1305
|
+
}, reason, this.now());
|
|
1306
|
+
if (!mark) {
|
|
1307
|
+
return false;
|
|
1308
|
+
}
|
|
1309
|
+
await record.cut(ctx, mark);
|
|
1310
|
+
// Messages still queued wait in storage, as for a park: one that started a turn
|
|
1311
|
+
// now would throw the cut turn away.
|
|
1312
|
+
const interrupts = [];
|
|
1313
|
+
for (const queued of session.runner.queue.drainAll()) {
|
|
1314
|
+
if (queued.deliveryMode === 'interrupt') {
|
|
1315
|
+
interrupts.push(queued);
|
|
1316
|
+
continue;
|
|
1317
|
+
}
|
|
1318
|
+
await keepForLater(session, record, queued);
|
|
1319
|
+
}
|
|
1320
|
+
for (const interrupt of interrupts.reverse()) {
|
|
1321
|
+
session.runner.queue.prepend(interrupt);
|
|
1322
|
+
}
|
|
1323
|
+
this.cutOfContext.set(ctx, {
|
|
1324
|
+
reason,
|
|
1325
|
+
attempt: mark.count,
|
|
1326
|
+
wakeAt: this.cuts.dueAt(mark),
|
|
1327
|
+
});
|
|
1328
|
+
// Before the turn answers as cut: whoever wakes it has to know when.
|
|
1329
|
+
await this.announceWakeTimeQuietly();
|
|
1330
|
+
return true;
|
|
1331
|
+
}
|
|
1332
|
+
/**
|
|
1333
|
+
* Another holder took the turn (spec 23 § Cut turns, A replaced harness). The
|
|
1334
|
+
* turn is theirs: this harness writes nothing to it, counts nothing, and leaves
|
|
1335
|
+
* its own queue alone. It is cut only while it is still on record under this
|
|
1336
|
+
* execution, when a wake can pick it up should that holder die; otherwise the
|
|
1337
|
+
* other holder ended it, and the response fails as before.
|
|
1338
|
+
*/
|
|
1339
|
+
async closeOutLostLease(threadId, ctx, stored) {
|
|
1340
|
+
if (!this.leaseOptions || stored?.executionId !== ctx.id || stored.parked || stored.stopped) {
|
|
1341
|
+
return false;
|
|
1342
|
+
}
|
|
1343
|
+
const heldUntil = await heldElsewhereUntil(this.leaseOptions, threadId).catch(() => undefined);
|
|
1344
|
+
this.cutOfContext.set(ctx, {
|
|
1345
|
+
reason: 'lease_lost',
|
|
1346
|
+
wakeAt: heldUntil ?? this.now(),
|
|
1347
|
+
});
|
|
1348
|
+
await this.announceWakeTimeQuietly();
|
|
1349
|
+
return true;
|
|
1350
|
+
}
|
|
1351
|
+
/**
|
|
1352
|
+
* Record the end of a turn whose work is done. Resolves true when that write was
|
|
1353
|
+
* refused and the turn was cut instead: a wake replays it to here.
|
|
1354
|
+
*/
|
|
1355
|
+
async keepOrCut(session, ctx, keep) {
|
|
1356
|
+
try {
|
|
1357
|
+
await keep();
|
|
1358
|
+
return false;
|
|
1359
|
+
}
|
|
1360
|
+
catch (error) {
|
|
1361
|
+
if (await this.closeOutCut(session, ctx, error)) {
|
|
1362
|
+
return true;
|
|
1363
|
+
}
|
|
1364
|
+
this.cuts?.forget(session.runner.threadId);
|
|
1365
|
+
throw error;
|
|
1366
|
+
}
|
|
1367
|
+
}
|
|
1368
|
+
/** The options a stored turn is woken with when the wake names none: `turnOptions`, or none. */
|
|
1369
|
+
async storedTurnOptions(threadId, turn, cut) {
|
|
1370
|
+
if (!this.turnOptionsFor) {
|
|
1371
|
+
return {};
|
|
1372
|
+
}
|
|
1373
|
+
return await this.turnOptionsFor({
|
|
1374
|
+
threadId,
|
|
1375
|
+
executionId: turn.executionId,
|
|
1376
|
+
messageIds: turn.messageIds,
|
|
1377
|
+
...(turn.version === undefined
|
|
1378
|
+
? {}
|
|
1379
|
+
: {
|
|
1380
|
+
version: turn.version,
|
|
1381
|
+
}),
|
|
1382
|
+
...(turn.parked
|
|
1383
|
+
? {
|
|
1384
|
+
parked: turn.parked,
|
|
1385
|
+
}
|
|
1386
|
+
: {}),
|
|
1387
|
+
...(cut
|
|
1388
|
+
? {
|
|
1389
|
+
cut,
|
|
1390
|
+
}
|
|
1391
|
+
: {}),
|
|
1392
|
+
});
|
|
1393
|
+
}
|
|
1218
1394
|
/**
|
|
1219
1395
|
* The earliest time the harness has something to do, in epoch ms: a parked turn
|
|
1220
1396
|
* that needs waking, or the next event of a scheduled source a trigger listens
|
|
@@ -1254,15 +1430,17 @@ export class AgentHarness {
|
|
|
1254
1430
|
return undefined;
|
|
1255
1431
|
}
|
|
1256
1432
|
// A turn with no park on record is cut off, unless it is simply running here.
|
|
1257
|
-
// (One that is parked may still be closing out in this process: it counts.)
|
|
1433
|
+
// (One that is parked, or cut, may still be closing out in this process: it counts.)
|
|
1258
1434
|
const runner = this.sessions.get(threadId)?.runner;
|
|
1259
|
-
|
|
1435
|
+
const closingCut = runner?.context !== undefined && this.cutOfContext.has(runner.context);
|
|
1436
|
+
if (!turn.parked && runner && runner.getStatus().kind !== 'idle' && !closingCut) {
|
|
1260
1437
|
// Running here. Should this process die, the turn is cut off, and it can be
|
|
1261
1438
|
// picked up once the lease it held has run out: that is when to look again.
|
|
1262
1439
|
// The turn ending, or parking, replaces this time with the real one.
|
|
1263
1440
|
return this.leaseOptions ? now + this.leaseOptions.ttlMs + LEASE_WAIT_MARGIN_MS : undefined;
|
|
1264
1441
|
}
|
|
1265
|
-
const
|
|
1442
|
+
const cut = turn.parked ? undefined : this.cuts?.markOf(threadId, turn);
|
|
1443
|
+
const due = turn.parked?.until ?? (cut && this.cuts ? this.cuts.dueAt(cut) : now);
|
|
1266
1444
|
const heldUntil = this.leaseOptions
|
|
1267
1445
|
? await heldElsewhereUntil(this.leaseOptions, threadId)
|
|
1268
1446
|
: undefined;
|
|
@@ -1320,7 +1498,29 @@ export class AgentHarness {
|
|
|
1320
1498
|
if (scope && 'executionId' in scope) {
|
|
1321
1499
|
return;
|
|
1322
1500
|
}
|
|
1323
|
-
|
|
1501
|
+
await this.wakeAnswered(scope?.threadId ?? DEFAULT_THREAD_ID, options);
|
|
1502
|
+
}
|
|
1503
|
+
/**
|
|
1504
|
+
* An `onHeld` handler's answer: for the execution that held the call, never for a
|
|
1505
|
+
* later turn on the same thread. Wakes the thread's turn when it is that execution.
|
|
1506
|
+
* @internal
|
|
1507
|
+
*/
|
|
1508
|
+
async answerHeld(answer) {
|
|
1509
|
+
await heldCallsOf(this).resolve(answer.executionId, {
|
|
1510
|
+
callId: answer.callId,
|
|
1511
|
+
argsHash: answer.argsHash,
|
|
1512
|
+
resolution: answer.resolution,
|
|
1513
|
+
});
|
|
1514
|
+
if (answer.threadId === undefined) {
|
|
1515
|
+
return;
|
|
1516
|
+
}
|
|
1517
|
+
if ((await this.turnExecutionId(answer.threadId)) !== answer.executionId) {
|
|
1518
|
+
return;
|
|
1519
|
+
}
|
|
1520
|
+
await this.wakeAnswered(answer.threadId);
|
|
1521
|
+
}
|
|
1522
|
+
/** A thread's turn was answered: resume it if parked, now or once it comes to rest. */
|
|
1523
|
+
async wakeAnswered(threadId, options) {
|
|
1324
1524
|
const runner = this.sessions.get(threadId)?.runner;
|
|
1325
1525
|
if (runner?.context === undefined) {
|
|
1326
1526
|
await this.wake({
|
|
@@ -1412,13 +1612,27 @@ export class AgentHarness {
|
|
|
1412
1612
|
});
|
|
1413
1613
|
return true;
|
|
1414
1614
|
}
|
|
1615
|
+
/**
|
|
1616
|
+
* The tool calls a resume of `executionId` goes on from rather than having the
|
|
1617
|
+
* model ask for them again: every call whose request its step ledger holds, in a
|
|
1618
|
+
* completed step or a recorded round, read from storage. `settled` says whether
|
|
1619
|
+
* the call's result is on record too; an unsettled call runs again on resume (spec
|
|
1620
|
+
* 23a § Tool calls in a round). A host that journals tool traffic of its own adds
|
|
1621
|
+
* none of these to a restored context, or the model sees them twice. Empty without
|
|
1622
|
+
* durable storage.
|
|
1623
|
+
* @public
|
|
1624
|
+
*/
|
|
1625
|
+
async recordedToolCalls(executionId) {
|
|
1626
|
+
const window = await this.stepLedgerStore?.load(executionId);
|
|
1627
|
+
return window ? recordedToolCalls(window) : [];
|
|
1628
|
+
}
|
|
1415
1629
|
/**
|
|
1416
1630
|
* What a run did, step by step: who ran each step, under which flow version, and
|
|
1417
1631
|
* the receipt of a step with a lasting effect (spec 23 § The trail). Marks outlive
|
|
1418
1632
|
* the ledger entries they came from, so the trail of a finished run stays readable.
|
|
1419
1633
|
*
|
|
1420
|
-
* `scope` names an execution, or a thread, whose
|
|
1421
|
-
*
|
|
1634
|
+
* `scope` names an execution, or a thread, whose turns are then listed in order:
|
|
1635
|
+
* every turn it began, two reads per turn.
|
|
1422
1636
|
* @public
|
|
1423
1637
|
*/
|
|
1424
1638
|
async getAuditTrail(scope) {
|
|
@@ -1450,6 +1664,129 @@ export class AgentHarness {
|
|
|
1450
1664
|
return marks;
|
|
1451
1665
|
}
|
|
1452
1666
|
//#endregion
|
|
1667
|
+
//#region Forgetting
|
|
1668
|
+
/**
|
|
1669
|
+
* Delete everything the harness keeps for a thread or an execution, so a host never
|
|
1670
|
+
* builds a storage key itself (spec 23 § Forgetting).
|
|
1671
|
+
*
|
|
1672
|
+
* A thread's forget covers every execution the thread ran, its context-layer state,
|
|
1673
|
+
* display output, record and turn lease. An execution's forget covers what is stored
|
|
1674
|
+
* under it and its layer state, and leaves any thread's record alone. Pending spend
|
|
1675
|
+
* is settled first: priced through the provider, waiting up to `patienceMs`, else
|
|
1676
|
+
* written off at its ceiling (at 0, flagged `unbounded`, when it has none). The trail
|
|
1677
|
+
* goes too unless `keepTrail`.
|
|
1678
|
+
*
|
|
1679
|
+
* A thread's forget holds and renews the thread's lease until it is done, and a
|
|
1680
|
+
* message sent to the thread on this harness meanwhile waits for it, then starts
|
|
1681
|
+
* the thread afresh.
|
|
1682
|
+
*
|
|
1683
|
+
* @throws NoeticError `lease_lost` when the thread has a turn running, queued or
|
|
1684
|
+
* being delivered in this harness, is already being forgotten, or the execution
|
|
1685
|
+
* has a run in flight; when another harness still holds the thread's lease after
|
|
1686
|
+
* `waitMs`; or when the lease is lost part way.
|
|
1687
|
+
* @throws NoeticError `ledger_write_failed` when a spend record could not be
|
|
1688
|
+
* settled; nothing was deleted.
|
|
1689
|
+
* @throws NoeticConfigError `INVALID_FORGET_SCOPE` for a scope with neither id.
|
|
1690
|
+
* @public
|
|
1691
|
+
*/
|
|
1692
|
+
async forget(scope, options) {
|
|
1693
|
+
if ('executionId' in scope) {
|
|
1694
|
+
return forgetExecution(this.forgetHost(), scope.executionId, options);
|
|
1695
|
+
}
|
|
1696
|
+
const threadId = scope.threadId;
|
|
1697
|
+
if (typeof threadId !== 'string' || threadId === '') {
|
|
1698
|
+
throw new NoeticConfigError({
|
|
1699
|
+
code: 'INVALID_FORGET_SCOPE',
|
|
1700
|
+
message: 'harness.forget() needs a threadId or an executionId.',
|
|
1701
|
+
hint: 'Pass { threadId } to forget a thread, or { executionId } to forget one execution.',
|
|
1702
|
+
});
|
|
1703
|
+
}
|
|
1704
|
+
const running = this.forgetting.get(threadId);
|
|
1705
|
+
if (running) {
|
|
1706
|
+
throw new NoeticErrorImpl({
|
|
1707
|
+
kind: 'lease_lost',
|
|
1708
|
+
executionId: threadId,
|
|
1709
|
+
term: 0,
|
|
1710
|
+
reason: `thread "${threadId}" is already being forgotten`,
|
|
1711
|
+
});
|
|
1712
|
+
}
|
|
1713
|
+
const forgetting = forgetThread(this.forgetHost(), threadId, options);
|
|
1714
|
+
this.forgetting.set(threadId, forgetting.catch(() => undefined));
|
|
1715
|
+
try {
|
|
1716
|
+
return await forgetting;
|
|
1717
|
+
}
|
|
1718
|
+
finally {
|
|
1719
|
+
this.forgetting.delete(threadId);
|
|
1720
|
+
this.cuts?.forget(threadId);
|
|
1721
|
+
await this.announceWakeTimeQuietly();
|
|
1722
|
+
}
|
|
1723
|
+
}
|
|
1724
|
+
/**
|
|
1725
|
+
* Every thread with a record, a turn lease, or display output stored: what
|
|
1726
|
+
* `forget({ threadId })` deletes. Sorted; `prefix` narrows to ids that start with it.
|
|
1727
|
+
* @public
|
|
1728
|
+
*/
|
|
1729
|
+
async listStoredThreads(options) {
|
|
1730
|
+
return listStoredThreads(this.forgetHost(), options);
|
|
1731
|
+
}
|
|
1732
|
+
/**
|
|
1733
|
+
* Every execution with anything stored, with what is stored for it. `resumable` is
|
|
1734
|
+
* set when a snapshot or ledger entries are: a trail alone is not a checkpoint.
|
|
1735
|
+
* Sorted; `prefix` narrows to ids that start with it.
|
|
1736
|
+
* @public
|
|
1737
|
+
*/
|
|
1738
|
+
async listStoredExecutions(options) {
|
|
1739
|
+
return listStoredExecutions(this.forgetHost(), options);
|
|
1740
|
+
}
|
|
1741
|
+
forgetHost() {
|
|
1742
|
+
return {
|
|
1743
|
+
storage: this.config.storage,
|
|
1744
|
+
outputStorage: this.outputStorage,
|
|
1745
|
+
checkpointStore: this.checkpointStore,
|
|
1746
|
+
sessionStore: this.sessionStore,
|
|
1747
|
+
leaseOptions: this.leaseOptions,
|
|
1748
|
+
threadBusy: (threadId) => {
|
|
1749
|
+
const session = this.sessions.get(threadId);
|
|
1750
|
+
if (!session) {
|
|
1751
|
+
return false;
|
|
1752
|
+
}
|
|
1753
|
+
return (session.lease !== undefined ||
|
|
1754
|
+
session.runner.context !== undefined ||
|
|
1755
|
+
session.runner.getStatus().kind !== 'idle' ||
|
|
1756
|
+
session.runner.queue.size > 0 ||
|
|
1757
|
+
(session.arriving ?? 0) > 0);
|
|
1758
|
+
},
|
|
1759
|
+
executionBusy: (executionId) => this.liveRoots.has(executionId),
|
|
1760
|
+
closeSpend: async (owns, patienceMs) => (await this.spend?.close(owns, patienceMs)) ?? [],
|
|
1761
|
+
clearCheckpoint: (executionId) => this.clearCheckpoint(executionId),
|
|
1762
|
+
settleOutput: async (threadId) => {
|
|
1763
|
+
const output = this.outputs.get(threadId);
|
|
1764
|
+
this.outputs.delete(threadId);
|
|
1765
|
+
await output?.flush().catch(() => undefined);
|
|
1766
|
+
},
|
|
1767
|
+
dropThread: (threadId) => {
|
|
1768
|
+
this.parkWatchers?.stop(threadId);
|
|
1769
|
+
this.sessions.delete(threadId);
|
|
1770
|
+
},
|
|
1771
|
+
layerIds: () => this.layerIds(),
|
|
1772
|
+
releaseConnections: (executionId) => this.#connections.registry.releaseRun(executionId),
|
|
1773
|
+
subprocess: this.subprocess,
|
|
1774
|
+
harness: this,
|
|
1775
|
+
};
|
|
1776
|
+
}
|
|
1777
|
+
/** Ids of the layers that may keep durable state: this harness's thread-wide layers, and any it has kept state for. */
|
|
1778
|
+
layerIds() {
|
|
1779
|
+
const ids = new Set(this.durableLayerIds);
|
|
1780
|
+
for (const layer of this._contextLayers ?? []) {
|
|
1781
|
+
if (layer.scope !== 'execution') {
|
|
1782
|
+
ids.add(layer.id);
|
|
1783
|
+
}
|
|
1784
|
+
}
|
|
1785
|
+
return [
|
|
1786
|
+
...ids,
|
|
1787
|
+
];
|
|
1788
|
+
}
|
|
1789
|
+
//#endregion
|
|
1453
1790
|
//#region Triggers
|
|
1454
1791
|
/**
|
|
1455
1792
|
* Add a trigger while the harness runs (spec 35 § Triggers). A trigger written
|
|
@@ -1533,7 +1870,8 @@ export class AgentHarness {
|
|
|
1533
1870
|
*/
|
|
1534
1871
|
async setAside(session, record, messages) {
|
|
1535
1872
|
const turn = await record.turn();
|
|
1536
|
-
|
|
1873
|
+
const cut = turn ? this.cuts?.markOf(session.runner.threadId, turn) : undefined;
|
|
1874
|
+
if (!turn || (!turn.parked && !turn.stuck && !cut)) {
|
|
1537
1875
|
return false;
|
|
1538
1876
|
}
|
|
1539
1877
|
if (messages.some((message) => message.deliveryMode === 'interrupt')) {
|
|
@@ -1664,6 +2002,21 @@ export class AgentHarness {
|
|
|
1664
2002
|
}
|
|
1665
2003
|
return true;
|
|
1666
2004
|
}
|
|
2005
|
+
/**
|
|
2006
|
+
* The thread whose turn `ctx` runs in, or `undefined` for a run the host started
|
|
2007
|
+
* itself. Where an `onHeld` answer goes.
|
|
2008
|
+
* @internal
|
|
2009
|
+
*/
|
|
2010
|
+
heldThreadOf(ctx) {
|
|
2011
|
+
const executionId = rootIdOf(ctx);
|
|
2012
|
+
for (const [threadId, session] of this.sessions) {
|
|
2013
|
+
const running = session.runner.context;
|
|
2014
|
+
if (running && rootIdOf(running) === executionId) {
|
|
2015
|
+
return threadId;
|
|
2016
|
+
}
|
|
2017
|
+
}
|
|
2018
|
+
return undefined;
|
|
2019
|
+
}
|
|
1667
2020
|
/** The execution whose held calls `scope` names. */
|
|
1668
2021
|
heldExecutionId(scope) {
|
|
1669
2022
|
if (scope && 'executionId' in scope) {
|
|
@@ -1701,6 +2054,7 @@ export class AgentHarness {
|
|
|
1701
2054
|
restore: (executionId, opts) => this.restore(executionId, opts),
|
|
1702
2055
|
clearCheckpoint: (executionId) => this.clearCheckpoint(executionId),
|
|
1703
2056
|
parseItems: (raw) => this.itemSchemas.parseMany(raw),
|
|
2057
|
+
layerIds: () => this.layerIds(),
|
|
1704
2058
|
}, threadId);
|
|
1705
2059
|
}
|
|
1706
2060
|
requireSession(scope) {
|
|
@@ -1741,16 +2095,6 @@ export class AgentHarness {
|
|
|
1741
2095
|
callId: request.callId,
|
|
1742
2096
|
ctx: request.ctx,
|
|
1743
2097
|
park: request.park,
|
|
1744
|
-
onHeld: (held) => {
|
|
1745
|
-
emitFrameworkEvent({
|
|
1746
|
-
broadcaster: getBroadcaster(request.ctx),
|
|
1747
|
-
agentName: this.config.name,
|
|
1748
|
-
eventType: 'tool_call_held',
|
|
1749
|
-
data: {
|
|
1750
|
-
...held,
|
|
1751
|
-
},
|
|
1752
|
-
});
|
|
1753
|
-
},
|
|
1754
2098
|
});
|
|
1755
2099
|
return approval.decision;
|
|
1756
2100
|
}
|
|
@@ -2152,6 +2496,16 @@ export class AgentHarness {
|
|
|
2152
2496
|
return this.channelStore.subscribe(channel, executionId);
|
|
2153
2497
|
}
|
|
2154
2498
|
/** Resolves layer-provided tools and merges with step tools into ctx.unifiedTools. */
|
|
2499
|
+
/** The tools a session turn offers: its own first (one named like another replaces it), then the flow's, the harness's and its connections'. */
|
|
2500
|
+
setTurnTools(ctx, turnTools, connectionTools) {
|
|
2501
|
+
const stepTools = this.agentGraph ? collectAllTools(this.agentGraph) : [];
|
|
2502
|
+
this.setUnifiedTools(ctx, [
|
|
2503
|
+
...turnTools,
|
|
2504
|
+
...stepTools,
|
|
2505
|
+
...this.harnessTools,
|
|
2506
|
+
...connectionTools,
|
|
2507
|
+
]);
|
|
2508
|
+
}
|
|
2155
2509
|
setUnifiedTools(ctx, stepTools) {
|
|
2156
2510
|
const layers = ctx.layers;
|
|
2157
2511
|
const layerTools = layers && layers.length > 0 ? resolveLayerTools(layers, this, ctx) : [];
|