@pontlabsai/eventdispatch 0.0.0-stage → 0.3.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.
@@ -0,0 +1,170 @@
1
+ import { CSRelease, CSWait, CsState } from "./cs.js";
2
+ import { Blackboard, Deserializers, Env, Handoff, Loggers, Registry, } from "./event.js";
3
+ /** Event ids are taken modulo this (spec queue.md#event-ids). */
4
+ export const MAX_EVENT_ID = 30000;
5
+ /**
6
+ * A queue dispatch (spec queue.md): drains its queue and dispatches
7
+ * every item, each event in its own task. Everything runs on one
8
+ * thread; an event that awaits never blocks another, but one that
9
+ * computes without awaiting does, as any JavaScript would.
10
+ */
11
+ export class Dispatcher {
12
+ name;
13
+ blackboard;
14
+ registry;
15
+ /** The dispatch switch (spec core.md#dispatch-switch): while off, items are dropped. */
16
+ switch = true;
17
+ logger;
18
+ queue = [];
19
+ running = false;
20
+ live = 0;
21
+ nextId = 0;
22
+ wakeup = null;
23
+ loop = null;
24
+ /** @internal */
25
+ cs;
26
+ constructor(name, options = {}) {
27
+ this.name = name;
28
+ this.blackboard = options.blackboard ?? new Blackboard();
29
+ this.registry = options.registry ?? new Registry();
30
+ this.logger = options.logger ?? Loggers.console;
31
+ this.cs = options.cs ? new CsState() : null;
32
+ if (this.cs) {
33
+ this.registry.register("CSWait", () => new CSWait(), Deserializers.anyArguments);
34
+ this.registry.register("CSRelease", () => new CSRelease(), Deserializers.anyArguments);
35
+ }
36
+ this.blackboard.set(`${name}_dispatch`, this);
37
+ }
38
+ /** Items queued and not yet taken by a drain. */
39
+ get queueLength() {
40
+ return this.queue.length;
41
+ }
42
+ /** Events dispatched whose finish has not returned. */
43
+ get liveEvents() {
44
+ return this.live;
45
+ }
46
+ register(name, factory, deserialize) {
47
+ this.registry.register(name, factory, deserialize);
48
+ }
49
+ /** Appends items to the queue in one batch, and wakes the dispatch. */
50
+ enqueue(...items) {
51
+ if (items.length === 0)
52
+ return;
53
+ this.queue.push(...items);
54
+ this.wake();
55
+ }
56
+ enqueueAll(items) {
57
+ this.enqueue(...items);
58
+ }
59
+ /** Starts the drain loop (once). */
60
+ start() {
61
+ if (this.loop)
62
+ return;
63
+ this.running = true;
64
+ this.loop = this.run().catch((e) => this.logger("error", `${this.name}: drain loop failed`, e));
65
+ }
66
+ /** Stops after the current drain. Events already dispatched are not interrupted. */
67
+ stop() {
68
+ this.running = false;
69
+ this.wake();
70
+ }
71
+ /** Resolves once the drain loop has ended. */
72
+ async join() {
73
+ await this.loop;
74
+ }
75
+ wake() {
76
+ const w = this.wakeup;
77
+ this.wakeup = null;
78
+ w?.();
79
+ }
80
+ /** Resolves on the next enqueue or stop. */
81
+ idle() {
82
+ return new Promise((r) => (this.wakeup = r));
83
+ }
84
+ // -- the drain loop ------------------------------------------------
85
+ async run() {
86
+ while (this.running) {
87
+ if (this.queue.length === 0) {
88
+ await this.idle();
89
+ continue;
90
+ }
91
+ const batch = this.queue;
92
+ this.queue = [];
93
+ const rest = this.cs ? await this.cs.gate(this, batch) : batch;
94
+ for (const it of rest)
95
+ this.dispatchItem(it);
96
+ }
97
+ }
98
+ /**
99
+ * Looks up, deserializes, constructs and dispatches one item; false
100
+ * (logged) if it fails (spec queue.md#failed-items).
101
+ * @internal
102
+ */
103
+ dispatchItem(it) {
104
+ try {
105
+ const { event, env, args } = this.prepare(it);
106
+ this.startEvent(event, env, args);
107
+ return true;
108
+ }
109
+ catch (e) {
110
+ this.logger("warn", `${this.name}: item failed: ${JSON.stringify(it)}`, e);
111
+ return false;
112
+ }
113
+ }
114
+ /** Deserializes and constructs an item's event, and reserves its id; throws if it fails. */
115
+ prepare(it) {
116
+ if (!Array.isArray(it) || it.length === 0)
117
+ throw new Error("empty item");
118
+ const name = it[0];
119
+ if (typeof name !== "string")
120
+ throw new Error(`item name ${String(name)} is not a string`);
121
+ const { event, args } = this.registry.create(name, it.slice(1));
122
+ const id = this.nextId;
123
+ this.nextId = (this.nextId + 1) % MAX_EVENT_ID;
124
+ if (!this.switch)
125
+ throw new Error("dispatch switch is off");
126
+ return { event, env: new Env(id, name, this.blackboard, this), args };
127
+ }
128
+ /** Runs an event in its own task. */
129
+ startEvent(event, env, args) {
130
+ this.live++;
131
+ void this.runEvent(event, env, args);
132
+ }
133
+ /** Dispatch, then finish unless dispatch failed; the event is released either way. */
134
+ async runEvent(event, env, args) {
135
+ try {
136
+ await Handoff.at("dispatch"); // its own task: never inside the drain
137
+ const dispatched = await this.guard("dispatch", env, () => event.dispatch(env, args));
138
+ await Handoff.at("finish");
139
+ if (dispatched)
140
+ await this.guard("finish", env, () => event.finish(env, args));
141
+ }
142
+ finally {
143
+ this.live--;
144
+ }
145
+ }
146
+ /** Runs `f`; logs and returns false if it throws or rejects. */
147
+ async guard(stage, env, f) {
148
+ try {
149
+ await f();
150
+ return true;
151
+ }
152
+ catch (e) {
153
+ this.logger("error", `${this.name}: ${env.name}@${env.id} ${stage} failed`, e);
154
+ return false;
155
+ }
156
+ }
157
+ /** Releases waiting CSWaits without their pending items (spec cs.md#clear): all, or those on left `key`. */
158
+ clearCSWaits(key) {
159
+ this.cs?.clear(key);
160
+ }
161
+ /** The composite semaphore registered for `left`, if any. */
162
+ semaphore(left) {
163
+ return this.cs?.registry.get(left);
164
+ }
165
+ /** @internal */
166
+ warn(message) {
167
+ this.logger("warn", `${this.name}: ${message}`);
168
+ }
169
+ }
170
+ //# sourceMappingURL=dispatcher.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dispatcher.js","sourceRoot":"","sources":["../src/dispatcher.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAErD,OAAO,EACL,UAAU,EACV,aAAa,EACb,GAAG,EACH,OAAO,EAKP,OAAO,EACP,QAAQ,GACT,MAAM,YAAY,CAAC;AAEpB,iEAAiE;AACjE,MAAM,CAAC,MAAM,YAAY,GAAG,KAAK,CAAC;AAUlC;;;;;GAKG;AACH,M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0,0 +1,77 @@
1
+ /**
2
+ * Core types: items, events, the registry, the blackboard, logging and
3
+ * the hand-off hook. Web-standard JavaScript only: no Node, Deno or Bun
4
+ * APIs, so the library runs in browsers and every server runtime.
5
+ */
6
+ import type { Dispatcher } from "./dispatcher.js";
7
+ /** The spec version this library implements (major.minor). */
8
+ export declare const SPEC_VERSION = "0.3";
9
+ /** A queue item: `[name, arg1, ...]`, as decoded from JSON. */
10
+ export type Item = unknown[];
11
+ /** Builds an item. */
12
+ export declare function item(name: string, ...args: unknown[]): Item;
13
+ /** What an event sees: its id, its registry name, the blackboard and its dispatcher. */
14
+ export declare class Env {
15
+ readonly id: number;
16
+ readonly name: string;
17
+ readonly blackboard: Blackboard;
18
+ readonly dispatcher: Dispatcher;
19
+ /** Appends items to the dispatcher's queue in one batch. */
20
+ enqueue(...items: Item[]): void;
21
+ }
22
+ /**
23
+ * An event (spec core.md#lifecycle). `dispatch` does the work in its
24
+ * own task; `finish` runs when it returns, and is the only place that
25
+ * decides what is dispatched next.
26
+ *
27
+ * An error thrown (or a rejected promise) in `dispatch` releases the
28
+ * event without `finish`; one in `finish` is logged and the dispatcher
29
+ * carries on.
30
+ */
31
+ export interface Event {
32
+ dispatch(env: Env, args: unknown[]): unknown;
33
+ finish(env: Env, args: unknown[]): void | Promise<void>;
34
+ }
35
+ /** Turns an item's arguments into dispatch arguments, or throws to reject the item. */
36
+ export type Deserializer = (args: unknown[]) => unknown[];
37
+ export declare const Deserializers: {
38
+ /** The default (spec queue.md#deserialize): arguments unchanged; rejects an item with none. */
39
+ default: Deserializer;
40
+ /** Accepts any arguments, including none (recording events use this). */
41
+ anyArguments: Deserializer;
42
+ };
43
+ /** Maps names to event factories. */
44
+ export declare class Registry {
45
+ private readonly map;
46
+ register(name: string, factory: () => Event, deserialize?: Deserializer): void;
47
+ has(name: string): boolean;
48
+ }
49
+ /** The key/value store shared by events and dispatchers (spec core.md#blackboard). */
50
+ export declare class Blackboard {
51
+ private readonly map;
52
+ get<T = unknown>(key: string): T | undefined;
53
+ set(key: string, value: unknown): void;
54
+ has(key: string): boolean;
55
+ delete(key: string): boolean;
56
+ /** Replaces a value with `f(old)`, and returns it. */
57
+ update<T>(key: string, f: (old: T | undefined) => T): T;
58
+ }
59
+ export type Level = "debug" | "warn" | "error";
60
+ /** Where a dispatcher reports failures. */
61
+ export type Logger = (level: Level, message: string, error?: unknown) => void;
62
+ export declare const Loggers: {
63
+ /** Warnings and errors to the console. */
64
+ console: Logger;
65
+ /** Logs nothing. */
66
+ discard: Logger;
67
+ };
68
+ /**
69
+ * The seam stress tests use: `hook` is awaited wherever work moves
70
+ * between tasks (spec conformance/README.md#stress-mode). Random delays
71
+ * there must never change an outcome. Null in production.
72
+ */
73
+ export declare const Handoff: {
74
+ hook: null | ((site: string) => void | Promise<void>);
75
+ /** @internal */
76
+ at(site: string): Promise<void>;
77
+ };
package/dist/event.js ADDED
@@ -0,0 +1,138 @@
1
+ /**
2
+ * Core types: items, events, the registry, the blackboard, logging and
3
+ * the hand-off hook. Web-standard JavaScript only: no Node, Deno or Bun
4
+ * APIs, so the library runs in browsers and every server runtime.
5
+ */
6
+ /** The spec version this library implements (major.minor). */
7
+ export const SPEC_VERSION = "0.3";
8
+ /** Builds an item. */
9
+ export function item(name, ...args) {
10
+ return [name, ...args];
11
+ }
12
+ /** What an event sees: its id, its registry name, the blackboard and its dispatcher. */
13
+ export class Env {
14
+ id;
15
+ name;
16
+ blackboard;
17
+ dispatcher;
18
+ /** @internal */
19
+ constructor(id, name, blackboard, dispatcher) {
20
+ this.id = id;
21
+ this.name = name;
22
+ this.blackboard = blackboard;
23
+ this.dispatcher = dispatcher;
24
+ }
25
+ /** Appends items to the dispatcher's queue in one batch. */
26
+ enqueue(...items) {
27
+ this.dispatcher.enqueue(...items);
28
+ }
29
+ }
30
+ export const Deserializers = {
31
+ /** The default (spec queue.md#deserialize): arguments unchanged; rejects an item with none. */
32
+ default: ((args) => {
33
+ if (args.length === 0)
34
+ throw new Error("item has no arguments");
35
+ return args;
36
+ }),
37
+ /** Accepts any arguments, including none (recording events use this). */
38
+ anyArguments: ((args) => args),
39
+ };
40
+ /** Maps names to event factories. */
41
+ export class Registry {
42
+ map = new Map();
43
+ register(name, factory, deserialize = Deserializers.default) {
44
+ this.map.set(name, { factory, deserialize });
45
+ }
46
+ has(name) {
47
+ return this.map.has(name);
48
+ }
49
+ /** @internal Deserializes (rejecting before constructing), then constructs. */
50
+ create(name, args) {
51
+ const reg = this.map.get(name);
52
+ if (!reg)
53
+ throw new Error(`no event registered as "${name}"`);
54
+ const dispatchArgs = reg.deserialize(args);
55
+ return { event: reg.factory(), args: dispatchArgs };
56
+ }
57
+ }
58
+ /** The key/value store shared by events and dispatchers (spec core.md#blackboard). */
59
+ export class Blackboard {
60
+ map = new Map();
61
+ get(key) {
62
+ return this.map.get(key);
63
+ }
64
+ set(key, value) {
65
+ this.map.set(key, value);
66
+ }
67
+ has(key) {
68
+ return this.map.has(key);
69
+ }
70
+ delete(key) {
71
+ return this.map.delete(key);
72
+ }
73
+ /** Replaces a value with `f(old)`, and returns it. */
74
+ update(key, f) {
75
+ const v = f(this.map.get(key));
76
+ this.map.set(key, v);
77
+ return v;
78
+ }
79
+ }
80
+ export const Loggers = {
81
+ /** Warnings and errors to the console. */
82
+ console: ((level, message, error) => {
83
+ if (level === "debug")
84
+ return;
85
+ const text = `eventdispatch ${level}: ${message}` + (error === undefined ? "" : `: ${String(error)}`);
86
+ if (level === "error")
87
+ console.error(text);
88
+ else
89
+ console.warn(text);
90
+ }),
91
+ /** Logs nothing. */
92
+ discard: (() => { }),
93
+ };
94
+ /**
95
+ * The seam stress tests use: `hook` is awaited wherever work moves
96
+ * between tasks (spec conformance/README.md#stress-mode). Random delays
97
+ * there must never change an outcome. Null in production.
98
+ */
99
+ export const Handoff = {
100
+ hook: null,
101
+ /** @internal */
102
+ async at(site) {
103
+ const h = Handoff.hook;
104
+ if (h)
105
+ await h(site);
106
+ },
107
+ };
108
+ /** @internal A promise with its resolver. */
109
+ export class Deferred {
110
+ promise;
111
+ resolve;
112
+ settled = false;
113
+ value;
114
+ constructor() {
115
+ this.promise = new Promise((r) => {
116
+ this.resolve = (v) => {
117
+ if (this.settled)
118
+ return;
119
+ this.settled = true;
120
+ this.value = v;
121
+ r(v);
122
+ };
123
+ });
124
+ }
125
+ }
126
+ /** @internal Wakes whoever is waiting; a wait made after a notify waits for the next one. */
127
+ export class Signal {
128
+ d = new Deferred();
129
+ wait() {
130
+ return this.d.promise;
131
+ }
132
+ notify() {
133
+ const d = this.d;
134
+ this.d = new Deferred();
135
+ d.resolve();
136
+ }
137
+ }
138
+ //# sourceMappingURL=event.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"event.js","sourceRoot":"","sources":["../src/event.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAIH,8DAA8D;AAC9D,MAAM,CAAC,MAAM,YAAY,GAAG,KAAK,CAAC;AAKlC,sBAAsB;AACtB,MAAM,UAAU,IAAI,CAAC,IAAY,EAAE,GAAG,IAAe;IACnD,OAAO,CAAC,IAAI,EAAE,GAAG,IAAI,CAAC,CAAC;AACzB,CAAC;AAED,wFAAwF;AACxF,MAAM,OAAO,GAAG;IAGH;IACA;IACA;IACA;IALX,gBAAgB;IAChB,YACW,EAAU,EACV,IAAY,EACZ,UAAsB,EACtB,UAAsB;QAHtB,OAAE,GAAF,EAAE,CAAQ;QACV,SAAI,GAAJ,IAAI,CAAQ;QACZ,eAAU,GAAV,UAAU,CAAY;QACtB,eAAU,GAAV,UAAU,CAAY;IAC9B,CAAC;IAEJ,4DAA4D;IAC5D,OAAO,CAAC,GAAG,KAAa;QACtB,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,GAAG,KAAK,CAAC,CAAC;IACpC,CAAC;CACF;AAmBD,MAAM,CAAC,MAAM,aAAa,GAAG;IAC3B,+FAA+F;IAC/F,OAAO,EAAE,CAAC,CAAC,IAAI,EAAE,EAAE;QACjB,IAAI,IAAI,CAAC,MAAM,KAA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I,CAAC;QACvB,IAAI,CAAC;YAAE,MAAM,CAAC,CAAC,IAAI,CAAC,CAAC;IACvB,CAAC;CACF,CAAC;AAEF,6CAA6C;AAC7C,MAAM,OAAO,QAAQ;IACV,OAAO,CAAa;IAC7B,OAAO,CAAkB;IACzB,OAAO,GAAG,KAAK,CAAC;IAChB,KAAK,CAAgB;IACrB;QACE,IAAI,CAAC,OAAO,GAAG,IAAI,OAAO,CAAI,CAAC,CAAC,EAAE,EAAE;YAClC,IAAI,CAAC,OAAO,GAAG,CAAC,CAAI,EAAE,EAAE;gBACtB,IAAI,IAAI,CAAC,OAAO;oBAAE,OAAO;gBACzB,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC;gBACpB,IAAI,CAAC,KAAK,GAAG,CAAC,CAAC;gBACf,CAAC,CAAC,CAAC,CAAC,CAAC;YACP,CAAC,CAAC;QACJ,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AAED,6FAA6F;AAC7F,MAAM,OAAO,MAAM;IACT,CAAC,GAAG,IAAI,QAAQ,EAAQ,CAAC;IACjC,IAAI;QACF,OAAO,IAAI,CAAC,CAAC,CAAC,OAAO,CAAC;IACxB,CAAC;IACD,MAAM;QACJ,MAAM,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC;QACjB,IAAI,CAAC,CAAC,GAAG,IAAI,QAAQ,EAAQ,CAAC;QAC9B,CAAC,CAAC,OAAO,EAAE,CAAC;IACd,CAAC;CACF"}
@@ -0,0 +1,13 @@
1
+ /**
2
+ * eventdispatch: work runs as Events, each constructed from a
3
+ * serialized queue item, dispatched in its own task, and finished —
4
+ * and only an event's finish decides what is dispatched next.
5
+ *
6
+ * eventdispatch spec v0.3: base, sim, recording.
7
+ */
8
+ export { Blackboard, Deserializers, Env, Handoff, item, Loggers, Registry, SPEC_VERSION, type Deserializer, type Event, type Item, type Level, type Logger, } from "./event.js";
9
+ export { Dispatcher, MAX_EVENT_ID, type DispatcherOptions } from "./dispatcher.js";
10
+ export { CompositeSemaphore, RightWaitingError, ROLLOVER } from "./semaphore.js";
11
+ export { CLEARED_STATUS, CSRelease, CSWait, parseLefts } from "./cs.js";
12
+ export { SimDispatcher, type Scheduled, type SimDispatcherOptions } from "./sim.js";
13
+ export { PREEMPTED, RECORDINGS_KEY, RecordingEvent, RecordingLog, SimRecordingDispatcher, WallRecordingDispatcher, type Record, } from "./recording.js";
package/dist/index.js ADDED
@@ -0,0 +1,14 @@
1
+ /**
2
+ * eventdispatch: work runs as Events, each constructed from a
3
+ * serialized queue item, dispatched in its own task, and finished —
4
+ * and only an event's finish decides what is dispatched next.
5
+ *
6
+ * eventdispatch spec v0.3: base, sim, recording.
7
+ */
8
+ export { Blackboard, Deserializers, Env, Handoff, item, Loggers, Registry, SPEC_VERSION, } from "./event.js";
9
+ export { Dispatcher, MAX_EVENT_ID } from "./dispatcher.js";
10
+ export { CompositeSemaphore, RightWaitingError, ROLLOVER } from "./semaphore.js";
11
+ export { CLEARED_STATUS, CSRelease, CSWait, parseLefts } from "./cs.js";
12
+ export { SimDispatcher } from "./sim.js";
13
+ export { PREEMPTED, RECORDINGS_KEY, RecordingEvent, RecordingLog, SimRecordingDispatcher, WallRecordingDispatcher, } from "./recording.js";
14
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,EACL,UAAU,EAAE,aAAa,EAAE,GAAG,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,QAAQ,EAAE,YAAY,GAE/E,MAAM,YAAY,CAAC;AACpB,OAAO,EAAE,UAAU,EAAE,YAAY,EAA0B,MAAM,iBAAiB,CAAC;AACnF,OAAO,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AACjF,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACxE,OAAO,EAAE,aAAa,EAA6C,MAAM,UAAU,CAAC;AACpF,OAAO,EACL,SAAS,EAAE,cAAc,EAAE,cAAc,EAAE,YAAY,EAAE,sBAAsB,EAAE,uBAAuB,GAEzG,MAAM,gBAAgB,CAAC"}
@@ -0,0 +1,103 @@
1
+ import { type DispatcherOptions, Dispatcher } from "./dispatcher.js";
2
+ import { type Env, type Event } from "./event.js";
3
+ import { type Scheduled, SimDispatcher, type SimDispatcherOptions } from "./sim.js";
4
+ /** The blackboard key of the recordings field (spec recording.md#blackboard-keys). */
5
+ export declare const RECORDINGS_KEY = "recordings";
6
+ /** The outcome of a preempted event's record. */
7
+ export declare const PREEMPTED = "PREEMPTED";
8
+ /** A record (spec schemas/record.schema.json). */
9
+ export interface Record {
10
+ event_id: number;
11
+ event: string;
12
+ args: unknown[];
13
+ started_at: number;
14
+ t: number;
15
+ wake: boolean;
16
+ outcome: unknown;
17
+ duration?: number;
18
+ actual_duration?: number;
19
+ elapsed?: number;
20
+ progress?: number;
21
+ notes?: {
22
+ [key: string]: unknown;
23
+ };
24
+ partial_outcome?: unknown;
25
+ }
26
+ /**
27
+ * The recordings field: a buffer with exactly one consumer (spec
28
+ * recording.md#the-recordings-field).
29
+ */
30
+ export declare class RecordingLog {
31
+ private records;
32
+ private arrived;
33
+ /** Resolves once at least one record is buffered, with everything buffered, in order; removes them. */
34
+ take(): Promise<Record[]>;
35
+ /** Records buffered now (not yet taken). */
36
+ get pending(): number;
37
+ /** A copy of everything buffered; does not consume. For tests and diagnostics. */
38
+ snapshot(): Record[];
39
+ }
40
+ /**
41
+ * An event that opts in to recording (spec recording.md#recording-protocol).
42
+ * Subclasses implement `runOutcome`, and `dispatch` (the quote) to run
43
+ * on the sim clock; never `finish`. Register them with
44
+ * `RecordingEvent.deserialize`, which accepts zero arguments.
45
+ */
46
+ export declare abstract class RecordingEvent implements Event {
47
+ /** The recording deserialize: any arguments, including none. */
48
+ static readonly deserialize: import("./event.js").Deserializer;
49
+ /** Whether this record requests the consumer's attention; the event's own decision. */
50
+ wake: boolean;
51
+ /** Set by runOutcome when the outcome took less than the quote. */
52
+ actualDuration: number | undefined;
53
+ private readonly preempt;
54
+ /** Scheduling only: keep the arguments, return a quote. Required on the sim clock; ignored on the wall clock. */
55
+ dispatch(_env: Env, _args: unknown[]): number | undefined;
56
+ /** The work: produce and apply the outcome, and return it. */
57
+ abstract runOutcome(env: Env, args: unknown[]): unknown;
58
+ /** Called when the event is preempted; may set wake and return notes. Must not change world state. */
59
+ onPreempt(_env: Env): {
60
+ [key: string]: unknown;
61
+ } | undefined | void;
62
+ /** On a dispatch that does not record: runs the outcome, records nothing. */
63
+ finish(env: Env, args: unknown[]): Promise<void>;
64
+ /** Aborted once the dispatch asks this event to stop. */
65
+ get preemptSignal(): AbortSignal;
66
+ preemptRequested(): boolean;
67
+ /** Resolves once a preempt is requested. */
68
+ waitPreempt(): Promise<void>;
69
+ }
70
+ /**
71
+ * Recording on the sim clock (spec recording.md). A recording event's
72
+ * runOutcome runs at completion time; its record carries the quote.
73
+ */
74
+ export declare class SimRecordingDispatcher extends SimDispatcher {
75
+ readonly recordings: RecordingLog;
76
+ constructor(name: string, options?: SimDispatcherOptions);
77
+ protected complete(s: Scheduled): Promise<void>;
78
+ /** Settles the clock back to started_at + actual_duration (spec recording.md#settling). */
79
+ private settle;
80
+ /** A cancelled recording event's PREEMPTED record is written now. */
81
+ protected cancelled(s: Scheduled): void;
82
+ }
83
+ /**
84
+ * Recording on the wall clock (spec recording.md#wall-clock): a CS
85
+ * queue dispatch whose `now` is monotonic seconds. A recording event's
86
+ * dispatch runs inline (its quote is ignored), then runOutcome runs in
87
+ * its own task; the record is written when it returns.
88
+ */
89
+ export declare class WallRecordingDispatcher extends Dispatcher {
90
+ readonly recordings: RecordingLog;
91
+ private readonly active;
92
+ constructor(name: string, options?: Omit<DispatcherOptions, "cs">);
93
+ get now(): number;
94
+ /**
95
+ * Asks a running recording event to stop; its PREEMPTED record is
96
+ * written when it returns. Returns whether it asked.
97
+ */
98
+ cancel(eventId: number): boolean;
99
+ /** Recording events running now. */
100
+ get runningRecordings(): number[];
101
+ protected startEvent(event: Event, env: Env, args: unknown[]): void;
102
+ private runRecording;
103
+ }