@mica-js/simulator 1.0.0 → 2.1.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,1059 +1,360 @@
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';
1
+ import { BlockIR } from '@mica-js/device-model';
2
+ import { DeviceIR } from '@mica-js/device-model';
3
+ import { DeviceMetadata } from '@mica-js/document/schematic';
4
+ import { DevicePortMetadata } from '@mica-js/document/schematic';
6
5
  import { Disposable } from '@mica-js/core/lifecycle';
7
- import { EntryRef } from '@mica-js/ir';
8
6
  import { Event as Event_2 } from '@mica-js/core/lifecycle';
9
- import { FunctionBuilder } from '@mica-js/ir';
10
- import { FunctionRef } from '@mica-js/ir';
11
- import { IRInterpreter } from '@mica-js/ir';
12
- import { IRJITTuning } from '@mica-js/ir';
13
- import { IRModule } from '@mica-js/ir';
14
- import { IRValidationOptions } from '@mica-js/ir';
15
- import { PayloadType } from '@mica-js/core/canvas';
16
- import { PropertyValue } from '@mica-js/core/schematic';
7
+ import { InputPath } from '@mica-js/device-model';
8
+ import { JitBlockBuilder } from '@mica-js/device-model';
17
9
  import { RpcEndpoint } from '@mica-js/core/rpc';
18
- import { RuntimeScalar } from '@mica-js/ir';
19
- import { ScalarType } from '@mica-js/ir';
20
- import { SchematicDocument } from '@mica-js/core/schematic';
21
- import { StateRef } from '@mica-js/ir';
22
- import { Value } from '@mica-js/ir';
10
+ import { RpcServiceId } from '@mica-js/core/rpc';
11
+ import { SchematicDocument } from '@mica-js/document/schematic';
12
+ import { SourceInfo } from '@mica-js/device-model';
13
+ import { TimePs } from '@mica-js/core';
23
14
 
