CoreRuntimeBridge class

Bridge to the core runtime via FFI.

Usage:

final bridge = CoreRuntimeBridge.create({
'app_id': 'com.example',
'subject_id': 'sub_abc123',
'mode': 'personal',
});
final session = bridge?.startSession();
bridge?.pushHr(DateTime.now().millisecondsSinceEpoch, 72.0);
bridge?.stopSession();
bridge?.dispose();

Properties

attachReadinessScoreJsonAvailable → bool
Whether the runtime can queue a Readiness Score onto the next HSI.
no setter
attachRecoveryScoreJsonAvailable → bool
Whether the runtime can queue a Recovery Score onto the next HSI.
no setter
deviceAuthTemporarilyDisabledForSubjectCompat → bool
final
hashCode → int
The hash code for this object.
no setterinherited
isAvailable → bool
Whether the native library was loaded and the handle is valid.
no setter
isHsiBuffered → bool
Whether HSI is currently delivered by polling rather than by callback.
no setter
isLabAvailable → bool
Whether the lab C ABI symbols are available.
no setter
isLabMetadataAvailable → bool
Whether the runtime exports the lab metadata symbols (older builds may not).
no setter
isLabReenqueueAvailable → bool
Whether the runtime exports the lab re-enqueue symbol (synheart_core_reenqueue_lab_session, engine v0.8.1+). Older runtime binaries return false; callers can fall back to running a fresh session.
no setter
isNetworkReachable → bool
no setter
isRunning → bool
Whether a session is running.
no setter
isRuntimeAvailable → bool
no setter
isSyniServiceAvailable → bool
Whether the linked runtime exports the complete Syni service ABI. Runtime 0.21.0 introduced this surface; older runtimes remain usable for every other Core feature and report Syni service as unsupported.
no setter
lastError → SynheartNativeError?
The structured error from the most recent runtime call made through this bridge, or null when that call succeeded. It describes the latest call, not the latest failure: a call that succeeds clears it, so a value here never belongs to an earlier, unrelated call. This mirrors the runtime, which clears its own per-thread slot on entry to every instrumented call. SynheartNativeError.op still names the call.
no setter
lastErrorCode → int
no setter
lastIngestSuccessAtMs → int?
Wall-clock timestamp (Unix ms) of the most recent successful ingest upload. Returns null when nothing has uploaded yet in this process. Hosts use this to render a "Synced / Syncing / Pending" pill instead of exposing raw queue counts.
no setter
mobileHostAbiSupport → Map<String, bool>
Which of the mobile-host ABI calls the loaded runtime actually exports.
no setter
runtimeType → Type
A representation of the runtime type of the object.
no setterinherited
sdkDeviceAuthAvailable → bool
True when this native build exports the full synheart_core_sdk_* device-auth ABI.
no setter
sdkDeviceLogoutAvailable → bool
Whether this runtime supports the v0.24 destructive identity logout verb.
no setter
sdkDeviceReattestAvailable → bool
Whether this runtime supports the v0.24 identity-preserving refresh verb.
no setter
supportsBufferedHsi → bool
Whether the loaded runtime exports the buffered HSI delivery symbols.
no setter
supportsRichBehaviorEvents → bool
Whether the loaded runtime can take rich behavior events at all.
no setter
syncPairingStatusAvailable → bool
Whether the loaded runtime exports synheart_core_sync_pairing_status.
no setter
uploadQueueLength → int
no setter

Methods

