@mica-js/simulator 0.2.1 → 0.3.0

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/index.d.ts CHANGED
@@ -1,249 +1,990 @@
1
- import { DeviceInstanceOptions } from '@mica-js/device';
2
- import { DevicePinHost } from '@mica-js/device';
3
- import { ElectricalPinInput } from '@mica-js/core';
4
- import { IDeviceProvider } from '@mica-js/device';
5
- import { LoadedDeviceModule } from '@mica-js/device';
6
- import { PowerDefinition } from '@mica-js/core';
7
- import { Scheduler } from '@mica-js/core';
8
- import { SchedulerOptions } from '@mica-js/core';
1
+ import { ArrayRef } from '@mica-js/ir';
2
+ import { BytesRef } from '@mica-js/ir';
3
+ import { CanvasBindingTarget } from '@mica-js/core/canvas';
4
+ import { DeviceReference } from '@mica-js/core/schematic';
5
+ import { DeviceSymbolProvider } from '@mica-js/core/schematic';
6
+ import { Disposable } from '@mica-js/core/lifecycle';
7
+ import { Event as Event_2 } from '@mica-js/core/lifecycle';
8
+ import { FunctionBuilder } from '@mica-js/ir';
9
+ import { FunctionRef } from '@mica-js/ir';
10
+ import { IRInterpreter } from '@mica-js/ir';
11
+ import { IRJITTuning } from '@mica-js/ir';
12
+ import { IRModule } from '@mica-js/ir';
13
+ import { IRValidationOptions } from '@mica-js/ir';
14
+ import { PayloadType } from '@mica-js/core/canvas';
15
+ import { RpcEndpoint } from '@mica-js/core/rpc';
16
+ import { ScalarType } from '@mica-js/ir';
9
17
  import { SchematicDocument } from '@mica-js/core/schematic';
