Skip to main content

Mobile SDKs

The Idiomark provides native mobile SDKs for both iOS and Android platforms. These SDKs enable you to integrate personality profiles, cloud synchronization, and AI inference directly into your mobile applications.

Overview​

Both SDKs provide:

  • Storage - Store and retrieve Idiomark personality files locally and from the cloud
  • Sync - Real-time WebSocket synchronization across devices
  • Inference - Generate personality-powered AI responses
  • Security - Client-side encryption and secure keychain storage
  • Reactive State - Modern reactive patterns (StateFlow for Android, Combine for iOS)

Requirements​

  • Android API 26+ (Android 8.0 Oreo)
  • Kotlin 1.9+
  • Gradle 8.0+

Installation​

Gradle (Kotlin DSL)​

Add to your build.gradle.kts (module level):

dependencies {
implementation("xyz.idiomark:sdk:1.0.0")
}

Gradle (Groovy)​

Add to your build.gradle:

dependencies {
implementation 'xyz.idiomark:sdk:1.0.0'
}

Maven​

<dependency>
<groupId>xyz.idiomark</groupId>
<artifactId>sdk</artifactId>
<version>1.0.0</version>
</dependency>

Quick Start​

Initialize the SDK​

import xyz.idiomark.sdk.IdiomarkSDK
import kotlinx.coroutines.launch

// In your Activity or Fragment
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)

// Start sync
IdiomarkSDK.startSync()

// Observe state
lifecycleScope.launch {
IdiomarkSDK.state.collect { state ->
updateConnectionUI(state.connected)
}
}
}
}

Load a Personality​

lifecycleScope.launch {
val file = IdiomarkSDK.load("personality-id")
file?.let {
println("Loaded: ${it.personality?.voice?.tone?.primary}")
}
}

Generate a Response​

lifecycleScope.launch {
val response = IdiomarkSDK.respond(
message = "What's your opinion on Kotlin?",
personalityId = "personality-id"
)
println(response)
}

Configuration​

The Android SDK uses a singleton pattern with default configuration:

// Configuration is handled internally with these defaults:
// - baseURL: "https://api.idiomark.protocol/storage"
// - syncURL: "wss://api.idiomark.protocol/ws"
// - enableSync: true
// - enableEncryption: true
// - timeout: 30000ms
// - maxRetries: 3

Core API​

Loading Personalities​

// Load by ID
val file = IdiomarkSDK.load("personality-id")

// Access personality data
file?.let {
println("Voice: ${it.personality?.voice?.tone?.primary}")
println("Domains: ${it.personality?.domains?.map { d -> d.name }}")
println("Confidence: ${it.personality?.voice?.confidence}")
}

Saving Personalities​

import xyz.idiomark.sdk.models.*
import java.util.Date
import java.util.UUID

lifecycleScope.launch {
val file = IdiomarkFile(
idiomark = "1.0.0",
id = UUID.randomUUID().toString(),
created = Date(),
updated = Date(),
metadata = IdiomarkMetadata(
entity = IdiomarkEntityType.HUMAN,
sources = listOf("twitter", "github"),
extractedAt = Date(),
sampleSize = 1000,
extractor = "my-app@1.0.0"
),
personality = personality,
signature = null
)

val result = IdiomarkSDK.save(file)
println("Saved: ${result.id}")
}

Generating Responses​

lifecycleScope.launch {
// Generate with personality ID
val response = IdiomarkSDK.respond(
message = "Tell me about yourself",
personalityId = "personality-id"
)
println("Response: $response")
}

// Or use the inference manager directly
IdiomarkSDK.inference.setPersonality(personality)
val response = IdiomarkSDK.inference.respond(
message = "Hello!",
personality = personality
)

Sync Control​

// Start automatic sync
IdiomarkSDK.startSync()

// Stop sync
IdiomarkSDK.stopSync()

// Observe sync state
lifecycleScope.launch {
IdiomarkSDK.state.collect { state ->
println("Connected: ${state.connected}")
println("Reconnecting: ${state.reconnecting}")
println("Pending events: ${state.pendingEvents}")
}
}

