SPB Git

Repository Public MIT

ARCHITECTURE.md 9.3 KB

# ORIX Astra — Architecture

# 1. Shape

One Swift package (AstraKit, Package.swift at the root) with seven modules under Packages/, and a thin iOS app target (App/, generated by XcodeGen from project.yml). Swift 6 language mode everywhere, iOS 18 minimum; the pure modules also build on macOS 15 so their tests run in seconds with swift test.

graph TD
    App[App target<br/>ORIXAstraApp, assets, Info.plist] --> UI
    UI[AstraUI<br/>shell, chat, models, arena, agents, knowledge, lab] --> Design[AstraDesign<br/>tokens, motion, components]
    UI --> Providers[AstraProviders<br/>OpenAI, Anthropic, Gemini, xAI, OpenRouter, custom]
    UI --> Local[AstraLocal<br/>MLX, Foundation Models, catalog, downloads, governors]
    UI --> Persistence[AstraPersistence<br/>GRDB store, migrations, export]
    UI --> Agents[AstraAgents<br/>tools, approvals, runner]
    Providers --> Core[AstraCore<br/>domain, events, provider protocol, orchestration,<br/>budget, cost, redaction, transport, credentials]
    Local --> Core
    Persistence --> Core
    Agents --> Core

Dependency rules, enforced by the package graph:

  • AstraCore depends on nothing but Foundation and Security.
  • AstraProviders, AstraLocal, AstraPersistence, AstraAgents depend on AstraCore only (plus their one external library: MLX for Local, GRDB for Persistence). They do not know each other.
  • AstraDesign depends on SwiftUI only.
  • AstraUI is the only module that sees everything; the app target sees only AstraUI.

Setting ASTRA_NO_MLX=1 removes AstraLocal and AstraUI from the manifest so the pure modules build and test without compiling MLX.

# 2. Core contracts (AstraCore)

Concept Type Notes
Model identity ModelRef (provider, endpoint, model id) Stable string id, persisted with conversations
Model metadata ModelInfo + MetadataSource Every capability, context size and price carries where it came from: provider API, documentation with date, runtime, user, unknown
Request GenerationRequest, PromptMessage, GenerationParameters, ToolDefinition, RoutingPreferences Provider-neutral
Stream StreamEvent: messageStarted, textDelta, reasoningSummaryDelta, toolCallStarted, toolCallDelta, toolCallCompleted, usage, messageCompleted, error The only thing the UI ever consumes; no transport type leaves an adapter
Provider protocol ChatProvider (listModels, verify, stream) Implemented by five cloud adapters, the custom endpoint adapter, MLX and Foundation Models
Orchestration InferenceOrchestrator, StreamValidator, GenerationOutcome See §3
Context ContextBudget, TruncationStrategy, TokenEstimator Whole-turn truncation; tool results stay with their call; the last user turn is never dropped
Cost UsageAccounting, CostEstimate, Pricing Reported cost wins; otherwise usage × dated price; otherwise "unavailable", never zero
Capabilities ParameterNegotiator Drops what a model does not accept and says so
Errors AstraError, mapHTTPError Typed, user-readable, redacted
Secrets CredentialStore (KeychainCredentialStore), Redactor, EndpointPolicy See SECURITY.md
Network protocol HTTPTransport (URLSessionTransport), SSEParser Adapters never touch URLSession; parsers are tested from recorded transcripts

# 3. A generation, end to end

sequenceDiagram
    participant V as ChatScreen
    participant C as ChatController (MainActor)
    participant S as AstraStore (GRDB)
    participant O as InferenceOrchestrator
    participant P as ChatProvider (cloud or local)
    V->>C: send(text, attachments)
    C->>S: appendUserMessage, beginAssistantMessage (status = streaming)
    C->>C: build prompt from the active branch, negotiate parameters, plan context budget
    C->>O: stream(request)
    O->>P: stream(request)
    P-->>O: StreamEvent…
    O-->>C: validated StreamEvent… (exactly one terminal event)
    C->>V: live text, at most ~25 publishes/s
    C->>S: updateStreaming every ~0.4 s (partial answer survives a kill)
    C->>S: finalizeAssistantMessage (usage, cost, timing, reported model)