24
- /**
25
- * Host-facing runtime of one compiled unified circuit (U02).
26
- *
27
- * ```ts
28
- * const circuit = await Circuit.create({
29
- * devices: [
30
- * { id: 'drive1', type: 'push-pull-driver', description: driverDescription() },
31
- * { id: 'sink1', type: 'lamp-sink', description: sinkDescription() },
32
- * ],
33
- * connections: [
34
- * { from: 'drive1.PA0', to: 'sink1.anode' },
35
- * { from: 'sink1.cathode', to: 'GND' },
36
- * ],
37
- * });
38
- *
39
- * circuit.runBatch(1_000_000); // one engine call
40
- * expect(circuit.tickCount).toBe(1_000_000n);
41
- *
42
- * circuit.reset();
43
- * circuit.step();
44
- * expect(circuit.devices.sink1.getState('lamp')).toBe(true);
45
- * ```
46
- *
47
- * `Circuit` owns the engine instance and the tick counter; the compiled module
48
- * keeps every device, net and the main loop in one `@mica-js/ir` module, so a
49
- * batch is one interpreter/JIT call for the whole circuit.
50
- */
51
- export declare class Circuit<I extends CircuitCompilationInput = CircuitCompilationInput> {
52
- #private;
53
- /** Typed per-device accessors, keyed by device id. */
54
- readonly devices: DeviceAccessorsOf<I>;
55
- private constructor();
56
- /**
57
- * Compiles `input`, builds the engine instance and runs the generated
58
- * `initialize` entry once.
59
- *
60
- * The input is inferred as a `const` type, so a literal device list keeps its
61
- * ids and `circuit.devices.<id>` is typed without a cast.
62
- *
63
- * @throws {UnifiedIRCompilerError} when the circuit cannot be compiled.
64
- * @throws {CircuitError} for invalid options.
65
- */
66
- static create<const I extends CircuitCompilationInput>(input: I, options?: CircuitRuntimeOptions): Promise<Circuit<I>>;
67
- /**
68
- * Runs `count` ticks inside one generated loop — the throughput path.
69
- *
70
- * The whole batch is one engine call. The clock advances by completed ticks,
71
- * including the completed prefix of a failed batch.
72
- *
73
- * @throws {CircuitError} with code `invalid-count` unless `count` is a u32.
74
- */
75
- runBatch(count: number, dt?: number): void;
76
- /**
77
- * Advances exactly one tick — the debugging path.
78
- *
79
- * Every call is one engine entry, so prefer `runBatch` for throughput.
80
- */
81
- step(dt?: number): void;
82
- /**
83
- * Restores every memory to its declared initial value, re-runs `initialize`
84
- * and resets `tickCount` to `0n`.
85
- *
86
- * Device state written by earlier ticks is discarded, so the circuit behaves
87
- * exactly like a freshly created one.
88
- */
89
- reset(): void;
90
- /**
91
- * Reads the level one pin observes.
92
- *
93
- * Requires an explicitly initialized digital input capability and applies
94
- * the circuit interpretation to the solved physical voltage.
95
- *
96
- * @throws {CircuitError} with code `pin-not-found`.
97
- */
98
- getPin(pinName: string): boolean;
99
- /** Physical pin voltage; floating results never contain a synthetic voltage. */
100
- getVoltage(pinName: string): ElectricalReading;
101
- /** Resistor/contact currents follow endpoint order; source and pin contributions flow outward. */
102
- getCurrent(resource: string | ElectricalCurrentTarget): ElectricalReading;
103
- /** Pull-based active diagnostics: one warning per resource; successful recovery removes it. */
104
- getDiagnostics(): readonly ElectricalDiagnostic[];
105
- /** Number of ticks completed since creation or the last `reset()`. */
106
- get tickCount(): bigint;
107
- /** Virtual tick time completed since creation or the last `reset()`. */
108
- get virtualTime(): number;
109
- /** Underlying engine instance, e.g. for diagnostics or custom entries. */
110
- get jit(): IRInterpreter;
111
- /** Whether `dispose()` already ran. */
112
- get disposed(): boolean;
113
- /**
114
- * Releases the runtime. Idempotent; every later call throws a `CircuitError`
115
- * with code `disposed`, including stale device accessors.
116
- */
117
- dispose(): void;
15
+ export declare interface Board extends Disposable {
16
+ readonly time: number;
17
+ readonly status: BoardStatus;
18
+ readonly topics: TopicBridge;
19
+ readonly onDidError: Event_2<RuntimeDiagnostic>;
20
+ readonly onDidDiagnostic: Event_2<RuntimeDiagnostic>;
21
+ runUntil(target: number): void;
118
22
  }
119
23
 
120
- /** Compiler input: devices plus the connections between their pins. */
121
- export declare interface CircuitCompilationInput {
122
- readonly devices: readonly DeviceConfig[];
123
- readonly connections: readonly Connection[];
24
+ export declare interface BoardDescription {
25
+ readonly instances: readonly InstanceDescription[];
26
+ readonly nets: readonly NetDescription[];
124
27
  }
125
28
 
126
- /** Options for the compiler. */
127
- export declare interface CircuitCompilationOptions {
128
- /** Explicit GND-referenced voltage sources; GND itself is always 0 V. */
129
- readonly sources?: Readonly<Record<string, {
130
- readonly voltage: number;
131
- }>>;
132
- readonly interpretation?: 'two-state' | 'retain-in-band';
133
- /** Reproducible mica-floating-v2 input seed; defaults to 0. */
134
- readonly floatingSeed?: number;
135
- /** Runs `validateIR` over the generated module. Defaults to `true`. */
136
- readonly validate?: boolean;
137
- /** Overrides for the generated entry-point names. */
138
- readonly entryPointNames?: {
139
- readonly tick?: string;
140
- readonly initialize?: string;
141
- readonly batch?: string;
142
- };
29
+ export declare interface BoardOptions {
30
+ /** uint32,省略为 0;实例派生算法见 execution/random。 */
31
+ readonly seed?: number;
32
+ readonly execution?: 'throughput' | 'precise';
33
+ /** CPU execution quantum in integer picoseconds, default 10_000_000. */
34
+ readonly cpuQuantum?: number;
143
35
  }
144
36
 
145
- export declare interface CircuitDeviceSimulationHostOptions {
146
- /** Circuit the caller already created. */
147
- readonly circuit: Circuit;
148
- /** Whether `dispose()` also disposes the circuit. Defaults to `true`. */
149
- readonly ownsCircuit?: boolean;
150
- /** Schematic the circuit was built from, reported through `getSchematic`. */
151
- readonly schematic?: SchematicDocument;
152
- /** Endpoints the running devices expose. */
153
- readonly topics?: readonly DeviceTopic[];
154
- /** Picoseconds per circuit step. Defaults to 10 ns. */
155
- readonly stepPs?: number;
156
- /** Routes one widget payload into the caller's device layer. */
157
- readonly deliver: (symbol: string, port: string, payload: unknown) => void;
158
- }
37
+ export declare type BoardStatus = 'ready' | 'faulted' | 'disposed';
159
38
 
160
- /** Electrical-solve options forwarded to `compileCircuit`. */
161
- export declare interface CircuitElectricalOptions {
162
- readonly sources?: CircuitCompilationOptions['sources'];
163
- readonly interpretation?: CircuitCompilationOptions['interpretation'];
164
- readonly floatingSeed?: CircuitCompilationOptions['floatingSeed'];
39
+ /** 句柄随所属板或本次翻译失效;内容稳定期与允许读取阶段由 memory 合同规定。 */
40
+ export declare interface BorrowedBytes extends ByteReader {
41
+ readonly [borrowedTag]: true;
165
42
  }
166
43
 
167
- /** Execution engine a `Circuit` runs on. */
168
- export declare type CircuitEngine = 'jit' | 'reference';
44
+ declare const borrowedTag: unique symbol;
169
45
 
170
- /**
171
- * Error raised while driving a `Circuit`.
172
- *
173
- * The code is stable and machine-checkable, and the message always names the
174
- * offending device/pin/state plus the values that would have been accepted.
175
- */
176
- export declare class CircuitError extends Error {
177
- readonly name = "CircuitError";
178
- readonly code: CircuitErrorCode;
179
- readonly deviceId: string | undefined;
180
- readonly pinName: string | undefined;
181
- readonly stateName: string | undefined;
182
- constructor(code: CircuitErrorCode, message: string, options?: CircuitErrorOptions);
46
+ declare interface ByteReader extends Iterable<number> {
47
+ readonly length: number;
48
+ readonly byteLength: number;
49
+ readonly [index: number]: number | undefined;
50
+ [Symbol.iterator](): IterableIterator<number>;
51
+ slice(start?: number, end?: number): Uint8Array;
183
52
  }
184
53
 
185
- /** Error codes raised by `CircuitError`. */
186
- export declare type CircuitErrorCode = 'invalid-options' | 'invalid-count' | 'unsupported-operation' | 'resource-not-found' | 'pin-not-found' | 'state-not-found' | 'invalid-state-value' | 'unresolved-device' | 'disposed';
187
-
188
- export declare interface CircuitErrorOptions {
189
- readonly deviceId?: string;
190
- readonly pinName?: string;
191
- readonly stateName?: string;
192
- readonly cause?: unknown;
54
+ export declare interface ChannelMessage<T> {
55
+ readonly time: number;
56
+ readonly value: T;
193
57
  }
194
58
 
195
- /**
196
- * Options for `Circuit.create`.
197
- *
198
- * @example
199
- * const circuit = await Circuit.create(input, { engine: 'reference' });
200
- */
201
- export declare interface CircuitRuntimeOptions {
202
- /** Execution engine. Defaults to `'jit'`; `'reference'` runs the interpreter. */
203
- readonly engine?: CircuitEngine;
204
- /** JIT tuning. The runtime always supplies the module's own validation grant. */
205
- readonly jit?: IRJITTuning;
206
- /**
207
- * Run `validateIR` over the generated module during compilation.
208
- * Defaults to `true`; pass `false` only for measured warm paths.
209
- */
210
- readonly validateIR?: boolean;
211
- /** Electrical-solve options. */
212
- readonly electrical?: CircuitElectricalOptions;
213
- /** Instance id reported to the engine. Defaults to `'unified-circuit'`. */
214
- readonly instanceId?: string;
215
- }
59
+ export declare function createBoard(library: DeviceLibrary, description: BoardDescription, options?: BoardOptions): Board;
216
60
 
217
- /**
218
- * Compiles several devices and their wiring into one unified IR module (U01).
219
- *
220
- * Device models are caller-supplied: every entry of `devices` carries the pins,
221
- * states and behaviors (or `kernel`) its type needs.
222
- *
223
- * ```ts
224
- * const circuit = compileCircuit({
225
- * devices: [
226
- * { id: 'drive1', type: 'push-pull-driver', description: driverDescription() },
227
- * { id: 'sink1', type: 'lamp-sink', description: sinkDescription() },
228
- * ],
229
- * connections: [
230
- * { from: 'drive1.channel0', to: 'sink1.anode' },
231
- * { from: 'sink1.cathode', to: 'GND' },
232
- * ],
233
- * });
234
- *
235
- * const jit = createIRJIT(circuit.module, { validation: circuit.validation });
236
- * jit.execute(circuit.entryPoints.refs.initialize, []);
237
- * jit.execute(circuit.entryPoints.refs.tick, []); // drive1 + nets + sink1
238
- * ```
239
- *
240
- * The pipeline is: validate the input, allocate the global pin and state
241
- * spaces, analyse the electrical topology, generate one function per device
242
- * phase, generate the resistive network solver and main loop, then validate the
243
- * resulting module with `validateIR`.
244
- *
245
- * @throws {UnifiedIRCompilerError} for malformed input, duplicate ids, unknown
246
- * pins, electrical conflicts, or when the generated module fails validation.
247
- */
248
- export declare function compileCircuit(input: CircuitCompilationInput, options?: CircuitCompilationOptions): CompiledCircuit;
61
+ export declare function createDeviceLibrary(entries: readonly DeviceLibraryEntry[]): DeviceLibrary;
249
62
 
250
- /** The compiled circuit: one module for every device, net and the main loop. */
251
- export declare interface CompiledCircuit {
252
- readonly module: IRModule;
253
- readonly entryPoints: CompiledEntryPoints;
254
- /** Completed ticks in the most recent step/batch, including before a fault. */
255
- readonly progress: StateRef<'u32'>;
256
- /** `'mcu1.PA0'` -> global pin id. */
257
- readonly pinMap: ReadonlyMap<string, number>;
258
- readonly deviceMap: ReadonlyMap<string, DeviceMetadata>;
259
- readonly pins: GlobalPinMap;
260
- readonly states: GlobalStateMap;
261
- /** Validation grants covering every instruction and memory of the module. */
262
- readonly validation: IRValidationOptions;
263
- /** Device ids in stable declaration order. */
264
- readonly executionOrder: readonly string[];
265
- /** Every generated function name, in definition order. */
266
- readonly functions: readonly string[];
267
- }
63
+ /** Runs self-contained SDK devices on an atomic, replaceable Board. */
64
+ export declare function createSimulationRuntime(options?: ISimulationRuntimeOptions): ISimulationRuntime;
268
65
 
269
- /** Generated entry points, both by name and as executable refs. */
270
- declare interface CompiledEntryPoints {
271
- readonly tick: string;
272
- readonly initialize: string;
273
- readonly batch: string;
274
- readonly refs: {
275
- readonly tick: FunctionRef<readonly [], readonly []>;
276
- readonly initialize: FunctionRef<readonly [], readonly []>;
277
- readonly batch: FunctionRef<readonly ['u32'], readonly []>;
278
- };
66
+ export declare interface DeviceAdapter<Batch extends DeviceBatch = DeviceBatch> extends Disposable {
67
+ sync(batch: Batch): void;
279
68
  }
280
69
 
281
- /** One pin-to-pin (or pin-to-rail) connection. */
282
- export declare interface Connection {
283
- /** `'mcu1.PA0'` or a rail name such as `'GND'`. */
284
- readonly from: string;
285
- readonly to: string;
70
+ export declare interface DeviceBatch<Outputs extends object = object> {
71
+ readonly from: number;
72
+ readonly to: number;
73
+ readonly outputs: Readonly<Outputs>;
286
74
  }
287
75
 
288
- export declare interface ContactDeclaration extends ResistorDeclaration {
289
- readonly initial: 'open' | 'closed';
76
+ /** 具体字段由生成模块或工厂泛型注解投影;这里不重复声明资源名称。 */
77
+ export declare interface DeviceContext<Props extends object = object, Inputs extends object = object, Memory extends object = object> extends JitHost {
78
+ readonly props: Readonly<Props>;
79
+ readonly inputs: Readonly<Inputs>;
80
+ readonly memory: Readonly<Memory>;
81
+ readonly topics: TopicBridge;
82
+ reportError(error: unknown): void;
290
83
  }
291
84
 
292
- /**
293
- * Adapts one already-loaded unified-IR circuit to the RFC 0018 device host.
294
- *
295
- * This is the same-thread adapter for an owner that keeps `Circuit` accessors for itself (a
296
- * diagnostics bench, for example). Application/canvas integration uses
297
- * `createDeviceSimulationHostFromSandbox` from `@mica-js/simulator/sandbox` and never holds a circuit.
298
- */
299
- export declare function createCircuitDeviceSimulationHost({ circuit, ownsCircuit, schematic, topics, stepPs, deliver, }: CircuitDeviceSimulationHostOptions): DeviceSimulationHost;
85
+ export declare type DeviceFactory<Context extends DeviceContext = DeviceContext, Batch extends DeviceBatch = DeviceBatch> = (context: Context) => DeviceAdapter<Batch>;
300
86
 
301
- /**
302
- * Compiles a schematic sheet into a circuit.
303
- *
304
- * Nets come from `deriveSchematicTopology`, so wires, junctions, labels and
305
- * power symbols keep their usual meaning: a net that names a rail connects
306
- * every member to that rail, and any other net joins its pins pairwise (the
307
- * compiler merges transitively).
308
- *
309
- * ```ts
310
- * const circuit = await createCircuitFromSchematic(schematic, {
311
- * devices: symbolProvider,
312
- * resolveDevice: (reference) => bindings.get(reference.deviceId),
313
- * });
314
- * ```
315
- *
316
- * @throws {CircuitError} with code `unresolved-device` when a component symbol
317
- * has no binding; `SchematicError` for malformed sheets.
318
- */
319
- export declare function createCircuitFromSchematic(schematic: SchematicDocument, options: SchematicCircuitOptions): Promise<Circuit>;
320
-
321
- /**
322
- * Builds the validation grants a module needs to run on the reference engine or
323
- * the JIT: every instruction the model uses, authorized once, plus a grant for
324
- * each declared memory.
325
- *
326
- * `@mica-js/ir` deliberately keeps its core instruction list internal, so the
327
- * names are collected from the generated bodies instead of being restated here.
328
- *
329
- * @param module - Generated module whose bodies and memories are granted.
330
- * @param updateResources - Read-only byte regions that opt into the host-only
331
- * versioned update path (for example MCU firmware patching).
332
- */
333
- export declare function createModuleValidation(module: IRModule, updateResources?: readonly BytesRef[]): IRValidationOptions;
334
-
335
- /**
336
- * Compiles a schematic and reports which circuit device each symbol became.
337
- *
338
- * {@link createCircuitFromSchematic} returns only the circuit; hosts that route
339
- * schematic endpoints to circuit accessors need the mapping as well.
340
- */
341
- export declare function createSchematicCircuit(schematic: SchematicDocument, options: SchematicCircuitOptions): Promise<SchematicCircuitResult>;
342
-
343
- /**
344
- * Same-thread `DeviceSimulationHost` over a schematic compiled by the unified-IR runtime.
345
- *
346
- * The host owns the circuit: `loadSchematic` reads, parses and compiles it, `tick` advances one
347
- * circuit step and publishes the output topics that changed, and `deliver` queues widget payloads
348
- * for the next step. Device models and their endpoints come from `resolveDevice`, so the host stays
349
- * generic. Nothing here touches the DOM, so the sandbox guest and a Node test use the same
350
- * implementation.
351
- */
352
- export declare function createSchematicDeviceSimulationHost(options: SchematicDeviceSimulationHostOptions): DeviceSimulationHost;
353
-
354
- /** Global pin addresses one device may own; enough for the largest packages. */
355
- export declare const DEVICE_PIN_STRIDE = 512;
356
-
357
- /**
358
- * What every device accessor offers, whatever its type.
359
- *
360
- * `readPin` returns the level the *device* drives onto one of its pins (its
361
- * output latch), while `Circuit.getPin('device.pin')` returns the level the pin
362
- * *observes* after the electrical solve. Host changes use device state; there
363
- * is no direct pin override API.
364
- */
365
- export declare interface DeviceAccessor {
366
- /** Circuit-unique device id. */
367
- readonly deviceId: string;
368
- /** Device type, e.g. `'push-pull-driver'`. */
369
- readonly type: string;
370
- /** Declared pin names, in declaration order. */
371
- readonly pinNames: readonly string[];
372
- /** Declared internal state names, in declaration order. */
373
- readonly stateNames: readonly string[];
374
- /** Reads the level the device drives onto `pinName`. */
375
- readPin(pinName: string): boolean;
376
- /** Writes the level the device drives onto `pinName`. */
377
- /** Reads one declared internal state. */
378
- getState(name: string): unknown;
379
- /** Writes one declared internal state. */
380
- setState(name: string, value: unknown): void;
381
- /** Consumes inputs at a host step boundary, when declared by the paired factory. */
382
- applyInputs?(inputs: readonly DeviceInput[]): void;
383
- /** Publishes outputs after the host finishes evaluating the step. */
384
- flushOutputs?(publish: (port: string, payload: unknown) => void): void;
87
+ /** 已校验并捕获模型和登记关系的可复用库;没有运行中资源。 */
88
+ export declare interface DeviceLibrary {
89
+ readonly [libraryTag]: true;
385
90
  }
386
91
 
387
- /**
388
- * Builds the typed accessor of a device after its module is compiled.
389
- *
390
- * A description that supplies `accessor` replaces the generic accessor the
391
- * runtime would otherwise synthesize from `type`. The factory runs once per
392
- * circuit and closes over the layout its IR factory allocated.
393
- */
394
- export declare type DeviceAccessorFactory = (context: DeviceAccessorFactoryContext) => DeviceAccessorSurface;
395
-
396
- /** Host services handed to a device accessor factory at circuit creation. */
397
- export declare interface DeviceAccessorFactoryContext {
398
- readonly deviceId: string;
399
- /** Live engine storage (`IRStorage` in practice). */
400
- readonly storage: unknown;
401
- /** Throws once the owning circuit has been disposed. */
402
- readonly assertActive: () => void;
403
- /** Advances the owning circuit by one tick. */
404
- readonly step: () => void;
405
- /** Advances the owning circuit by `count` ticks. */
406
- readonly runBatch: (count: number) => void;
92
+ /** 异构登记在库边界擦除器件泛型;工厂使用生成类型或精确的 SDK 泛型注解。 */
93
+ export declare interface DeviceLibraryEntry {
94
+ readonly id: string;
95
+ readonly model: DeviceIR;
96
+ readonly create: DeviceFactory<any, any>;
407
97
  }
408
98
 
409
- /** Every accessor of one circuit, keyed by device id. */
410
- export declare type DeviceAccessors = Readonly<Record<string, DeviceAccessor>>;
411
-
412
- /**
413
- * Accessor map derived from a literal compilation input.
414
- *
415
- * `Circuit.create` infers the device ids of a `const` input, so
416
- * `circuit.devices.<id>` is typed without a cast. A device package that wants a
417
- * richer surface builds it through `DeviceDescription.accessor` and casts at
418
- * the call site.
419
- */
420
- export declare type DeviceAccessorsOf<I extends CircuitCompilationInput> = {
421
- readonly [D in I['devices'][number] as D['id']]: DeviceAccessor;
422
- };
423
-
424
- /**
425
- * Structural surface every device accessor exposes.
426
- *
427
- * The compiler keeps this declaration independent from the runtime's
428
- * `DeviceAccessor` so a device kernel can ship its own typed accessor without
429
- * making the compiler depend on the runtime module.
430
- */
431
- declare interface DeviceAccessorSurface {
432
- readonly deviceId: string;
433
- readonly type: string;
434
- readonly pinNames: readonly string[];
435
- readonly stateNames: readonly string[];
436
- readPin(pinName: string): boolean;
437
- getState(name: string): unknown;
438
- setState(name: string, value: unknown): void;
439
- }
99
+ export { Disposable }
440
100
 
441
- /** Build surface handed to one device behavior. */
442
- export declare interface DeviceBehaviorApi {
443
- readonly deviceId: string;
444
- readonly builder: FunctionBuilder<readonly []>;
445
- /**
446
- * Module the phase is generated into. Complex devices use it to declare
447
- * their own typed arrays (`module.array`, `module.bytes`) and providers;
448
- * simple devices never need to touch it.
449
- */
450
- readonly module: IRModule;
451
- /** Instance configuration from {@link DeviceConfig.config}. */
452
- readonly config: Readonly<Record<string, unknown>> | undefined;
453
- /** Every declared pin of the device, in declaration order. */
454
- readonly pins: readonly DevicePinHandle[];
455
- /** Pins initialized with physical drive capability. */
456
- readonly outputs: readonly DevicePinHandle[];
457
- pin(name: string): DevicePinHandle;
458
- resistor(name: string): DeviceResistorHandle;
459
- writeDigitalGroup(names: readonly string[], levels: readonly Value<'bool'>[]): void;
460
- applyResistors(names: readonly string[], ohms: readonly Value<'f64'>[]): void;
461
- applyConnections(names: readonly string[], closed: readonly Value<'bool'>[]): void;
462
- state<T extends ScalarType = ScalarType>(name: string): DeviceStateHandle<T>;
463
- }
101
+ export { Event_2 as Event }
464
102
 
465
- /**
466
- * Per-device behavior hooks. The compiler emits one IR function per hook:
467
- * `initialize` -> `<id>_initialize`, `tick` -> `<id>_tick`,
468
- * `update` -> `<id>_update`. Missing hooks simply produce no function.
469
- */
470
- export declare interface DeviceBehaviors {
471
- readonly initialize?: (api: DeviceBehaviorApi) => void;
472
- readonly tick?: (api: DeviceBehaviorApi) => void;
473
- readonly update?: (api: DeviceBehaviorApi) => void;
103
+ export declare interface InputChannel<T> {
104
+ send(value: T): void;
474
105
  }
475
106
 
476
- export declare interface DeviceBridgeHooks {
477
- readonly applyInputs?: (io: DeviceInputIo) => void;
478
- readonly flushOutputs?: (io: DeviceOutputIo) => void;
107
+ export declare interface InputNotification {
108
+ notify(): void;
479
109
  }
480
110
 
481
- /** One device instance of the circuit. */
482
- export declare interface DeviceConfig {
483
- /** Circuit-unique identity; prefix of every generated function name. */
111
+ export declare interface InstanceDescription {
484
112
  readonly id: string;
485
- /** Device type, e.g. `'push-pull-driver'`; free-form label of the device model. */
486
113
  readonly type: string;
487
- readonly description: DeviceDescription;
488
- /** Persistent instance values resolved against the JSON property declarations. */
489
- readonly properties?: Readonly<Record<string, PropertyValue>>;
490
- /** Instance configuration; reserved for device kernels that take parameters. */
491
- readonly config?: Readonly<Record<string, unknown>>;
492
- }
493
-
494
- /** IR-level device description consumed by the compiler. */
495
- export declare interface DeviceDescription extends DeviceBridgeHooks {
496
- readonly name?: string;
497
- readonly pins: DevicePinMap;
498
- readonly properties?: Readonly<Record<string, unknown>>;
499
- readonly resistors?: Readonly<Record<string, ResistorDeclaration>>;
500
- readonly connections?: Readonly<Record<string, ContactDeclaration>>;
501
- /** Paired synchronous JS factory, invoked once per instance before IR generation. */
502
- readonly factory: (context: ElectricalFactoryContext) => DeviceImplementation | void;
503
- readonly states?: Readonly<Record<string, DeviceStateDescription>>;
504
- readonly behaviors?: DeviceBehaviors;
505
- /**
506
- * Complex-kernel hook. Runs once per module before phase generation so the
507
- * kernel may declare typed arrays, byte memories and providers, then return
508
- * the behaviour hooks the compiler should call inside each phase.
509
- */
510
- readonly kernel?: DeviceKernelFactory;
511
- /**
512
- * Optional typed accessor factory. Kernels with a richer surface than the
513
- * generic state/pin accessor (a register file, a memory map) use it.
514
- */
515
- readonly accessor?: DeviceAccessorFactory;
516
- /**
517
- * Read-only byte regions the kernel wants host updates for. The compiler
518
- * grants `update` access on top of the normal `read` grant so kernels can
519
- * expose firmware patching without allowing guest stores.
520
- */
521
- readonly updateResources?: readonly BytesRef[];
522
- }
523
-
524
- export declare interface DeviceElectricalInitialization {
525
- initializeResistor(id: string, initial: ResistorInitialState): void;
526
- initializePin(id: string, initial: PinElectricalDescription): void;
527
- }
528
-
529
- /** Per-instance construction and boundary hooks returned by the paired factory. */
530
- export declare interface DeviceImplementation extends DeviceBehaviors, DeviceBridgeHooks {
531
- readonly kernel?: DeviceKernelFactory;
532
- }
533
-
534
- export declare interface DeviceInput {
535
- readonly port: string;
536
- readonly payload: unknown;
537
- }
538
-
539
- export declare interface DeviceInputIo {
540
- takeInput(port: string): unknown;
541
- takeInputs(port: string): readonly unknown[];
542
- writeState(name: string, value: unknown): void;
543
- call(entry: EntryRef, args: readonly RuntimeScalar[]): void;
544
- }
545
-
546
- /**
547
- * Everything a complex device kernel needs to declare its own IR before any
548
- * phase function body is opened: the module (for `array`/`bytes`/`provider`),
549
- * typed operations through `bind(builder)` and the allocated pin ids.
550
- */
551
- export declare interface DeviceKernelContext {
552
- readonly deviceId: string;
553
- readonly config: Readonly<Record<string, unknown>> | undefined;
554
- readonly module: IRModule;
555
- bind(builder: FunctionBuilder<readonly []>): DeviceBehaviorApi;
556
- readonly pins: readonly DeviceKernelPin[];
557
- }
558
-
559
- /**
560
- * Builds the phase hooks of a complex device after resource allocation but
561
- * before phase functions are generated. Declaring arrays, byte memories and
562
- * providers is only legal here (never inside a function body).
563
- *
564
- * Returning {@link DeviceKernelRuntime} lets the kernel own its phase
565
- * functions directly; returning {@link DeviceBehaviors} asks the compiler to
566
- * generate `<id>_initialize` / `<id>_tick` / `<id>_update` wrappers.
567
- */
568
- export declare type DeviceKernelFactory = (context: DeviceKernelContext) => DeviceBehaviors | DeviceKernelRuntime;
569
-
570
- /** One pin as seen by a device kernel factory (no builder attached yet). */
571
- declare interface DeviceKernelPin {
572
- readonly name: string;
573
- readonly globalPinId: number;
114
+ readonly props?: Readonly<Record<string, PropertyInput>>;
115
+ readonly randomState?: RandomState;
574
116
  }
575
117
 
576
- /**
577
- * Direct phase refs a complex kernel may return instead of behaviour hooks.
578
- * The compiler then uses these functions as the device's loop entries, with
579
- * no wrapper phase around them.
580
- */
581
- export declare interface DeviceKernelRuntime {
582
- readonly initialize?: FunctionRef<readonly [], readonly []>;
583
- readonly tick?: FunctionRef<readonly [], readonly []>;
584
- readonly update?: FunctionRef<readonly [], readonly []>;
585
- }
586
-
587
- /** Metadata of one compiled device. */
588
- declare interface DeviceMetadata extends DeviceBridgeHooks {
589
- readonly deviceId: string;
590
- readonly entries?: readonly EntryRef[];
591
- readonly type: string;
592
- /** First global pin id of the device. */
593
- readonly pinOffset: number;
594
- /** First slot ordinal of the device in the global state space. */
595
- readonly stateOffset: number;
596
- readonly pins: ReadonlyMap<string, number>;
597
- readonly states: ReadonlyMap<string, DeviceStateSlot>;
598
- /** Every IR function generated for this device. */
599
- readonly functions: readonly string[];
600
- readonly initialize: string | undefined;
601
- readonly tick: string | undefined;
602
- readonly update: string | undefined;
603
- /** Typed accessor factory supplied by the device description, if any. */
604
- readonly accessor: DeviceAccessorFactory | undefined;
118
+ export declare interface InstructionHook {
119
+ readonly when: string;
120
+ readonly call: string;
605
121
  }
606
122
 
607
- export declare interface DeviceOutputIo {
608
- readState(name: string): unknown;
609
- publish(port: string, payload: unknown): void;
123
+ /** A prepared schematic and its separately resolved resource bytes. */
124
+ export declare interface IPreparedSimulation {
125
+ readonly schematic: SchematicDocument;
126
+ readonly devices: readonly IPreparedSimulationDevice[];
127
+ /** Fixed board voltages by exact schematic net name; ignored for empty sheets. Ground stays zero. */
128
+ readonly voltageReferences?: Readonly<Record<string, number>>;
129
+ /** assets[symbolId][src]; required for every effective image/binary resource reference. */
130
+ readonly assets?: Readonly<Record<string, Readonly<Record<string, Uint8Array>>>>;
610
131
  }
611
132
 
612
- /** Pins of one device mapped into the global pin space. */
613
- declare interface DevicePinAllocation {
614
- readonly deviceId: string;
615
- /** First global pin id of the device. */
616
- readonly offset: number;
617
- readonly pins: ReadonlyMap<string, number>;
618
- readonly resolved: ReadonlyMap<string, ResolvedDevicePin>;
133
+ /** A current SDK device: JSON metadata plus self-contained ESM with named model/create exports. */
134
+ export declare interface IPreparedSimulationDevice {
135
+ readonly id: string;
136
+ readonly definition: DeviceMetadata;
137
+ /** Imported only by the runtime guest, never by the editor that prepares this DTO. */
138
+ readonly code: string;
619
139
  }
620
140
 
621
- /**
622
- * Types for the unified IR compiler (U01).
623
- *
624
- * The compiler turns several device descriptions plus a pin-to-pin netlist into
625
- * one `@mica-js/ir` module. Device logic, the electrical solve and the main
626
- * loop all share one global pin space, one state space and one engine entry, so
627
- * a tick costs one interpreter/JIT call for the whole circuit.
628
- *
629
- * The shared constants (`UNIFIED_PIN_CAPACITY`, `DEVICE_PIN_STRIDE`, `PIN_MODE`)
630
- * live in `../pin-space` and are reused here. The compiler ships no device
631
- * models: every description is supplied by the caller.
632
- */
633
- /** One pin declared by the paired electrical device definition. */
634
- export declare interface DevicePinDescription {
635
- readonly kind: 'signal' | 'power' | 'gnd';
636
- readonly side?: 'left' | 'right' | 'top' | 'bottom';
637
- }
141
+ export declare type ISimulationDeviceTopicDefinition = DevicePortMetadata;
638
142
 
639
- /** Pin operations a behavior may use; each call inlines into global memory. */
640
- declare interface DevicePinHandle {
641
- readonly name: string;
642
- readonly globalId: number;
643
- /** Selects the physical output configuration. */
644
- configure(mode: number): void;
645
- setOutputEnabled(enabled: Value<'bool'>): void;
646
- setPull(pull: 'none' | 'up' | 'down'): void;
647
- writeVoltage(voltage: Value<'f64'>): void;
648
- /** Writes digital drive intent through the finite output impedance. */
649
- writeDigital(level: Value<'bool'>): void;
650
- /** Samples the solved voltage with the explicitly declared input thresholds. */
651
- sampleDigital(): Value<'bool'>;
652
- sampleVoltage(): Value<'f64'>;
653
- /** Reads this pin's digital drive intent. */
654
- readDrivenDigital(): Value<'bool'>;
143
+ /** Serializable projection of a board diagnostic or invalid device topic publication. */
144
+ export declare interface ISimulationDiagnostic {
145
+ readonly code: SimulationDiagnosticCode;
146
+ /** Empty only for a board-wide diagnostic with no associated instance. */
147
+ readonly symbol: string;
148
+ readonly port?: string;
149
+ readonly message: string;
150
+ readonly simTime: TimePs;
151
+ readonly runtimeCode?: RuntimeDiagnosticCode;
152
+ readonly phase?: RuntimePhase;
655
153
  }
656
154
 
657
- /**
658
- * Declared pins of one device. A `Map` keeps duplicate names impossible and an
659
- * object keeps authored descriptions terse; both preserve declaration order.
660
- */
661
- declare type DevicePinMap = ReadonlyMap<string, DevicePinDescription> | Readonly<Record<string, DevicePinDescription>>;
662
-
663
- declare interface DeviceResistorHandle {
664
- setResistance(ohms: Value<'f64'>): void;
665
- setEnabled(enabled: Value<'bool'>): void;
666
- /** Solved current in amperes, positive from the first declared pin to the second. */
667
- sampleCurrent(): Value<'f64'>;
155
+ export declare interface ISimulationMessage {
156
+ readonly target: ISimulationMessageTarget;
157
+ readonly payload: unknown;
158
+ /** End of the tick that delivered this publication, in integer picoseconds. */
159
+ readonly simTime: TimePs;
668
160
  }
669
161
 
670
- /** What one {@link DeviceSimulationHost.tick} call executed. */
671
- export declare interface DeviceSimTickReport {
672
- /** Simulation time after the step, in picoseconds. */
673
- readonly simTime: number;
674
- /** Circuit steps executed by this call. */
675
- readonly executed: number;
676
- /** Isolated device boundary-hook failures; absent when the step has none. */
677
- readonly diagnostics?: readonly {
678
- readonly code: 'device/input-failed' | 'device/output-failed';
679
- readonly deviceId: string;
680
- readonly message: string;
681
- }[];
162
+ export declare interface ISimulationMessageTarget {
163
+ readonly symbol: string;
164
+ readonly port: string;
682
165
  }
683
166
 
684
- /**
685
- * Simulation the canvas runtime drives (RFC 0018).
686
- *
687
- * Every method returns a promise, so a same-thread implementation and a cross-thread one are called
688
- * the same way and `WidgetHost` and the simulation can live on different threads. The host owns the
689
- * frame clock: it calls {@link tick} with one fixed step at a time and reads the current simulation
690
- * time back from {@link getSimTime}, so there is exactly one authority for time.
691
- */
692
- export declare interface DeviceSimulationHost {
693
- /**
694
- * Reads and mounts the schematic behind `uri`; `undefined` clears the runtime.
695
- *
696
- * The implementation reads the bytes through its own `fs` and resolves the `image` / `binary`
697
- * properties of every symbol against that schematic URI.
698
- */
699
- loadSchematic(uri: string | undefined): Promise<void>;
700
- /** Resets the loaded runtime to its initial state without unloading the schematic. */
167
+ /** Owns a Board; failed load/reset leaves the previous board and queued inputs intact. */
168
+ export declare interface ISimulationRuntime {
169
+ load(input: IPreparedSimulation): Promise<void>;
170
+ /** Recreates the captured board synchronously without re-importing modules. */
701
171
  reset(): Promise<void>;
702
- /** Advances one fixed step of `dt` picoseconds when the widget host is in simulation mode. */
703
- tick(dt: number): Promise<DeviceSimTickReport>;
704
- /** Queues one payload for a device endpoint; consumed at the next {@link tick}. */
705
- deliver(target: CanvasBindingTarget, payload: unknown, simTime?: number): Promise<void>;
706
- /** Subscribes to device publishes; registering itself is a local operation. */
707
- readonly onDidPublish: Event_2<SimulationPublish>;
708
- /** Endpoints of the running devices, in schematic order. */
709
- getTopics(): Promise<readonly DeviceTopic[]>;
710
- /** Current simulation time, in picoseconds. */
711
- getSimTime(): Promise<number>;
712
- /** Schematic the runtime was built from. */
713
- getSchematic(): Promise<SchematicDocument | undefined>;
714
- /** Releases the runtime. */
172
+ /** Advances by a positive integer number of picoseconds, up to MAX_TIME_PS. */
173
+ tick(dt: TimePs): Promise<ISimulationTickReport>;
174
+ /** Snapshots a declared input; the next tick delivers it before Board.runUntil. */
175
+ deliver(message: ISimulationMessage): Promise<void>;
176
+ readonly onDidPublish: Event_2<ISimulationMessage>;
177
+ readonly onDidDiagnostic: Event_2<ISimulationDiagnostic>;
715
178
  dispose(): Promise<void>;
716
179
  }
717
180
 
718
- /** Running guest: where the typed services live and which ports the worker was handed. */
719
- export declare interface DeviceSimulationHostGuest {
720
- /**
721
- * Endpoint the typed device simulation services are registered on. A worker script that owns
722
- * further capabilities registers them here instead of opening a second sandbox channel.
723
- */
181
+ export declare interface ISimulationRuntimeErrorOptions {
182
+ /** Device the failure belongs to, as the prepared simulation names it. */
183
+ readonly deviceId?: string;
184
+ readonly cause?: unknown;
185
+ }
186
+
187
+ /** Running runtime guest: where the typed service lives and which ports it owns. */
188
+ export declare interface ISimulationRuntimeGuest {
724
189
  readonly rpc: RpcEndpoint;
725
- /** Extra startup ports, in the order the worker received them. */
726
190
  readonly ports: readonly MessagePort[];
727
- /** Releases the circuit and closes the endpoint. */
191
+ readonly runtime: ISimulationRuntime;
728
192
  dispose(): Promise<void>;
729
193
  }
730
194
 
731
- /**
732
- * Device wiring a worker script hands to {@link startDeviceSimulationHostGuest}.
733
- *
734
- * The simulator ships no device models, so every option defaults to "knows no references": a
735
- * package that owns devices bundles its own worker script and supplies these.
736
- */
737
- export declare interface DeviceSimulationHostGuestOptions {
738
- /** Fixed electrical configuration supplied by the owning worker module. */
739
- readonly electrical?: CircuitElectricalOptions;
740
- /** Symbol geometry of the schematics this guest loads, or a factory called per load. */
741
- readonly devices?: DeviceSymbolProvider | (() => DeviceSymbolProvider);
742
- /** Resolves a schematic device reference; when omitted every reference stays unresolved. */
743
- readonly resolveDevice?: (reference: DeviceReference) => SchematicDeviceBinding | undefined;
744
- /**
745
- * Awaited before the first schematic load, so a device library can be read through the host file
746
- * system before anything compiles. Runs at most once.
747
- */
748
- readonly prepare?: () => Promise<void>;
749
- /**
750
- * Extra ports the worker received in the first ordinary message. The RPC port comes first, so these are
751
- * `event.ports` from index 1 onward, in the order the caller transferred them. The first one is
752
- * the direct topic channel (RFC 0018): the widget guest holds the other end and talks to this
753
- * guest without the host relaying.
754
- */
195
+ /** Startup options of the in-process runtime guest; none of them travel over RPC. */
196
+ export declare interface ISimulationRuntimeGuestOptions {
197
+ readonly importer?: SimulationModuleImporter;
198
+ /** Extra ports the worker received; the first one is the direct topic channel. */
755
199
  readonly ports?: readonly MessagePort[];
756
200
  }
757
201
 
758
- /** One scalar internal state of a device, allocated in the global state space. */
759
- export declare interface DeviceStateDescription {
760
- readonly type: ScalarType;
761
- readonly initial: boolean | number;
762
- }
763
-
764
- /** Internal state slot a behavior may read and write. */
765
- declare interface DeviceStateHandle<T extends ScalarType = ScalarType> {
766
- readonly name: string;
767
- readonly type: T;
768
- /** Index inside the generated `device_state_<type>` array. */
769
- readonly index: number;
770
- load(): Value<T>;
771
- store(value: Value<T>): void;
202
+ export declare interface ISimulationRuntimeOptions {
203
+ /** Defaults to a blob-URL dynamic import in the runtime worker. */
204
+ readonly importer?: SimulationModuleImporter;
772
205
  }
773
206
 
774
- /** One device state slot inside the global state space. */
775
- declare interface DeviceStateSlot {
776
- readonly name: string;
777
- readonly deviceId: string;
778
- readonly type: ScalarType;
779
- /** Generated array that holds the slot. */
780
- readonly array: ArrayRef;
781
- /** Index inside {@link array}. */
782
- readonly index: number;
783
- /** Ordinal in the whole state space, across scalar types. */
784
- readonly slot: number;
207
+ /** Methods the runtime guest exposes over the primary sandbox RPC channel. */
208
+ export declare interface ISimulationRuntimeRpc {
209
+ load(input: IPreparedSimulation): Promise<void>;
210
+ reset(): Promise<void>;
211
+ tick(dt: TimePs): Promise<ISimulationTickReport>;
212
+ deliver(message: ISimulationMessage): Promise<void>;
213
+ onDidPublish(listener: (message: ISimulationMessage) => void): () => void;
214
+ onDidDiagnostic(listener: (diagnostic: ISimulationDiagnostic) => void): () => void;
215
+ dispose(): Promise<void>;
785
216
  }
786
217
 
787
- /** One endpoint of a mounted device instance, as the simulation reports it. */
788
- export declare interface DeviceTopic {
789
- readonly symbol: string;
790
- /** Reference designator shown to users; informational for the canvas. */
791
- readonly designator?: string;
792
- readonly port: string;
793
- readonly direction: 'input' | 'output';
794
- readonly type: PayloadType;
795
- readonly title?: string;
218
+ /** The data plane the direct topic port exposes: deliveries in, publishes out. */
219
+ export declare interface ISimulationRuntimeTopicRpc {
220
+ deliver(message: ISimulationMessage): Promise<void>;
221
+ onDidPublish(listener: (message: ISimulationMessage) => void): () => void;
796
222
  }
797
223
 
798
- export { Disposable }
799
-
800
- /**
801
- * Types of the unified circuit runtime (U02).
802
- *
803
- * `Circuit` is the host-facing facade over one compiled unified IR module: it
804
- * owns the engine instance, exposes typed per-device accessors and keeps the
805
- * tick counter. Everything here is transport-neutral; no type mentions the
806
- * device host or the schematic editor.
807
- */
808
- export declare type ElectricalCurrentTarget = {
809
- readonly kind: 'resistor' | 'contact';
810
- readonly device: string;
811
- readonly name: string;
812
- } | {
813
- readonly kind: 'drive' | 'pull-up' | 'pull-down';
814
- readonly device: string;
815
- readonly pin: string;
816
- } | {
817
- readonly kind: 'source';
818
- readonly name: string;
819
- };
820
-
821
- export declare class ElectricalDefinitionError extends Error {
822
- readonly code: ElectricalDefinitionErrorCode;
823
- readonly name = "ElectricalDefinitionError";
824
- constructor(code: ElectricalDefinitionErrorCode, message: string);
224
+ export declare interface ISimulationTickReport {
225
+ readonly simTime: TimePs;
226
+ /** One successful Board.runUntil call, or zero when no board is loaded. */
227
+ readonly executed: number;
825
228
  }
826
229
 
827
- export declare type ElectricalDefinitionErrorCode = 'electrical/invalid-definition' | 'electrical/invalid-parameter' | 'electrical/unknown-resource' | 'electrical/duplicate-initialization' | 'electrical/missing-initialization' | 'electrical/factory-closed';
828
-
829
- /** Active diagnostics of the last published electrical snapshot, plus any latched solve fault. */
830
- export declare type ElectricalDiagnostic = {
831
- readonly code: 'electrical/overcurrent';
832
- readonly severity: 'warning';
833
- readonly target: ElectricalCurrentTarget;
834
- readonly current: number;
835
- readonly maxAbsCurrent: number;
836
- } | {
837
- readonly code: 'electrical/invalid-parameter' | 'electrical/source-conflict' | 'electrical/numerical-failure';
838
- readonly severity: 'error';
839
- /** Identifiable failed operation or resource; absent for a matrix-level failure. */
840
- readonly target?: ElectricalCurrentTarget;
841
- /** Resources associated with the affected network, not a list of proven culprits. */
842
- readonly resources: readonly ElectricalCurrentTarget[];
843
- readonly pins: readonly string[];
844
- };
845
-
846
- export declare interface ElectricalFactoryContext {
847
- readonly properties: Readonly<Record<string, PropertyValue>>;
848
- readonly electrical: DeviceElectricalInitialization;
230
+ export declare interface JitHost {
231
+ attachJit(options: JitOptions): Disposable;
232
+ loadBytes(memory: string, bytes: Uint8Array, offset?: number): void;
849
233
  }
850
234
 
851
- export declare interface ElectricalPinDeclaration {
852
- readonly kind: 'signal' | 'power' | 'gnd';
853
- readonly side?: 'left' | 'right' | 'top' | 'bottom';
235
+ export declare interface JitOptions {
236
+ readonly entry: string;
237
+ readonly code: string;
238
+ readonly pc: string;
239
+ readonly beforeInstruction?: InstructionHook;
240
+ readonly polling?: readonly {
241
+ readonly pc: number;
242
+ readonly predicate: string;
243
+ }[];
244
+ readonly translate: JitTranslate;
854
245
  }
855
246
 
856
- declare type ElectricalReading = {
857
- readonly state: 'determinate';
858
- readonly value: number;
859
- } | {
860
- readonly state: 'floating';
861
- } | {
862
- readonly state: 'indeterminate';
863
- };
247
+ export declare type JitTranslate = (input: JitTranslateInput, builder: JitBlockBuilder) => BlockIR;
864
248
 
865
- export declare interface ElectricalReference {
866
- readonly source: string;
249
+ export declare interface JitTranslateInput {
250
+ readonly pc: number;
251
+ /** 仅在本次同步 translate 回调内有效。 */
252
+ readonly code: BorrowedBytes;
867
253
  }
868
254
 
869
- export { Event_2 as Event }
255
+ declare const libraryTag: unique symbol;
870
256
 
871
- /** Result of the global pin allocation. */
872
- declare interface GlobalPinMap {
873
- /** `'mcu1.PA0'` -> global pin id. */
874
- readonly pins: ReadonlyMap<string, number>;
875
- readonly devices: ReadonlyMap<string, DevicePinAllocation>;
876
- readonly totalPins: number;
877
- readonly capacity: number;
257
+ export declare interface NetDescription {
258
+ readonly id: string;
259
+ readonly pins: readonly PinEndpoint[];
260
+ /** 有限对地电压,0 表示地;省略时不建立理想参考。 */
261
+ readonly voltage?: number;
878
262
  }
879
263
 
880
- /** Result of the global state allocation. */
881
- declare interface GlobalStateMap {
882
- readonly devices: ReadonlyMap<string, ReadonlyMap<string, DeviceStateSlot>>;
883
- /** One generated array per scalar type actually used. */
884
- readonly arrays: ReadonlyMap<ScalarType, ArrayRef>;
885
- /** Slot count per scalar type. */
886
- readonly totals: ReadonlyMap<ScalarType, number>;
887
- readonly totalStates: number;
264
+ declare interface Notification_2 {
265
+ readonly time: number;
888
266
  }
267
+ export { Notification_2 as Notification }
889
268
 
890
- /** Physical output configuration values. */
891
- export declare const PIN_MODE: Readonly<{
892
- readonly highZ: 0;
893
- readonly pushPull: 1;
894
- readonly openDrain: 2;
895
- readonly analog: 3;
896
- }>;
897
-
898
- export declare interface PinElectricalDescription {
899
- readonly drive?: {
900
- readonly reference: ElectricalReference;
901
- readonly highResistance: number;
902
- readonly lowResistance: number;
903
- readonly analogResistance?: number;
904
- readonly maxAbsCurrent?: number;
905
- };
906
- readonly bias?: {
907
- readonly reference: ElectricalReference;
908
- readonly upResistance: number;
909
- readonly downResistance: number;
910
- };
911
- readonly input?: {
912
- readonly reference: ElectricalReference;
913
- readonly low: number;
914
- readonly high: number;
915
- };
269
+ export declare interface PinEndpoint {
270
+ readonly instance: string;
271
+ readonly pin: string;
916
272
  }
917
273
 
918
- /** One physical output configuration value. */
919
- export declare type PinMode = (typeof PIN_MODE)[keyof typeof PIN_MODE];
274
+ export declare type PropertyInput = number | boolean | string | null | Uint8Array;
920
275
 
921
- export declare interface ResistorDeclaration {
922
- readonly pins: readonly [string, string];
923
- }
276
+ /** 四个 uint32,不能全零;精确数值合法性在创建前校验。 */
277
+ export declare type RandomState = readonly [number, number, number, number];
924
278
 
925
- export declare interface ResistorInitialState {
926
- readonly resistance: number;
927
- readonly enabled: boolean;
928
- readonly maxAbsCurrent?: number;
279
+ /** 可跨推进和销毁留存的自有只读快照;slice 返回调用方拥有的可变副本。 */
280
+ export declare interface ReadonlyBytes extends ByteReader {
281
+ readonly [snapshotTag]: true;
929
282
  }
930
283
 
931
- /** One resolved pin in the global pin space. */
932
- declare interface ResolvedDevicePin {
933
- readonly name: string;
934
- readonly deviceId: string;
935
- readonly globalPinId: number;
284
+ /** cause 保留原异常引用;只读约束不要求冻结宿主异常对象。 */
285
+ export declare interface RuntimeDiagnostic {
286
+ readonly code: RuntimeDiagnosticCode;
287
+ readonly message: string;
288
+ readonly phase: RuntimePhase;
289
+ readonly time: number | null;
290
+ readonly instanceId?: string;
291
+ readonly resource?: string;
292
+ readonly path?: InputPath;
293
+ readonly source?: SourceInfo;
294
+ readonly cause?: unknown;
295
+ readonly related: readonly RuntimeDiagnostic[];
936
296
  }
937
297
 
938
- /** One component symbol of a compiled schematic. */
939
- export declare interface SchematicCircuitBinding {
940
- /** Symbol id as written in the schematic. */
941
- readonly symbolId: string;
942
- /** Compiler-safe device id assigned to the symbol. */
943
- readonly deviceId: string;
944
- /** Parsed `"<packageId>:<deviceId>"` reference. */
945
- readonly reference: DeviceReference;
946
- /** Device type from the resolved runtime binding. */
947
- readonly type: string;
948
- }
298
+ export declare type RuntimeDiagnosticCode = 'INVALID_CONFIGURATION' | 'MODEL_VALIDATION_FAILED' | 'RESOURCE_ALLOCATION_FAILED' | 'INVALID_ELECTRICAL_PARAMETER' | 'CONFLICTING_REFERENCE' | 'ELECTRICAL_SOLVE_FAILED' | 'CHANNEL_CONSUMER_CONFLICT' | 'INVALID_CALL_STATE' | 'OBJECT_DISPOSED' | 'BOARD_FAULTED' | 'INVALID_BINDING' | 'MODEL_EXECUTION_FAILED' | 'JIT_FAILED' | 'DEVICE_CALLBACK_FAILED' | 'ASYNC_HOOK_RESULT' | 'CHANNEL_OVERFLOW' | 'REPORTED_ERROR' | 'CLEANUP_FAILED' | 'STALE_REPORT' | 'HOST_LISTENER_FAILED';
949
299
 
950
- /** Options for {@link createCircuitFromSchematic}. */
951
- export declare interface SchematicCircuitOptions extends CircuitRuntimeOptions {
952
- /**
953
- * Symbol geometry provider — pass the same provider that authored the
954
- * schematic. Without it the derived topology contains no pins.
955
- */
956
- readonly devices?: DeviceSymbolProvider;
957
- /** Resolves a schematic device reference to its runtime description. */
958
- readonly resolveDevice: (reference: DeviceReference) => SchematicDeviceBinding | undefined;
959
- /** Coordinate tolerance used when matching pins to wires. */
960
- readonly tolerance?: number;
961
- }
300
+ export declare type RuntimePhase = 'library' | 'assembly' | 'initialize' | 'execute' | 'translate' | 'sync' | 'topic' | 'dispose' | 'host' | 'report';
962
301
 
963
- /** A compiled schematic circuit plus the symbol-to-device mapping it produced. */
964
- declare interface SchematicCircuitResult {
965
- readonly circuit: Circuit;
966
- /** Component symbols in schematic order; non-component symbols are absent. */
967
- readonly bindings: readonly SchematicCircuitBinding[];
968
- }
302
+ export declare type SimulationDiagnosticCode = 'device/input-failed' | 'device/output-failed' | 'board/error' | 'board/diagnostic';
969
303
 
970
- /** Runtime behaviour of one schematic device package. */
971
- export declare interface SchematicDeviceBinding {
972
- /** Device type, e.g. `'counter-ir'`. */
973
- readonly type: string;
974
- /** IR description: pins, states and behaviours. */
975
- readonly description: DeviceDescription;
976
- /** Instance configuration reserved for device kernels. */
977
- readonly config?: Readonly<Record<string, unknown>>;
978
- /** Endpoints the simulation host exposes; absent means the device has none. */
979
- readonly topics?: readonly SchematicDeviceTopic[];
980
- /** Bridges one input topic payload onto the compiled device accessor. */
981
- deliver?(accessor: DeviceAccessor, port: string, payload: unknown): void;
982
- /** Reads one output topic from the compiled device accessor. */
983
- read?(accessor: DeviceAccessor, port: string): unknown;
304
+ export declare class SimulationError extends Error {
305
+ readonly code: RuntimeDiagnosticCode;
306
+ readonly diagnostic: RuntimeDiagnostic;
307
+ readonly related: readonly RuntimeDiagnostic[];
308
+ constructor(diagnostic: RuntimeDiagnostic);
984
309
  }
985
310
 
986
- /** Reads the bytes of one schematic URI; the caller resolves relative references. */
987
- export declare interface SchematicDeviceSimulationHostOptions {
988
- /** Local startup configuration, not an RPC method or payload. */
989
- readonly electrical?: CircuitElectricalOptions;
990
- readonly read: (uri: string) => Promise<Uint8Array>;
991
- /**
992
- * Symbol geometry of the schematics this host loads. Pass the same provider the schematic was
993
- * authored with; without it the derived topology contains no pins. A factory is called when a
994
- * schematic loads, so a caller can read its device library first.
995
- */
996
- readonly devices?: DeviceSymbolProvider | (() => DeviceSymbolProvider);
997
- /**
998
- * Resolves one schematic device reference to its runtime description and endpoints.
999
- *
1000
- * The host ships no device models: the package that owns the devices decides which references
1001
- * exist, what they look like and which topics they expose.
1002
- */
1003
- readonly resolveDevice: (reference: DeviceReference) => SchematicDeviceBinding | undefined;
1004
- }
311
+ export declare type SimulationModuleImporter = (code: string, deviceId: string) => Promise<unknown>;
1005
312
 
1006
313
  /**
1007
- * One endpoint a caller-supplied device declares to the simulation host.
314
+ * Error raised while preparing or driving a prepared simulation.
1008
315
  *
1009
- * The simulator never guesses ports from a device type: the package that
1010
- * resolves the reference states which payloads the device accepts and which it
1011
- * publishes, in the same place it supplies the IR description.
316
+ * The code is stable and machine-checkable; the message names the offending device, symbol or
317
+ * asset so a caller can report it without parsing the cause chain.
1012
318
  */
1013
- export declare interface SchematicDeviceTopic {
1014
- readonly port: string;
1015
- readonly direction: 'input' | 'output';
1016
- readonly type: PayloadType;
1017
- readonly title?: string;
319
+ export declare class SimulationRuntimeError extends Error {
320
+ readonly name = "SimulationRuntimeError";
321
+ readonly code: SimulationRuntimeErrorCode;
322
+ readonly deviceId: string | undefined;
323
+ constructor(code: SimulationRuntimeErrorCode, message: string, options?: ISimulationRuntimeErrorOptions);
1018
324
  }
1019
325
 
1020
- /** One payload a simulation published for an endpoint the canvas can bind to. */
1021
- export declare interface SimulationPublish {
1022
- readonly target: CanvasBindingTarget;
1023
- readonly payload: unknown;
1024
- readonly simTime: number;
1025
- }
326
+ /** Stable failure codes of the prepared-simulation runtime. */
327
+ export declare type SimulationRuntimeErrorCode = 'invalid-input' | 'invalid-device' | 'unresolved-device' | 'unresolved-asset' | 'not-loaded' | 'disposed';
1026
328
 
1027
329
  /**
1028
- * Registers RFC 0018's device simulation services on a sandbox RPC port.
330
+ * Wire name of the prepared simulation runtime.
1029
331
  *
1030
- * A worker script obtains the port from `event.ports[0]` and calls this function; nothing else is
1031
- * needed, because the guest is a plain module the `@mica-js/sandbox/vite` plugin bundles into a
1032
- * self-contained script. The guest registers `deviceSimulationHostGuestService` and reads schematics
1033
- * through `deviceSimulationHostFileSystemService`, so schematic bytes never enter the guest's own
1034
- * message handling and every payload is a typed RPC DTO.
332
+ * The same id is registered on the primary sandbox RPC channel and on the direct topic port, so a
333
+ * widget guest reaches the running simulation without a second protocol.
1035
334
  */
1036
- export declare function startDeviceSimulationHostGuest(port: MessagePort, options?: DeviceSimulationHostGuestOptions): DeviceSimulationHostGuest;
335
+ export declare const simulationRuntimeService: RpcServiceId<ISimulationRuntimeRpc>;
1037
336
 
1038
- /** Global pin addresses available to one circuit (8 devices x 512 pins). */
1039
- export declare const UNIFIED_PIN_CAPACITY = 4096;
337
+ /** Topic-port view of the same wire service registered by the runtime guest. */
338
+ export declare const simulationRuntimeTopicService: RpcServiceId<ISimulationRuntimeTopicRpc>;
1040
339
 
1041
- /** Error raised while compiling a circuit. */
1042
- export declare class UnifiedIRCompilerError extends Error {
1043
- readonly name = "UnifiedIRCompilerError";
1044
- readonly code: UnifiedIRCompilerErrorCode;
1045
- readonly deviceId: string | undefined;
1046
- readonly pinName: string | undefined;
1047
- constructor(code: UnifiedIRCompilerErrorCode, message: string, options?: UnifiedIRCompilerErrorOptions);
1048
- }
340
+ declare const snapshotTag: unique symbol;
341
+
342
+ /**
343
+ * Starts the prepared simulation runtime on one sandbox RPC port.
344
+ *
345
+ * A worker script calls this after taking `event.ports[0]`; extra ports stay in order. The returned
346
+ * node owns the runtime and disposes it with the registrations.
347
+ */
348
+ export declare function startSimulationRuntimeGuest(port: MessagePort, options?: ISimulationRuntimeGuestOptions): ISimulationRuntimeGuest;
1049
349
 
1050
- /** Error codes raised by {@link UnifiedIRCompilerError}. */
1051
- export declare type UnifiedIRCompilerErrorCode = 'invalid-input' | 'duplicate-device' | 'state-not-found' | 'capacity-exceeded' | 'invalid-ir';
350
+ export declare interface TopicBridge {
351
+ readonly onDidReceive: Event_2<TopicMessage>;
352
+ publish(topic: string, payload: unknown): void;
353
+ }
1052
354
 
1053
- export declare interface UnifiedIRCompilerErrorOptions {
1054
- readonly deviceId?: string;
1055
- readonly pinName?: string;
1056
- readonly cause?: unknown;
355
+ export declare interface TopicMessage {
356
+ readonly topic: string;
357
+ readonly payload: unknown;
1057
358
  }
1058
359
 
1059
360
  export { }