allowsChannel(String channel) → bool?
The runtime's decision for one consent channel (biosignals.vitals, phone_context.device_motion, ...): what an ingest push on it gets right now. Null when the loaded runtime predates the call.
attachClosedDayStrainJson() → String?
Score the local day the engine closed last and queue it onto the next frame: {local_date, start_ms, end_ms, strain}. Call once a day after local midnight, once that day's vendor dailies (steps, active minutes) are pushed. Null before any day has closed, when the closed day has nothing to score, or when the call is absent.
attachReadinessScoreJson(String inputJson) → String?
Compute a daily Readiness Score from inputJson and queue it to ride the next emitted HSI as the readiness reading. Returns the ReadinessScoreResult JSON, or null when the runtime lacks the symbol (check attachReadinessScoreJsonAvailable) or the input does not parse.
attachRecoveryScoreJson(String inputJson) → String?
Compute a daily Recovery Score from inputJson and queue it to ride the next emitted HSI as the recovery reading, which is how it reaches the cloud. Returns the RecoveryScoreResult JSON, the same value recoveryScoreComputeJson returns.
attachRecoveryScoreToday(int score) → int
Attach today's daily Recovery Score (0.=100). Sticky across windows until cleared or replaced. Returns 0 on success.
attachSleepScore(SleepScoreResult result) → int
Typed form of attachSleepScoreJson — serializes the result internally. Returns 0 on success.
attachSleepScoreJson(String resultJson) → int
Queue a batch SleepScoreResult JSON to ride the next HSI and feed the Path-B rolling median. Returns 0 on success.
attachStrainScoreJson() → String?
Score today's accumulated Strain and queue it onto the next HSI frame.
baselineBeginRestBlock(int tsMs) → int?
Start a new rest block at tsMs (a protocol's rest phase). Returns 0, 1002, -1, or null when absent.
baselineExportOffline({required String passphrase}) → Future<Uint8List?>
Encrypt every cached baseline envelope into a passphrase-keyed offline blob (.srm.synheart). Returns the raw bytes ready for the OS share sheet, or null when the runtime binary doesn't ship the FFI / no envelopes are cached / the passphrase is empty.
baselineHydrateLocal() → Future<Map<String, dynamic>?>
Read the latest locally-persisted baseline envelope per kind (synchronous on-device SQLite read + decryption — no network). Returns {snapshots: [...]} so the Dart-side facade can parse envelopes uniformly. Null when the runtime binary doesn't ship the symbol.
baselineImportOffline({required String passphrase, required Uint8List blob}) → Future<Map<String, dynamic>?>
Decrypt + import a .srm.synheart blob into local storage. Returns {imported, skipped, errors, kinds, exporter_device_id, created_at_ms}. Null when the runtime binary doesn't ship the FFI; an {"error": ...} map for wrong passphrase / tampered blob.
baselineProfileJson() → String?
What the personal baselines know, as JSON. Device-only.
baselineRequirementsJson(int nowMs) → String?
Whether this host feeds the personal baselines what they need, judged at nowMs, as JSON. Act on every requirement whose status is unmet.
baselineRhythmJson() → String?
The person's rhythm of active use as JSON, or the literal null before any active minute. Device-only.
baselinesJson() → String?
baselineWindowDigestJson(int year, int month, int day) → String?
Which windows taught the personal baselines on year-month-day, as a JSON array of {device, windows, digest}. Null without a pipeline, for a date that does not exist, or when the call is absent.
breathingEvaluateJson() → Map<String, dynamic>?
breathingReset() → void
breathingSetPopulation(int profile) → void
breathingSetTargetBpm(double bpm) → void
breathingSetWindowSecs(int secs) → void
buildProofHeader(String method, String absoluteUrl) → String?
§4 — compact JWS value for X-Synheart-Proof (non-ingest APIs). Use uppercase method.
cancelAccountDeletion() → bool
clearHsiCallback() → void
Unregister HSI delivery.
clearRecoveryScoreToday() → int
Drop today's Recovery Score so personalization Stage 2 reverts to the per-component composite. Returns 0 on success.
clearStreamCallback() → void
Unregister the stream callback.
closeOrphanSession(String sessionId) → bool
Mark a stranded state='active' session as closed. Returns true on success (or when the session was already closed). Used by startup orphan-session sweeps.
computeSleepScore(SleepScoreInput input) → SleepScoreResult?
Typed form of sleepScoreComputeJson. Returns null if the engine rejected the input or the JSON couldn't be parsed.
computeSleepScoreTraced(SleepScoreInput input, String correlationId) → SleepScoreResult?
Typed form of sleepScoreComputeJsonTraced.
configId() → String?
The comparability key for anything you cache.
consentClearStored() → bool
consentConfigureCloud(String baseUrl, String appId) → bool
consentEffectiveState() → Map<String, dynamic>?
consentGetEditableForm() → Map<String, dynamic>?
consentNeedsTokenRefresh() → bool
consentStatus() → Map<String, dynamic>?
consentSubmitForm({required String deviceId, required String platform, String? userId, required Map<String, dynamic> formJson}) → Future<Map<String, dynamic>?>
currentConsent() → Map<String, dynamic>?
currentFocusKind() → int
Currently active focus kind discriminant.
currentSession() → Map<String, dynamic>?
Get the current session as a map, or null.
currentTaskType() → int
Currently active task type discriminant.
currentWorkoutKind() → int
Currently active workout kind discriminant.
dailyBaselineRefsJson() → String?
The Recovery Score's baselines object as JSON (hrv_rmssd_ms, hrv_confidence, resting_hr_bpm, rhr_confidence), or null until overnight RMSSD and resting HR both have a reference, or when the runtime predates C ABI 4.2.
dailySleepBaselinesJson() → String?
The Sleep Score's baselines object as JSON (midpoint_h, overnight_hr_bpm, deep_min, rem_min, each {value, confidence} or null), or null without a pipeline or before C ABI 4.2.
declareRestWindow(int tsMs) → void
Declare that the window containing tsMs is a rest window.
deleteSession(String sessionId) → bool
deleteVendorEventsForProvider(String provider) → int
Delete all vendor events for a provider. Returns deleted count, or -1 on error.
diagnostics() → String?
dispose() → void
Release the native handle. Must be called when done.
drainHsi() → void
Deliver every frame pending in the runtime's ring to the registered sink, oldest first. No-op outside buffered mode.
droppedHsiFrames() → int
Frames the runtime evicted from the ring (or lost to channel lag) since buffered mode was last initialised. Always 0 while something drains at least every hsiBufferCapacity frames; anything else is a gap in the host's drain loop, not back-pressure to tune.
enqueueHsi(String hsiJson, int timestampMs) → void
enrolResearchStudy({required String accessCode, required String studyCode, bool validateOnly = false}) → Future<Map<String, dynamic>?>
Redeem a research-study access + study code, or (when validateOnly) preview the pair without redeeming. Returns the runtime's JSON response.
ensurePipeline() → void
Create the engine pipeline without starting a background tick task. Used by the ingest buffer which handles ticking via ingestBatch.
exportBaselineSnapshot() → String?
Every personal baseline (per-window references, daily values, consent lineage, the sleep-score ring) as one opaque base64 snapshot. Store it as private health data and never parse it. The runtime also seals it to its own data directory, so a host that keeps that directory needs neither this nor loadBaselineSnapshot. Null before any pipeline has run, or when the runtime does not export the call.
exportSessionState() → String?
fetchCloudHsiWindows({required int fromMs, required int toMs}) → Future<List<Map<String, dynamic>>>
Fetch archived HSI windows from the cloud archive for [fromMs, toMs] (epoch ms). Each map is a full HSI window payload exactly as archived (any HSI version) — the host parses it with the same path it uses for local windows. Returns empty on error, when no cloud connector is configured, or when the native symbol is absent (older vendored lib).
flushPending(int nowMs) → String?
Emit every window still held by the lateness budget, as a JSON array in the same shape tickAll returns.
flushUploads() → Future<Map<String, dynamic>?>
Flush the outbound ingest queue to the cloud.
frameCount() → int
Number of HSI frames produced in the current session.
getAmbientCapture() → bool
Read the runtime's ambient-capture gate. true when the gate is on. Useful for diagnostics — Mirror's own AmbientCaptureService is the source of truth for the app-side flag.
getDataDeletion(String requestId) → Future<Map<String, dynamic>?>
Poll the status of a deletion request. status transitions through pending → in_progress → completed (or failed). On success the result field carries per-layer purge stats from the server.
getHsiWindows(String sessionId, {int startMs = 0, int endMs = 0, int limit = 0}) → List?
getLatestVendorEvent(String provider, String type) → Map<String, dynamic>?
Get the latest vendor event for a provider + type. Returns JSON map or null.
getSessionSummary(String sessionId) → String?
getStorageUsage() → Map<String, dynamic>?
grantConsent(String type) → Future<bool>
hasConsent(String type) → bool
hsiHistoryClear() → bool
Wipe on-device HSI history. Intended for user-initiated "delete my data" flows. Returns true on success.
hsiHistoryCount() → int
Number of archived HSI payloads on-device. Returns 0 on error.
hsiHistoryList({DateTime? since, int? limit}) → List<Map<String, dynamic>>
List archived HSI payloads in upload order (oldest first).
hsmSchemaConsent() → Map<String, dynamic>?
What the app's HSM Schema needs from the person; null on a runtime that does not export it.
ingestBatch(String batchJson, int nowMs) → String?
Batch ingest. Returns HSI JSON if a window completed.
ingestStatus() → Map<String, dynamic>?
Cloud ingest health: queue depth, consent readiness, evicted and refused totals, last successful upload, and the background loop's stall reason. Null when the vendored runtime predates the symbol.
ingestVendorEvent(String eventJson) → bool
Ingest a canonical vendor event (JSON map from CanonicalWearableEvent.toMap()).
labCloseWindow(String windowId, int endedAtMs) → bool
Close a window in the active lab session.
labCurrentMetadataId() → String?
Cached meta_id to stamp on lab sessions, or null if nothing is cached.
labEnsureMetadata({required String deviceId, required String platform, required String osVersion, String? userInfoJson, String? deviceExtraJson}) → String?
Build the metadata payload from current config + caller-supplied device and user info, then upload it if the canonical hash differs from the cached copy or the dirty flag is set. Returns the active meta_id, or null on error.
labEnsureMetadataAsync({required String deviceId, required String platform, required String osVersion, String? userInfoJson, String? deviceExtraJson}) → Future<String?>
labEnsureMetadata on a helper isolate.
labExportJson() → String?
Get the last lab export JSON (populated after session end in research mode).
labFinalize(int endedAtMs) → String?
Finalize the lab session. Returns the complete payload JSON.
labMarkMetadataDirty(String reason) → bool
Mark the cached lab metadata as needing re-upload (profile edit, device swap, app version bump, consent change). The next labEnsureMetadata call will POST regardless of hash.
labMergeExtraData(String patchJson) → String?
Merge session-level metadata into extra_data. Returns null on success, or 'lab_merge_extra_data: error code N' when the runtime rejected the patch (e.g. no active lab session, malformed JSON).
labOpenWindow(String? parentId, String windowType, String? label, int startedAtMs) → String?
Open a window in the active lab session. Returns the window ID.
labReenqueueSession(String sessionJson) → LabReenqueueResult
Re-enqueue a previously-finalized lab session JSON for cloud upload.
labSetStateOverrides(String windowId, String overridesJson) → bool
Set per-window state-data overrides.
labSetWindowValues(String windowId, String valuesJson) → bool
Set protocol-specific values on a lab window.
labStart(String protocolJson, int startedAtMs) → String?
Start a lab session. Returns null on success, or a short error string identifying the failure code from the runtime.
lastFeatures() → String?
lastHsv() → String?
The most recent human-state vector as JSON, or null before the first window has closed (a normal early-session state, not an error).
lastSleepScoreJson() → String?
Get the last live-head SleepScore JSON (rulepack://sleep_autonomic_v1). Null if no window has completed.
lastSleepScoreRawJson() → String?
Typed form of lastSleepScoreJson — returns the live-head SleepScore as raw JSON (path/mode/components/tier/baseline). The live-head and batch shapes differ; use computeSleepScore for the batch form.
listDataDeletions({int limit = 20, int offset = 0}) → Future<Map<String, dynamic>?>
List recent deletion requests for this caller's org. Mostly useful for dashboards / audit views; most apps will only call requestDataDeletion + getDataDeletion.
listSessions() → List?
loadBaselineSnapshot(String snapshotB64) → bool
Restore a snapshot from exportBaselineSnapshot. Needs a running pipeline. False when there is none, the text is not base64, or the engine refused it (damaged, from a newer build, or another subject's); the baselines are then left as they were.
loadCapabilityToken(String tokenJson, String secret) → bool
loadSessionState(String json) → int?
Restore a previously exported session state.
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
personalizationContextJson() → String?
Last PersonalizationContext as JSON. Returns null before the first window has completed. Schema mirrors the Synheart Runtime's PersonalizationContext JSON-serialized form.
pushAccel(int tsMs, double x, double y, double z, {String? provider}) → void
pushBehavior(int tsMs, int eventType, double value) → void
pushBehaviorEventJson(String eventJson) → int?
Push one rich behavior event as JSON. Returns the runtime's status (0 = accepted), or null when the runtime does not export the symbol.
pushContextEventJson(String eventJson) → int?
Push a foreground-app context event as JSON. Returns 0 on acceptance, or null when the symbol is absent.
pushHr(int tsMs, double bpm, {String? provider}) → void
pushInputsJson(String inputsJson) → Map<String, dynamic>?
Push a batch of typed inputs (the runtime's input envelope) as a JSON array. Returns the batch's account as a map: accepted, regressions, late, invalid, not_stored, malformed, not_permitted. Null with no pipeline, input that is not a JSON array, or when the call is absent.
pushRr(int tsMs, double rrMs, {String provider = 'default_sensor'}) → void
Push an RR interval with provider attribution.
pushRrBatch(int anchorTsMs, List<double> rrMs, {int order = 0, String provider = 'default_sensor'}) → void
Push a batch of RR intervals that arrived together in one sensor notification (e.g. a BLE Heart Rate Measurement packet carrying several RR values under one arrival timestamp).
pushSleepStages(String json) → void
pushSpeed(int tsMs, double speedMps) → void
Push a GPS-derived ground speed sample in m/s.
pushVendorHrv(int tsMs, {double rmssd = -1.0, double sdnn = -1.0, double stress = -1.0, double recovery = -1.0}) → void
Push vendor-reported HRV metrics (Tier 2). Pass -1.0 for unavailable fields.
pushVendorVitals(int tsMs, {double spo2 = -1.0, double respiration = -1.0}) → void
Push vendor vitals (SpO2, respiration) to lab windows.
pushWorkoutEvent(int startMs, int endMs, {int workoutKind = 0, double vendorStrain = -1.0, double vendorRecovery = -1.0}) → void
Push a workout/exercise event with optional vendor scalars. Workout-kind discriminants: 0=Unknown, 1=Cardio, 2=Strength, 3=Hiit, 4=LowIntensity, 5=Sport. Pass -1.0 for missing vendor scalars.
pushWornAccel(int tsMs, double x, double y, double z, int placement, {String? provider}) → void
pushWristAccel(int tsMs, double x, double y, double z, {String? provider}) → void
queryVendorEvents({String? provider, String? type, int? startMs, int? endMs, int limit = 100}) → List?
Query stored vendor events. Returns parsed JSON list, or null on error.
readinessScoreComputeJson(String inputJson) → String?
Compute a daily Readiness Score.
readinessScoreComputeJsonTraced(String inputJson, String correlationId) → String?
Same as readinessScoreComputeJson but with a caller-supplied correlation ID attached to tracing events.
rebindSubjectId(String subjectId, {bool invalidateToken = true}) → int
Atomically rebind the runtime subject id, re-pointing consent (cached_subject_id + token slot) and the cloud connector (user_id + subject-scoped queue) without a full dispose/reinit. Returns 1 when a consent re-mint is required for the new subject, 0 when a valid token is already loaded, and -1 on error (disposed handle or empty subject).
recordMetric(Map<String, dynamic> event) → bool
recordStudyConsent(Map<String, dynamic> payload) → Future<Map<String, dynamic>?>
Persist a durable study-consent record via the consent service. payload carries the record body (consent_document_version, optional study_id / consent_document_hash / affirmations / signature, signed_at, …). Returns the created record's {id, created_at} on success, or null when the native runtime (or this symbol) is unavailable.
recoveryScoreComputeJson(String inputJson) → String?
Compute a daily Recovery Score (stateless).
recoveryScoreComputeJsonTraced(String inputJson, String correlationId) → String?
Same as recoveryScoreComputeJson but with a caller-supplied correlation ID attached to tracing events.
requestAccountDeletion() → bool
requestDataDeletion({String? reason, String? contact, bool dryRun = false}) → Future<Map<String, dynamic>?>
Request cloud-side deletion of every byte the platform holds for the currently-bound subject (the value derived from your client_id at register time). Returns the persisted request row as parsed JSON, or {"error": "..."} if the call failed.
requestStudyDataDeletion({bool dryRun = false}) → Future<Map<String, dynamic>?>
Request erasure of the data the participant contributed to their study. dryRun returns an inventory preview without deleting; a real request is accepted asynchronously and carries a request_id.
researchStudyStatus() → Future<Map<String, dynamic>?>
Read the device's CURRENT active research-study enrolment for this app — the authoritative attribution state (same lookup the consent mint uses). Returns {enrolled: bool, study: {...}, enrolment: {...}}. Hosts should use this to correct a stale local "enrolled" flag.
revokeConsent(String type) → Future<bool>
runtimeSubjectId() → String?
The runtime's canonical subject id (RFC-0008), or null when unavailable. Read this back after init to pick up a subject the runtime derived itself (e.g. from client_id when device-auth is on), so Dart-side state can be reconciled with the native source of truth.
sdkDeviceAuthStatus() → Map<String, dynamic>?
§3 / §5 — JSON snapshot from synheart_core_sdk_device_auth_status.
sdkLogout() → Future<Map<String, dynamic>?>
End the installed device identity and clear its native sync membership. The runtime defines logout as idempotent, but still returns an envelope so the allocation can be released consistently. The call is blocking in C.
sdkReattestDevice() → Future<Map<String, dynamic>?>
Refresh the current device's attestation without changing its device ID. Runs off the UI isolate because the native v0.24 call is blocking.
sdkRegisterDevice(String clientId) → Future<Map<String, dynamic>?>
§3 — device registration (attestation). clientId is the app user id for this session. Runs on a background isolate so the blocking FFI call doesn't ANR the UI thread.
setAccelPlacement(int placementCode) → void
Declare where the accelerometer sits. See AccelPlacement.
setAmbientCapture(bool enabled) → void
Toggle the runtime's out-of-session HSI emission gate. When off (the default), the runtime forwards HSI windows only while a session is active; when on, it forwards every window. Hosts use this to drop the FFI fan-out cost on the background-capture path when the participant has revoked or paused ambient consent.
setCallActive({required bool active, required int tsMs}) → bool
Report whether a call is on, from tsMs on, as the OS microphone or camera indicator shows it. A level, like setInputCapture. True when accepted.
setFocusKind(int focusKind) → void
Set the active focus-kind sub-classification. No effect outside an active Focus task. See FocusKind for discriminants.
setHsiCallback(void onHsi(String json), {bool preferBuffered = true}) → void
Register a callback for real-time HSI state updates.
setInputCapture({required bool running, required int tsMs}) → bool
Report whether keyboard and pointer/touch capture is running, from tsMs on — including when the OS revokes its permission or the person pauses capture. Without these reports a host that captures input never certifies a window as rest, so resting HR and HRV never learn. A level: it holds across session stop and start. True when accepted.
setRetentionDays(int days) → int
setSdkCryptoCallbacks(Pointer<SynheartSdkCryptoCallbacks> table) → int
Register host crypto callbacks (§2). Must be called before sdkRegisterDevice / proof APIs.
setStorageCallbacks() → int
Attach host-provided secure-storage callbacks so the native core can persist state (consent tokens, device records, …) across app restarts.
setStreamCallback(void onEvent(String json)) → void
Register a callback for RAMEN stream events.
setSyncEnabled(bool enabled) → void
setTaskType(int taskKind) → void
Set the active task type. 0=Unknown, 1=Focus, 2=Recovery, 3=Movement, 4=Conversation. Prefer the typed TaskType enum on SynheartCore over calling this with raw integers.
sleepScoreComputeJson(String inputJson) → String?
Compute a nightly sleep score (stateless).
sleepScoreComputeJsonTraced(String inputJson, String correlationId) → String?
Same as sleepScoreComputeJson but with a caller-supplied correlation ID attached to tracing events.
srmDrainEventsJson() → String?
Personal-baseline events since the last call, oldest first (JSON array). Device-only: they name the person's context cells.
srmForgetBaselines(String scopeJson) → int?
Forget part of the personal baselines at the person's request. scopeJson is e.g. {"scope":"everything"}. Returns 0, 1 (bad scope), 1002 (busy), -1 (no pipeline), or null when absent. Snapshots the host exported earlier are the host's to delete.
srmOverallStatus() → Map<String, dynamic>?
srmPushWearableDaily({required String provider, required String metric, required int year, required int month, required int day, required double value, bool vendorSummary = true}) → int
Write one local date's value of a daily metric into the personal baselines, from provider ("apple_health", "whoop", …).
srmRefreshWearableReference(int year, int month, int day) → int?
Rebuild the wearable reference from the daily values of the local dates before year-month-day, so a day never sits in its own baseline. Call once a day after the day's values are pushed, with the date after the last complete one. Returns 0, 1004 (no such date), 1002 (the engine was busy), -1 (no pipeline), or null when the runtime does not export the call.
srmRegisterDirection(String directionJson) → String?
Register an episode direction (directionJson as the runtime defines it). Returns the direction's key as JSON, or null when refused.
srmSetDayType(int year, int month, int day, int dayType) → int?
Declare what kind of day year-month-day is, so the personal baselines key behaviour by day type: 0 workday, 1 free day, 2 leave, 3 sick, 4 travel, 5 on-call. Sick, leave and travel days teach a separate side reference. Returns 0, 1004, -1, or null when the runtime does not export the call.
startSession() → Map<String, dynamic>?
Start a session. Returns session JSON or null on error.
startStream(Map<String, dynamic> config) → int
Start the RAMEN streaming connection.
stopSession() → bool
Stop the current session. On failure, lastError describes it.
stopStream() → int
Stop the RAMEN streaming connection.
streamState() → String?
Get the current stream connection state.
syncClearLocalSpace() → Future<Map<String, dynamic>?>
Clear only LOCAL sync-space state — the "start over on this device" path. Does NOT touch the server (this device stays a member remotely); use syncLeaveSpace to also remove it server-side. Returns {ok: true} on success, null when the engine isn't wired.
syncCreateSpace({String? deviceName}) → Future<Map<String, dynamic>?>
Create a new sync-space on the cloud and become its first device. Returns {sync_space_id, recovery_key} — the recovery key is the SRK fragment the user must store; without it a lost device cannot rejoin. Returns null when the engine isn't wired.
syncDeleteSpace() → Future<Map<String, dynamic>?>
Delete the current sync-space entirely (all devices, cloud state). Returns {ok: true} on success. Returns null when the engine isn't wired.
syncGeneratePairing() → Future<Map<String, dynamic>?>
Generate a short-lived pairing token on the current sync-space. Returns {token, expires_in} — show the token to the user so a second device can call syncJoinSpace with it.
syncJoinSpace({required String pairingToken, String? deviceName}) → Future<Map<String, dynamic>?>
Join an existing sync-space using a pairing token from syncGeneratePairing. Returns {sync_space_id, status} on success. The new device becomes the second member of the space and the next syncNow will pull every artifact the originator has pushed.
syncLeaveSpace() → Future<Map<String, dynamic>?>
Leave the current sync-space for this device only. Returns {ok: true} on success. Returns null when the engine isn't wired.
syncListDevices() → Future<Map<String, dynamic>?>
List the devices paired into the current sync-space. Returns {devices: [{device_id, device_name, is_primary, trusted_at, last_seen_at, revoked}, …]}. Returns null when the engine isn't wired.
syncNow() → Future<Map<String, dynamic>?>
Run a sync cycle (push + pull). This performs a blocking network round-trip in the native runtime, so it runs on a background isolate (_runFfi) rather than _callJson — calling it inline on the UI isolate froze the main thread until the request completed/timed out (a user-triggered ANR on the manual-sync path, and a stall on the periodic path). Returns null when the bridge is disposed or the engine isn't wired.
syncPairingStatus(String token) → Future<Map<String, dynamic>?>
The server's verdict on a pairing token this device minted with syncGeneratePairing: {status, sync_space_id, joined_device, joined_at, expires_at}, where status is waiting, joined, expired or unknown. Network call; runs on the sync worker. Null when the runtime predates the call.
syncReadiness() → Map<String, dynamic>?
Unified native sync-readiness snapshot: individual prerequisite booleans (configured, storage_present, device_registered, engine_ready, active_space, srk_ready, …) plus one primary state — the first unmet gate in priority order (CONFIGURATION_MISSING, STORAGE_UNAVAILABLE, DEVICE_REVOKED, DEVICE_REGISTRATION_REQUIRED, ENGINE_NOT_INITIALIZED, NO_ACTIVE_SPACE, SRK_UNAVAILABLE, READY). Use state for UI/logs instead of inferring readiness from separate checks. Cloud-upload consent is intentionally excluded — the host owns that gate. Null when the runtime bridge isn't wired.
syncRecoverSpace({required String recoveryKey, required String spaceId}) → Future<Map<String, dynamic>?>
Recover access to a sync-space on a fresh device using the recovery key (SRK fragment) issued at creation plus the target space id. Returns {sync_space_id, owner_user_id, status} on success. Returns null when the engine isn't wired.
syncRevokeDevice({required String deviceId}) → Future<Map<String, dynamic>?>
Revoke a specific device from the current sync-space by its device_id. Returns {ok: true} on success. Returns null when the engine isn't wired.
syncStatus() → Map<String, dynamic>?
Local sync-engine state, no network: {enabled, sync_space_id, pending_count, last_success_ms, srk_ready, account_owned} on runtime 0.39.0 and later (older runtimes sent {enabled, sync_space_id, device_count}, with device_count always 0). The device roster lives on the server: read it with syncListDevices for a "paired with N devices" line.
syniChatJson(String requestJson) → Future<Map<String, dynamic>>
syniCloseSessionJson(String sessionId) → Future<Map<String, dynamic>>
syniGetSessionJson(String sessionId) → Future<Map<String, dynamic>>
syniGetSessionMessagesJson(String sessionId, {int limit = 0}) → Future<Map<String, dynamic>>
syniListSessionsJson({int limit = 0}) → Future<Map<String, dynamic>>
tick(int nowMs) → String?
Advance the pipeline clock. Returns HSI JSON if a window completed.
tickAll(int nowMs) → String?
Drain every completed window, oldest first, as a JSON array.
toString() → String
A string representation of this object.
inherited
uploadMetadata() → Map<String, dynamic>?
wearableReference() → WearableReferenceView?
Typed form of wearableReferenceJson — returns just the Path-B fields callers usually need (status, recent_sleep_score_median). For the full reference, parse the raw JSON yourself.
wearableReferenceJson() → String?
Get the current wearable reference, including Path-B recent_sleep_score_median. Null if no reference is set.
wellnessJson() → String?
Always null on current runtimes, which no longer compute a Wellness score. Read stress from the HSI stream for a live view relative to the person's baseline, and recovery or readiness for the daily one.
wipeLocalData() → bool
withdrawResearchStudy() → Future<Map<String, dynamic>?>
Withdraw from the device's active research study for this app. No codes needed — participant + app come from the device's signed cloud credential. Returns the service response ({"withdrawn": bool, ...}) or null.

Operators

operator ==(Object other) → bool
The equality operator.
inherited

Static Properties

bufferedDrainInterval ↔ Duration
How often buffered mode polls the runtime's ring buffer. ~4 Hz adds at most ~250 ms latency to diagnostic lines — an acceptable trade for removing the hot-restart crash class.
getter/setter pair
defaultRuntimeLogEnvFilter ↔ String
Default env_filter when initRuntimeLogging is called with a null/empty filter.
getter/setter pair
hsiBufferCapacity ↔ int
Ring capacity handed to init_hsi_buffered. Frames arrive at ~1 Hz during an active session and the oldest is evicted when the ring is full, so size it for the worst gap between drains the host expects, not for typical operation. 64 covers a minute with nobody polling.
getter/setter pair
hsiDrainInterval ↔ Duration
Drain cadence in buffered mode. Frames are ~1 Hz, so polling faster buys nothing; slower adds that much latency to onStateUpdate. A host that ticks the engine itself gets its frames in the same turn regardless — see drainHsi.
getter/setter pair
lastCreateError ↔ SynheartNativeError?
Why the most recent create or createAsync returned null: the runtime's structured error (CONFIGURATION_INVALID, INVALID_ARGUMENT, …), or null when it succeeded, the library did not load, or the runtime predates ABI 2.0.
getter/setter pair

Static Methods

buildInfo() → Map<String, dynamic>?
All synheart crate versions, target, profile, and features as JSON. No handle needed — compile-time info.
create(Map<String, dynamic> config) → CoreRuntimeBridge?
Create a bridge from a config map. Returns null if the native library is unavailable or config is invalid.
createAsync(Map<String, dynamic> config) → Future<CoreRuntimeBridge?>
create, with the native synheart_core_new call on a background isolate.
initRuntimeLogging({SynheartCoreFFI? ffi, String? envFilter, void onLine(String line)?, bool preferBuffered = true}) → int
Initialize Runtime tracing once per process (call before create if you need a custom filter or sink). See the book: book/src/abi/logging.md.
runtimeDroppedLogLines() → int
Lines the runtime dropped due to ring overflow (buffered mode) or channel backpressure — a growing value means the drain pump or callback is falling behind. Returns 0 when logging isn't initialised or the runtime is too old to report it.
shutdownRuntimeLogging() → int
Tear down runtime log forwarding installed by initRuntimeLogging.
utcOffsetMinAt(int tsMs) → int
The device's offset from UTC, in minutes, in force at tsMs (epoch ms).
version() → String?
The native synheart-engine version string, or null.