Reactive State​

Both SDKs provide reactive state management for UI updates.

Using StateFlow in Activities/Fragments​

class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)

// Observe state with lifecycle awareness
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
IdiomarkSDK.state.collect { state ->
updateUI(state)
}
}
}
}

private fun updateUI(state: IdiomarkState) {
when {
state.connected -> binding.status.text = "Connected"
state.reconnecting -> binding.status.text = "Reconnecting..."
else -> binding.status.text = "Disconnected"
}
binding.pendingEvents.text = "${state.pendingEvents} pending"
}
}

Using StateFlow in Compose​

@Composable
fun IdiomarkScreen() {
val state by IdiomarkSDK.state.collectAsState()

Column {
if (state.connected) {
Text("Connected", color = Color.Green)
}

Text("Pending: ${state.pendingEvents} events")

if (state.activePersonalityId != null) {
Text("Active: ${state.activePersonalityId}")
}
}
}

Callbacks​

// File change callback
IdiomarkSDK.onFileChanged = { file ->
println("File changed: ${file.id}")
}

// Sync complete callback
IdiomarkSDK.onSyncComplete = { result ->
if (result.success) {
println("Synced ${result.fileCount} files")
} else {
println("Sync failed: ${result.error}")
}
}

// Error callback
IdiomarkSDK.onError = { error ->
println("Error: ${error.message}")
}

Service Managers​

Access lower-level service managers for advanced use cases.

Storage​

val storage = IdiomarkSDK.storage

// List files
val files = storage.list(ListRequest(limit = 50))

// Get specific file
val file = storage.get("file-id")

// Create file
val result = storage.create(file)

// Update file
val result = storage.update(file)

// Delete file
storage.delete("file-id")

// Check existence
val exists = storage.exists("file-id")

// Clear cache
storage.clearCache()

Sync​

val sync = IdiomarkSDK.sync

// Connect
sync.connect()

// Disconnect
sync.disconnect()

// Subscribe to channels
sync.subscribe("idiomark:file-id")
sync.subscribe("user:user-id")

// Unsubscribe
sync.unsubscribe("idiomark:file-id")

// Update presence
sync.updatePresence("online", mapOf("device" to "Android"))

// Pull sync
sync.syncPull(since = timestamp)

Inference​

val inference = IdiomarkSDK.inference

// Set active personality
inference.setPersonality(personality)

// Clear active personality
inference.clearPersonality()

// Generate response
val response = inference.respond(
message = "Hello!",
personality = personality
)

// Stream response (experimental)
inference.streamResponse(message, personality)
.collect { chunk ->
print(chunk.delta)
}

iOS-Specific Features​

The iOS SDK includes additional features tailored for Apple platforms.

Profile Manager​

let profileManager = IdiomarkProfileManager()

// Load all profiles
let profiles = try await profileManager.loadProfiles()

// Set active profile
try profileManager.setActiveProfile(id: profile.id)

// Get active profile
let active = profileManager.getActiveProfile()

// Search profiles
let results = profileManager.searchProfiles(query: "developer")

// Filter by entity type
let humans = profileManager.filterProfiles(by: .human)

// Sort by confidence
let sorted = profileManager.sortByConfidence(ascending: false)

Import/Export​

// Import from JSON
let jsonData = try Data(contentsOf: fileURL)
let profile = try await profileManager.importProfile(from: jsonData)

// Export to JSON
let exported = try await profileManager.exportProfile(id: profile.id)
try exported.write(to: exportURL)

Encryption​

let encryption = IdiomarkEncryptionService()

// Encrypt a profile
let encrypted = try await encryption.encryptProfile(profile)

// Decrypt a profile
let decrypted = try await encryption.decryptProfile(encrypted)

// Derive key from password
let (key, salt) = try encryption.deriveKey(
from: "secure-password",
salt: nil
)

Keychain Integration​

let keychain = IdiomarkKeychainService.default

// Store auth token
try keychain.storeAuthToken("your-token-here")

// Retrieve token
let token = try keychain.getAuthToken()

