@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
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
* (spec 23a § Connection Steps).
|
|
8
8
|
*/
|
|
9
9
|
import { frameworkCast, NoeticErrorImpl } from '@noetic-tools/types';
|
|
10
|
+
import { ContextImpl } from '../runtime/context-impl.js';
|
|
10
11
|
import { evaluateTarget, reconcilePending, resolveStepConnection, signalOf, } from './connection-steps.js';
|
|
11
12
|
import { isStepList } from './step-walk.js';
|
|
12
13
|
//#endregion
|
|
@@ -30,9 +31,24 @@ async function runAround(steps, input, ctx, executeStep) {
|
|
|
30
31
|
}
|
|
31
32
|
return current;
|
|
32
33
|
}
|
|
34
|
+
/**
|
|
35
|
+
* Runs the step's filter on one event. A filter is work, not waiting: while it runs
|
|
36
|
+
* the turn must not park, or a filter slower than the park's grace would be cut off
|
|
37
|
+
* on every wake and its event never delivered.
|
|
38
|
+
*/
|
|
39
|
+
async function passesFilter(filter, event, listen) {
|
|
40
|
+
const { ctx, input } = listen;
|
|
41
|
+
const busy = ctx instanceof ContextImpl ? ctx.ledger?.parking.enter(undefined) : undefined;
|
|
42
|
+
try {
|
|
43
|
+
return await filter(event, input, ctx);
|
|
44
|
+
}
|
|
45
|
+
finally {
|
|
46
|
+
busy?.();
|
|
47
|
+
}
|
|
48
|
+
}
|
|
33
49
|
/** Consumes the stream until an event the filter accepts arrives, or the stream ends. */
|
|
34
50
|
async function listenForMatch(listen) {
|
|
35
|
-
const { step,
|
|
51
|
+
const { step, stream } = listen;
|
|
36
52
|
// The registry's stream emits `connection_event` and `stream_changed` (once each).
|
|
37
53
|
for await (const message of stream) {
|
|
38
54
|
if (message.type === 'gap') {
|
|
@@ -48,7 +64,7 @@ async function listenForMatch(listen) {
|
|
|
48
64
|
if (event.type !== step.event) {
|
|
49
65
|
continue;
|
|
50
66
|
}
|
|
51
|
-
if (step.filter && !(await step.filter
|
|
67
|
+
if (step.filter && !(await passesFilter(step.filter, event, listen))) {
|
|
52
68
|
continue;
|
|
53
69
|
}
|
|
54
70
|
return {
|
|
@@ -61,12 +77,16 @@ async function listenForMatch(listen) {
|
|
|
61
77
|
reason: 'the event stream closed',
|
|
62
78
|
};
|
|
63
79
|
}
|
|
64
|
-
/**
|
|
65
|
-
function
|
|
80
|
+
/** The harness clock (`AgentHarness({ now })`), which deadlines are read from. */
|
|
81
|
+
function nowOf(ctx) {
|
|
82
|
+
return ctx.harness.config.now?.() ?? Date.now();
|
|
83
|
+
}
|
|
84
|
+
/** Resolves `undefined` once `remainingMs` pass or `signal` aborts; `clear` cancels the timer. */
|
|
85
|
+
function deadlineTimer(remainingMs, signal) {
|
|
66
86
|
let timer;
|
|
67
87
|
let onAbort;
|
|
68
88
|
const promise = new Promise((resolve) => {
|
|
69
|
-
timer = setTimeout(() => resolve(undefined), Math.max(0,
|
|
89
|
+
timer = setTimeout(() => resolve(undefined), Math.max(0, remainingMs));
|
|
70
90
|
onAbort = () => resolve(undefined);
|
|
71
91
|
signal.addEventListener('abort', onAbort, {
|
|
72
92
|
once: true,
|
|
@@ -98,8 +118,8 @@ function timeoutError(step) {
|
|
|
98
118
|
});
|
|
99
119
|
}
|
|
100
120
|
/** Waits for the listener or the deadline, whichever comes first; `undefined` means the deadline. */
|
|
101
|
-
async function awaitOutcome(matched,
|
|
102
|
-
const timer = deadlineTimer(
|
|
121
|
+
async function awaitOutcome(matched, remainingMs, signal) {
|
|
122
|
+
const timer = deadlineTimer(remainingMs, signal);
|
|
103
123
|
try {
|
|
104
124
|
return await Promise.race([
|
|
105
125
|
matched,
|
|
@@ -114,7 +134,7 @@ async function awaitOutcome(matched, deadline, signal) {
|
|
|
114
134
|
async function recordListening(listen, prior) {
|
|
115
135
|
const { step, connection, stream } = listen;
|
|
116
136
|
const { cursor } = await stream.ready;
|
|
117
|
-
const deadline = prior?.deadline ??
|
|
137
|
+
const deadline = prior?.deadline ?? nowOf(frameworkCast(listen.ctx)) + step.timeoutMs;
|
|
118
138
|
await connection.pending?.write({
|
|
119
139
|
stepId: step.id,
|
|
120
140
|
kind: 'wait',
|
|
@@ -123,6 +143,12 @@ async function recordListening(listen, prior) {
|
|
|
123
143
|
identity: connection.resolved.identity(),
|
|
124
144
|
cursor: prior?.cursor ?? cursor,
|
|
125
145
|
deadline,
|
|
146
|
+
event: step.event,
|
|
147
|
+
...(replaysFromCursor(listen)
|
|
148
|
+
? {
|
|
149
|
+
durable: true,
|
|
150
|
+
}
|
|
151
|
+
: {}),
|
|
126
152
|
...(connection.resolved.lease
|
|
127
153
|
? {
|
|
128
154
|
leaseId: connection.resolved.lease.id,
|
|
@@ -142,7 +168,15 @@ async function waitOnStream(opts) {
|
|
|
142
168
|
const around = step.around === undefined
|
|
143
169
|
? undefined
|
|
144
170
|
: await runAround(aroundSteps(step), input, ctx, executeStep);
|
|
145
|
-
const
|
|
171
|
+
const baseCtx = frameworkCast(ctx);
|
|
172
|
+
const stopWaiting = markWaiting(listen, deadline);
|
|
173
|
+
let outcome;
|
|
174
|
+
try {
|
|
175
|
+
outcome = await awaitOutcome(matched, deadline - nowOf(baseCtx), runSignal);
|
|
176
|
+
}
|
|
177
|
+
finally {
|
|
178
|
+
stopWaiting();
|
|
179
|
+
}
|
|
146
180
|
const event = matchedEvent(listen, outcome, runSignal);
|
|
147
181
|
await listen.connection.pending?.clear();
|
|
148
182
|
return {
|
|
@@ -154,6 +188,30 @@ async function waitOnStream(opts) {
|
|
|
154
188
|
}),
|
|
155
189
|
};
|
|
156
190
|
}
|
|
191
|
+
/** True when the event this wait listens for replays from a cursor. */
|
|
192
|
+
function replaysFromCursor(listen) {
|
|
193
|
+
return listen.connection.resolved.manifest.events[listen.step.event]?.replay === 'durable';
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* Tells the turn's parking that this step is now only waiting, when the wait can be
|
|
197
|
+
* picked up again without loss: the event replays from a cursor, so a turn that
|
|
198
|
+
* parks here and wakes later still sees an event that arrived in between
|
|
199
|
+
* (spec 23 § Parked turns). Returns what to call when the wait ends.
|
|
200
|
+
*/
|
|
201
|
+
function markWaiting(listen, deadline) {
|
|
202
|
+
const { ctx } = listen;
|
|
203
|
+
if (!(ctx instanceof ContextImpl) || !ctx.ledger) {
|
|
204
|
+
return () => { };
|
|
205
|
+
}
|
|
206
|
+
if (!replaysFromCursor(listen)) {
|
|
207
|
+
return () => { };
|
|
208
|
+
}
|
|
209
|
+
// A wait whose time is already up is about to fail, not to wait.
|
|
210
|
+
if (deadline <= nowOf(frameworkCast(ctx))) {
|
|
211
|
+
return () => { };
|
|
212
|
+
}
|
|
213
|
+
return ctx.ledger.parking.wait(ctx.currentDispatch()?.path, deadline);
|
|
214
|
+
}
|
|
157
215
|
/**
|
|
158
216
|
* The event that ended the wait (the registry already emitted it as `connection_event`).
|
|
159
217
|
*
|
|
@@ -288,6 +288,8 @@ async function executeStep(step, input, ctx) {
|
|
|
288
288
|
}
|
|
289
289
|
return replay.output;
|
|
290
290
|
}
|
|
291
|
+
// Parking needs to know which steps are in flight (spec 23 § Parked turns).
|
|
292
|
+
const leaveParking = ledger?.parking.enter(lane?.currentDispatch()?.path);
|
|
291
293
|
let result;
|
|
292
294
|
try {
|
|
293
295
|
await beginEmitItems(step, input, stepCtx);
|
|
@@ -310,6 +312,7 @@ async function executeStep(step, input, ctx) {
|
|
|
310
312
|
}
|
|
311
313
|
}
|
|
312
314
|
catch (error) {
|
|
315
|
+
leaveParking?.();
|
|
313
316
|
lane?.releaseDispatch();
|
|
314
317
|
drains?.release(frameworkCast(stepCtx));
|
|
315
318
|
throw error;
|
|
@@ -350,5 +353,6 @@ async function executeStep(step, input, ctx) {
|
|
|
350
353
|
// they are charged and the step recorded. A call a failed record leaves
|
|
351
354
|
// behind is released when an enclosing step ends.
|
|
352
355
|
drains?.release(frameworkCast(stepCtx));
|
|
356
|
+
leaveParking?.();
|
|
353
357
|
return result;
|
|
354
358
|
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Errors that end the whole turn, whichever step they surface in (spec 23
|
|
3
|
+
* § Versions, § One writer per turn). A step that retries, wraps, collects or
|
|
4
|
+
* skips its children's errors must let these through as they are: the harness
|
|
5
|
+
* reads the kind to know why the turn stopped, and a retry could not help.
|
|
6
|
+
*/
|
|
7
|
+
import { NoeticErrorImpl } from '@noetic-tools/types';
|
|
8
|
+
/** @internal The kinds that end a turn. */
|
|
9
|
+
export declare const TURN_ENDING_KINDS: ReadonlySet<string>;
|
|
10
|
+
/**
|
|
11
|
+
* @internal
|
|
12
|
+
* The turn-ending error inside `error`, when there is one: `error` itself, the
|
|
13
|
+
* cause of a `step_failed`, or a path's failure folded into a `fork_partial`.
|
|
14
|
+
*/
|
|
15
|
+
export declare function turnEndingIn(error: unknown): NoeticErrorImpl | undefined;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Errors that end the whole turn, whichever step they surface in (spec 23
|
|
3
|
+
* § Versions, § One writer per turn). A step that retries, wraps, collects or
|
|
4
|
+
* skips its children's errors must let these through as they are: the harness
|
|
5
|
+
* reads the kind to know why the turn stopped, and a retry could not help.
|
|
6
|
+
*/
|
|
7
|
+
import { isNoeticError, NoeticErrorImpl } from '@noetic-tools/types';
|
|
8
|
+
/** @internal The kinds that end a turn. */
|
|
9
|
+
export const TURN_ENDING_KINDS = new Set([
|
|
10
|
+
'turn_stuck',
|
|
11
|
+
'lease_lost',
|
|
12
|
+
'ledger_write_failed',
|
|
13
|
+
]);
|
|
14
|
+
function endingIn(error) {
|
|
15
|
+
if (TURN_ENDING_KINDS.has(error.kind)) {
|
|
16
|
+
return error;
|
|
17
|
+
}
|
|
18
|
+
if (error.kind === 'fork_partial') {
|
|
19
|
+
for (const failure of error.failed) {
|
|
20
|
+
const found = endingIn(failure.error);
|
|
21
|
+
if (found) {
|
|
22
|
+
return found;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
return undefined;
|
|
26
|
+
}
|
|
27
|
+
if (error.kind === 'step_failed') {
|
|
28
|
+
return isNoeticError(error.cause) ? endingIn(error.cause.noeticError) : undefined;
|
|
29
|
+
}
|
|
30
|
+
return undefined;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* @internal
|
|
34
|
+
* The turn-ending error inside `error`, when there is one: `error` itself, the
|
|
35
|
+
* cause of a `step_failed`, or a path's failure folded into a `fork_partial`.
|
|
36
|
+
*/
|
|
37
|
+
export function turnEndingIn(error) {
|
|
38
|
+
if (!isNoeticError(error)) {
|
|
39
|
+
return undefined;
|
|
40
|
+
}
|
|
41
|
+
const found = endingIn(error.noeticError);
|
|
42
|
+
if (!found) {
|
|
43
|
+
return undefined;
|
|
44
|
+
}
|
|
45
|
+
return found === error.noeticError ? error : new NoeticErrorImpl(found);
|
|
46
|
+
}
|
|
@@ -11,4 +11,4 @@ export { spawn } from '../builders/spawn-builder.js';
|
|
|
11
11
|
/** @public */
|
|
12
12
|
export { callModel, invokeTool, runCode, step } from '../builders/step-builders.js';
|
|
13
13
|
/** @public */
|
|
14
|
-
export { tool, toolWithGenerator } from '../builders/tool-builder.js';
|
|
14
|
+
export { hold, tool, toolWithGenerator } from '../builders/tool-builder.js';
|
|
@@ -14,4 +14,4 @@ export { spawn } from '../builders/spawn-builder.js';
|
|
|
14
14
|
/** @public */
|
|
15
15
|
export { callModel, invokeTool, runCode, step } from '../builders/step-builders.js';
|
|
16
16
|
/** @public */
|
|
17
|
-
export { tool, toolWithGenerator } from '../builders/tool-builder.js';
|
|
17
|
+
export { hold, tool, toolWithGenerator } from '../builders/tool-builder.js';
|
|
@@ -2,3 +2,7 @@
|
|
|
2
2
|
export { AgentHarness } from '../harness/agent-harness.js';
|
|
3
3
|
/** @public */
|
|
4
4
|
export { createInMemoryStorage } from '../runtime/in-memory-storage.js';
|
|
5
|
+
/** @public */
|
|
6
|
+
export type { OutputSnapshot } from '../runtime/output-store.js';
|
|
7
|
+
/** @public */
|
|
8
|
+
export { OutputStore, OutputStoreError } from '../runtime/output-store.js';
|
package/dist/portable/runtime.js
CHANGED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Parking: letting a turn stop holding a process while every part of it waits
|
|
3
|
+
* (spec 23 § Parked turns).
|
|
4
|
+
*
|
|
5
|
+
* A turn that reaches a `wait` step today sits on a timer until the event comes.
|
|
6
|
+
* What it waits for is already in storage (the pending entry: connection, event,
|
|
7
|
+
* cursor, deadline), so the process adds nothing but its own uptime. A parked
|
|
8
|
+
* turn drops the process: its record says `parked` and when to wake it, its lease
|
|
9
|
+
* is handed back, and any harness on the same storage picks it up later. The
|
|
10
|
+
* ledger replays what finished, and the wait listens again from its cursor.
|
|
11
|
+
*
|
|
12
|
+
* `Parking` decides when that is safe. It tracks the steps in flight and parks
|
|
13
|
+
* only when every innermost one is a wait that can be resumed without loss. A
|
|
14
|
+
* step doing anything else — a model call, user code, a tool — keeps the turn
|
|
15
|
+
* live.
|
|
16
|
+
*/
|
|
17
|
+
/** The abort reason of a context whose turn parked. */
|
|
18
|
+
export declare const PARK_REASON = "parked";
|
|
19
|
+
/** @public How long every in-flight step must stay waiting before a turn parks, by default. */
|
|
20
|
+
export declare const DEFAULT_PARK_GRACE_MS = 100;
|
|
21
|
+
/** @internal What arms a turn's parking. */
|
|
22
|
+
export interface ParkingOptions {
|
|
23
|
+
/** How long every in-flight step must stay waiting before the turn parks. */
|
|
24
|
+
readonly graceMs: number;
|
|
25
|
+
/** Called once, with the earliest deadline among the waits. */
|
|
26
|
+
readonly onPark: (wakeAt: number) => void;
|
|
27
|
+
}
|
|
28
|
+
/** Whether `path` lies in the subtree under `parent` — a lane below it or a child context's prefix. */
|
|
29
|
+
export declare function isBeneath(path: string, parent: string): boolean;
|
|
30
|
+
/**
|
|
31
|
+
* @internal
|
|
32
|
+
* One execution's parking state. Lives on the step ledger, which every context
|
|
33
|
+
* of the execution already shares.
|
|
34
|
+
*/
|
|
35
|
+
export declare class Parking {
|
|
36
|
+
private readonly running;
|
|
37
|
+
private armed;
|
|
38
|
+
private timer;
|
|
39
|
+
private until;
|
|
40
|
+
private anonymous;
|
|
41
|
+
/** Turn parking on for this execution. Without it nothing ever parks. */
|
|
42
|
+
arm(options: ParkingOptions): void;
|
|
43
|
+
/** When the parked turn should be woken, or undefined while it has not parked. */
|
|
44
|
+
get parkedUntil(): number | undefined;
|
|
45
|
+
/**
|
|
46
|
+
* A step began running at `path`. Returns what to call when it is done. A step
|
|
47
|
+
* with no path is tracked on its own, so it still keeps the turn live.
|
|
48
|
+
*/
|
|
49
|
+
enter(path: string | undefined): () => void;
|
|
50
|
+
/**
|
|
51
|
+
* The step at `path` is waiting until `until` and can be resumed without loss.
|
|
52
|
+
* Returns what to call when it stops waiting.
|
|
53
|
+
*/
|
|
54
|
+
wait(path: string | undefined, until: number): () => void;
|
|
55
|
+
/** The step in flight that `path` is directly beneath. */
|
|
56
|
+
private parentOf;
|
|
57
|
+
/** The earliest deadline when every innermost step is waiting, else undefined. */
|
|
58
|
+
private wakeAt;
|
|
59
|
+
/** Start or cancel the countdown to parking, after any change. */
|
|
60
|
+
private settle;
|
|
61
|
+
}
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Parking: letting a turn stop holding a process while every part of it waits
|
|
3
|
+
* (spec 23 § Parked turns).
|
|
4
|
+
*
|
|
5
|
+
* A turn that reaches a `wait` step today sits on a timer until the event comes.
|
|
6
|
+
* What it waits for is already in storage (the pending entry: connection, event,
|
|
7
|
+
* cursor, deadline), so the process adds nothing but its own uptime. A parked
|
|
8
|
+
* turn drops the process: its record says `parked` and when to wake it, its lease
|
|
9
|
+
* is handed back, and any harness on the same storage picks it up later. The
|
|
10
|
+
* ledger replays what finished, and the wait listens again from its cursor.
|
|
11
|
+
*
|
|
12
|
+
* `Parking` decides when that is safe. It tracks the steps in flight and parks
|
|
13
|
+
* only when every innermost one is a wait that can be resumed without loss. A
|
|
14
|
+
* step doing anything else — a model call, user code, a tool — keeps the turn
|
|
15
|
+
* live.
|
|
16
|
+
*/
|
|
17
|
+
//#region Types
|
|
18
|
+
/** The abort reason of a context whose turn parked. */
|
|
19
|
+
export const PARK_REASON = 'parked';
|
|
20
|
+
/** @public How long every in-flight step must stay waiting before a turn parks, by default. */
|
|
21
|
+
export const DEFAULT_PARK_GRACE_MS = 100;
|
|
22
|
+
//#endregion
|
|
23
|
+
//#region Paths
|
|
24
|
+
/** Whether `path` lies in the subtree under `parent` — a lane below it or a child context's prefix. */
|
|
25
|
+
export function isBeneath(path, parent) {
|
|
26
|
+
return path.startsWith(`${parent}/`) || path.startsWith(`${parent}[`);
|
|
27
|
+
}
|
|
28
|
+
//#endregion
|
|
29
|
+
//#region Parking
|
|
30
|
+
/**
|
|
31
|
+
* @internal
|
|
32
|
+
* One execution's parking state. Lives on the step ledger, which every context
|
|
33
|
+
* of the execution already shares.
|
|
34
|
+
*/
|
|
35
|
+
export class Parking {
|
|
36
|
+
running = new Map();
|
|
37
|
+
armed;
|
|
38
|
+
timer;
|
|
39
|
+
until;
|
|
40
|
+
anonymous = 0;
|
|
41
|
+
/** Turn parking on for this execution. Without it nothing ever parks. */
|
|
42
|
+
arm(options) {
|
|
43
|
+
this.armed = options;
|
|
44
|
+
}
|
|
45
|
+
/** When the parked turn should be woken, or undefined while it has not parked. */
|
|
46
|
+
get parkedUntil() {
|
|
47
|
+
return this.until;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* A step began running at `path`. Returns what to call when it is done. A step
|
|
51
|
+
* with no path is tracked on its own, so it still keeps the turn live.
|
|
52
|
+
*/
|
|
53
|
+
enter(path) {
|
|
54
|
+
const key = path ?? `~${this.anonymous++}`;
|
|
55
|
+
const parent = path === undefined ? undefined : this.parentOf(path);
|
|
56
|
+
if (parent) {
|
|
57
|
+
parent.children += 1;
|
|
58
|
+
}
|
|
59
|
+
this.running.set(key, {
|
|
60
|
+
children: 0,
|
|
61
|
+
});
|
|
62
|
+
this.settle();
|
|
63
|
+
return () => {
|
|
64
|
+
if (!this.running.delete(key)) {
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
if (parent) {
|
|
68
|
+
parent.children -= 1;
|
|
69
|
+
}
|
|
70
|
+
this.settle();
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* The step at `path` is waiting until `until` and can be resumed without loss.
|
|
75
|
+
* Returns what to call when it stops waiting.
|
|
76
|
+
*/
|
|
77
|
+
wait(path, until) {
|
|
78
|
+
const entry = path === undefined ? undefined : this.running.get(path);
|
|
79
|
+
if (!entry) {
|
|
80
|
+
return () => { };
|
|
81
|
+
}
|
|
82
|
+
entry.until = until;
|
|
83
|
+
this.settle();
|
|
84
|
+
return () => {
|
|
85
|
+
entry.until = undefined;
|
|
86
|
+
this.settle();
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
/** The step in flight that `path` is directly beneath. */
|
|
90
|
+
parentOf(path) {
|
|
91
|
+
let found;
|
|
92
|
+
for (const key of this.running.keys()) {
|
|
93
|
+
if (isBeneath(path, key) && (found === undefined || key.length > found.length)) {
|
|
94
|
+
found = key;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
return found === undefined ? undefined : this.running.get(found);
|
|
98
|
+
}
|
|
99
|
+
/** The earliest deadline when every innermost step is waiting, else undefined. */
|
|
100
|
+
wakeAt() {
|
|
101
|
+
let earliest;
|
|
102
|
+
for (const entry of this.running.values()) {
|
|
103
|
+
if (entry.children > 0) {
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
106
|
+
if (entry.until === undefined) {
|
|
107
|
+
return undefined;
|
|
108
|
+
}
|
|
109
|
+
earliest = earliest === undefined ? entry.until : Math.min(earliest, entry.until);
|
|
110
|
+
}
|
|
111
|
+
return earliest;
|
|
112
|
+
}
|
|
113
|
+
/** Start or cancel the countdown to parking, after any change. */
|
|
114
|
+
settle() {
|
|
115
|
+
const armed = this.armed;
|
|
116
|
+
if (!armed || this.until !== undefined) {
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
if (this.timer !== undefined) {
|
|
120
|
+
clearTimeout(this.timer);
|
|
121
|
+
this.timer = undefined;
|
|
122
|
+
}
|
|
123
|
+
if (this.wakeAt() === undefined) {
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
this.timer = setTimeout(() => {
|
|
127
|
+
this.timer = undefined;
|
|
128
|
+
const wakeAt = this.wakeAt();
|
|
129
|
+
if (wakeAt === undefined) {
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
this.until = wakeAt;
|
|
133
|
+
armed.onPark(wakeAt);
|
|
134
|
+
}, armed.graceMs);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
//#endregion
|
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
import type { StorageAdapter } from '@noetic-tools/context';
|
|
15
15
|
import { z } from 'zod';
|
|
16
16
|
declare const SessionRecordSchema: z.ZodObject<{
|
|
17
|
+
term: z.ZodOptional<z.ZodNumber>;
|
|
17
18
|
items: z.ZodArray<z.ZodUnknown>;
|
|
18
19
|
usage: z.ZodOptional<z.ZodObject<{
|
|
19
20
|
inputTokens: z.ZodNumber;
|
|
@@ -25,24 +26,61 @@ declare const SessionRecordSchema: z.ZodObject<{
|
|
|
25
26
|
turn: z.ZodOptional<z.ZodObject<{
|
|
26
27
|
executionId: z.ZodString;
|
|
27
28
|
messageIds: z.ZodArray<z.ZodString>;
|
|
29
|
+
stopped: z.ZodOptional<z.ZodObject<{
|
|
30
|
+
at: z.ZodNumber;
|
|
31
|
+
reason: z.ZodString;
|
|
32
|
+
}, z.core.$strip>>;
|
|
33
|
+
version: z.ZodOptional<z.ZodString>;
|
|
34
|
+
stuck: z.ZodOptional<z.ZodObject<{
|
|
35
|
+
path: z.ZodString;
|
|
36
|
+
from: z.ZodString;
|
|
37
|
+
to: z.ZodString;
|
|
38
|
+
}, z.core.$strip>>;
|
|
39
|
+
accept: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodString]>>;
|
|
40
|
+
parked: z.ZodOptional<z.ZodObject<{
|
|
41
|
+
until: z.ZodOptional<z.ZodNumber>;
|
|
42
|
+
}, z.core.$strip>>;
|
|
28
43
|
}, z.core.$strip>>;
|
|
44
|
+
done: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
45
|
+
messageIds: z.ZodArray<z.ZodString>;
|
|
46
|
+
text: z.ZodString;
|
|
47
|
+
executionId: z.ZodOptional<z.ZodString>;
|
|
48
|
+
}, z.core.$strip>>>;
|
|
29
49
|
steers: z.ZodOptional<z.ZodArray<z.ZodObject<{
|
|
30
50
|
id: z.ZodString;
|
|
31
51
|
input: z.ZodUnknown;
|
|
32
52
|
deliveryMode: z.ZodEnum<{
|
|
53
|
+
"next-turn": "next-turn";
|
|
33
54
|
"between-rounds": "between-rounds";
|
|
34
55
|
"next-item": "next-item";
|
|
35
56
|
}>;
|
|
36
57
|
enqueuedAt: z.ZodNumber;
|
|
58
|
+
resourceId: z.ZodOptional<z.ZodString>;
|
|
37
59
|
}, z.core.$strip>>>;
|
|
38
60
|
}, z.core.$strip>;
|
|
39
61
|
/** @internal One thread's stored session. */
|
|
40
62
|
export type SessionRecord = z.infer<typeof SessionRecordSchema>;
|
|
63
|
+
/** @internal A session record as read: the stored value, and the record it parses to. */
|
|
64
|
+
export interface StoredSession {
|
|
65
|
+
/** Exactly what storage holds, or null when nothing is. */
|
|
66
|
+
raw: unknown;
|
|
67
|
+
/** Undefined when nothing is stored or it does not parse. */
|
|
68
|
+
record: SessionRecord | undefined;
|
|
69
|
+
}
|
|
41
70
|
/** @internal Reads and writes session records under `session:<threadId>`. */
|
|
42
71
|
export interface SessionStore {
|
|
43
72
|
/** The thread's record, or undefined when none is stored or it does not parse. */
|
|
44
73
|
load(threadId: string): Promise<SessionRecord | undefined>;
|
|
45
74
|
save(threadId: string, record: SessionRecord): Promise<void>;
|
|
75
|
+
/** The record as stored, with the value it parsed from, for a compare-and-set. */
|
|
76
|
+
read(threadId: string): Promise<StoredSession>;
|
|
77
|
+
/**
|
|
78
|
+
* Store `next` only if what is stored is still `prev` (a `read`'s `raw`).
|
|
79
|
+
* Absent on storage that cannot compare-and-set.
|
|
80
|
+
*/
|
|
81
|
+
swap?: (threadId: string, prev: unknown, next: SessionRecord) => Promise<boolean>;
|
|
82
|
+
/** The ids of every thread with a stored record. */
|
|
83
|
+
threads(): Promise<string[]>;
|
|
46
84
|
}
|
|
47
85
|
/** @internal */
|
|
48
86
|
export declare function createSessionStore(storage: StorageAdapter): SessionStore;
|
|
@@ -14,6 +14,11 @@
|
|
|
14
14
|
import { z } from 'zod';
|
|
15
15
|
//#region Schema
|
|
16
16
|
const SessionRecordSchema = z.object({
|
|
17
|
+
/**
|
|
18
|
+
* The lease term of the last turn that wrote this record (spec 23 § One writer per
|
|
19
|
+
* turn). A turn holding a lower term was replaced, and its writes are refused.
|
|
20
|
+
*/
|
|
21
|
+
term: z.number().int().nonnegative().optional(),
|
|
17
22
|
/** The thread's history after its last finished turn. */
|
|
18
23
|
items: z.array(z.unknown()),
|
|
19
24
|
/** What the thread's turns have spent, summed as each turn settles. */
|
|
@@ -32,8 +37,61 @@ const SessionRecordSchema = z.object({
|
|
|
32
37
|
executionId: z.string(),
|
|
33
38
|
/** The ids of the messages the turn delivers, in order. */
|
|
34
39
|
messageIds: z.array(z.string()),
|
|
40
|
+
/**
|
|
41
|
+
* Set when the turn ended in a live process without finishing: it failed or was
|
|
42
|
+
* cancelled. A turn with neither this nor `parked` was cut off by its process
|
|
43
|
+
* dying. A routine wake resumes only the latter; delivering the turn's messages
|
|
44
|
+
* again resumes either.
|
|
45
|
+
*/
|
|
46
|
+
stopped: z
|
|
47
|
+
.object({
|
|
48
|
+
at: z.number(),
|
|
49
|
+
reason: z.string(),
|
|
50
|
+
})
|
|
51
|
+
.optional(),
|
|
52
|
+
/** The flow version the turn was last run under, when the harness names one. */
|
|
53
|
+
version: z.string().optional(),
|
|
54
|
+
/**
|
|
55
|
+
* Set when the turn stopped rather than redo a step that had a lasting effect
|
|
56
|
+
* under another flow version (spec 23 § Versions). It waits for the host.
|
|
57
|
+
*/
|
|
58
|
+
stuck: z
|
|
59
|
+
.object({
|
|
60
|
+
path: z.string(),
|
|
61
|
+
from: z.string(),
|
|
62
|
+
to: z.string(),
|
|
63
|
+
})
|
|
64
|
+
.optional(),
|
|
65
|
+
/** The host looked at the stuck turn and chose to go on: its next run may discard such steps. */
|
|
66
|
+
/** The step a host chose to go on past (`true` in records written before that was kept). */
|
|
67
|
+
accept: z
|
|
68
|
+
.union([
|
|
69
|
+
z.boolean(),
|
|
70
|
+
z.string(),
|
|
71
|
+
])
|
|
72
|
+
.optional(),
|
|
73
|
+
/** Set while the turn is parked: every part of it waits, and no harness holds it. */
|
|
74
|
+
parked: z
|
|
75
|
+
.object({
|
|
76
|
+
/** Epoch ms of the earliest deadline among its waits. Absent when none has one. */
|
|
77
|
+
until: z.number().optional(),
|
|
78
|
+
})
|
|
79
|
+
.optional(),
|
|
35
80
|
})
|
|
36
81
|
.optional(),
|
|
82
|
+
/**
|
|
83
|
+
* The thread's most recent finished turns, oldest first: the messages each
|
|
84
|
+
* delivered and the answer it gave. A message delivered again after its turn
|
|
85
|
+
* finished is answered from here instead of run again.
|
|
86
|
+
*/
|
|
87
|
+
done: z
|
|
88
|
+
.array(z.object({
|
|
89
|
+
messageIds: z.array(z.string()),
|
|
90
|
+
text: z.string(),
|
|
91
|
+
/** The turn's execution, under which its trail is kept. */
|
|
92
|
+
executionId: z.string().optional(),
|
|
93
|
+
}))
|
|
94
|
+
.optional(),
|
|
37
95
|
/** Steers sent into the turn in flight, in arrival order. */
|
|
38
96
|
steers: z
|
|
39
97
|
.array(z.object({
|
|
@@ -43,13 +101,18 @@ const SessionRecordSchema = z.object({
|
|
|
43
101
|
deliveryMode: z.enum([
|
|
44
102
|
'between-rounds',
|
|
45
103
|
'next-item',
|
|
104
|
+
// Kept only across a park: a message that waits for the parked turn to end.
|
|
105
|
+
'next-turn',
|
|
46
106
|
]),
|
|
47
107
|
enqueuedAt: z.number(),
|
|
108
|
+
/** The `resourceId` it was sent with: the one option storage can hold. */
|
|
109
|
+
resourceId: z.string().optional(),
|
|
48
110
|
}))
|
|
49
111
|
.optional(),
|
|
50
112
|
});
|
|
51
113
|
/** @internal */
|
|
52
114
|
export function createSessionStore(storage) {
|
|
115
|
+
const swap = storage.swap?.bind(storage);
|
|
53
116
|
return {
|
|
54
117
|
load: async (threadId) => {
|
|
55
118
|
const raw = await storage.get(sessionKey(threadId));
|
|
@@ -66,9 +129,24 @@ export function createSessionStore(storage) {
|
|
|
66
129
|
save: async (threadId, record) => {
|
|
67
130
|
await storage.set(sessionKey(threadId), record);
|
|
68
131
|
},
|
|
132
|
+
read: async (threadId) => {
|
|
133
|
+
const raw = await storage.get(sessionKey(threadId));
|
|
134
|
+
const parsed = raw === null ? undefined : SessionRecordSchema.safeParse(raw);
|
|
135
|
+
return {
|
|
136
|
+
raw,
|
|
137
|
+
record: parsed?.success ? parsed.data : undefined,
|
|
138
|
+
};
|
|
139
|
+
},
|
|
140
|
+
...(swap
|
|
141
|
+
? {
|
|
142
|
+
swap: (threadId, prev, next) => swap(sessionKey(threadId), prev, next),
|
|
143
|
+
}
|
|
144
|
+
: {}),
|
|
145
|
+
threads: async () => (await storage.list(SESSION_PREFIX)).map((key) => key.slice(SESSION_PREFIX.length)),
|
|
69
146
|
};
|
|
70
147
|
}
|
|
148
|
+
const SESSION_PREFIX = 'session:';
|
|
71
149
|
function sessionKey(threadId) {
|
|
72
|
-
return
|
|
150
|
+
return `${SESSION_PREFIX}${threadId}`;
|
|
73
151
|
}
|
|
74
152
|
//#endregion
|