@noetic-tools/core 5.21.0 → 5.22.0-next.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapters/openrouter.d.ts +6 -1
- package/dist/adapters/openrouter.js +10 -0
- package/dist/builders/decide-builders.d.ts +7 -0
- package/dist/builders/tool-builder.d.ts +25 -1
- package/dist/builders/tool-builder.js +25 -1
- package/dist/builders/workflow-control-nodes.js +1 -0
- package/dist/builders/workflow-hydrator.d.ts +19 -0
- package/dist/builders/workflow-hydrator.js +19 -0
- package/dist/builders/workflow-step.js +7 -1
- package/dist/connections/cron-schedule.js +12 -3
- package/dist/connections/durability.d.ts +1 -2
- package/dist/connections/durability.js +1 -4
- package/dist/connections/gates.js +6 -2
- package/dist/connections/harness-wiring.d.ts +5 -0
- package/dist/connections/harness-wiring.js +76 -10
- package/dist/connections/in-memory-connection.d.ts +4 -0
- package/dist/connections/in-memory-connection.js +10 -0
- package/dist/connections/model-tools.js +5 -1
- package/dist/connections/registry.d.ts +6 -2
- package/dist/connections/registry.js +10 -0
- package/dist/connections/sources.js +261 -20
- package/dist/connections/triggers.d.ts +62 -2
- package/dist/connections/triggers.js +375 -35
- package/dist/harness/agent-harness.d.ts +317 -4
- package/dist/harness/agent-harness.js +1264 -96
- package/dist/harness/connection-gate.d.ts +3 -0
- package/dist/harness/connection-gate.js +4 -0
- package/dist/harness/decide-call.d.ts +15 -0
- package/dist/harness/decide-call.js +57 -7
- package/dist/harness/deps/runtime.d.ts +3 -0
- package/dist/harness/deps/runtime.js +2 -0
- package/dist/harness/flow-version.d.ts +13 -0
- package/dist/harness/flow-version.js +66 -0
- package/dist/harness/harness-options.d.ts +91 -0
- package/dist/harness/llm-client.d.ts +2 -0
- package/dist/harness/llm-client.js +9 -5
- package/dist/harness/model-call.js +8 -0
- package/dist/harness/model-rounds.d.ts +30 -0
- package/dist/harness/model-rounds.js +146 -1
- package/dist/harness/model-tool-round.d.ts +3 -0
- package/dist/harness/model-tool-round.js +249 -22
- package/dist/harness/park-watchers.d.ts +93 -0
- package/dist/harness/park-watchers.js +217 -0
- package/dist/harness/read-decision.d.ts +23 -0
- package/dist/harness/read-decision.js +100 -0
- package/dist/harness/spend.js +4 -0
- package/dist/harness/steer-inbox.js +3 -1
- package/dist/harness/thread-record.d.ts +77 -1
- package/dist/harness/thread-record.js +272 -13
- package/dist/index.d.ts +22 -8
- package/dist/index.js +12 -2
- package/dist/interpreter/acp-resume.d.ts +77 -0
- package/dist/interpreter/acp-resume.js +164 -0
- package/dist/interpreter/acp-tools.d.ts +11 -0
- package/dist/interpreter/acp-tools.js +94 -7
- package/dist/interpreter/connection-steps.d.ts +24 -1
- package/dist/interpreter/connection-steps.js +77 -2
- package/dist/interpreter/execute-acp-agent.js +111 -15
- package/dist/interpreter/execute-action.js +7 -0
- package/dist/interpreter/execute-call.js +30 -4
- package/dist/interpreter/execute-control.js +21 -0
- package/dist/interpreter/execute-decide.js +5 -0
- package/dist/interpreter/execute-invoke-tool.js +149 -5
- package/dist/interpreter/execute-wait.js +67 -9
- package/dist/interpreter/execute.js +4 -0
- package/dist/interpreter/turn-ending.d.ts +15 -0
- package/dist/interpreter/turn-ending.js +46 -0
- package/dist/portable/builders.d.ts +1 -1
- package/dist/portable/builders.js +1 -1
- package/dist/portable/runtime.d.ts +4 -0
- package/dist/portable/runtime.js +2 -0
- package/dist/runtime/durable/parking.d.ts +61 -0
- package/dist/runtime/durable/parking.js +137 -0
- package/dist/runtime/durable/session-store.d.ts +38 -0
- package/dist/runtime/durable/session-store.js +79 -1
- package/dist/runtime/durable/step-ledger.d.ts +121 -2
- package/dist/runtime/durable/step-ledger.js +352 -15
- package/dist/runtime/durable/turn-lease.d.ts +128 -0
- package/dist/runtime/durable/turn-lease.js +307 -0
- package/dist/runtime/event-broadcaster.d.ts +9 -1
- package/dist/runtime/event-broadcaster.js +16 -1
- package/dist/runtime/held-calls.d.ts +192 -0
- package/dist/runtime/held-calls.js +496 -0
- package/dist/runtime/in-memory-storage.d.ts +10 -1
- package/dist/runtime/in-memory-storage.js +20 -2
- package/dist/runtime/message-queue.d.ts +2 -0
- package/dist/runtime/message-queue.js +8 -0
- package/dist/runtime/output-store.d.ts +88 -0
- package/dist/runtime/output-store.js +241 -0
- package/dist/runtime/session-runner.d.ts +18 -2
- package/dist/runtime/session-runner.js +88 -3
- package/dist/runtime/session-streams.d.ts +28 -7
- package/dist/runtime/session-streams.js +112 -67
- package/dist/runtime/tool-approval.d.ts +46 -6
- package/dist/runtime/tool-approval.js +160 -38
- package/dist/runtime/tool-call.d.ts +34 -2
- package/dist/runtime/tool-call.js +182 -13
- package/dist/runtime/tool-context.d.ts +15 -1
- package/dist/runtime/tool-context.js +38 -2
- package/package.json +3 -3
- package/schema/noetic-workflow.schema.json +27 -0
|
@@ -1,20 +1,100 @@
|
|
|
1
|
-
import { CONNECTION_EVENT_ITEM_TYPE, frameworkCast, ItemSchemaRegistry, NoeticConfigError, } from '@noetic-tools/types';
|
|
1
|
+
import { CONNECTION_EVENT_ITEM_TYPE, frameworkCast, ItemSchemaRegistry, isDecisionItem, isNoeticError, NoeticConfigError, NoeticErrorImpl, } from '@noetic-tools/types';
|
|
2
2
|
import { toStep } from '../builders/sequence.js';
|
|
3
3
|
import { runEvery } from '../connections/settle.js';
|
|
4
|
+
import { pendingTasksOf, resumableWaitsOf } from '../interpreter/connection-steps.js';
|
|
5
|
+
import { turnEndingIn } from '../interpreter/turn-ending.js';
|
|
4
6
|
import { AcpSessionStore } from '../runtime/acp-session-store.js';
|
|
7
|
+
import { emitFrameworkEvent, getBroadcaster } from '../runtime/broadcaster-utils.js';
|
|
8
|
+
import { stubOf } from '../runtime/durable/step-ledger.js';
|
|
9
|
+
import { heldCallsOf, toHeldCall } from '../runtime/held-calls.js';
|
|
10
|
+
import { OutputStore } from '../runtime/output-store.js';
|
|
11
|
+
import { awaitApproval } from '../runtime/tool-approval.js';
|
|
5
12
|
import { ConnectionGate } from './connection-gate.js';
|
|
6
13
|
import { afterModelCallLayers, allocateBudgets, assembleView, beforeToolCallLayers, completeLayers, contextToExecCtx, createContextCacheStore, createLayerStateStore, createRecallCache, DEFAULT_PROJECTION, disposeLayers, executeRerender, initLayers, notifyDecision, onSteerLayers, projectHistoryLayers, recallLayers, recallLayersAtomic, recallLayersEventual, resolveLayerTools, runAppendPipeline, storeLayers, } from './deps/context.js';
|
|
7
14
|
import { clearPendingEntries, collectAllTools, collectCustomItems, deduplicateTools, dispatchStepThroughAdapter, execute, isRootRunning, prepareBandedView, runRootOf, } from './deps/interpreter.js';
|
|
8
|
-
import { buildItemStream, ChannelStore, ContextImpl, captureCheckpoint, clearCheckpoint, collectContextTree, createInMemoryStorage, createSessionStore, createSpendLog, createStepLedgerStore, customItemGates, Drains, filterReasoningStream, filterTextStream, INTERRUPT_REASON, isSteer, resolveStepLedgerRetention, restoreFromCheckpoint, rootIdOf, SessionRunner, StepLedger, snapshotCwdState, } from './deps/runtime.js';
|
|
15
|
+
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';
|
|
9
16
|
import { SteeringAction } from './deps/types.js';
|
|
17
|
+
import { flowVersionOf } from './flow-version.js';
|
|
10
18
|
import { resolveCheckpointStore, resolveEnvironmentAdapters } from './harness-options.js';
|
|
11
19
|
import { createHarnessSpan, recordChannelWarning, resolveTraceExporter } from './harness-tracing.js';
|
|
12
20
|
import { LlmGateway } from './llm-client.js';
|
|
13
21
|
import { buildItemSchemaRegistry } from './model-schema.js';
|
|
22
|
+
import { DEFAULT_TASK_POLL_MS, DEFAULT_WAKE_DEBOUNCE_MS, ParkWatchers } from './park-watchers.js';
|
|
23
|
+
import { readDecision } from './read-decision.js';
|
|
14
24
|
import { Spend } from './spend.js';
|
|
15
25
|
import { ThreadRecord } from './thread-record.js';
|
|
26
|
+
/** Keep `message` in storage for after the thread's parked turn, with its options. */
|
|
27
|
+
function keepForLater(session, record, message) {
|
|
28
|
+
session.keptOptions.set(message.id, message.options);
|
|
29
|
+
return record.keepQueued(message);
|
|
30
|
+
}
|
|
16
31
|
//#endregion
|
|
17
32
|
const DEFAULT_THREAD_ID = '__default__';
|
|
33
|
+
/** What a `turn_stuck` error says about where the turn stopped, or undefined for any other error. */
|
|
34
|
+
function stuckOf(error) {
|
|
35
|
+
const ending = turnEndingIn(error)?.noeticError;
|
|
36
|
+
if (ending?.kind !== 'turn_stuck') {
|
|
37
|
+
return undefined;
|
|
38
|
+
}
|
|
39
|
+
const { path, from, to } = ending;
|
|
40
|
+
return {
|
|
41
|
+
path,
|
|
42
|
+
from,
|
|
43
|
+
to,
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
/** True when `execute()` was handed a list. `Array.isArray` does not narrow a readonly one. */
|
|
47
|
+
function isItemList(input) {
|
|
48
|
+
return Array.isArray(input);
|
|
49
|
+
}
|
|
50
|
+
function isLeaseLost(error) {
|
|
51
|
+
return isNoeticError(error) && error.noeticError.kind === 'lease_lost';
|
|
52
|
+
}
|
|
53
|
+
/** Added to the lease period for the default wait on a held lease. */
|
|
54
|
+
const LEASE_WAIT_MARGIN_MS = 1e3;
|
|
55
|
+
/** What a turn's run resolves to when it parked instead of finishing. */
|
|
56
|
+
const PARKED = Symbol('parked');
|
|
57
|
+
/** When the turn on `ctx` parked until, or undefined when it did not park. */
|
|
58
|
+
function parkedUntil(ctx) {
|
|
59
|
+
if (ctx.abortReason !== PARK_REASON || !(ctx instanceof ContextImpl)) {
|
|
60
|
+
return undefined;
|
|
61
|
+
}
|
|
62
|
+
return ctx.ledger?.parking.parkedUntil;
|
|
63
|
+
}
|
|
64
|
+
/** The grace before a turn parks, or undefined when parking is off. */
|
|
65
|
+
function resolveParkGrace(park) {
|
|
66
|
+
if (!park) {
|
|
67
|
+
return undefined;
|
|
68
|
+
}
|
|
69
|
+
return park === true ? DEFAULT_PARK_GRACE_MS : (park.graceMs ?? DEFAULT_PARK_GRACE_MS);
|
|
70
|
+
}
|
|
71
|
+
/** Lease settings for sessions on `storage`, or none when it cannot compare-and-set. */
|
|
72
|
+
function resolveLeaseOptions(storage, config) {
|
|
73
|
+
if (!canSwap(storage)) {
|
|
74
|
+
return undefined;
|
|
75
|
+
}
|
|
76
|
+
const ttlMs = config?.ttlMs ?? DEFAULT_LEASE_TTL_MS;
|
|
77
|
+
// One lease period, and a little more: a dead holder's lease runs out in that time.
|
|
78
|
+
const waitMs = config?.waitMs ?? ttlMs + LEASE_WAIT_MARGIN_MS;
|
|
79
|
+
// A lease of no length is lost before the turn's first write; one that never
|
|
80
|
+
// ends is never taken over.
|
|
81
|
+
const ttlOk = Number.isFinite(ttlMs) && ttlMs > 0;
|
|
82
|
+
const waitOk = Number.isFinite(waitMs) && waitMs >= 0;
|
|
83
|
+
if (!ttlOk || !waitOk || config?.holder === '') {
|
|
84
|
+
throw new NoeticConfigError({
|
|
85
|
+
code: 'INVALID_LEASE_OPTIONS',
|
|
86
|
+
message: `environment.storage.lease is not usable: ttlMs ${ttlMs}, waitMs ${waitMs}, holder ${JSON.stringify(config?.holder)}.`,
|
|
87
|
+
hint: 'Give ttlMs a finite number of milliseconds above 0, waitMs a finite number from 0 up, and holder a non-empty name, or leave them out for the defaults.',
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
return {
|
|
91
|
+
storage,
|
|
92
|
+
holder: config?.holder ?? crypto.randomUUID(),
|
|
93
|
+
ttlMs,
|
|
94
|
+
waitMs,
|
|
95
|
+
now: config?.now ?? Date.now,
|
|
96
|
+
};
|
|
97
|
+
}
|
|
18
98
|
/** Default idle-timeout for a single model call's streaming response. Chosen to be
|
|
19
99
|
* long enough that slow models aren't falsely aborted, but short enough that a
|
|
20
100
|
* stalled SSE becomes a visible error rather than a silent hang. */
|
|
@@ -98,10 +178,34 @@ export class AgentHarness {
|
|
|
98
178
|
liveRoots = new Map();
|
|
99
179
|
/** Stored sessions for `execute()` threads. Present exactly when durability is on. */
|
|
100
180
|
sessionStore;
|
|
181
|
+
/** Set when sessions are durable and storage can compare-and-set. */
|
|
182
|
+
leaseOptions;
|
|
183
|
+
/** The flow version this harness runs, when the host names one. */
|
|
184
|
+
version;
|
|
185
|
+
/** Set when turns park (`environment.storage.park`): the grace before one does. */
|
|
186
|
+
parkGraceMs;
|
|
187
|
+
/** Set when this harness wakes the turns it parked (`park.autoWake`). */
|
|
188
|
+
parkWatchers;
|
|
189
|
+
/** Who hears when the next wake time changes (`onWakeTimeChange`). */
|
|
190
|
+
wakeTimeListeners = new Set();
|
|
191
|
+
/** The wake time listeners last heard; `null` until they have heard one. */
|
|
192
|
+
announcedWakeTime = null;
|
|
193
|
+
/** The announcement in flight, so two never run out of order. */
|
|
194
|
+
announcing = Promise.resolve();
|
|
101
195
|
/** Checkpoint capture in flight per execution id — see `saveCheckpoint`. */
|
|
102
196
|
pendingCheckpoints = new Map();
|
|
103
197
|
defaultDeliveryMode;
|
|
104
198
|
sessions = new Map();
|
|
199
|
+
/** Whether threads keep their streamed output for display (`opts.interactive`). */
|
|
200
|
+
interactive;
|
|
201
|
+
/** Where display output is kept: the harness's storage, or memory without one. */
|
|
202
|
+
outputStorage;
|
|
203
|
+
/** The display output each thread of an interactive harness records, by thread id. */
|
|
204
|
+
outputs = new Map();
|
|
205
|
+
/** Thread id → what stops recording it. */
|
|
206
|
+
stopRecording = new Map();
|
|
207
|
+
/** Threads named by a host-built context's own id, dropped when its run ends. */
|
|
208
|
+
ownThreads = new Set();
|
|
105
209
|
/**
|
|
106
210
|
* @internal Live ACP connections. Reached by the interpreter via
|
|
107
211
|
* `frameworkCast`; use {@link listAcpSessions}, {@link getAcpSession},
|
|
@@ -190,6 +294,7 @@ export class AgentHarness {
|
|
|
190
294
|
* access from outside core. */
|
|
191
295
|
itemSchemas;
|
|
192
296
|
constructor(opts) {
|
|
297
|
+
this.interactive = opts.interactive ?? false;
|
|
193
298
|
const validatedParams = opts.paramsSchema ? opts.paramsSchema.parse(opts.params) : opts.params;
|
|
194
299
|
const environment = opts.environment;
|
|
195
300
|
const storageEnv = environment?.storage;
|
|
@@ -205,7 +310,9 @@ export class AgentHarness {
|
|
|
205
310
|
decisionModel: opts.decisionModel,
|
|
206
311
|
emitItemsOnReplay: opts.emitItemsOnReplay,
|
|
207
312
|
approveToolCall: opts.approveToolCall,
|
|
313
|
+
now: opts.now,
|
|
208
314
|
};
|
|
315
|
+
this.outputStorage = this.config.storage ?? createInMemoryStorage();
|
|
209
316
|
const adapters = resolveEnvironmentAdapters(environment);
|
|
210
317
|
this.fs = adapters.fs;
|
|
211
318
|
this.shell = adapters.shell;
|
|
@@ -220,10 +327,17 @@ export class AgentHarness {
|
|
|
220
327
|
this.sessionStore = this.checkpointStore
|
|
221
328
|
? createSessionStore(this.config.storage ?? createInMemoryStorage())
|
|
222
329
|
: undefined;
|
|
330
|
+
this.leaseOptions = resolveLeaseOptions(this.sessionStore ? this.config.storage : undefined, {
|
|
331
|
+
now: opts.now,
|
|
332
|
+
...storageEnv?.lease,
|
|
333
|
+
});
|
|
334
|
+
this.parkGraceMs = resolveParkGrace(this.leaseOptions ? storageEnv?.park : undefined);
|
|
335
|
+
this.parkWatchers = this.createParkWatchers(storageEnv?.park);
|
|
223
336
|
this.spend = this.checkpointStore
|
|
224
337
|
? this.createSpend(this.config.storage ?? createInMemoryStorage())
|
|
225
338
|
: undefined;
|
|
226
339
|
this.agentGraph = opts.agentGraph ? toStep(opts.agentGraph) : undefined;
|
|
340
|
+
this.version = opts.version ?? flowVersionOf(frameworkCast(this.agentGraph));
|
|
227
341
|
this.harnessTools = opts.tools ?? [];
|
|
228
342
|
this._contextLayers = opts.contextLayers;
|
|
229
343
|
this.llm = new LlmGateway({
|
|
@@ -255,11 +369,10 @@ export class AgentHarness {
|
|
|
255
369
|
...(this.agentGraph
|
|
256
370
|
? collectCustomItems(frameworkCast(this.agentGraph)).map((item) => item.type)
|
|
257
371
|
: []),
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
: []),
|
|
372
|
+
// Always known: a trigger can be added while the harness runs, and one added
|
|
373
|
+
// on an earlier run comes back from storage, so its turns must be able to
|
|
374
|
+
// carry the event.
|
|
375
|
+
CONNECTION_EVENT_ITEM_TYPE,
|
|
263
376
|
]),
|
|
264
377
|
});
|
|
265
378
|
this.rootCwdState = {
|
|
@@ -270,6 +383,7 @@ export class AgentHarness {
|
|
|
270
383
|
harness: this,
|
|
271
384
|
connections: opts.connections,
|
|
272
385
|
triggers: opts.triggers,
|
|
386
|
+
onSchedule: () => this.announceWakeTimeQuietly(),
|
|
273
387
|
storage: this.config.storage ?? createInMemoryStorage(),
|
|
274
388
|
artifacts: this.artifacts,
|
|
275
389
|
secrets: environment?.secrets,
|
|
@@ -288,6 +402,78 @@ export class AgentHarness {
|
|
|
288
402
|
*/
|
|
289
403
|
async start() {
|
|
290
404
|
await this.#connections.start();
|
|
405
|
+
// Once started, a scheduled source's next event is known: say when it is.
|
|
406
|
+
if (this.announcedWakeTime === null) {
|
|
407
|
+
await this.announceWakeTime();
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
/**
|
|
411
|
+
* Hear when `getNextWakeTime()` changes: a turn parks, resumes or ends, a
|
|
412
|
+
* trigger is added or removed, or a scheduled source's event is read. `listener`
|
|
413
|
+
* gets the new time, or `undefined` when there is nothing to wake for. The first
|
|
414
|
+
* call comes when the harness starts. A host with no process of its own between
|
|
415
|
+
* events sets its alarm from it.
|
|
416
|
+
*
|
|
417
|
+
* The harness waits for the listener before a parking turn answers, and a
|
|
418
|
+
* listener that throws there fails that turn's response: a turn nothing will
|
|
419
|
+
* wake must not look safely parked. Anywhere else a throw is logged.
|
|
420
|
+
*
|
|
421
|
+
* It does not replace the harness's own timer (`park.autoWake`).
|
|
422
|
+
*
|
|
423
|
+
* @returns a function that stops the listener hearing.
|
|
424
|
+
* @public
|
|
425
|
+
*/
|
|
426
|
+
onWakeTimeChange(listener) {
|
|
427
|
+
this.wakeTimeListeners.add(listener);
|
|
428
|
+
return () => {
|
|
429
|
+
this.wakeTimeListeners.delete(listener);
|
|
430
|
+
};
|
|
431
|
+
}
|
|
432
|
+
/** Tell the listeners the next wake time, when it is not the one they last heard. */
|
|
433
|
+
announceWakeTime() {
|
|
434
|
+
if (this.wakeTimeListeners.size === 0) {
|
|
435
|
+
return Promise.resolve();
|
|
436
|
+
}
|
|
437
|
+
const run = this.announcing.then(async () => {
|
|
438
|
+
const at = await this.getNextWakeTime();
|
|
439
|
+
if (at === this.announcedWakeTime) {
|
|
440
|
+
return;
|
|
441
|
+
}
|
|
442
|
+
for (const listener of this.wakeTimeListeners) {
|
|
443
|
+
await listener(at);
|
|
444
|
+
}
|
|
445
|
+
this.announcedWakeTime = at;
|
|
446
|
+
});
|
|
447
|
+
this.announcing = run.catch(() => undefined);
|
|
448
|
+
return run;
|
|
449
|
+
}
|
|
450
|
+
/** `announceWakeTime`, where a listener's failure has no turn to land on. */
|
|
451
|
+
async announceWakeTimeQuietly() {
|
|
452
|
+
try {
|
|
453
|
+
await this.announceWakeTime();
|
|
454
|
+
}
|
|
455
|
+
catch (error) {
|
|
456
|
+
console.warn('[noetic] onWakeTimeChange listener error:', error);
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
/**
|
|
460
|
+
* Resolves once the harness has nothing in hand: every scheduled event that is
|
|
461
|
+
* due has been read by its trigger, and every turn has finished or parked. A
|
|
462
|
+
* serverless host awaits it after `start()` and `wake()`, before it lets its
|
|
463
|
+
* process go.
|
|
464
|
+
* @public
|
|
465
|
+
*/
|
|
466
|
+
async waitForIdle() {
|
|
467
|
+
for (;;) {
|
|
468
|
+
await this.#connections.triggers.idle();
|
|
469
|
+
const busy = [
|
|
470
|
+
...this.sessions.values(),
|
|
471
|
+
].filter((session) => session.runner.getStatus().kind !== 'idle');
|
|
472
|
+
if (busy.length === 0) {
|
|
473
|
+
return;
|
|
474
|
+
}
|
|
475
|
+
await Promise.allSettled(busy.map((session) => session.runner.getAgentResponse()));
|
|
476
|
+
}
|
|
291
477
|
}
|
|
292
478
|
/**
|
|
293
479
|
* Each connection's state, identity and pool usage; one entry for `name`, or all.
|
|
@@ -305,7 +491,11 @@ export class AgentHarness {
|
|
|
305
491
|
* @public
|
|
306
492
|
*/
|
|
307
493
|
async close() {
|
|
494
|
+
this.parkWatchers?.stopAll();
|
|
308
495
|
await runEvery([
|
|
496
|
+
...[
|
|
497
|
+
...this.outputs.values(),
|
|
498
|
+
].map((output) => () => output.flush()),
|
|
309
499
|
() => this.#connections.close(),
|
|
310
500
|
() => this.closeAcpSessions(),
|
|
311
501
|
]);
|
|
@@ -324,7 +514,110 @@ export class AgentHarness {
|
|
|
324
514
|
this.rootCwdState.cwd = nextCwd;
|
|
325
515
|
}
|
|
326
516
|
//#region Session Accessors
|
|
327
|
-
|
|
517
|
+
/**
|
|
518
|
+
* Hand the thread a message, a person's decision, or both.
|
|
519
|
+
*
|
|
520
|
+
* A {@link DecisionItem} answers a tool call the thread's turn holds, or settles
|
|
521
|
+
* its stuck turn. It is not written to the conversation, and input that holds
|
|
522
|
+
* nothing else starts no turn: the turn the decision is for goes on.
|
|
523
|
+
*
|
|
524
|
+
* Several decisions in one list are read first, so a malformed one changes
|
|
525
|
+
* nothing, and then taken in order: one the thread's state refuses throws, and
|
|
526
|
+
* those before it stay taken. `options` reach the turn a decision resumes.
|
|
527
|
+
*
|
|
528
|
+
* @throws NoeticError `hold_refused` when an answer to a held call cannot be
|
|
529
|
+
* taken: the thread holds no such call, `argsHash` names other arguments, the
|
|
530
|
+
* answer is the wrong kind for the hold, the call was already answered
|
|
531
|
+
* differently, its `output` is not a JSON value, or a `function_call_output`
|
|
532
|
+
* item names a held call.
|
|
533
|
+
* @throws NoeticError `decision_refused` when a decision does not fit what the
|
|
534
|
+
* thread is waiting on: no turn is stuck, it carries both an `action` and an
|
|
535
|
+
* `output`, or its action is the wrong kind for a decision with, or without,
|
|
536
|
+
* a `callId`.
|
|
537
|
+
* @public
|
|
538
|
+
*/
|
|
539
|
+
async execute(input, options) {
|
|
540
|
+
const message = await this.takeDecisions(input, options);
|
|
541
|
+
if (message === undefined) {
|
|
542
|
+
return;
|
|
543
|
+
}
|
|
544
|
+
return this.deliverInput(message, options);
|
|
545
|
+
}
|
|
546
|
+
/**
|
|
547
|
+
* Act on the decisions in `input` and resolve what is left of it: the message to
|
|
548
|
+
* deliver, or undefined when the input was decisions only.
|
|
549
|
+
*
|
|
550
|
+
* Every decision is read before any is acted on, so a list with a malformed one
|
|
551
|
+
* changes nothing. They are then acted on in order: one the thread's state
|
|
552
|
+
* refuses throws, and those before it stay taken.
|
|
553
|
+
*/
|
|
554
|
+
async takeDecisions(input, options) {
|
|
555
|
+
if (typeof input === 'string') {
|
|
556
|
+
return input;
|
|
557
|
+
}
|
|
558
|
+
const threadId = options?.threadId ?? DEFAULT_THREAD_ID;
|
|
559
|
+
const given = isItemList(input)
|
|
560
|
+
? input
|
|
561
|
+
: [
|
|
562
|
+
input,
|
|
563
|
+
];
|
|
564
|
+
const rest = [];
|
|
565
|
+
const decisions = [];
|
|
566
|
+
for (const item of given) {
|
|
567
|
+
if (isDecisionItem(item)) {
|
|
568
|
+
decisions.push(readDecision(threadId, item));
|
|
569
|
+
continue;
|
|
570
|
+
}
|
|
571
|
+
rest.push(item);
|
|
572
|
+
}
|
|
573
|
+
await this.refuseResultsForHeldCalls(threadId, rest);
|
|
574
|
+
for (const decision of decisions) {
|
|
575
|
+
await this.takeDecision(decision, options);
|
|
576
|
+
}
|
|
577
|
+
if (rest.length === given.length) {
|
|
578
|
+
return frameworkCast(input);
|
|
579
|
+
}
|
|
580
|
+
return rest.length === 0 ? undefined : rest;
|
|
581
|
+
}
|
|
582
|
+
/**
|
|
583
|
+
* A held call's result comes in a decision. A `function_call_output` for one
|
|
584
|
+
* would go into the conversation and leave the call waiting, so it is refused.
|
|
585
|
+
*/
|
|
586
|
+
async refuseResultsForHeldCalls(threadId, items) {
|
|
587
|
+
const outputs = items.filter((item) => item.type === 'function_call_output');
|
|
588
|
+
if (outputs.length === 0) {
|
|
589
|
+
return;
|
|
590
|
+
}
|
|
591
|
+
const held = new Set((await this.pending({
|
|
592
|
+
threadId,
|
|
593
|
+
})).map((call) => call.callId));
|
|
594
|
+
for (const item of outputs) {
|
|
595
|
+
if ('callId' in item && typeof item.callId === 'string' && held.has(item.callId)) {
|
|
596
|
+
throw new NoeticErrorImpl({
|
|
597
|
+
kind: 'hold_refused',
|
|
598
|
+
callId: item.callId,
|
|
599
|
+
reason: "a held call's result is given in a decision item, not a function_call_output",
|
|
600
|
+
});
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
/** Act on one decision: an answer to a held call, or the settling of a stuck turn. */
|
|
605
|
+
async takeDecision(decision, options) {
|
|
606
|
+
if ('answer' in decision) {
|
|
607
|
+
await this.resolveHeld(decision.scope, decision.answer, options);
|
|
608
|
+
return;
|
|
609
|
+
}
|
|
610
|
+
if (await this.settleStuckTurn(decision.threadId, decision.settle, options)) {
|
|
611
|
+
return;
|
|
612
|
+
}
|
|
613
|
+
throw new NoeticErrorImpl({
|
|
614
|
+
kind: 'decision_refused',
|
|
615
|
+
threadId: decision.threadId,
|
|
616
|
+
action: decision.settle,
|
|
617
|
+
reason: 'the thread has no stuck turn',
|
|
618
|
+
});
|
|
619
|
+
}
|
|
620
|
+
deliverInput(input, options) {
|
|
328
621
|
if (!this.agentGraph) {
|
|
329
622
|
return Promise.reject(new NoeticConfigError({
|
|
330
623
|
code: 'NO_STEP_CONFIGURED',
|
|
@@ -352,12 +645,40 @@ export class AgentHarness {
|
|
|
352
645
|
void session.runner.abort(INTERRUPT_REASON);
|
|
353
646
|
return Promise.resolve();
|
|
354
647
|
}
|
|
648
|
+
return this.deliver(session, message);
|
|
649
|
+
}
|
|
650
|
+
/**
|
|
651
|
+
* Hand a message to its thread. One at a time per thread: what to do with a
|
|
652
|
+
* message is decided by looking at the thread and then acting, and two
|
|
653
|
+
* deliveries doing that at once would each miss the other.
|
|
654
|
+
*/
|
|
655
|
+
deliver(session, message) {
|
|
656
|
+
const turn = (session.delivering ?? Promise.resolve())
|
|
657
|
+
.catch(() => undefined)
|
|
658
|
+
.then(() => this.deliverOne(session, message));
|
|
659
|
+
session.delivering = turn;
|
|
660
|
+
return turn;
|
|
661
|
+
}
|
|
662
|
+
async deliverOne(session, message) {
|
|
663
|
+
if (await this.deliverToParked(session, message)) {
|
|
664
|
+
return;
|
|
665
|
+
}
|
|
666
|
+
if (await this.answerAgain(session, message)) {
|
|
667
|
+
return;
|
|
668
|
+
}
|
|
669
|
+
if (await this.inHand(session, message)) {
|
|
670
|
+
return;
|
|
671
|
+
}
|
|
355
672
|
const steersRunningTurn = session.runner.getStatus().kind === 'generating' && isSteer(message);
|
|
356
673
|
session.runner.enqueue(message);
|
|
357
674
|
if (steersRunningTurn) {
|
|
358
675
|
void session.record?.keepSteer(message);
|
|
676
|
+
// A round waiting on a held call offers the steer to the layers at once.
|
|
677
|
+
const running = session.runner.context;
|
|
678
|
+
if (running) {
|
|
679
|
+
heldCallsOf(this).notify(rootIdOf(running));
|
|
680
|
+
}
|
|
359
681
|
}
|
|
360
|
-
return Promise.resolve();
|
|
361
682
|
}
|
|
362
683
|
/** The turn's response. `items` holds final items: standard ones and the graph's declared custom items. */
|
|
363
684
|
getAgentResponse(scope) {
|
|
@@ -372,6 +693,43 @@ export class AgentHarness {
|
|
|
372
693
|
const session = this.requireSession(scope);
|
|
373
694
|
return frameworkCast(buildItemStream(session.runner.broadcaster, this.itemSchemas));
|
|
374
695
|
}
|
|
696
|
+
/**
|
|
697
|
+
* A thread's display output (spec 08 § Display output): the latest snapshot of
|
|
698
|
+
* every item it streamed, unfinished ones included, read from storage. An
|
|
699
|
+
* `interactive` harness records it; any harness over the same storage reads it.
|
|
700
|
+
* For showing a thread again, never for resuming one.
|
|
701
|
+
*
|
|
702
|
+
* @throws OutputStoreError when storage fails, or holds something else under the key.
|
|
703
|
+
* @public
|
|
704
|
+
*/
|
|
705
|
+
getSessionOutput(scope) {
|
|
706
|
+
return this.outputOf(scope?.threadId ?? DEFAULT_THREAD_ID).read();
|
|
707
|
+
}
|
|
708
|
+
/**
|
|
709
|
+
* Save display snapshots for a thread, each replacing the stored one with its
|
|
710
|
+
* id, and resolve the thread's whole display output. For a protocol adapter
|
|
711
|
+
* that shows a thread in its own item shapes. Model history is untouched.
|
|
712
|
+
*
|
|
713
|
+
* @throws OutputStoreError when `items` are not snapshots (objects with a string
|
|
714
|
+
* `type`), or storage fails.
|
|
715
|
+
* @public
|
|
716
|
+
*/
|
|
717
|
+
saveSessionOutput(items, scope) {
|
|
718
|
+
return this.outputOf(scope.threadId ?? DEFAULT_THREAD_ID).write(items);
|
|
719
|
+
}
|
|
720
|
+
/**
|
|
721
|
+
* The thread's one output store: every write for a thread goes through it, so
|
|
722
|
+
* this harness's writes queue behind each other instead of racing.
|
|
723
|
+
*/
|
|
724
|
+
outputOf(threadId) {
|
|
725
|
+
const known = this.outputs.get(threadId);
|
|
726
|
+
if (known) {
|
|
727
|
+
return known;
|
|
728
|
+
}
|
|
729
|
+
const output = new OutputStore(this.outputStorage, threadId, this.itemSchemas);
|
|
730
|
+
this.outputs.set(threadId, output);
|
|
731
|
+
return output;
|
|
732
|
+
}
|
|
375
733
|
getTextStream(scope) {
|
|
376
734
|
const session = this.requireSession(scope);
|
|
377
735
|
return filterTextStream(session.runner.broadcaster);
|
|
@@ -387,7 +745,10 @@ export class AgentHarness {
|
|
|
387
745
|
}
|
|
388
746
|
async abort(scope) {
|
|
389
747
|
const threadId = scope?.threadId ?? DEFAULT_THREAD_ID;
|
|
390
|
-
|
|
748
|
+
// A parked turn lives in storage, so a harness that never ran the thread can
|
|
749
|
+
// still be the one asked to abort it.
|
|
750
|
+
const session = this.sessions.get(threadId) ??
|
|
751
|
+
(this.sessionStore ? this.getOrCreateSession(threadId) : undefined);
|
|
391
752
|
if (!session) {
|
|
392
753
|
return undefined;
|
|
393
754
|
}
|
|
@@ -395,6 +756,14 @@ export class AgentHarness {
|
|
|
395
756
|
const ctx = runner.context;
|
|
396
757
|
if (!ctx) {
|
|
397
758
|
await runner.abort(scope?.reason);
|
|
759
|
+
// Nothing is running, but a parked turn is still the thread's turn: drop it,
|
|
760
|
+
// or the next wake would bring back what the host just cancelled.
|
|
761
|
+
await runner.whenIdle();
|
|
762
|
+
if ((await session.record?.turn())?.parked) {
|
|
763
|
+
this.parkWatchers?.stop(threadId);
|
|
764
|
+
await session.record?.drop();
|
|
765
|
+
await this.announceWakeTimeQuietly();
|
|
766
|
+
}
|
|
398
767
|
return undefined;
|
|
399
768
|
}
|
|
400
769
|
const draining = this.drains.stop(ctx);
|
|
@@ -501,8 +870,12 @@ export class AgentHarness {
|
|
|
501
870
|
}
|
|
502
871
|
const record = this.threadRecord(threadId);
|
|
503
872
|
// Save a turn's items as the thread's history for the next turn.
|
|
504
|
-
const keepHistory = async (ctx) => {
|
|
873
|
+
const keepHistory = async (ctx, answer) => {
|
|
505
874
|
if (record) {
|
|
875
|
+
// A finished turn's answer is kept, so its messages delivered again get it back.
|
|
876
|
+
if (answer !== undefined) {
|
|
877
|
+
await record.answered(ctx, answer);
|
|
878
|
+
}
|
|
506
879
|
await record.end(ctx, ctx.itemLog.items, session.runner.queue.peekAll().map((message) => message.id));
|
|
507
880
|
return;
|
|
508
881
|
}
|
|
@@ -512,6 +885,7 @@ export class AgentHarness {
|
|
|
512
885
|
};
|
|
513
886
|
const session = {
|
|
514
887
|
accumulatedItems: [],
|
|
888
|
+
keptOptions: new Map(),
|
|
515
889
|
record,
|
|
516
890
|
runner: new SessionRunner({
|
|
517
891
|
threadId,
|
|
@@ -522,88 +896,46 @@ export class AgentHarness {
|
|
|
522
896
|
// are ignored. `deliveryMode` is resolved per-message at enqueue
|
|
523
897
|
// time and doesn't apply here.
|
|
524
898
|
createContext: async (items, _turnId, messages) => {
|
|
525
|
-
|
|
526
|
-
const
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
],
|
|
542
|
-
threadId,
|
|
543
|
-
resourceId: perTurnOptions.resourceId,
|
|
544
|
-
state: perTurnOptions.state,
|
|
545
|
-
contextLayers: perTurnOptions.contextLayers,
|
|
546
|
-
extraContextLayers: perTurnOptions.extraContextLayers,
|
|
547
|
-
_connectionViews: views.layers,
|
|
548
|
-
_broadcaster: session.runner.broadcaster,
|
|
549
|
-
});
|
|
550
|
-
// A resumed context was made without the turn's view layers.
|
|
551
|
-
if (!resumed) {
|
|
552
|
-
views.bind(ctx);
|
|
553
|
-
}
|
|
554
|
-
frameworkCast(ctx)._sessionQueue = session.runner.queue;
|
|
555
|
-
await this.start();
|
|
556
|
-
const connectionTools = await this.#connections.openTurn(ctx, perTurnOptions.connections, graph);
|
|
557
|
-
if (this.agentGraph || this.harnessTools.length > 0 || connectionTools.length > 0) {
|
|
558
|
-
const stepTools = this.agentGraph ? collectAllTools(this.agentGraph) : [];
|
|
559
|
-
this.setUnifiedTools(ctx, [
|
|
560
|
-
...stepTools,
|
|
561
|
-
...this.harnessTools,
|
|
562
|
-
...connectionTools,
|
|
563
|
-
]);
|
|
564
|
-
}
|
|
565
|
-
// Steers the last harness accepted but never applied go back in the queue;
|
|
566
|
-
// ones already in the conversation are skipped when offered.
|
|
567
|
-
for (const steer of (await record?.steers()) ?? []) {
|
|
568
|
-
const queued = session.runner.queue.peekAll().some((m) => m.id === steer.id);
|
|
569
|
-
if (!queued && !messageIds.includes(steer.id)) {
|
|
570
|
-
session.runner.queue.enqueue(steer);
|
|
899
|
+
// One harness drives a thread's turn: take its lease before reading anything.
|
|
900
|
+
const lease = record && this.leaseOptions
|
|
901
|
+
? await TurnLease.take(this.leaseOptions, threadId, {
|
|
902
|
+
// Aborting the thread ends the wait for a lease held elsewhere.
|
|
903
|
+
signal: session.runner.signal,
|
|
904
|
+
// A lease record that was deleted must not start again below the
|
|
905
|
+
// term the thread's own record was last written at.
|
|
906
|
+
above: await record.term(),
|
|
907
|
+
})
|
|
908
|
+
: undefined;
|
|
909
|
+
record?.hold(lease);
|
|
910
|
+
session.lease = lease;
|
|
911
|
+
try {
|
|
912
|
+
if (record && (await this.setAside(session, record, messages))) {
|
|
913
|
+
await this.releaseLease(session);
|
|
914
|
+
return undefined;
|
|
571
915
|
}
|
|
916
|
+
return await buildTurnContext(items, messages, lease);
|
|
917
|
+
}
|
|
918
|
+
catch (error) {
|
|
919
|
+
await this.releaseLease(session);
|
|
920
|
+
throw error;
|
|
572
921
|
}
|
|
573
|
-
await record?.begin(ctx, messageIds);
|
|
574
|
-
return ctx;
|
|
575
922
|
},
|
|
576
923
|
runTurn: async (ctx, _turn, signal) => {
|
|
577
|
-
|
|
578
|
-
await
|
|
579
|
-
throw new NoeticConfigError({
|
|
580
|
-
code: 'NO_STEP_CONFIGURED',
|
|
581
|
-
message: 'No agentGraph configured on this harness.',
|
|
582
|
-
hint: 'Pass `agentGraph` in constructor options.',
|
|
583
|
-
});
|
|
584
|
-
}
|
|
585
|
-
// Wire signal-abort to context-abort so the interpreter bails cleanly.
|
|
586
|
-
if (signal.aborted) {
|
|
587
|
-
ctx.abort(signal.reason ? String(signal.reason) : 'aborted');
|
|
588
|
-
}
|
|
589
|
-
else {
|
|
590
|
-
signal.addEventListener('abort', () => {
|
|
591
|
-
ctx.abort(signal.reason ? String(signal.reason) : 'aborted');
|
|
592
|
-
}, {
|
|
593
|
-
once: true,
|
|
594
|
-
});
|
|
924
|
+
try {
|
|
925
|
+
return await runTurn(ctx, signal);
|
|
595
926
|
}
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
//
|
|
599
|
-
|
|
600
|
-
|
|
927
|
+
finally {
|
|
928
|
+
await this.releaseLease(session);
|
|
929
|
+
// An answer that landed while this harness still held the lease could not
|
|
930
|
+
// wake the turn. Now that it is free, do that.
|
|
931
|
+
if (parkedUntil(ctx) !== undefined) {
|
|
932
|
+
void this.wakeIfAnswered(threadId, ctx.id);
|
|
601
933
|
}
|
|
602
|
-
|
|
603
|
-
});
|
|
604
|
-
await keepHistory(ctx);
|
|
605
|
-
return result;
|
|
934
|
+
}
|
|
606
935
|
},
|
|
936
|
+
heldCalls: async (ctx) => (await heldCallsOf(this).list(rootIdOf(ctx)))
|
|
937
|
+
.filter((held) => held.resolution === undefined)
|
|
938
|
+
.map(toHeldCall),
|
|
607
939
|
// Stored totals are the session's usage; the runner only mirrors them.
|
|
608
940
|
onTurnUsage: record
|
|
609
941
|
? async (spent) => {
|
|
@@ -612,12 +944,752 @@ export class AgentHarness {
|
|
|
612
944
|
: undefined,
|
|
613
945
|
}),
|
|
614
946
|
};
|
|
947
|
+
const buildTurnContext = async (items, messages, lease) => {
|
|
948
|
+
const perTurnOptions = messages[0]?.options ?? {};
|
|
949
|
+
// The turn is starting or resuming here: nothing needs to watch over it.
|
|
950
|
+
session.turnOptions = perTurnOptions;
|
|
951
|
+
this.parkWatchers?.stop(threadId);
|
|
952
|
+
const messageIds = messages.map((m) => m.id);
|
|
953
|
+
const history = record ? await record.history() : session.accumulatedItems;
|
|
954
|
+
const graph = this.agentGraph ? frameworkCast(this.agentGraph) : undefined;
|
|
955
|
+
const views = this.#connections.turnViews(perTurnOptions.connections, graph);
|
|
956
|
+
// A re-delivery of a cut-off turn's messages picks that turn up where it died.
|
|
957
|
+
const resumed = await record?.resume(messageIds, {
|
|
958
|
+
state: perTurnOptions.state,
|
|
959
|
+
contextLayers: perTurnOptions.contextLayers,
|
|
960
|
+
_broadcaster: session.runner.broadcaster,
|
|
961
|
+
});
|
|
962
|
+
const ctx = resumed ??
|
|
963
|
+
this.createContext({
|
|
964
|
+
items: [
|
|
965
|
+
...history,
|
|
966
|
+
...items,
|
|
967
|
+
],
|
|
968
|
+
threadId,
|
|
969
|
+
resourceId: perTurnOptions.resourceId,
|
|
970
|
+
state: perTurnOptions.state,
|
|
971
|
+
contextLayers: perTurnOptions.contextLayers,
|
|
972
|
+
extraContextLayers: perTurnOptions.extraContextLayers,
|
|
973
|
+
_connectionViews: views.layers,
|
|
974
|
+
_broadcaster: session.runner.broadcaster,
|
|
975
|
+
});
|
|
976
|
+
if (lease) {
|
|
977
|
+
lease.bind(ctx.id);
|
|
978
|
+
if (ctx instanceof ContextImpl) {
|
|
979
|
+
ctx.ledger?.fence(lease);
|
|
980
|
+
}
|
|
981
|
+
lease.keep((reason) => ctx.abort(`lease_lost: ${reason}`));
|
|
982
|
+
if (this.parkGraceMs !== undefined && ctx instanceof ContextImpl) {
|
|
983
|
+
ctx.ledger?.parking.arm({
|
|
984
|
+
graceMs: this.parkGraceMs,
|
|
985
|
+
onPark: () => ctx.abort(PARK_REASON),
|
|
986
|
+
});
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
// A resumed context was made without the turn's view layers.
|
|
990
|
+
if (!resumed) {
|
|
991
|
+
views.bind(ctx);
|
|
992
|
+
}
|
|
993
|
+
frameworkCast(ctx)._sessionQueue = session.runner.queue;
|
|
994
|
+
await this.start();
|
|
995
|
+
const connectionTools = await this.#connections.openTurn(ctx, perTurnOptions.connections, graph);
|
|
996
|
+
if (this.agentGraph || this.harnessTools.length > 0 || connectionTools.length > 0) {
|
|
997
|
+
const stepTools = this.agentGraph ? collectAllTools(this.agentGraph) : [];
|
|
998
|
+
this.setUnifiedTools(ctx, [
|
|
999
|
+
...stepTools,
|
|
1000
|
+
...this.harnessTools,
|
|
1001
|
+
...connectionTools,
|
|
1002
|
+
]);
|
|
1003
|
+
}
|
|
1004
|
+
// Steers the last harness accepted but never applied go back in the queue;
|
|
1005
|
+
// ones already in the conversation are skipped when offered.
|
|
1006
|
+
for (const steer of (await record?.steers()) ?? []) {
|
|
1007
|
+
const queued = session.runner.queue.peekAll().some((m) => m.id === steer.id);
|
|
1008
|
+
if (!queued && !messageIds.includes(steer.id)) {
|
|
1009
|
+
// With the options it was sent with, when this process is the one it was sent to.
|
|
1010
|
+
const options = session.keptOptions.get(steer.id) ?? steer.options;
|
|
1011
|
+
session.keptOptions.delete(steer.id);
|
|
1012
|
+
session.runner.queue.enqueue({
|
|
1013
|
+
...steer,
|
|
1014
|
+
options,
|
|
1015
|
+
});
|
|
1016
|
+
}
|
|
1017
|
+
}
|
|
1018
|
+
// A stuck turn the host chose to go on with may discard what no longer matches.
|
|
1019
|
+
const accept = (await record?.turn())?.accept;
|
|
1020
|
+
if (accept && ctx instanceof ContextImpl) {
|
|
1021
|
+
ctx.ledger?.acceptVersionLoss(typeof accept === 'string' ? accept : undefined);
|
|
1022
|
+
}
|
|
1023
|
+
await record?.begin(ctx, messageIds);
|
|
1024
|
+
// A turn on record can be cut off from here on. A host that sleeps between
|
|
1025
|
+
// requests has to know when to come back and look (see `turnDueAt`).
|
|
1026
|
+
if (record && this.leaseOptions) {
|
|
1027
|
+
await this.announceWakeTimeQuietly();
|
|
1028
|
+
}
|
|
1029
|
+
return ctx;
|
|
1030
|
+
};
|
|
1031
|
+
/**
|
|
1032
|
+
* A parked turn is not a failed one: its record stays, marked with when to wake
|
|
1033
|
+
* it, and the response says so. Resolves true when the turn on `ctx` parked.
|
|
1034
|
+
*/
|
|
1035
|
+
const closeOutPark = async (ctx) => {
|
|
1036
|
+
const wakeAt = parkedUntil(ctx);
|
|
1037
|
+
if (wakeAt === undefined || !record) {
|
|
1038
|
+
return false;
|
|
1039
|
+
}
|
|
1040
|
+
// Messages still queued wait in storage, not in this process: the woken
|
|
1041
|
+
// turn gets them back, and the runner is left with nothing to start.
|
|
1042
|
+
const interrupts = [];
|
|
1043
|
+
for (const queued of session.runner.queue.drainAll()) {
|
|
1044
|
+
if (queued.deliveryMode === 'interrupt') {
|
|
1045
|
+
interrupts.push(queued);
|
|
1046
|
+
continue;
|
|
1047
|
+
}
|
|
1048
|
+
await keepForLater(session, record, queued);
|
|
1049
|
+
}
|
|
1050
|
+
// An interrupt replaces the turn, parked or not: it stays for the runner to start.
|
|
1051
|
+
for (const interrupt of interrupts.reverse()) {
|
|
1052
|
+
session.runner.queue.prepend(interrupt);
|
|
1053
|
+
}
|
|
1054
|
+
const until = Number.isFinite(wakeAt) ? wakeAt : undefined;
|
|
1055
|
+
await record.park(ctx, until);
|
|
1056
|
+
await this.#connections.release(ctx.id);
|
|
1057
|
+
this.parkWatchers?.watch(threadId, {
|
|
1058
|
+
executionId: ctx.id,
|
|
1059
|
+
until,
|
|
1060
|
+
options: session.turnOptions ?? {},
|
|
1061
|
+
});
|
|
1062
|
+
// Before the turn answers as parked: whoever wakes it has to know when.
|
|
1063
|
+
await this.announceWakeTime();
|
|
1064
|
+
return true;
|
|
1065
|
+
};
|
|
1066
|
+
const runTurn = async (ctx, signal) => {
|
|
1067
|
+
if (!this.agentGraph) {
|
|
1068
|
+
await this.#connections.release(ctx.id);
|
|
1069
|
+
throw new NoeticConfigError({
|
|
1070
|
+
code: 'NO_STEP_CONFIGURED',
|
|
1071
|
+
message: 'No agentGraph configured on this harness.',
|
|
1072
|
+
hint: 'Pass `agentGraph` in constructor options.',
|
|
1073
|
+
});
|
|
1074
|
+
}
|
|
1075
|
+
// Wire signal-abort to context-abort so the interpreter bails cleanly.
|
|
1076
|
+
if (signal.aborted) {
|
|
1077
|
+
ctx.abort(signal.reason ? String(signal.reason) : 'aborted');
|
|
1078
|
+
}
|
|
1079
|
+
else {
|
|
1080
|
+
signal.addEventListener('abort', () => {
|
|
1081
|
+
ctx.abort(signal.reason ? String(signal.reason) : 'aborted');
|
|
1082
|
+
}, {
|
|
1083
|
+
once: true,
|
|
1084
|
+
});
|
|
1085
|
+
}
|
|
1086
|
+
const result = await this.initAndRun(this.agentGraph, '', ctx).catch(async (error) => {
|
|
1087
|
+
// An interrupted turn restarts from what it finished, so the
|
|
1088
|
+
// interrupting message lands after the work it interrupted.
|
|
1089
|
+
if (ctx.abortReason === INTERRUPT_REASON) {
|
|
1090
|
+
await keepHistory(ctx);
|
|
1091
|
+
}
|
|
1092
|
+
// A parked turn is not a failed one: its record stays, marked with when
|
|
1093
|
+
// to wake it, and the response says so.
|
|
1094
|
+
if (await closeOutPark(ctx)) {
|
|
1095
|
+
return PARKED;
|
|
1096
|
+
}
|
|
1097
|
+
// The turn ended here, in a live process. Say so, or a routine wake would
|
|
1098
|
+
// take it for one cut off by a crash and run it again, every time.
|
|
1099
|
+
// It stopped rather than redo a recorded effect under a newer flow version:
|
|
1100
|
+
// it waits, marked, for the host to settle it.
|
|
1101
|
+
const stuck = stuckOf(error);
|
|
1102
|
+
if (record && stuck) {
|
|
1103
|
+
await record.stick(ctx, stuck);
|
|
1104
|
+
await this.announceWakeTimeQuietly();
|
|
1105
|
+
throw error;
|
|
1106
|
+
}
|
|
1107
|
+
// A harness that was replaced says nothing about the turn: it is the new
|
|
1108
|
+
// holder's now, and marking it stopped would keep a wake from resuming it.
|
|
1109
|
+
const replaced = isLeaseLost(error) || session.lease?.lost === true;
|
|
1110
|
+
if (ctx.aborted && !replaced && ctx.abortReason !== INTERRUPT_REASON) {
|
|
1111
|
+
await heldCallsOf(this).clear(ctx.id);
|
|
1112
|
+
}
|
|
1113
|
+
if (record && !replaced && ctx.abortReason !== INTERRUPT_REASON) {
|
|
1114
|
+
await record.stop(ctx, error instanceof Error ? error.message : String(error), this.now());
|
|
1115
|
+
}
|
|
1116
|
+
await this.announceWakeTimeQuietly();
|
|
1117
|
+
throw error;
|
|
1118
|
+
});
|
|
1119
|
+
// A flow that caught the wait's cancellation and returned is parked all the
|
|
1120
|
+
// same: the wait it was in has not ended, and the woken turn goes back to it.
|
|
1121
|
+
if (result === PARKED || (await closeOutPark(ctx))) {
|
|
1122
|
+
return '';
|
|
1123
|
+
}
|
|
1124
|
+
await keepHistory(ctx, result);
|
|
1125
|
+
this.parkWatchers?.forget(threadId, ctx.id);
|
|
1126
|
+
await this.announceWakeTimeQuietly();
|
|
1127
|
+
return result;
|
|
1128
|
+
};
|
|
1129
|
+
if (this.interactive) {
|
|
1130
|
+
const output = this.outputOf(threadId);
|
|
1131
|
+
this.stopRecording.set(threadId, session.runner.broadcaster.observe((event) => output.record(event)));
|
|
1132
|
+
}
|
|
615
1133
|
this.sessions.set(threadId, session);
|
|
616
1134
|
if (record) {
|
|
617
1135
|
void record.usage().then((usage) => session.runner.seedUsage(usage));
|
|
618
1136
|
}
|
|
619
1137
|
return session;
|
|
620
1138
|
}
|
|
1139
|
+
/**
|
|
1140
|
+
* Resume turns that are parked or were cut off (spec 23 § Parked turns).
|
|
1141
|
+
*
|
|
1142
|
+
* With no `threadId`, every stored thread is looked at: a parked turn is resumed
|
|
1143
|
+
* once its wake time has come, and a cut-off turn at once. With a `threadId`, that
|
|
1144
|
+
* thread's turn is resumed whether or not it is due — the call a host makes when
|
|
1145
|
+
* it knows the event a parked turn waits for has arrived. A turn another harness
|
|
1146
|
+
* holds, or one already running here, is left alone.
|
|
1147
|
+
*
|
|
1148
|
+
* 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.
|
|
1150
|
+
*
|
|
1151
|
+
* Resolves the ids of the threads it resumed. Durable sessions only.
|
|
1152
|
+
* @public
|
|
1153
|
+
*/
|
|
1154
|
+
async wake(scope) {
|
|
1155
|
+
if (!this.sessionStore) {
|
|
1156
|
+
return [];
|
|
1157
|
+
}
|
|
1158
|
+
const now = this.now();
|
|
1159
|
+
const threadIds = scope?.threadId
|
|
1160
|
+
? [
|
|
1161
|
+
scope.threadId,
|
|
1162
|
+
]
|
|
1163
|
+
: await this.sessionStore.threads();
|
|
1164
|
+
const woken = [];
|
|
1165
|
+
for (const threadId of threadIds) {
|
|
1166
|
+
// A turn asked for by name may be closing out its park this instant: its
|
|
1167
|
+
// runner is busy, though nothing is running. Wait for it rather than skip.
|
|
1168
|
+
const closing = scope?.threadId ? this.sessions.get(threadId)?.runner : undefined;
|
|
1169
|
+
if (closing && closing.context === undefined) {
|
|
1170
|
+
await closing.whenIdle();
|
|
1171
|
+
}
|
|
1172
|
+
const turn = (await this.sessionStore.load(threadId))?.turn;
|
|
1173
|
+
// A stuck turn waits for the host to settle it, however the wake was asked for.
|
|
1174
|
+
if (!turn || turn.stuck) {
|
|
1175
|
+
continue;
|
|
1176
|
+
}
|
|
1177
|
+
// A routine wake leaves alone a parked turn that is not due, one with no
|
|
1178
|
+
// deadline at all (it waits for an answer, not for a time), and one that
|
|
1179
|
+
// failed or was cancelled here: only a turn cut off by a crash resumes unasked.
|
|
1180
|
+
const notDue = turn.parked && (turn.parked.until === undefined || turn.parked.until > now);
|
|
1181
|
+
if (!scope?.threadId && (notDue || (turn.stopped && !turn.parked))) {
|
|
1182
|
+
// A parked turn found in storage, as at boot, is watched over from here on.
|
|
1183
|
+
if (turn.parked && this.parkWatchers && !this.parkWatchers.has(threadId)) {
|
|
1184
|
+
this.parkWatchers.watch(threadId, {
|
|
1185
|
+
executionId: turn.executionId,
|
|
1186
|
+
until: turn.parked.until,
|
|
1187
|
+
options: scope?.options ?? {},
|
|
1188
|
+
});
|
|
1189
|
+
}
|
|
1190
|
+
continue;
|
|
1191
|
+
}
|
|
1192
|
+
const session = this.getOrCreateSession(threadId);
|
|
1193
|
+
if (session.runner.getStatus().kind !== 'idle' || session.runner.queue.size > 0) {
|
|
1194
|
+
continue;
|
|
1195
|
+
}
|
|
1196
|
+
// A routine wake leaves a turn another harness holds for a later pass. One
|
|
1197
|
+
// asked for by name goes ahead: taking the lease waits for the holder's to
|
|
1198
|
+
// run out, and if it does not, that is an error the caller hears about.
|
|
1199
|
+
const held = this.leaseOptions && (await heldElsewhere(this.leaseOptions, threadId));
|
|
1200
|
+
if (held && !scope?.threadId) {
|
|
1201
|
+
continue;
|
|
1202
|
+
}
|
|
1203
|
+
// Re-deliver the turn's own messages: the same ids resume it, and a resumed
|
|
1204
|
+
// turn reads its input from its checkpoint, not from these. They go back as
|
|
1205
|
+
// one arrival: handed over one at a time, the first would start a turn of
|
|
1206
|
+
// its own and that turn would not be this one.
|
|
1207
|
+
session.runner.queue.enqueueAll(turn.messageIds.map((id) => ({
|
|
1208
|
+
id,
|
|
1209
|
+
input: [],
|
|
1210
|
+
deliveryMode: 'next-turn',
|
|
1211
|
+
options: scope?.options ?? {},
|
|
1212
|
+
enqueuedAt: Date.now(),
|
|
1213
|
+
})));
|
|
1214
|
+
woken.push(threadId);
|
|
1215
|
+
}
|
|
1216
|
+
return woken;
|
|
1217
|
+
}
|
|
1218
|
+
/**
|
|
1219
|
+
* The earliest time the harness has something to do, in epoch ms: a parked turn
|
|
1220
|
+
* that needs waking, or the next event of a scheduled source a trigger listens
|
|
1221
|
+
* to (`cron()`). Undefined when there is neither. A host with no process of its
|
|
1222
|
+
* own between events (a serverless worker) schedules its next `start()` and
|
|
1223
|
+
* `wake()` from this.
|
|
1224
|
+
* @public
|
|
1225
|
+
*/
|
|
1226
|
+
async getNextWakeTime() {
|
|
1227
|
+
let earliest = await this.#connections.triggers.nextDue();
|
|
1228
|
+
if (!this.sessionStore) {
|
|
1229
|
+
return earliest;
|
|
1230
|
+
}
|
|
1231
|
+
const now = this.now();
|
|
1232
|
+
for (const threadId of await this.sessionStore.threads()) {
|
|
1233
|
+
const due = await this.turnDueAt(threadId, now);
|
|
1234
|
+
if (due !== undefined) {
|
|
1235
|
+
earliest = earliest === undefined ? due : Math.min(earliest, due);
|
|
1236
|
+
}
|
|
1237
|
+
}
|
|
1238
|
+
return earliest;
|
|
1239
|
+
}
|
|
1240
|
+
/**
|
|
1241
|
+
* When a routine `wake()` would have something to do for the thread's turn: a
|
|
1242
|
+
* parked turn at its deadline, a turn cut off by a crash at once. Never before
|
|
1243
|
+
* another harness's lease on it runs out, since a wake before then does nothing.
|
|
1244
|
+
* Undefined for a turn that waits on something other than time, and one that is
|
|
1245
|
+
* stuck or stopped. A turn this harness is running is due one lease period from
|
|
1246
|
+
* now: the time to come back if the process running it is gone.
|
|
1247
|
+
*/
|
|
1248
|
+
async turnDueAt(threadId, now) {
|
|
1249
|
+
const turn = (await this.sessionStore?.load(threadId))?.turn;
|
|
1250
|
+
if (!turn || turn.stuck || (turn.stopped && !turn.parked)) {
|
|
1251
|
+
return undefined;
|
|
1252
|
+
}
|
|
1253
|
+
if (turn.parked && turn.parked.until === undefined) {
|
|
1254
|
+
return undefined;
|
|
1255
|
+
}
|
|
1256
|
+
// 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.)
|
|
1258
|
+
const runner = this.sessions.get(threadId)?.runner;
|
|
1259
|
+
if (!turn.parked && runner && runner.getStatus().kind !== 'idle') {
|
|
1260
|
+
// Running here. Should this process die, the turn is cut off, and it can be
|
|
1261
|
+
// picked up once the lease it held has run out: that is when to look again.
|
|
1262
|
+
// The turn ending, or parking, replaces this time with the real one.
|
|
1263
|
+
return this.leaseOptions ? now + this.leaseOptions.ttlMs + LEASE_WAIT_MARGIN_MS : undefined;
|
|
1264
|
+
}
|
|
1265
|
+
const due = turn.parked?.until ?? now;
|
|
1266
|
+
const heldUntil = this.leaseOptions
|
|
1267
|
+
? await heldElsewhereUntil(this.leaseOptions, threadId)
|
|
1268
|
+
: undefined;
|
|
1269
|
+
return heldUntil === undefined ? due : Math.max(due, heldUntil);
|
|
1270
|
+
}
|
|
1271
|
+
/**
|
|
1272
|
+
* The tool calls a thread's turn holds for a person (spec 08 § Held tool calls):
|
|
1273
|
+
* calls waiting for approval, and calls whose tool left its result open. Each
|
|
1274
|
+
* carries what a decision needs to answer it.
|
|
1275
|
+
* @public
|
|
1276
|
+
*/
|
|
1277
|
+
async pending(scope) {
|
|
1278
|
+
const executionId = await this.heldExecutionId(scope);
|
|
1279
|
+
if (executionId === undefined) {
|
|
1280
|
+
return [];
|
|
1281
|
+
}
|
|
1282
|
+
const records = await heldCallsOf(this).list(executionId);
|
|
1283
|
+
return records.filter((record) => record.resolution === undefined).map(toHeldCall);
|
|
1284
|
+
}
|
|
1285
|
+
/**
|
|
1286
|
+
* Answer a held tool call: a decision for one that waits for approval, an output
|
|
1287
|
+
* for one that waits for its result. The turn then goes on — at once when it is
|
|
1288
|
+
* running here, and by being woken when it is parked.
|
|
1289
|
+
*
|
|
1290
|
+
* `scope` names the thread, or with `{ executionId }` an execution a host runs
|
|
1291
|
+
* itself through `harness.run()`.
|
|
1292
|
+
*
|
|
1293
|
+
* The first answer wins. The same answer again is a no-op, so a host may retry.
|
|
1294
|
+
* Pass the `argsHash` the call was shown with to make sure the answer is for it.
|
|
1295
|
+
*
|
|
1296
|
+
* @throws NoeticError `hold_refused` when the thread holds no such call,
|
|
1297
|
+
* `argsHash` names different arguments, the answer is the wrong kind for the
|
|
1298
|
+
* hold, or the call was already answered differently.
|
|
1299
|
+
* @internal Hosts answer through `execute()` with a `DecisionItem`, which
|
|
1300
|
+
* carries an `executionId` for a call held by a run the host started itself.
|
|
1301
|
+
* This is what that calls.
|
|
1302
|
+
*/
|
|
1303
|
+
async resolveHeld(scope, answer, options) {
|
|
1304
|
+
const executionId = await this.heldExecutionId(scope);
|
|
1305
|
+
if (executionId === undefined) {
|
|
1306
|
+
throw new NoeticErrorImpl({
|
|
1307
|
+
kind: 'hold_refused',
|
|
1308
|
+
callId: answer.callId,
|
|
1309
|
+
reason: 'the thread has no turn holding a call',
|
|
1310
|
+
});
|
|
1311
|
+
}
|
|
1312
|
+
const { callId, argsHash, ...resolution } = answer;
|
|
1313
|
+
await heldCallsOf(this).resolve(executionId, {
|
|
1314
|
+
callId,
|
|
1315
|
+
argsHash,
|
|
1316
|
+
resolution,
|
|
1317
|
+
});
|
|
1318
|
+
// A turn running here was told; a parked one has to be resumed. An execution
|
|
1319
|
+
// the host runs itself is the host's to resume.
|
|
1320
|
+
if (scope && 'executionId' in scope) {
|
|
1321
|
+
return;
|
|
1322
|
+
}
|
|
1323
|
+
const threadId = scope?.threadId ?? DEFAULT_THREAD_ID;
|
|
1324
|
+
const runner = this.sessions.get(threadId)?.runner;
|
|
1325
|
+
if (runner?.context === undefined) {
|
|
1326
|
+
await this.wake({
|
|
1327
|
+
threadId,
|
|
1328
|
+
options,
|
|
1329
|
+
});
|
|
1330
|
+
return;
|
|
1331
|
+
}
|
|
1332
|
+
// The turn is running here and was told. But it may have been parking as the
|
|
1333
|
+
// answer landed, too late to hear it: once it has come to rest, look again.
|
|
1334
|
+
void runner
|
|
1335
|
+
.whenIdle()
|
|
1336
|
+
.then(async () => {
|
|
1337
|
+
if ((await this.sessionStore?.load(threadId))?.turn?.parked) {
|
|
1338
|
+
await this.wake({
|
|
1339
|
+
threadId,
|
|
1340
|
+
options,
|
|
1341
|
+
});
|
|
1342
|
+
}
|
|
1343
|
+
})
|
|
1344
|
+
.catch(() => undefined);
|
|
1345
|
+
}
|
|
1346
|
+
//#region Versions and the trail
|
|
1347
|
+
/**
|
|
1348
|
+
* The turns that stopped rather than redo a step that had a lasting effect under
|
|
1349
|
+
* another flow version (spec 23 § Versions). Each waits for a `DecisionItem`
|
|
1350
|
+
* with `continue`, `restart` or `abandon`, passed to `execute()` on its thread.
|
|
1351
|
+
* @public
|
|
1352
|
+
*/
|
|
1353
|
+
async listStuckRuns() {
|
|
1354
|
+
if (!this.sessionStore) {
|
|
1355
|
+
return [];
|
|
1356
|
+
}
|
|
1357
|
+
const found = [];
|
|
1358
|
+
for (const threadId of await this.sessionStore.threads()) {
|
|
1359
|
+
const turn = (await this.sessionStore.load(threadId))?.turn;
|
|
1360
|
+
if (!turn?.stuck) {
|
|
1361
|
+
continue;
|
|
1362
|
+
}
|
|
1363
|
+
found.push({
|
|
1364
|
+
threadId,
|
|
1365
|
+
executionId: turn.executionId,
|
|
1366
|
+
...turn.stuck,
|
|
1367
|
+
});
|
|
1368
|
+
}
|
|
1369
|
+
return found;
|
|
1370
|
+
}
|
|
1371
|
+
/**
|
|
1372
|
+
* Settle a stuck turn (spec 23 § Versions). Resolves false when the thread has none.
|
|
1373
|
+
*
|
|
1374
|
+
* - `continue`: accept the difference. The turn resumes on this harness's
|
|
1375
|
+
* version, and the step that no longer matches runs again.
|
|
1376
|
+
* - `restart`: forget what the turn recorded and run it from the top on this
|
|
1377
|
+
* harness's version. Every step runs again, effects included.
|
|
1378
|
+
* - `abandon`: drop the turn. Its trail is kept.
|
|
1379
|
+
*/
|
|
1380
|
+
async settleStuckTurn(threadId, action, options) {
|
|
1381
|
+
const record = this.threadRecord(threadId);
|
|
1382
|
+
const turn = await record?.settle(action);
|
|
1383
|
+
if (!turn) {
|
|
1384
|
+
return false;
|
|
1385
|
+
}
|
|
1386
|
+
if (action === 'abandon') {
|
|
1387
|
+
await this.clearCheckpoint(turn.executionId);
|
|
1388
|
+
return true;
|
|
1389
|
+
}
|
|
1390
|
+
if (action === 'restart') {
|
|
1391
|
+
// The snapshot stays: it holds the turn's input. What the run recorded goes.
|
|
1392
|
+
// What the first run did still happened: its marks go on the trail first.
|
|
1393
|
+
const store = this.stepLedgerStore;
|
|
1394
|
+
if (store) {
|
|
1395
|
+
const { entries, seqs } = await store.load(turn.executionId);
|
|
1396
|
+
for (const [path, entry] of entries) {
|
|
1397
|
+
const seq = seqs.get(path);
|
|
1398
|
+
if (seq !== undefined) {
|
|
1399
|
+
await store.mark(turn.executionId, seq, stubOf(entry));
|
|
1400
|
+
}
|
|
1401
|
+
}
|
|
1402
|
+
await store.clear(turn.executionId);
|
|
1403
|
+
}
|
|
1404
|
+
await heldCallsOf(this).clear(turn.executionId);
|
|
1405
|
+
if (this.config.storage) {
|
|
1406
|
+
await clearPendingEntries(this.config.storage, turn.executionId);
|
|
1407
|
+
}
|
|
1408
|
+
}
|
|
1409
|
+
await this.wake({
|
|
1410
|
+
threadId,
|
|
1411
|
+
options,
|
|
1412
|
+
});
|
|
1413
|
+
return true;
|
|
1414
|
+
}
|
|
1415
|
+
/**
|
|
1416
|
+
* What a run did, step by step: who ran each step, under which flow version, and
|
|
1417
|
+
* the receipt of a step with a lasting effect (spec 23 § The trail). Marks outlive
|
|
1418
|
+
* the ledger entries they came from, so the trail of a finished run stays readable.
|
|
1419
|
+
*
|
|
1420
|
+
* `scope` names an execution, or a thread, whose recent turns are then listed in
|
|
1421
|
+
* order.
|
|
1422
|
+
* @public
|
|
1423
|
+
*/
|
|
1424
|
+
async getAuditTrail(scope) {
|
|
1425
|
+
const store = this.stepLedgerStore;
|
|
1426
|
+
if (!store) {
|
|
1427
|
+
return [];
|
|
1428
|
+
}
|
|
1429
|
+
const executionIds = 'executionId' in scope
|
|
1430
|
+
? [
|
|
1431
|
+
scope.executionId,
|
|
1432
|
+
]
|
|
1433
|
+
: ((await this.threadRecord(scope.threadId ?? DEFAULT_THREAD_ID)?.executions()) ?? []);
|
|
1434
|
+
const marks = [];
|
|
1435
|
+
for (const executionId of executionIds) {
|
|
1436
|
+
const kept = await store.trail(executionId);
|
|
1437
|
+
const live = [
|
|
1438
|
+
...(await store.load(executionId)).entries.values(),
|
|
1439
|
+
].map(stubOf);
|
|
1440
|
+
for (const mark of [
|
|
1441
|
+
...kept,
|
|
1442
|
+
...live,
|
|
1443
|
+
]) {
|
|
1444
|
+
marks.push({
|
|
1445
|
+
executionId,
|
|
1446
|
+
...mark,
|
|
1447
|
+
});
|
|
1448
|
+
}
|
|
1449
|
+
}
|
|
1450
|
+
return marks;
|
|
1451
|
+
}
|
|
1452
|
+
//#endregion
|
|
1453
|
+
//#region Triggers
|
|
1454
|
+
/**
|
|
1455
|
+
* Add a trigger while the harness runs (spec 35 § Triggers). A trigger written
|
|
1456
|
+
* with expressions only is kept in storage, so it is there again after a restart;
|
|
1457
|
+
* one with a function in it lasts for this process.
|
|
1458
|
+
*
|
|
1459
|
+
* @throws NoeticConfigError `CONNECTION_INVALID` for an id already in use, a
|
|
1460
|
+
* missing event or an expression that does not parse; `CONNECTION_UNKNOWN` for
|
|
1461
|
+
* an unknown connection.
|
|
1462
|
+
* @public
|
|
1463
|
+
*/
|
|
1464
|
+
async addTrigger(trigger) {
|
|
1465
|
+
await this.start();
|
|
1466
|
+
await this.#connections.triggers.add(trigger);
|
|
1467
|
+
await this.announceWakeTimeQuietly();
|
|
1468
|
+
}
|
|
1469
|
+
/**
|
|
1470
|
+
* Stop and forget a trigger. Resolves false when there is none with that id.
|
|
1471
|
+
* @public
|
|
1472
|
+
*/
|
|
1473
|
+
async removeTrigger(id) {
|
|
1474
|
+
// Started first, so a trigger kept from an earlier run is known to be there.
|
|
1475
|
+
await this.#connections.start();
|
|
1476
|
+
const removed = await this.#connections.triggers.remove(id);
|
|
1477
|
+
await this.announceWakeTimeQuietly();
|
|
1478
|
+
return removed;
|
|
1479
|
+
}
|
|
1480
|
+
/**
|
|
1481
|
+
* Every trigger the harness has: its own, and those added while it ran.
|
|
1482
|
+
* @public
|
|
1483
|
+
*/
|
|
1484
|
+
listTriggers() {
|
|
1485
|
+
return this.#connections.triggers.list();
|
|
1486
|
+
}
|
|
1487
|
+
//#endregion
|
|
1488
|
+
/** The watchers that wake this harness's parked turns, when auto-wake is on. */
|
|
1489
|
+
createParkWatchers(park) {
|
|
1490
|
+
if (this.parkGraceMs === undefined) {
|
|
1491
|
+
return undefined;
|
|
1492
|
+
}
|
|
1493
|
+
const config = park === true || park === undefined || park === false ? {} : park;
|
|
1494
|
+
if (config.autoWake === false) {
|
|
1495
|
+
return undefined;
|
|
1496
|
+
}
|
|
1497
|
+
const storage = this.config.storage;
|
|
1498
|
+
return new ParkWatchers({
|
|
1499
|
+
listen: async (connection, request) => {
|
|
1500
|
+
await this.start();
|
|
1501
|
+
return this.#connections.registry.listenRaw(connection, request);
|
|
1502
|
+
},
|
|
1503
|
+
waits: async (executionId) => (storage ? resumableWaitsOf(storage, executionId) : []),
|
|
1504
|
+
tasks: async (executionId) => (storage ? pendingTasksOf(storage, executionId) : []),
|
|
1505
|
+
taskState: async (task, signal) => {
|
|
1506
|
+
try {
|
|
1507
|
+
await this.start();
|
|
1508
|
+
const status = await this.#connections.registry.taskStatus(task.connection, task.taskId, signal);
|
|
1509
|
+
return status.state;
|
|
1510
|
+
}
|
|
1511
|
+
catch {
|
|
1512
|
+
return undefined;
|
|
1513
|
+
}
|
|
1514
|
+
},
|
|
1515
|
+
wake: async (threadId, options) => (await this.wake({
|
|
1516
|
+
threadId,
|
|
1517
|
+
options,
|
|
1518
|
+
})).length > 0,
|
|
1519
|
+
parked: async (threadId) => {
|
|
1520
|
+
const turn = (await this.sessionStore?.load(threadId))?.turn;
|
|
1521
|
+
return turn?.parked && !turn.stuck ? turn.executionId : undefined;
|
|
1522
|
+
},
|
|
1523
|
+
now: () => this.now(),
|
|
1524
|
+
}, config.wakeDebounceMs ?? DEFAULT_WAKE_DEBOUNCE_MS, config.taskPollMs ?? DEFAULT_TASK_POLL_MS);
|
|
1525
|
+
}
|
|
1526
|
+
/**
|
|
1527
|
+
* Messages that reached the runner while the thread's turn is parked or stuck
|
|
1528
|
+
* (one that landed as the turn was closing out, say). Starting a turn with them
|
|
1529
|
+
* would throw the waiting one away, so they are kept in storage for after it. A
|
|
1530
|
+
* steer wakes a parked turn, as one delivered a moment later would. An
|
|
1531
|
+
* `interrupt` is not set aside: replacing the turn is what it asks for.
|
|
1532
|
+
* Resolves true when the messages were set aside.
|
|
1533
|
+
*/
|
|
1534
|
+
async setAside(session, record, messages) {
|
|
1535
|
+
const turn = await record.turn();
|
|
1536
|
+
if (!turn || (!turn.parked && !turn.stuck)) {
|
|
1537
|
+
return false;
|
|
1538
|
+
}
|
|
1539
|
+
if (messages.some((message) => message.deliveryMode === 'interrupt')) {
|
|
1540
|
+
return false;
|
|
1541
|
+
}
|
|
1542
|
+
if (messages.every((message) => turn.messageIds.includes(message.id))) {
|
|
1543
|
+
return false;
|
|
1544
|
+
}
|
|
1545
|
+
for (const message of messages) {
|
|
1546
|
+
if (!turn.messageIds.includes(message.id)) {
|
|
1547
|
+
await keepForLater(session, record, message);
|
|
1548
|
+
}
|
|
1549
|
+
}
|
|
1550
|
+
if (turn.parked && messages.some(isSteer)) {
|
|
1551
|
+
const { threadId } = session.runner;
|
|
1552
|
+
void session.runner.whenIdle().then(() => this.wake({
|
|
1553
|
+
threadId,
|
|
1554
|
+
options: messages[0]?.options,
|
|
1555
|
+
}));
|
|
1556
|
+
}
|
|
1557
|
+
return true;
|
|
1558
|
+
}
|
|
1559
|
+
/** Resume a parked turn when one of its held calls already has an answer. */
|
|
1560
|
+
async wakeIfAnswered(threadId, executionId) {
|
|
1561
|
+
const records = await heldCallsOf(this).list(executionId);
|
|
1562
|
+
if (!records.some((record) => record.resolution !== undefined)) {
|
|
1563
|
+
return;
|
|
1564
|
+
}
|
|
1565
|
+
// The runner is still closing the parked turn out; let it go idle first.
|
|
1566
|
+
await this.sessions.get(threadId)?.runner.whenIdle();
|
|
1567
|
+
await this.wake({
|
|
1568
|
+
threadId,
|
|
1569
|
+
});
|
|
1570
|
+
}
|
|
1571
|
+
/**
|
|
1572
|
+
* A message delivered again after its turn finished (spec 23a § Sessions): a queue
|
|
1573
|
+
* that delivers at least once, or a webhook the sender retried. It is answered
|
|
1574
|
+
* with the answer that turn gave, and nothing runs. Resolves true when it was.
|
|
1575
|
+
*/
|
|
1576
|
+
async answerAgain(session, message) {
|
|
1577
|
+
const record = session.record;
|
|
1578
|
+
if (!record || session.runner.getStatus().kind !== 'idle' || session.runner.queue.size > 0) {
|
|
1579
|
+
return false;
|
|
1580
|
+
}
|
|
1581
|
+
const text = await record.answerFor(message.id);
|
|
1582
|
+
if (text === undefined) {
|
|
1583
|
+
return false;
|
|
1584
|
+
}
|
|
1585
|
+
session.runner.answerWith({
|
|
1586
|
+
items: await record.history(),
|
|
1587
|
+
usage: {
|
|
1588
|
+
inputTokens: 0,
|
|
1589
|
+
outputTokens: 0,
|
|
1590
|
+
},
|
|
1591
|
+
text,
|
|
1592
|
+
replayed: true,
|
|
1593
|
+
}, message.id);
|
|
1594
|
+
return true;
|
|
1595
|
+
}
|
|
1596
|
+
/**
|
|
1597
|
+
* A message delivered again while this harness already has it in hand: its turn is
|
|
1598
|
+
* running, it is queued to run, or its turn finished a moment ago and the runner
|
|
1599
|
+
* has not gone idle yet (spec 23a § Sessions). Queuing it would run the same
|
|
1600
|
+
* message as a second turn once the first ends. It is dropped; the caller reads
|
|
1601
|
+
* the answer of the turn that has it. Resolves true when it was.
|
|
1602
|
+
*/
|
|
1603
|
+
async inHand(session, message) {
|
|
1604
|
+
if (message.deliveryMode === 'interrupt') {
|
|
1605
|
+
return false;
|
|
1606
|
+
}
|
|
1607
|
+
const { runner, record } = session;
|
|
1608
|
+
if (runner.getStatus().kind === 'idle' && runner.queue.size === 0) {
|
|
1609
|
+
return false;
|
|
1610
|
+
}
|
|
1611
|
+
if (runner.queue.peekAll().some((queued) => queued.id === message.id)) {
|
|
1612
|
+
return true;
|
|
1613
|
+
}
|
|
1614
|
+
// Known from the first instant of the turn, before its record is written and
|
|
1615
|
+
// on a harness with no storage at all.
|
|
1616
|
+
if (runner.isRunning(message.id)) {
|
|
1617
|
+
return true;
|
|
1618
|
+
}
|
|
1619
|
+
if (!record) {
|
|
1620
|
+
return false;
|
|
1621
|
+
}
|
|
1622
|
+
if ((await record.turn())?.messageIds.includes(message.id)) {
|
|
1623
|
+
return true;
|
|
1624
|
+
}
|
|
1625
|
+
if ((await record.answerFor(message.id)) === undefined) {
|
|
1626
|
+
return false;
|
|
1627
|
+
}
|
|
1628
|
+
// Its turn finished earlier, and another is running now. It is not run again,
|
|
1629
|
+
// and it is not left unanswered: once the thread rests it is delivered again,
|
|
1630
|
+
// and answered from the record then (`turn_replayed` carries the answer).
|
|
1631
|
+
void runner
|
|
1632
|
+
.whenIdle()
|
|
1633
|
+
.then(() => this.deliver(session, message))
|
|
1634
|
+
.catch(() => undefined);
|
|
1635
|
+
return true;
|
|
1636
|
+
}
|
|
1637
|
+
/**
|
|
1638
|
+
* A message for a thread whose turn is parked (spec 23 § Parked turns). It must not
|
|
1639
|
+
* start a turn of its own: the thread has one in flight, and starting another would
|
|
1640
|
+
* abandon it. Resolves true when the message was taken care of here.
|
|
1641
|
+
*
|
|
1642
|
+
* - `next-turn` waits in storage for the parked turn to end.
|
|
1643
|
+
* - A steer wakes the turn, which offers it to the context layers as it would mid-round.
|
|
1644
|
+
* - `interrupt` is not handled here: it replaces the turn, as it does a running one.
|
|
1645
|
+
*/
|
|
1646
|
+
async deliverToParked(session, message) {
|
|
1647
|
+
const record = session.record;
|
|
1648
|
+
if (!record || message.deliveryMode === 'interrupt') {
|
|
1649
|
+
return false;
|
|
1650
|
+
}
|
|
1651
|
+
if (session.runner.getStatus().kind !== 'idle' || session.runner.queue.size > 0) {
|
|
1652
|
+
return false;
|
|
1653
|
+
}
|
|
1654
|
+
const turn = await record.turn();
|
|
1655
|
+
if (!turn?.parked || turn.messageIds.includes(message.id)) {
|
|
1656
|
+
return false;
|
|
1657
|
+
}
|
|
1658
|
+
await keepForLater(session, record, message);
|
|
1659
|
+
if (isSteer(message)) {
|
|
1660
|
+
await this.wake({
|
|
1661
|
+
threadId: session.runner.threadId,
|
|
1662
|
+
options: message.options,
|
|
1663
|
+
});
|
|
1664
|
+
}
|
|
1665
|
+
return true;
|
|
1666
|
+
}
|
|
1667
|
+
/** The execution whose held calls `scope` names. */
|
|
1668
|
+
heldExecutionId(scope) {
|
|
1669
|
+
if (scope && 'executionId' in scope) {
|
|
1670
|
+
return Promise.resolve(scope.executionId);
|
|
1671
|
+
}
|
|
1672
|
+
return this.turnExecutionId(scope?.threadId ?? DEFAULT_THREAD_ID);
|
|
1673
|
+
}
|
|
1674
|
+
/** The execution of the thread's turn in flight: running here, or stored. */
|
|
1675
|
+
async turnExecutionId(threadId) {
|
|
1676
|
+
const running = this.sessions.get(threadId)?.runner.context;
|
|
1677
|
+
if (running) {
|
|
1678
|
+
return rootIdOf(running);
|
|
1679
|
+
}
|
|
1680
|
+
return (await this.sessionStore?.load(threadId))?.turn?.executionId;
|
|
1681
|
+
}
|
|
1682
|
+
/** The harness clock. */
|
|
1683
|
+
now() {
|
|
1684
|
+
return this.config.now?.() ?? Date.now();
|
|
1685
|
+
}
|
|
1686
|
+
/** Hand the turn's lease back and return the thread record to best-effort writes. */
|
|
1687
|
+
async releaseLease(session) {
|
|
1688
|
+
const lease = session.lease;
|
|
1689
|
+
session.lease = undefined;
|
|
1690
|
+
session.record?.hold(undefined);
|
|
1691
|
+
await lease?.release();
|
|
1692
|
+
}
|
|
621
1693
|
/** The stored record for `threadId`, when durability is on. */
|
|
622
1694
|
threadRecord(threadId) {
|
|
623
1695
|
if (!this.sessionStore) {
|
|
@@ -625,6 +1697,7 @@ export class AgentHarness {
|
|
|
625
1697
|
}
|
|
626
1698
|
return new ThreadRecord({
|
|
627
1699
|
store: this.sessionStore,
|
|
1700
|
+
version: this.version,
|
|
628
1701
|
restore: (executionId, opts) => this.restore(executionId, opts),
|
|
629
1702
|
clearCheckpoint: (executionId) => this.clearCheckpoint(executionId),
|
|
630
1703
|
parseItems: (raw) => this.itemSchemas.parseMany(raw),
|
|
@@ -654,6 +1727,33 @@ export class AgentHarness {
|
|
|
654
1727
|
async decide(request) {
|
|
655
1728
|
return this.llm.decide(request, (r) => this.callModel(r));
|
|
656
1729
|
}
|
|
1730
|
+
/**
|
|
1731
|
+
* The approval seam (spec 08 § Held tool calls): the `approveToolCall` approver
|
|
1732
|
+
* decides, and with none, or when it answers `hold`, the action is held until
|
|
1733
|
+
* a decision answers it. Resolves the settled decision.
|
|
1734
|
+
* @public
|
|
1735
|
+
*/
|
|
1736
|
+
async approve(request) {
|
|
1737
|
+
const approval = await awaitApproval({
|
|
1738
|
+
harness: this,
|
|
1739
|
+
toolName: request.toolName,
|
|
1740
|
+
toolArgs: request.toolArgs,
|
|
1741
|
+
callId: request.callId,
|
|
1742
|
+
ctx: request.ctx,
|
|
1743
|
+
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
|
+
});
|
|
1755
|
+
return approval.decision;
|
|
1756
|
+
}
|
|
657
1757
|
async notifyDecision(layers, record, ctx) {
|
|
658
1758
|
await this.trackHook(ctx, notifyDecision({
|
|
659
1759
|
layers,
|
|
@@ -795,7 +1895,8 @@ export class AgentHarness {
|
|
|
795
1895
|
}
|
|
796
1896
|
try {
|
|
797
1897
|
await entry.ready;
|
|
798
|
-
|
|
1898
|
+
const result = await execute(s, input, ctx);
|
|
1899
|
+
return result;
|
|
799
1900
|
}
|
|
800
1901
|
catch (error) {
|
|
801
1902
|
entry.failed = true;
|
|
@@ -819,9 +1920,39 @@ export class AgentHarness {
|
|
|
819
1920
|
}
|
|
820
1921
|
// The turn's own connections end with it; a resume attaches them again.
|
|
821
1922
|
await this.#connections.release(ctx.id);
|
|
1923
|
+
await this.saveOutputOfRun(ctx.threadId);
|
|
1924
|
+
this.forgetOwnThread(ctx.threadId);
|
|
822
1925
|
}
|
|
823
1926
|
}
|
|
824
1927
|
}
|
|
1928
|
+
/**
|
|
1929
|
+
* Wait for what a run streamed to be saved. Display output never decides a run:
|
|
1930
|
+
* a save that failed is logged, stays queued for the next flush, and the run's
|
|
1931
|
+
* own result or error stands.
|
|
1932
|
+
*/
|
|
1933
|
+
async saveOutputOfRun(threadId) {
|
|
1934
|
+
try {
|
|
1935
|
+
await this.outputs.get(threadId)?.flush();
|
|
1936
|
+
}
|
|
1937
|
+
catch (error) {
|
|
1938
|
+
console.warn('[noetic] could not save the display output of a run:', error);
|
|
1939
|
+
}
|
|
1940
|
+
}
|
|
1941
|
+
/**
|
|
1942
|
+
* A thread named by a host-built context's own id has no later turns: once its
|
|
1943
|
+
* run ends, the harness drops its session and output store. What was saved stays
|
|
1944
|
+
* in storage under `output:<ctx.id>`.
|
|
1945
|
+
*/
|
|
1946
|
+
forgetOwnThread(threadId) {
|
|
1947
|
+
// The thread is named by its context's id, so that context's root run is its only one.
|
|
1948
|
+
if (!this.ownThreads.delete(threadId) || this.liveRoots.has(threadId)) {
|
|
1949
|
+
return;
|
|
1950
|
+
}
|
|
1951
|
+
this.stopRecording.get(threadId)?.();
|
|
1952
|
+
this.stopRecording.delete(threadId);
|
|
1953
|
+
this.outputs.delete(threadId);
|
|
1954
|
+
this.sessions.delete(threadId);
|
|
1955
|
+
}
|
|
825
1956
|
/**
|
|
826
1957
|
* Fix the point a resume of this run starts from, and queue it for saving — so even
|
|
827
1958
|
* a run whose first step dies leaves a snapshot to restore. The save is not awaited:
|
|
@@ -953,9 +2084,18 @@ export class AgentHarness {
|
|
|
953
2084
|
* can be keyed to it — the ledger's storage keys and `ctx.id` must agree for a
|
|
954
2085
|
* later `restore()` to find what this run recorded. */
|
|
955
2086
|
const executionId = crypto.randomUUID();
|
|
2087
|
+
const ledger = this.stepLedgerStore
|
|
2088
|
+
? new StepLedger({
|
|
2089
|
+
executionId,
|
|
2090
|
+
store: this.stepLedgerStore,
|
|
2091
|
+
retention: this.stepLedgerRetention,
|
|
2092
|
+
})
|
|
2093
|
+
: undefined;
|
|
2094
|
+
ledger?.runAs(this.version);
|
|
956
2095
|
return new ContextImpl({
|
|
957
2096
|
...rest,
|
|
958
2097
|
id: executionId,
|
|
2098
|
+
...this.interactiveThread(resolved, executionId),
|
|
959
2099
|
harness: this,
|
|
960
2100
|
channelStore: this.channelStore,
|
|
961
2101
|
layers: effectiveLayers,
|
|
@@ -964,15 +2104,27 @@ export class AgentHarness {
|
|
|
964
2104
|
// Without this `ctx.checkpoint()` is inert, and the boundaries below never
|
|
965
2105
|
// persist anything (a no-op when no CheckpointStore is configured).
|
|
966
2106
|
checkpointFn: (c) => this.checkpoint(c),
|
|
967
|
-
ledger
|
|
968
|
-
? new StepLedger({
|
|
969
|
-
executionId,
|
|
970
|
-
store: this.stepLedgerStore,
|
|
971
|
-
retention: this.stepLedgerRetention,
|
|
972
|
-
})
|
|
973
|
-
: undefined,
|
|
2107
|
+
ledger,
|
|
974
2108
|
});
|
|
975
2109
|
}
|
|
2110
|
+
/**
|
|
2111
|
+
* On an interactive harness, a root context a host builds joins its thread: it
|
|
2112
|
+
* gets the thread's broadcaster, so `run()` on it streams, and is recorded, like
|
|
2113
|
+
* a session turn. A context with no `threadId` is its own thread, named by its id.
|
|
2114
|
+
*/
|
|
2115
|
+
interactiveThread(opts, executionId) {
|
|
2116
|
+
if (!this.interactive || opts.parent || opts._broadcaster) {
|
|
2117
|
+
return {};
|
|
2118
|
+
}
|
|
2119
|
+
const threadId = opts.threadId ?? executionId;
|
|
2120
|
+
if (opts.threadId === undefined) {
|
|
2121
|
+
this.ownThreads.add(threadId);
|
|
2122
|
+
}
|
|
2123
|
+
return {
|
|
2124
|
+
threadId,
|
|
2125
|
+
_broadcaster: this.getOrCreateSession(threadId).runner.broadcaster,
|
|
2126
|
+
};
|
|
2127
|
+
}
|
|
976
2128
|
send(channel, value, ctx) {
|
|
977
2129
|
// Internal sender: back-pressured on full queue channels. The calling
|
|
978
2130
|
// context's abort signal rejects a parked send with 'cancelled'.
|
|
@@ -1202,7 +2354,13 @@ export class AgentHarness {
|
|
|
1202
2354
|
*/
|
|
1203
2355
|
saveCheckpoint(ctx) {
|
|
1204
2356
|
const prior = this.pendingCheckpoints.get(ctx.id);
|
|
1205
|
-
const next = (prior ?? Promise.resolve(true)).then(() =>
|
|
2357
|
+
const next = (prior ?? Promise.resolve(true)).then(() => {
|
|
2358
|
+
// A harness that was replaced must not overwrite the new holder's snapshot.
|
|
2359
|
+
if (ctx instanceof ContextImpl && ctx.ledger?.isHeld === false) {
|
|
2360
|
+
return false;
|
|
2361
|
+
}
|
|
2362
|
+
return captureCheckpoint(this, ctx);
|
|
2363
|
+
});
|
|
1206
2364
|
this.pendingCheckpoints.set(ctx.id, next);
|
|
1207
2365
|
void next.finally(() => {
|
|
1208
2366
|
if (this.pendingCheckpoints.get(ctx.id) === next) {
|
|
@@ -1245,6 +2403,10 @@ export class AgentHarness {
|
|
|
1245
2403
|
if (restored.fromSnapshot) {
|
|
1246
2404
|
this.restoredExecutions.add(executionId);
|
|
1247
2405
|
}
|
|
2406
|
+
// The restored ledger is a new one: it records under this harness's version too.
|
|
2407
|
+
if (restored.ctx instanceof ContextImpl) {
|
|
2408
|
+
restored.ctx.ledger?.runAs(this.version);
|
|
2409
|
+
}
|
|
1248
2410
|
await this.spend?.adopt(restored.ctx);
|
|
1249
2411
|
// Granted only to the context this restore returns: a restore that fails, or a
|
|
1250
2412
|
// later plain restore of the same id, never inherits it (spec 35 § Durability).
|
|
@@ -1267,7 +2429,13 @@ export class AgentHarness {
|
|
|
1267
2429
|
* behind, and nothing else enumerates them.
|
|
1268
2430
|
*/
|
|
1269
2431
|
async clearCheckpoint(executionId) {
|
|
1270
|
-
|
|
2432
|
+
await clearCheckpoint(this, executionId);
|
|
2433
|
+
// Calls the execution held for a person have nobody left to answer to.
|
|
2434
|
+
await heldCallsOf(this).clear(executionId);
|
|
2435
|
+
// Nor is anything left to pick up what its steps were waiting on.
|
|
2436
|
+
if (this.config.storage) {
|
|
2437
|
+
await clearPendingEntries(this.config.storage, executionId);
|
|
2438
|
+
}
|
|
1271
2439
|
}
|
|
1272
2440
|
//#endregion
|
|
1273
2441
|
//#region Spend
|