Guarantees provided by the orchestrator, each covered by a test:

  • Ordering: one messageStarted first (synthesised if an adapter forgets it), tool deltas only for started calls, nothing after the terminal event.
  • Exactly one terminal event, whatever the adapter does: a clean messageCompleted, or one error.
  • Never throws to the UI: failures arrive as a terminal .error, so text already shown stays valid and is saved as a stopped or failed answer.
  • Safe retry only: a transient failure is retried only if nothing at all was received (no partial answer, no tool call), and never past a long Retry-After.
  • Cancellation propagates: cancelling the consuming task cancels the provider stream, which cancels the HTTP request or stops the local decode loop.

Measurements (GenerationTiming) are taken by the orchestrator's caller with wall-clock time; tokens per second are shown only when the provider or runtime reported an output token count.

# 4. Concurrency

  • UI state lives in @MainActor @Observable classes: AppModel, ModelLibrary, LocalModels, ChatController, and one controller per feature.
  • Mutable shared state off the main actor lives in actors: LocalEngine (model lifecycle, one generation at a time), DownloadCoordinator, the MLX runtime.
  • The database is a GRDB pool behind AstraStore; every API is async, nothing on the main actor waits on disk.
  • Image decoding, PDF text extraction, hashing and file measurement run in detached tasks.
  • Streams use AsyncStream / AsyncThrowingStream with onTermination wired to task cancellation at every hop.

# 5. Persistence

SQLite through GRDB, one file in Application Support, WAL, foreign keys with cascades, versioned DatabaseMigrator migrations with a schema-stability test. Conversations are a message tree (parentID, activeLeafID): edit-and-resend and regenerate create siblings, the version arrows walk them, and nothing is overwritten. Full-text search uses FTS5 over titles, message text and document chunks, with hostile-query escaping. Attachment bytes live in files named by SHA-256 (the display name is never used to build a path). Credentials are not in the database; they are in the Keychain.

# 6. On-device inference

  • MLX (mlx-swift 0.33, mlx-swift-lm 3.33): MLXProvider → LocalEngine actor → MLXRuntime. One model in memory on iPhone, KV cache reused across turns of a conversation, unload on memory pressure and on critical thermal state. MemoryGovernor gives a conservative fit verdict before a download and before a load; ThermalGovernor reduces limits when the device is hot.
  • Apple Foundation Models: AppleFoundationProvider, offered only when SystemLanguageModel reports availability, with the system's own reason shown otherwise. It is never presented as downloadable.
  • Model library: a catalogue (ModelCatalog, LocalModelCard) bundled with the app and refreshed from https://www.orixlab.dev/astra/models/v1/catalog.json. A refreshed card for a known model is accepted only if its file hashes equal the bundled ones. Downloads are mirror-first (the owner's site) with Hugging Face as fallback, resumable by HTTP range, and every file is verified by SHA-256 before a model is marked installed.
  • MLX does not run in the iOS Simulator; the app states this there and offers the other paths.

# 7. Agents

AgentRunner drives a bounded loop over the same orchestrator: model turn → validated tool calls → approvals → tool execution → results back in a delimited "untrusted data" envelope. Permissions, allowlists and budgets are enforced in code, never by the prompt. There is no code-execution tool. See SECURITY.md §6.

# 8. App target

App/ contains only ORIXAstraApp.swift, the asset catalogue (icon, accent, launch colour, vector logos), Info.plist, the entitlement file (increased memory limit) and the privacy manifest. DEBUG-only launch arguments (-ORIXReset, -ORIXTab, -ORIXAppearance, -ORIXAutoSend, -ORIXModel, -ORIXSkipOnboarding, -ORIXInMemory) drive screenshots and UI tests; they are compiled out of Release builds.

# 9. Risk register

Risk Status Mitigation
No physical iPhone was available during development Open MLX verified on Apple silicon macOS with the same framework and weights; every device-only item is listed as unverified in TEST_RESULTS.md
Memory limits on iPhone for models above ~2 GB Open Fit verdicts, one loaded model, increased-memory-limit entitlement, unload on pressure; to be measured on hardware
Provider APIs change (model ids, parameters) Managed Model lists come from the providers at runtime; curated metadata is dated; unsupported parameters are dropped after the provider names them
App Review: downloading model weights, third-party logos, AI content Open Sizes disclosed before download, consent before sending data to a third party, trademark notice; see RELEASE_CHECKLIST.md
Redistribution terms of some model licences Managed Only Apache-2.0 / MIT weights are mirrored; others come from Hugging Face
Background execution By design No background inference is claimed or attempted
Files main
Menu

Theme