// Check biometric availability
if keychain.isBiometricAvailable {
let type = keychain.biometricType // .faceID or .touchID

// Store with biometric protection
try keychain.setWithBiometrics(
key: .encryptionKey,
value: sensitiveData,
prompt: "Authenticate to access key"
)
}

Personality Injector​

let injector = IdiomarkInjector(personality: personality)

// Inject personality into text
let input = "Hello, how are you?"
let output = injector.inject(into: input)

// Generate a response
let response = injector.generateResponse(to: input)

// With custom config
let config = IdiomarkInjectorConfig(
strength: 0.8,
enableEmoji: true,
enablePunctuation: true,
enableCapitalization: true
)
let injector = IdiomarkInjector(personality: personality, config: config)

Error Handling​

try {
val response = IdiomarkSDK.respond(
message = "Hello!",
personalityId = "personality-id"
)
} catch (e: StorageError.NetworkError) {
// Handle network error
println("Network error: ${e.message}")
} catch (e: StorageError.AuthenticationError) {
// Handle auth error
println("Authentication failed: ${e.message}")
} catch (e: StorageError.NotFoundError) {
// Handle not found
println("Profile not found: ${e.id}")
} catch (e: StorageError.ValidationError) {
// Handle validation error
println("Validation error: ${e.message}")
} catch (e: StorageError.RateLimitError) {
// Handle rate limit
println("Rate limited. Retry after: ${e.retryAfter}ms")
} catch (e: Exception) {
// Handle other errors
println("Error: ${e.message}")
}

Data Models​

IdiomarkFile / IdiomarkProfile​

data class IdiomarkFile(
val idiomark: String, // Protocol version
val id: String, // Unique ID
val created: Date, // Creation time
val updated: Date, // Last update
val metadata: IdiomarkMetadata?,
val personality: Personality?,
val signature: String? // Digital signature
)

Personality​

data class Personality(
val voice: Voice?, // Tone & style
val patterns: Patterns?, // Communication patterns
val domains: List<Domain>?, // Expertise areas
val values: List<Value>?, // Beliefs & values
val knowledge: Knowledge? // Topics & mentions
)

Entity Types​

enum class IdiomarkEntityType {
HUMAN, // Real person
BRAND, // Company/brand
BOT, // Automated account
FICTIONAL // Fictional character
}

Cross-Platform Considerations​

API Parity​

Both SDKs provide consistent APIs across platforms:

FeatureAndroidiOS
StorageIdiomarkStorageIdiomarkStorage
SyncIdiomarkSyncIdiomarkSync
InferenceIdiomarkInferenceIdiomarkInference
Reactive StateStateFlow@Published
Coroutines/AsyncCoroutinesasync/await
EncryptionAES-GCMCryptoKit AES-GCM

Platform Differences​

note

The iOS SDK includes additional Apple-specific features like Keychain integration, biometric authentication, and SwiftUI-friendly models.

  • Uses Kotlin coroutines and StateFlow
  • OkHttp for networking
  • Gson for JSON serialization
  • ProGuard/R8 rules required

ProGuard / R8 (Android)​

Add to your proguard-rules.pro:

# Idiomark SDK
-keep class xyz.idiomark.sdk.** { *; }
-keepclassmembers class xyz.idiomark.sdk.models.** { *; }
-dontwarn xyz.idiomark.sdk.**

Dependencies​

The SDK requires these dependencies (automatically included):

implementation("com.squareup.okhttp3:okhttp:4.12.0")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3")
implementation("com.google.code.gson:gson:2.10.1")

Testing​

Run tests with:

./gradlew test

For instrumented tests:

./gradlew connectedAndroidTest

Best Practices​

  1. Reuse SDK instance - Both SDKs use singletons; don't create multiple instances
  2. Cache personality files - Don't reload on every request
  3. Handle offline gracefully - Both SDKs queue events when offline
  4. Set appropriate timeouts - Adjust based on your use case
  5. Use encryption - Enable encryption for sensitive profiles
  6. Validate profiles - Check isValid before using personality data
  7. Implement error handling - Always wrap calls in try/catch

Support​