10
- import { SchematicSymbol } from '@mica-js/core/schematic';
11
- import { TimePs } from '@mica-js/core';
12
- import { TopicPayload } from '@mica-js/device';
13
- import { TopicPayloadType } from '@mica-js/device';
14
- import { TopologyDefinition } from '@mica-js/core';
15
- import { TopologyRuntime } from '@mica-js/core';
16
-
17
- export declare type AdvanceReason = 'until' | 'empty' | 'entry-limit' | 'paused';
18
-
19
- /** Result of one {@link DeviceSimExecutor.advance} call. */
20
- export declare interface AdvanceReport {
21
- readonly from: TimePs;
22
- /** Virtual time after the call; equals {@link DeviceSimExecutor.getSimTime}. */
23
- readonly to: TimePs;
24
- /** Entries the scheduler executed during this call. */
25
- readonly executed: number;
26
- readonly reason: AdvanceReason;
18
+ import { Value } from '@mica-js/ir';
19
+
20
+ /**
21
+ * Host-facing runtime of one compiled unified circuit (U02).
22
+ *
23
+ * ```ts
24
+ * const circuit = await Circuit.create({
25
+ * devices: [
26
+ * { id: 'drive1', type: 'push-pull-driver', description: driverDescription() },
27
+ * { id: 'sink1', type: 'lamp-sink', description: sinkDescription() },
28
+ * ],
29
+ * connections: [
30
+ * { from: 'drive1.PA0', to: 'sink1.anode' },
31
+ * { from: 'sink1.cathode', to: 'GND' },
32
+ * ],
33
+ * });
34
+ *
35
+ * circuit.runBatch(1_000_000); // one engine call
36
+ * expect(circuit.tickCount).toBe(1_000_000n);
37
+ *
38
+ * circuit.reset();
39
+ * circuit.setPin('drive1.PA0', true); // host drives the pin
40
+ * circuit.step();
41
+ * expect(circuit.devices.sink1.getState('lamp')).toBe(true);
42
+ * ```
43
+ *
44
+ * `Circuit` owns the engine instance and the tick counter; the compiled module
45
+ * keeps every device, net and the main loop in one `@mica-js/ir` module, so a
46
+ * batch is one interpreter/JIT call for the whole circuit.
47
+ */
48
+ export declare class Circuit<I extends CircuitCompilationInput = CircuitCompilationInput> {
49
+ #private;
50
+ /** Typed per-device accessors, keyed by device id. */
51
+ readonly devices: DeviceAccessorsOf<I>;
52
+ private constructor();
53
+ /**
54
+ * Compiles `input`, builds the engine instance and runs the generated
55
+ * `initialize` entry once.
56
+ *
57
+ * The input is inferred as a `const` type, so a literal device list keeps its
58
+ * ids and `circuit.devices.<id>` is typed without a cast.
59
+ *
60
+ * @throws {UnifiedIRCompilerError} when the circuit cannot be compiled.
61
+ * @throws {CircuitError} for invalid options.
62
+ */
63
+ static create<const I extends CircuitCompilationInput>(input: I, options?: CircuitRuntimeOptions): Promise<Circuit<I>>;
64
+ /**
65
+ * Runs `count` ticks inside one generated loop — the throughput path.
66
+ *
67
+ * The whole batch is one engine call; `tickCount` grows by `count` once the
68
+ * call returns, so a failed batch never advances the clock.
69
+ *
70
+ * @throws {CircuitError} with code `invalid-count` unless `count` is a u32.
71
+ */
72
+ runBatch(count: number): void;
73
+ /**
74
+ * Advances exactly one tick — the debugging path.
75
+ *
76
+ * Every call is one engine entry, so prefer `runBatch` for throughput.
77
+ */
78
+ step(): void;
79
+ /**
80
+ * Restores every memory to its declared initial value, re-runs `initialize`
81
+ * and resets `tickCount` to `0n`.
82
+ *
83
+ * Device state written by earlier ticks is discarded, so the circuit behaves
84
+ * exactly like a freshly created one.
85
+ */
86
+ reset(): void;
87
+ /**
88
+ * Reads the level one pin observes.
89
+ *
90
+ * A sensing pin (input, passive or bidirectional) reports the solved net
91
+ * level; a pure driver pin reports the level it actually drives, which is
92
+ * `false` unless it is configured push-pull.
93
+ *
94
+ * @throws {CircuitError} with code `pin-not-found`.
95
+ */
96
+ getPin(pinName: string): boolean;
97
+ /**
98
+ * Forces the level of one pin from the host.
99
+ *
100
+ * A driver pin gets its output latch written, so the level survives the next
101
+ * electrical solve. A sensing pin gets the solved-value slot overridden, which
102
+ * lasts until the next tick recomputes its net.
103
+ *
104
+ * @throws {CircuitError} with code `pin-not-found`.
105
+ */
106
+ setPin(pinName: string, value: boolean): void;
107
+ /** Number of ticks completed since creation or the last `reset()`. */
108
+ get tickCount(): bigint;
109
+ /** Virtual tick time completed since creation or the last `reset()`. */
110
+ get virtualTime(): number;
111
+ /** Underlying engine instance, e.g. for diagnostics or custom entries. */
112
+ get jit(): IRInterpreter;
113
+ /** Whether `dispose()` already ran. */
114
+ get disposed(): boolean;
115
+ /**
116
+ * Releases the runtime. Idempotent; every later call throws a `CircuitError`
117
+ * with code `disposed`, including stale device accessors.
118
+ */
119
+ dispose(): void;
27
120
  }
28
121
 
29
- /** Everything `createPowerRuntime` and the device instances need for one schematic. */
30
- export declare interface CircuitLayout {
31
- readonly topology: TopologyDefinition;
32
- readonly power: PowerDefinition;
33
- /** Complete held-intent snapshot: one entry per declared pin. */
34
- readonly pinStates: readonly ElectricalPinInput[];
122
+ /** Compiler input: devices plus the connections between their pins. */
123
+ export declare interface CircuitCompilationInput {
124
+ readonly devices: readonly DeviceConfig[];
125
+ readonly connections: readonly Connection[];
35
126
  }
36
127
 
37
- export declare interface CircuitOptions {
38
- /** Voltage the schematic's power symbols hold, in volts. Defaults to 5. */
39
- readonly supplyVoltage?: number;
128
+ /** Options for the compiler. */
129
+ export declare interface CircuitCompilationOptions {
130
+ /** Named fixed-level rails; merged over `GND`/`VCC`/`VDD`. */
131
+ readonly rails?: Readonly<Record<string, boolean>>;
132
+ /**
133
+ * Accept nets with more than one driver pin and solve them as a wired-OR.
134
+ * Defaults to `false`, which reports a `driver-conflict` instead.
135
+ */
136
+ readonly allowMultiDriver?: boolean;
137
+ /** Runs `validateIR` over the generated module. Defaults to `true`. */
138
+ readonly validate?: boolean;
139
+ /** Overrides for the generated entry-point names. */
140
+ readonly entryPointNames?: {
141
+ readonly tick?: string;
142
+ readonly initialize?: string;
143
+ readonly batch?: string;
144
+ };
145
+ }
146
+
147
+ export declare interface CircuitDeviceSimulationHostOptions {
148
+ /** Circuit the caller already created. */
149
+ readonly circuit: Circuit;
150
+ /** Whether `dispose()` also disposes the circuit. Defaults to `true`. */
151
+ readonly ownsCircuit?: boolean;
152
+ /** Schematic the circuit was built from, reported through `getSchematic`. */
153
+ readonly schematic?: SchematicDocument;
154
+ /** Endpoints the running devices expose. */
155
+ readonly topics?: readonly DeviceTopic[];
156
+ /** Picoseconds per circuit step. Defaults to 10 ns. */
157
+ readonly stepPs?: number;
158
+ /** Routes one widget payload into the caller's device layer. */
159
+ readonly deliver: (symbol: string, port: string, payload: unknown) => void;
160
+ }
161
+
162
+ /** Electrical-solve options forwarded to `compileCircuit`. */
163
+ export declare interface CircuitElectricalOptions {
164
+ /**
165
+ * Accept nets with more than one driver and solve them as a wired-OR.
166
+ * Defaults to `false`, which reports a `driver-conflict` at compile time.
167
+ */
168
+ readonly allowMultiDriver?: boolean;
169
+ /** Named fixed-level rails; merged over `GND`/`VCC`/`VDD`. */
170
+ readonly rails?: Readonly<Record<string, boolean>>;
40
171
  }
41
172
 
42
173
  /**
43
- * Wiring host for schemes that are drawn, not described.
174
+ * Types of the unified circuit runtime (U02).
44
175
  *
45
- * Pass it as `DeviceSimExecutorOptions.host` and the executor mounts one electrical network per
46
- * runtime: the sheet's wires become nets, power/ground symbols become the supply rails, and every
47
- * device instance reads real pin voltages and connection states instead of host-recorded values.
176
+ * `Circuit` is the host-facing facade over one compiled unified IR module: it
177
+ * owns the engine instance, exposes typed per-device accessors and keeps the
178
+ * tick counter. Everything here is transport-neutral; no type mentions the
179
+ * scheduler, the device host or the schematic editor.
180
+ */
181
+ /** Execution engine a `Circuit` runs on. */
182
+ export declare type CircuitEngine = 'jit' | 'reference';
183
+
184
+ /**
185
+ * Error raised while driving a `Circuit`.
186
+ *
187
+ * The code is stable and machine-checkable, and the message always names the
188
+ * offending device/pin/state plus the values that would have been accepted.
189
+ */
190
+ export declare class CircuitError extends Error {
191
+ readonly name = "CircuitError";
192
+ readonly code: CircuitErrorCode;
193
+ readonly deviceId: string | undefined;
194
+ readonly pinName: string | undefined;
195
+ readonly stateName: string | undefined;
196
+ constructor(code: CircuitErrorCode, message: string, options?: CircuitErrorOptions);
197
+ }
198
+
199
+ /** Error codes raised by `CircuitError`. */
200
+ export declare type CircuitErrorCode = 'invalid-options' | 'invalid-count' | 'pin-not-found' | 'pin-not-writable' | 'state-not-found' | 'invalid-state-value' | 'unresolved-device' | 'disposed';
201
+
202
+ export declare interface CircuitErrorOptions {
203
+ readonly deviceId?: string;
204
+ readonly pinName?: string;
205
+ readonly stateName?: string;
206
+ readonly cause?: unknown;
207
+ }
208
+
209
+ /**
210
+ * Options for `Circuit.create`.
48
211
  *
49
212
  * @example
50
- * createDeviceSimExecutor({ devices, host: createCircuitHost() });
213
+ * const circuit = await Circuit.create(input, { engine: 'reference' });
51
214
  */
52
- export declare function createCircuitHost(options?: CircuitOptions): DeviceSimHostFactory;
215
+ export declare interface CircuitRuntimeOptions {
216
+ /** Execution engine. Defaults to `'jit'`; `'reference'` runs the interpreter. */
217
+ readonly engine?: CircuitEngine;
218
+ /** JIT tuning. The runtime always supplies the module's own validation grant. */
219
+ readonly jit?: IRJITTuning;
220
+ /**
221
+ * Run `validateIR` over the generated module during compilation.
222
+ * Defaults to `true`; pass `false` only for measured warm paths.
223
+ */
224
+ readonly validateIR?: boolean;
225
+ /** Electrical-solve options. */
226
+ readonly electrical?: CircuitElectricalOptions;
227
+ /** Instance id reported to the engine. Defaults to `'unified-circuit'`. */
228
+ readonly instanceId?: string;
229
+ }
230
+
231
+ /** One electrical-analysis finding; errors abort `compileCircuit`. */
232
+ export declare interface CompilationDiagnostic {
233
+ readonly code: CompilationDiagnosticCode;
234
+ readonly severity: CompilationDiagnosticSeverity;
235
+ readonly message: string;
236
+ readonly netId: number | undefined;
237
+ readonly endpoints: readonly string[];
238
+ }
239
+
240
+ /** Diagnostic codes produced by the compiler's electrical analysis. */
241
+ export declare type CompilationDiagnosticCode = 'driver-conflict' | 'power-short' | 'rail-conflict' | 'floating-net';
242
+
243
+ declare type CompilationDiagnosticSeverity = 'error' | 'warning';
53
244
 
54
245
  /**
55
- * Creates an executor for one schematic at a time.
246
+ * Compiles several devices and their wiring into one unified IR module (U01).
247
+ *
248
+ * Device models are caller-supplied: every entry of `devices` carries the pins,
249
+ * states and behaviors (or `kernel`) its type needs.
250
+ *
251
+ * ```ts
252
+ * const circuit = compileCircuit({
253
+ * devices: [
254
+ * { id: 'drive1', type: 'push-pull-driver', description: driverDescription() },
255
+ * { id: 'sink1', type: 'lamp-sink', description: sinkDescription() },
256
+ * ],
257
+ * connections: [
258
+ * { from: 'drive1.channel0', to: 'sink1.anode' },
259
+ * { from: 'sink1.cathode', to: 'GND' },
260
+ * ],
261
+ * });
262
+ *
263
+ * const jit = createIRJIT(circuit.module, { validation: circuit.validation });
264
+ * jit.execute(circuit.entryPoints.refs.initialize, []);
265
+ * jit.execute(circuit.entryPoints.refs.tick, []); // drive1 + nets + sink1
266
+ * ```
267
+ *
268
+ * The pipeline is: validate the input, allocate the global pin and state
269
+ * spaces, analyse the electrical topology, generate one function per device
270
+ * phase, generate one solver per net, generate the main loop, then validate the
271
+ * resulting module with `validateIR`.
56
272
  *
57
- * Every component symbol becomes a device instance on a private scheduler. Pin and connection
58
- * wiring comes from `options.host`, which is rebuilt for every runtime so it always belongs to the
59
- * scheduler that is running; schematic wiring itself is available as `createCircuitHost`.
273
+ * @throws {UnifiedIRCompilerError} for malformed input, duplicate ids, unknown
274
+ * pins, electrical conflicts, or when the generated module fails validation.
60
275
  */
61
- export declare function createDeviceSimExecutor(options: DeviceSimExecutorOptions): DeviceSimExecutor;
276
+ export declare function compileCircuit(input: CircuitCompilationInput, options?: CircuitCompilationOptions): CompiledCircuit;
62
277
 
63
- /** One payload a device published while the simulation was running. */
64
- export declare interface DevicePublish {
65
- readonly target: DeviceTopicTarget;
66
- readonly payload: TopicPayload;
67
- /** Virtual time captured when the device published. */
68
- readonly simTime: TimePs;
278
+ /** The compiled circuit: one module for every device, net and the main loop. */
279
+ export declare interface CompiledCircuit {
280
+ readonly module: IRModule;
281
+ readonly entryPoints: CompiledEntryPoints;
282
+ /** `'mcu1.PA0'` -> global pin id. */
283
+ readonly pinMap: ReadonlyMap<string, number>;
284
+ readonly deviceMap: ReadonlyMap<string, DeviceMetadata>;
285
+ readonly netlist: CompiledNetlist;
286
+ readonly pins: GlobalPinMap;
287
+ readonly states: GlobalStateMap;
288
+ readonly memory: CompiledCircuitMemory;
289
+ /** Validation grants covering every instruction and memory of the module. */
290
+ readonly validation: IRValidationOptions;
291
+ /** Device ids in dependency order (drivers before the devices they feed). */
292
+ readonly executionOrder: readonly string[];
293
+ /** Every generated function name, in definition order. */
294
+ readonly functions: readonly string[];
69
295
  }
70
296
 
297
+ /** Pin memories every device and every net solver shares. */
298
+ declare interface CompiledCircuitMemory {
299
+ readonly mode: ArrayRef<'u8'>;
300
+ readonly output: ArrayRef<'bool'>;
301
+ readonly input: ArrayRef<'bool'>;
302
+ }
303
+
304
+ /** Generated entry points, both by name and as executable refs. */
305
+ declare interface CompiledEntryPoints {
306
+ readonly tick: string;
307
+ readonly initialize: string;
308
+ readonly batch: string;
309
+ readonly refs: {
310
+ readonly tick: FunctionRef<readonly [], readonly []>;
311
+ readonly initialize: FunctionRef<readonly [], readonly []>;
312
+ readonly batch: FunctionRef<readonly ['u32'], readonly []>;
313
+ };
314
+ }
315
+
316
+ /** One electrical net: a connected component of pins and rails. */
317
+ declare interface CompiledNet {
318
+ readonly netId: number;
319
+ readonly pins: readonly CompiledPinConnection[];
320
+ readonly rails: readonly CompiledRail[];
321
+ readonly drivers: readonly CompiledPinConnection[];
322
+ /** Pins whose role is `load`. */
323
+ readonly loads: readonly CompiledPinConnection[];
324
+ /** Every pin that reads the solved level, including bidirectional drivers. */
325
+ readonly sinks: readonly CompiledPinConnection[];
326
+ readonly source: CompiledNetSource;
327
+ /** Constant level of a driver-less net; unused when `source === 'driver'`. */
328
+ readonly level: boolean;
329
+ }
330
+
331
+ /** Result of the network topology analysis. */
332
+ declare interface CompiledNetlist {
333
+ readonly nets: readonly CompiledNet[];
334
+ readonly diagnostics: readonly CompilationDiagnostic[];
335
+ }
336
+
337
+ /** Where a net's level comes from. */
338
+ declare type CompiledNetSource = 'driver' | 'rail' | 'floating';
339
+
340
+ /** One pin resolved onto a net. */
341
+ declare interface CompiledPinConnection {
342
+ /** `'mcu1.PA0'`. */
343
+ readonly endpoint: string;
344
+ readonly deviceId: string;
345
+ readonly pinName: string;
346
+ readonly globalPinId: number;
347
+ readonly role: CompiledPinRole;
348
+ readonly senses: boolean;
349
+ }
350
+
351
+ /** Role a pin plays on its net; v1 supports one driver per net. */
352
+ declare type CompiledPinRole = 'driver' | 'load';
353
+
354
+ /** One fixed-level rail on a net, e.g. `GND` (low) or `VCC` (high). */
355
+ declare interface CompiledRail {
356
+ readonly name: string;
357
+ readonly level: boolean;
358
+ }
359
+
360
+ /** One pin-to-pin (or pin-to-rail) connection. */
361
+ export declare interface Connection {
362
+ /** `'mcu1.PA0'` or a rail name such as `'GND'`. */
363
+ readonly from: string;
364
+ readonly to: string;
365
+ }
366
+
367
+ /**
368
+ * Adapts one already-loaded unified-IR circuit to the RFC 0018 device host.
369
+ *
370
+ * This is the same-thread adapter for an owner that keeps `Circuit` accessors for itself (a
371
+ * diagnostics bench, for example). Application/canvas integration uses
372
+ * `createDeviceSimulationHostFromSandbox` from `@mica-js/simulator/sandbox` and never holds a circuit.
373
+ */
374
+ export declare function createCircuitDeviceSimulationHost({ circuit, ownsCircuit, schematic, topics, stepPs, deliver, }: CircuitDeviceSimulationHostOptions): DeviceSimulationHost;
375
+
376
+ /**
377
+ * Compiles a schematic sheet into a circuit.
378
+ *
379
+ * Nets come from `deriveSchematicTopology`, so wires, junctions, labels and
380
+ * power symbols keep their usual meaning: a net that names a rail connects
381
+ * every member to that rail, and any other net joins its pins pairwise (the
382
+ * compiler merges transitively).
383
+ *
384
+ * ```ts
385
+ * const circuit = await createCircuitFromSchematic(schematic, {
386
+ * devices: symbolProvider,
387
+ * resolveDevice: (reference) => bindings.get(reference.deviceId),
388
+ * });
389
+ * ```
390
+ *
391
+ * @throws {CircuitError} with code `unresolved-device` when a component symbol
392
+ * has no binding; `SchematicError` for malformed sheets.
393
+ */
394
+ export declare function createCircuitFromSchematic(schematic: SchematicDocument, options: SchematicCircuitOptions): Promise<Circuit>;
395
+
71
396
  /**
72
- * Runs the devices of one schematic on a single virtual clock.
397
+ * Builds the validation grants a module needs to run on the reference engine or
398
+ * the JIT: every instruction the model uses, authorized once, plus a grant for
399
+ * each declared memory.
73
400
  *
74
- * The executor owns the scheduler, the device instances and the topic routing; the host owns the
75
- * clock: it calls {@link advance} with the slice of time it wants simulated and dispatches widget
76
- * input through {@link deliver}. The executor itself never leaves the caller's thread — there is
77
- * no worker and no message channel — so a host can wire it to `WidgetHost` and read a publish
78
- * while the stack that produced it is still running.
401
+ * `@mica-js/ir` deliberately keeps its core instruction list internal, so the
402
+ * names are collected from the generated bodies instead of being restated here.
79
403
  *
80
- * Every method except `loadSchematic` is synchronous: once a schematic is loaded, a host can
81
- * advance, deliver, reset and dispose from plain event handlers.
404
+ * @param module - Generated module whose bodies and memories are granted.
405
+ * @param updateResources - Read-only byte regions that opt into the host-only
406
+ * versioned update path (for example MCU firmware patching).
82
407
  */
83
- export declare interface DeviceSimExecutor {
84
- getState(): SimulationState;
85
- /** Current virtual time; `0` before the first `loadSchematic`. */
86
- getSimTime(): TimePs;
87
- /** Schematic the current runtime was built from; the empty sheet before the first load. */
88
- getSchematic(): SchematicDocument;
89
- /** Endpoints of the running instances, in schematic order; empty while `idle`. */
90
- getTopics(): readonly DeviceTopic[];
408
+ export declare function createModuleValidation(module: IRModule, updateResources?: readonly BytesRef[]): IRValidationOptions;
409
+
410
+ /**
411
+ * Compiles a schematic and reports which circuit device each symbol became.
412
+ *
413
+ * {@link createCircuitFromSchematic} returns only the circuit; hosts that route
414
+ * schematic endpoints to circuit accessors need the mapping as well.
415
+ */
416
+ export declare function createSchematicCircuit(schematic: SchematicDocument, options: SchematicCircuitOptions): Promise<SchematicCircuitResult>;
417
+
418
+ /**
419
+ * Same-thread `DeviceSimulationHost` over a schematic compiled by the unified-IR runtime.
420
+ *
421
+ * The host owns the circuit: `loadSchematic` reads, parses and compiles it, `tick` advances one
422
+ * circuit step and publishes the output topics that changed, and `deliver` queues widget payloads
423
+ * for the next step. Device models and their endpoints come from `resolveDevice`, so the host stays
424
+ * generic. Nothing here touches the DOM, so the sandbox guest and a Node test use the same
425
+ * implementation.
426
+ */
427
+ export declare function createSchematicDeviceSimulationHost(options: SchematicDeviceSimulationHostOptions): DeviceSimulationHost;
428
+
429
+ /** Rails every circuit understands without declaring them. */
430
+ export declare const DEFAULT_RAILS: Readonly<Record<string, boolean>>;
431
+
432
+ /** Global pin addresses reserved per device (one 32-pin port). */
433
+ export declare const DEVICE_PIN_STRIDE = 32;
434
+
435
+ /**
436
+ * What every device accessor offers, whatever its type.
437
+ *
438
+ * `readPin` returns the level the *device* drives onto one of its pins (its
439
+ * output latch), while `Circuit.getPin('device.pin')` returns the level the pin
440
+ * *observes* after the electrical solve. Writing a pin only makes sense for
441
+ * driver pins, so `writePin` rejects load and passive pins.
442
+ */
443
+ export declare interface DeviceAccessor {
444
+ /** Circuit-unique device id. */
445
+ readonly deviceId: string;
446
+ /** Device type, e.g. `'push-pull-driver'`. */
447
+ readonly type: string;
448
+ /** Declared pin names, in declaration order. */
449
+ readonly pinNames: readonly string[];
450
+ /** Declared internal state names, in declaration order. */
451
+ readonly stateNames: readonly string[];
452
+ /** Reads the level the device drives onto `pinName`. */
453
+ readPin(pinName: string): boolean;
454
+ /** Writes the level the device drives onto `pinName`. */
455
+ writePin(pinName: string, value: boolean): void;
456
+ /** Reads one declared internal state. */
457
+ getState(name: string): unknown;
458
+ /** Writes one declared internal state. */
459
+ setState(name: string, value: unknown): void;
460
+ }
461
+
462
+ /**
463
+ * Builds the typed accessor of a device after its module is compiled.
464
+ *
465
+ * A description that supplies `accessor` replaces the generic accessor the
466
+ * runtime would otherwise synthesize from `type`. The factory runs once per
467
+ * circuit and closes over the layout its IR factory allocated.
468
+ */
469
+ export declare type DeviceAccessorFactory = (context: DeviceAccessorFactoryContext) => DeviceAccessorSurface;
470
+
471
+ /** Host services handed to a device accessor factory at circuit creation. */
472
+ export declare interface DeviceAccessorFactoryContext {
473
+ readonly deviceId: string;
474
+ /** Live engine storage (`IRStorage` in practice). */
475
+ readonly storage: unknown;
476
+ /** Throws once the owning circuit has been disposed. */
477
+ readonly assertActive: () => void;
478
+ /** Advances the owning circuit by one tick. */
479
+ readonly step: () => void;
480
+ /** Advances the owning circuit by `count` ticks. */
481
+ readonly runBatch: (count: number) => void;
482
+ }
483
+
484
+ /** Every accessor of one circuit, keyed by device id. */
485
+ export declare type DeviceAccessors = Readonly<Record<string, DeviceAccessor>>;
486
+
487
+ /**
488
+ * Accessor map derived from a literal compilation input.
489
+ *
490
+ * `Circuit.create` infers the device ids of a `const` input, so
491
+ * `circuit.devices.<id>` is typed without a cast. A device package that wants a
492
+ * richer surface builds it through `DeviceDescription.accessor` and casts at
493
+ * the call site.
494
+ */
495
+ export declare type DeviceAccessorsOf<I extends CircuitCompilationInput> = {
496
+ readonly [D in I['devices'][number] as D['id']]: DeviceAccessor;
497
+ };
498
+
499
+ /**
500
+ * Structural surface every device accessor exposes.
501
+ *
502
+ * The compiler keeps this declaration independent from the runtime's
503
+ * `DeviceAccessor` so a device kernel can ship its own typed accessor without
504
+ * making the compiler depend on the runtime module.
505
+ */
506
+ declare interface DeviceAccessorSurface {
507
+ readonly deviceId: string;
508
+ readonly type: string;
509
+ readonly pinNames: readonly string[];
510
+ readonly stateNames: readonly string[];
511
+ readPin(pinName: string): boolean;
512
+ writePin(pinName: string, value: boolean): void;
513
+ getState(name: string): unknown;
514
+ setState(name: string, value: unknown): void;
515
+ }
516
+
517
+ /** Build surface handed to one device behavior. */
518
+ export declare interface DeviceBehaviorApi {
519
+ readonly deviceId: string;
520
+ readonly builder: FunctionBuilder<readonly []>;
91
521
  /**
92
- * Builds a runtime for `document` and mounts one device instance per symbol.
93
- *
94
- * Asynchronous only because device modules are fetched through the provider: everything after
95
- * that runs synchronously. The new runtime is built before the old one is dropped, so a rejected
96
- * load leaves the previous simulation untouched. Resolves once every `initialize` entry has run,
97
- * with the clock back at 0.
98
- *
99
- * @throws {SimulatorError} when a device cannot be loaded or instantiated.
522
+ * Module the phase is generated into. Complex devices use it to declare
523
+ * their own typed arrays (`module.array`, `module.bytes`) and providers;
524
+ * simple devices never need to touch it.
100
525
  */
101
- loadSchematic(document: SchematicDocument): Promise<void>;
526
+ readonly module: IRModule;
527
+ /** Shared `pin_mode` / `pin_output` / `pin_input` memories. */
528
+ readonly memory: CompiledCircuitMemory;
529
+ /** Instance configuration from {@link DeviceConfig.config}. */
530
+ readonly config: Readonly<Record<string, unknown>> | undefined;
531
+ /** Every declared pin of the device, in declaration order. */
532
+ readonly pins: readonly DevicePinHandle[];
533
+ /** Pins whose role is `driver`. */
534
+ readonly outputs: readonly DevicePinHandle[];
535
+ pin(name: string): DevicePinHandle;
536
+ state<T extends ScalarType = ScalarType>(name: string): DeviceStateHandle<T>;
537
+ }
538
+
539
+ /**
540
+ * Per-device behavior hooks. The compiler emits one IR function per hook:
541
+ * `initialize` -> `<id>_initialize`, `tick` -> `<id>_tick`,
542
+ * `update` -> `<id>_update`. Missing hooks simply produce no function.
543
+ */
544
+ export declare interface DeviceBehaviors {
545
+ readonly initialize?: (api: DeviceBehaviorApi) => void;
546
+ readonly tick?: (api: DeviceBehaviorApi) => void;
547
+ readonly update?: (api: DeviceBehaviorApi) => void;
548
+ }
549
+
550
+ /** One device instance of the circuit. */
551
+ export declare interface DeviceConfig {
552
+ /** Circuit-unique identity; prefix of every generated function name. */
553
+ readonly id: string;
554
+ /** Device type, e.g. `'push-pull-driver'`; free-form label of the device model. */
555
+ readonly type: string;
556
+ readonly description: DeviceDescription;
557
+ /** Instance configuration; reserved for device kernels that take parameters. */
558
+ readonly config?: Readonly<Record<string, unknown>>;
559
+ }
560
+
561
+ /** IR-level device description consumed by the compiler. */
562
+ export declare interface DeviceDescription {
563
+ readonly name?: string;
564
+ readonly pins: DevicePinMap;
565
+ readonly states?: Readonly<Record<string, DeviceStateDescription>>;
566
+ readonly behaviors?: DeviceBehaviors;
102
567
  /**
103
- * Advances the virtual clock by `delta` picoseconds and runs everything scheduled up to it.
104
- *
105
- * The whole slice runs inside the call, so the host can drive it from a frame loop and read
106
- * {@link AdvanceReport} right away. Payloads queued by {@link deliver} are consumed at the start
107
- * of the slice.
108
- *
109
- * @throws {SimulatorError} when the executor is idle, disposed or `delta` is not positive.
110
- * @throws when a device faults; `getState()` is then `'faulted'`.
568
+ * Complex-kernel hook. Runs once per module before phase generation so the
569
+ * kernel may declare typed arrays, byte memories and providers, then return
570
+ * the behaviour hooks the compiler should call inside each phase.
111
571
  */
112
- advance(delta: TimePs): AdvanceReport;
113
- /** Subscribes to device publishes; returns the unsubscribe function. */
114
- onPublish(listener: (publish: DevicePublish) => void): () => void;
572
+ readonly kernel?: DeviceKernelFactory;
115
573
  /**
116
- * Queues one payload for a device input port.
117
- *
118
- * The payload is `unknown` on purpose: the host forwards what a widget published, and the device
119
- * layer rejects a payload that does not match the port type.
120
- *
121
- * Delivery is deferred to the next {@link advance}, so a host can post several events for the
122
- * same instant and have the devices observe them in call order.
123
- *
124
- * @throws {SimulatorError} when the symbol or port is unknown, or the port is an output.
574
+ * Optional typed accessor factory. Kernels with a richer surface than the
575
+ * generic state/pin accessor (a register file, a memory map) use it.
125
576
  */
126
- deliver(target: DeviceTopicTarget, payload: unknown): void;
577
+ readonly accessor?: DeviceAccessorFactory;
127
578
  /**
128
- * Drops the running instances and rebuilds them from the current schematic at time 0.
129
- *
130
- * Synchronous: the devices were already loaded by `loadSchematic`, so this is a fresh set of
131
- * instances, not a reload.
579
+ * Read-only byte regions the kernel wants host updates for. The compiler
580
+ * grants `update` access on top of the normal `read` grant so kernels can
581
+ * expose firmware patching without allowing guest stores.
132
582
  */
133
- reset(): void;
134
- /** Destroys every instance and releases the runtime. Idempotent. */
135
- dispose(): void;
583
+ readonly updateResources?: readonly BytesRef[];
136
584
  }
137
585
 
138
- export declare interface DeviceSimExecutorOptions {
139
- /** Device descriptions and code; the schematic only names device ids. */
140
- readonly devices: IDeviceProvider;
141
- readonly scheduler?: SchedulerOptions;
142
- readonly onDiagnostic?: (diagnostic: SimulationDiagnostic) => void;
143
- /**
144
- * Host-owned pin/connection wiring, built once per runtime with that runtime's scheduler.
145
- *
146
- * Without it the instances get neither `pinHost` nor a topology, so a device whose IR touches
147
- * pins or connections fails to load with the device layer's own error. A factory that throws
148
- * rejects `loadSchematic` and `reset`; the running runtime is then left untouched.
149
- */
150
- readonly host?: DeviceSimHostFactory;
586
+ /**
587
+ * Everything a complex device kernel needs to declare its own IR before any
588
+ * phase function body is opened: the module (for `array`/`bytes`/`provider`),
589
+ * the shared pin memories and the allocated pin ids.
590
+ */
591
+ export declare interface DeviceKernelContext {
592
+ readonly deviceId: string;
593
+ readonly config: Readonly<Record<string, unknown>> | undefined;
594
+ readonly module: IRModule;
595
+ readonly memory: CompiledCircuitMemory;
596
+ readonly pins: readonly DeviceKernelPin[];
151
597
  }
152
598
 
153
599
  /**
154
- * Host-owned wiring handed to every instance of one runtime.
600
+ * Builds the phase hooks of a complex device after resource allocation but
601
+ * before phase functions are generated. Declaring arrays, byte memories and
602
+ * providers is only legal here (never inside a function body).
155
603
  *
156
- * The executor builds it through {@link DeviceSimHostFactory} on every `loadSchematic` and
157
- * `reset()`, so the pin host and the topology always belong to the scheduler that is running.
604
+ * Returning {@link DeviceKernelRuntime} lets the kernel own its phase
605
+ * functions directly; returning {@link DeviceBehaviors} asks the compiler to
606
+ * generate `<id>_initialize` / `<id>_tick` / `<id>_update` wrappers.
158
607
  */
159
- export declare interface DeviceSimHost {
160
- /** Electrical/pin host passed to every instance as `pinHost`. */
161
- readonly pinHost?: DevicePinHost;
162
- /** Topology passed to every instance as `connections.topology`. */
163
- readonly topology?: TopologyRuntime;
164
- /** Adds per-symbol options such as `updateResources`; omitted fields keep the defaults. */
165
- instanceOptions?(symbol: SchematicSymbol): DeviceSimInstanceOptions | undefined;
166
- /** Releases what the factory created; runs once every instance of the runtime is destroyed. */
167
- dispose?(): void;
608
+ export declare type DeviceKernelFactory = (context: DeviceKernelContext) => DeviceBehaviors | DeviceKernelRuntime;
609
+
610
+ /** One pin as seen by a device kernel factory (no builder attached yet). */
611
+ declare interface DeviceKernelPin {
612
+ readonly name: string;
613
+ readonly globalPinId: number;
614
+ readonly role: CompiledPinRole;
168
615
  }
169
616
 
170
- export declare interface DeviceSimHostContext {
171
- /** Scheduler of the runtime being built; a new one for every load and every reset. */
172
- readonly scheduler: Scheduler;
173
- readonly schematic: SchematicDocument;
174
- /**
175
- * Device modules the schematic resolves to, keyed by device id.
176
- *
177
- * Pin geometry and connection pairs live in the descriptions, so a wiring host that derives nets
178
- * from the sheet (see `createCircuitHost`) reads them from here instead of loading them twice.
179
- */
180
- readonly modules: ReadonlyMap<string, LoadedDeviceModule>;
617
+ /**
618
+ * Direct phase refs a complex kernel may return instead of behaviour hooks.
619
+ * The compiler then uses these functions as the device's loop entries, with
620
+ * no wrapper phase around them.
621
+ */
622
+ export declare interface DeviceKernelRuntime {
623
+ readonly initialize?: FunctionRef<readonly [], readonly []>;
624
+ readonly tick?: FunctionRef<readonly [], readonly []>;
625
+ readonly update?: FunctionRef<readonly [], readonly []>;
181
626
  }
182
627
 
183
- /** Builds the wiring for one runtime. */
184
- export declare type DeviceSimHostFactory = (context: DeviceSimHostContext) => DeviceSimHost;
628
+ /** Metadata of one compiled device. */
629
+ declare interface DeviceMetadata {
630
+ readonly deviceId: string;
631
+ readonly type: string;
632
+ /** First global pin id of the device. */
633
+ readonly pinOffset: number;
634
+ /** First slot ordinal of the device in the global state space. */
635
+ readonly stateOffset: number;
636
+ readonly pins: ReadonlyMap<string, number>;
637
+ readonly states: ReadonlyMap<string, DeviceStateSlot>;
638
+ /** Every IR function generated for this device. */
639
+ readonly functions: readonly string[];
640
+ readonly initialize: string | undefined;
641
+ readonly tick: string | undefined;
642
+ readonly update: string | undefined;
643
+ /** Typed accessor factory supplied by the device description, if any. */
644
+ readonly accessor: DeviceAccessorFactory | undefined;
645
+ /** Kernel factory that generated the device's extra IR resources. */
646
+ readonly kernel: DeviceKernelFactory | undefined;
647
+ }
648
+
649
+ /** Pins of one device mapped into the global pin space. */
650
+ declare interface DevicePinAllocation {
651
+ readonly deviceId: string;
652
+ /** First global pin id of the device. */
653
+ readonly offset: number;
654
+ readonly pins: ReadonlyMap<string, number>;
655
+ readonly resolved: ReadonlyMap<string, ResolvedDevicePin>;
656
+ }
657
+
658
+ /** One pin declared by a device description. */
659
+ export declare interface DevicePinDescription {
660
+ /** Defaults to `'passive'`: the pin only senses the net. */
661
+ readonly direction?: DevicePinDirection;
662
+ /** Overrides the role derived from `direction`. */
663
+ readonly role?: CompiledPinRole;
664
+ /** Purely informational kind, e.g. `'signal'`, `'power'`, `'gnd'`. */
665
+ readonly kind?: string;
666
+ }
185
667
 
186
668
  /**
187
- * Extra instance options a host may add per symbol.
669
+ * Types for the unified IR compiler (U01).
670
+ *
671
+ * The compiler turns several device descriptions plus a pin-to-pin netlist into
672
+ * one `@mica-js/ir` module. Device logic, the electrical solve and the main
673
+ * loop all share one global pin space, one state space and one engine entry, so
674
+ * a tick costs one interpreter/JIT call for the whole circuit.
188
675
  *
189
- * Identity, the symbol's properties and the pin/connection hosts stay with the executor, so a
190
- * host cannot rebind one instance to another runtime's wiring.
676
+ * The shared constants (`UNIFIED_PIN_CAPACITY`, `DEVICE_PIN_STRIDE`, `PIN_MODE`)
677
+ * live in `../pin-space` and are reused here. The compiler ships no device
678
+ * models: every description is supplied by the caller.
191
679
  */
192
- export declare type DeviceSimInstanceOptions = Omit<DeviceInstanceOptions, 'instanceId' | 'onTopic' | 'pinHost' | 'connections' | 'properties'>;
680
+ /** Electrical intent of one device pin. */
681
+ export declare type DevicePinDirection = 'input' | 'output' | 'bidirectional' | 'passive';
682
+
683
+ /** Pin operations a behavior may use; each call inlines into global memory. */
684
+ declare interface DevicePinHandle {
685
+ readonly name: string;
686
+ readonly globalId: number;
687
+ /** `pin.configure`: writes `pin_mode[globalId]`. */
688
+ configure(mode: number): void;
689
+ /** `pin.write_digital`: writes `pin_output[globalId]`. */
690
+ writeDigital(level: Value<'bool'>): void;
691
+ /** `pin.sample_digital`: reads the solved `pin_input[globalId]`. */
692
+ sampleDigital(): Value<'bool'>;
693
+ /** Reads the device's own `pin_output[globalId]`. */
694
+ readDrivenDigital(): Value<'bool'>;
695
+ }
696
+
697
+ /**
698
+ * Declared pins of one device. A `Map` keeps duplicate names impossible and an
699
+ * object keeps authored descriptions terse; both preserve declaration order.
700
+ */
701
+ declare type DevicePinMap = ReadonlyMap<string, DevicePinDescription> | Readonly<Record<string, DevicePinDescription>>;
702
+
703
+ /** What one {@link DeviceSimulationHost.tick} call executed. */
704
+ export declare interface DeviceSimTickReport {
705
+ /** Simulation time after the step, in picoseconds. */
706
+ readonly simTime: number;
707
+ /** Circuit steps executed by this call. */
708
+ readonly executed: number;
709
+ }
193
710
 
194
711
  /**
195
- * One logical endpoint of the running schematic.
712
+ * Simulation the canvas runtime drives (RFC 0018).
196
713
  *
197
- * `symbol` + `port` is the same pair a canvas binding refers to, and `direction` / `type` match
198
- * `DevicePortDescriptor`, so a host can build binding candidates without touching the devices.
714
+ * Every method returns a promise, so a same-thread implementation and a cross-thread one are called
715
+ * the same way and `WidgetHost` and the simulation can live on different threads. The host owns the
716
+ * frame clock: it calls {@link tick} with one fixed step at a time and reads the current simulation
717
+ * time back from {@link getSimTime}, so there is exactly one authority for time.
199
718
  */
200
- export declare interface DeviceTopic {
201
- /** Symbol id inside the schematic (`SchematicSymbol.id`); this is what a binding stores. */
202
- readonly symbol: string;
719
+ export declare interface DeviceSimulationHost {
720
+ /**
721
+ * Reads and mounts the schematic behind `uri`; `undefined` clears the runtime.
722
+ *
723
+ * The implementation reads the bytes through its own `fs` and resolves the `image` / `binary`
724
+ * properties of every symbol against that schematic URI.
725
+ */
726
+ loadSchematic(uri: string | undefined): Promise<void>;
727
+ /** Resets the loaded runtime to its initial state without unloading the schematic. */
728
+ reset(): Promise<void>;
729
+ /** Advances one fixed step of `dt` picoseconds when the widget host is in simulation mode. */
730
+ tick(dt: number): Promise<DeviceSimTickReport>;
731
+ /** Queues one payload for a device endpoint; consumed at the next {@link tick}. */
732
+ deliver(target: CanvasBindingTarget, payload: unknown, simTime?: number): Promise<void>;
733
+ /** Subscribes to device publishes; registering itself is a local operation. */
734
+ readonly onDidPublish: Event_2<SimulationPublish>;
735
+ /** Endpoints of the running devices, in schematic order. */
736
+ getTopics(): Promise<readonly DeviceTopic[]>;
737
+ /** Current simulation time, in picoseconds. */
738
+ getSimTime(): Promise<number>;
739
+ /** Schematic the runtime was built from. */
740
+ getSchematic(): Promise<SchematicDocument | undefined>;
741
+ /** Releases the runtime. */
742
+ dispose(): Promise<void>;
743
+ }
744
+
745
+ /** Running guest: where the typed services live and which ports the worker was handed. */
746
+ export declare interface DeviceSimulationHostGuest {
203
747
  /**
204
- * Reference designator shown to users (`U1`), following `designatorOf`: the symbol's own
205
- * `designator`, or its id when the schematic does not set one.
748
+ * Endpoint the typed device simulation services are registered on. A worker script that owns
749
+ * further capabilities registers them here instead of opening a second sandbox channel.
206
750
  */
207
- readonly designator: string;
208
- /** Port key declared by the device description. */
751
+ readonly rpc: RpcEndpoint;
752
+ /** Extra startup ports, in the order the worker received them. */
753
+ readonly ports: readonly MessagePort[];
754
+ /** Releases the circuit and closes the endpoint. */
755
+ dispose(): Promise<void>;
756
+ }
757
+
758
+ /**
759
+ * Device wiring a worker script hands to {@link startDeviceSimulationHostGuest}.
760
+ *
761
+ * The simulator ships no device models, so every option defaults to "knows no references": a
762
+ * package that owns devices bundles its own worker script and supplies these.
763
+ */
764
+ export declare interface DeviceSimulationHostGuestOptions {
765
+ /** Symbol geometry of the schematics this guest loads, or a factory called per load. */
766
+ readonly devices?: DeviceSymbolProvider | (() => DeviceSymbolProvider);
767
+ /** Resolves a schematic device reference; when omitted every reference stays unresolved. */
768
+ readonly resolveDevice?: (reference: DeviceReference) => SchematicDeviceBinding | undefined;
769
+ /**
770
+ * Awaited before the first schematic load, so a device library can be read through the host file
771
+ * system before anything compiles. Runs at most once.
772
+ */
773
+ readonly prepare?: () => Promise<void>;
774
+ /**
775
+ * Extra ports the worker received in the first ordinary message. The RPC port comes first, so these are
776
+ * `event.ports` from index 1 onward, in the order the caller transferred them. The first one is
777
+ * the direct topic channel (RFC 0018): the widget guest holds the other end and talks to this
778
+ * guest without the host relaying.
779
+ */
780
+ readonly ports?: readonly MessagePort[];
781
+ }
782
+
783
+ /** One scalar internal state of a device, allocated in the global state space. */
784
+ export declare interface DeviceStateDescription {
785
+ readonly type: ScalarType;
786
+ readonly initial: boolean | number;
787
+ }
788
+
789
+ /** Internal state slot a behavior may read and write. */
790
+ declare interface DeviceStateHandle<T extends ScalarType = ScalarType> {
791
+ readonly name: string;
792
+ readonly type: T;
793
+ /** Index inside the generated `device_state_<type>` array. */
794
+ readonly index: number;
795
+ load(): Value<T>;
796
+ store(value: Value<T>): void;
797
+ }
798
+
799
+ /** One device state slot inside the global state space. */
800
+ declare interface DeviceStateSlot {
801
+ readonly name: string;
802
+ readonly deviceId: string;
803
+ readonly type: ScalarType;
804
+ /** Generated array that holds the slot. */
805
+ readonly array: ArrayRef;
806
+ /** Index inside {@link array}. */
807
+ readonly index: number;
808
+ /** Ordinal in the whole state space, across scalar types. */
809
+ readonly slot: number;
810
+ }
811
+
812
+ /** One endpoint of a mounted device instance, as the simulation reports it. */
813
+ export declare interface DeviceTopic {
814
+ readonly symbol: string;
815
+ /** Reference designator shown to users; informational for the canvas. */
816
+ readonly designator?: string;
209
817
  readonly port: string;
210
818
  readonly direction: 'input' | 'output';
211
- readonly type: TopicPayloadType;
819
+ readonly type: PayloadType;
212
820
  readonly title?: string;
213
821
  }
214
822
 
215
- export declare interface DeviceTopicTarget {
216
- readonly symbol: string;
823
+ export { Disposable }
824
+
825
+ export { Event_2 as Event }
826
+
827
+ /** Result of the global pin allocation. */
828
+ declare interface GlobalPinMap {
829
+ /** `'mcu1.PA0'` -> global pin id. */
830
+ readonly pins: ReadonlyMap<string, number>;
831
+ readonly devices: ReadonlyMap<string, DevicePinAllocation>;
832
+ readonly totalPins: number;
833
+ readonly capacity: number;
834
+ }
835
+
836
+ /** Result of the global state allocation. */
837
+ declare interface GlobalStateMap {
838
+ readonly devices: ReadonlyMap<string, ReadonlyMap<string, DeviceStateSlot>>;
839
+ /** One generated array per scalar type actually used. */
840
+ readonly arrays: ReadonlyMap<ScalarType, ArrayRef>;
841
+ /** Slot count per scalar type. */
842
+ readonly totals: ReadonlyMap<ScalarType, number>;
843
+ readonly totalStates: number;
844
+ }
845
+
846
+ /** Values stored in the global `pin_mode` array. */
847
+ export declare const PIN_MODE: Readonly<{
848
+ readonly highZ: 0;
849
+ readonly pushPull: 1;
850
+ readonly openDrain: 2;
851
+ readonly analog: 3;
852
+ }>;
853
+
854
+ /** One value of the global `pin_mode` array. */
855
+ export declare type PinMode = (typeof PIN_MODE)[keyof typeof PIN_MODE];
856
+
857
+ /** One resolved pin in the global pin space. */
858
+ declare interface ResolvedDevicePin {
859
+ readonly name: string;
860
+ readonly deviceId: string;
861
+ readonly globalPinId: number;
862
+ readonly direction: DevicePinDirection;
863
+ readonly role: CompiledPinRole;
864
+ /** Whether the device reads the solved value of this pin. */
865
+ readonly senses: boolean;
866
+ }
867
+
868
+ /** One component symbol of a compiled schematic. */
869
+ export declare interface SchematicCircuitBinding {
870
+ /** Symbol id as written in the schematic. */
871
+ readonly symbolId: string;
872
+ /** Compiler-safe device id assigned to the symbol. */
873
+ readonly deviceId: string;
874
+ /** Parsed `"<packageId>:<deviceId>"` reference. */
875
+ readonly reference: DeviceReference;
876
+ /** Device type from the resolved runtime binding. */
877
+ readonly type: string;
878
+ }
879
+
880
+ /** Options for {@link createCircuitFromSchematic}. */
881
+ export declare interface SchematicCircuitOptions extends CircuitRuntimeOptions {
882
+ /**
883
+ * Symbol geometry provider — pass the same provider that authored the
884
+ * schematic. Without it the derived topology contains no pins.
885
+ */
886
+ readonly devices?: DeviceSymbolProvider;
887
+ /** Resolves a schematic device reference to its runtime description. */
888
+ readonly resolveDevice: (reference: DeviceReference) => SchematicDeviceBinding | undefined;
889
+ /** Coordinate tolerance used when matching pins to wires. */
890
+ readonly tolerance?: number;
891
+ }
892
+
893
+ /** A compiled schematic circuit plus the symbol-to-device mapping it produced. */
894
+ declare interface SchematicCircuitResult {
895
+ readonly circuit: Circuit;
896
+ /** Component symbols in schematic order; non-component symbols are absent. */
897
+ readonly bindings: readonly SchematicCircuitBinding[];
898
+ }
899
+
900
+ /** Runtime behaviour of one schematic device package. */
901
+ export declare interface SchematicDeviceBinding {
902
+ /** Device type, e.g. `'counter-ir'`. */
903
+ readonly type: string;
904
+ /** IR description: pins, states and behaviours. */
905
+ readonly description: DeviceDescription;
906
+ /** Instance configuration reserved for device kernels. */
907
+ readonly config?: Readonly<Record<string, unknown>>;
908
+ /** Endpoints the simulation host exposes; absent means the device has none. */
909
+ readonly topics?: readonly SchematicDeviceTopic[];
910
+ /** Bridges one input topic payload onto the compiled device accessor. */
911
+ deliver?(accessor: DeviceAccessor, port: string, payload: unknown): void;
912
+ /** Reads one output topic from the compiled device accessor. */
913
+ read?(accessor: DeviceAccessor, port: string): unknown;
914
+ }
915
+
916
+ /** Reads the bytes of one schematic URI; the caller resolves relative references. */
917
+ export declare interface SchematicDeviceSimulationHostOptions {
918
+ readonly read: (uri: string) => Promise<Uint8Array>;
919
+ /**
920
+ * Symbol geometry of the schematics this host loads. Pass the same provider the schematic was
921
+ * authored with; without it the derived topology contains no pins. A factory is called when a
922
+ * schematic loads, so a caller can read its device library first.
923
+ */
924
+ readonly devices?: DeviceSymbolProvider | (() => DeviceSymbolProvider);
925
+ /**
926
+ * Resolves one schematic device reference to its runtime description and endpoints.
927
+ *
928
+ * The host ships no device models: the package that owns the devices decides which references
929
+ * exist, what they look like and which topics they expose.
930
+ */
931
+ readonly resolveDevice: (reference: DeviceReference) => SchematicDeviceBinding | undefined;
932
+ }
933
+
934
+ /**
935
+ * One endpoint a caller-supplied device declares to the simulation host.
936
+ *
937
+ * The simulator never guesses ports from a device type: the package that
938
+ * resolves the reference states which payloads the device accepts and which it
939
+ * publishes, in the same place it supplies the IR description.
940
+ */
941
+ export declare interface SchematicDeviceTopic {
217
942
  readonly port: string;
943
+ readonly direction: 'input' | 'output';
944
+ readonly type: PayloadType;
945
+ readonly title?: string;
218
946
  }
219
947
 
220
- /** A problem the executor survives; the simulation keeps running unless stated otherwise. */
221
- export declare interface SimulationDiagnostic {
222
- readonly code: SimulationDiagnosticCode;
223
- readonly message: string;
224
- /** Symbol the problem belongs to, when it is attributable to one. */
225
- readonly symbol?: string;
226
- readonly cause?: unknown;
948
+ /** One payload a simulation published for an endpoint the canvas can bind to. */
949
+ export declare interface SimulationPublish {
950
+ readonly target: CanvasBindingTarget;
951
+ readonly payload: unknown;
952
+ readonly simTime: number;
227
953
  }
228
954
 
229
- export declare type SimulationDiagnosticCode = 'simulator/device-load-failed' | 'simulator/instance-create-failed' | 'simulator/advance-failed' | 'simulator/publish-failed' | 'simulator/dispose-failed';
955
+ /**
956
+ * Registers RFC 0018's device simulation services on a sandbox RPC port.
957
+ *
958
+ * A worker script obtains the port from `event.ports[0]` and calls this function; nothing else is
959
+ * needed, because the guest is a plain module the `@mica-js/sandbox/vite` plugin bundles into a
960
+ * self-contained script. The guest registers `deviceSimulationHostGuestService` and reads schematics
961
+ * through `deviceSimulationHostFileSystemService`, so schematic bytes never enter the guest's own
962
+ * message handling and every payload is a typed RPC DTO.
963
+ */
964
+ export declare function startDeviceSimulationHostGuest(port: MessagePort, options?: DeviceSimulationHostGuestOptions): DeviceSimulationHostGuest;
230
965
 
231
- /** Lifecycle of one executor. `ready` is the only state that can advance. */
232
- export declare type SimulationState = 'idle' | 'ready' | 'faulted' | 'disposed';
966
+ /** Global pin addresses available to one circuit (8 devices x 32 pins). */
967
+ export declare const UNIFIED_PIN_CAPACITY = 256;
233
968
 
234
- /** Error raised by the executor's host-facing calls. */
235
- export declare class SimulatorError extends Error {
236
- readonly name = "SimulatorError";
237
- readonly code: SimulatorErrorCode;
238
- readonly symbol: string | undefined;
239
- constructor(code: SimulatorErrorCode, message: string, options?: SimulatorErrorOptions);
969
+ /** Error raised while compiling a circuit. */
970
+ export declare class UnifiedIRCompilerError extends Error {
971
+ readonly name = "UnifiedIRCompilerError";
972
+ readonly code: UnifiedIRCompilerErrorCode;
973
+ readonly deviceId: string | undefined;
974
+ readonly pinName: string | undefined;
975
+ readonly netId: number | undefined;
976
+ readonly diagnostics: readonly CompilationDiagnostic[];
977
+ constructor(code: UnifiedIRCompilerErrorCode, message: string, options?: UnifiedIRCompilerErrorOptions);
240
978
  }
241
979
 
242
- export declare type SimulatorErrorCode = 'simulator/disposed' | 'simulator/not-ready' | 'simulator/invalid-delta' | 'simulator/unknown-target' | 'simulator/unknown-port' | 'simulator/device-load-failed' | 'simulator/instance-create-failed';
980
+ /** Error codes raised by {@link UnifiedIRCompilerError}. */
981
+ export declare type UnifiedIRCompilerErrorCode = 'invalid-input' | 'duplicate-device' | 'unknown-device' | 'pin-not-found' | 'state-not-found' | 'invalid-connection' | 'capacity-exceeded' | 'unsupported-device' | 'driver-conflict' | 'power-short' | 'rail-conflict' | 'invalid-ir';
243
982
 
244
- export declare interface SimulatorErrorOptions {
245
- /** Symbol the failure belongs to, when it is attributable to one. */
246
- readonly symbol?: string;
983
+ export declare interface UnifiedIRCompilerErrorOptions {
984
+ readonly deviceId?: string;
985
+ readonly pinName?: string;
986
+ readonly netId?: number;
987
+ readonly diagnostics?: readonly CompilationDiagnostic[];
247
988
  readonly cause?: unknown;
248
989
  }
249
990