SPB Git

Repository Public MIT

ARCHITECTURE.md 9.3 KB 115 lines markdown

1# ORIX Astra — Architecture23## 1. Shape45One 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`.67```mermaid8graph TD9    App[App target<br/>ORIXAstraApp, assets, Info.plist] --> UI10    UI[AstraUI<br/>shell, chat, models, arena, agents, knowledge, lab] --> Design[AstraDesign<br/>tokens, motion, components]11    UI --> Providers[AstraProviders<br/>OpenAI, Anthropic, Gemini, xAI, OpenRouter, custom]12    UI --> Local[AstraLocal<br/>MLX, Foundation Models, catalog, downloads, governors]13    UI --> Persistence[AstraPersistence<br/>GRDB store, migrations, export]14    UI --> Agents[AstraAgents<br/>tools, approvals, runner]15    Providers --> Core[AstraCore<br/>domain, events, provider protocol, orchestration,<br/>budget, cost, redaction, transport, credentials]16    Local --> Core17    Persistence --> Core18    Agents --> Core19```2021Dependency rules, enforced by the package graph:2223- `AstraCore` depends on nothing but Foundation and Security.24- `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.25- `AstraDesign` depends on SwiftUI only.26- `AstraUI` is the only module that sees everything; the app target sees only `AstraUI`.2728Setting `ASTRA_NO_MLX=1` removes `AstraLocal` and `AstraUI` from the manifest so the pure modules build and test without compiling MLX.2930## 2. Core contracts (`AstraCore`)3132| Concept | Type | Notes |33|---|---|---|34| Model identity | `ModelRef` (provider, endpoint, model id) | Stable string id, persisted with conversations |35| Model metadata | `ModelInfo` + `MetadataSource` | Every capability, context size and price carries where it came from: provider API, documentation with date, runtime, user, unknown |36| Request | `GenerationRequest`, `PromptMessage`, `GenerationParameters`, `ToolDefinition`, `RoutingPreferences` | Provider-neutral |37| Stream | `StreamEvent`: `messageStarted`, `textDelta`, `reasoningSummaryDelta`, `toolCallStarted`, `toolCallDelta`, `toolCallCompleted`, `usage`, `messageCompleted`, `error` | The only thing the UI ever consumes; no transport type leaves an adapter |38| Provider | `protocol ChatProvider` (`listModels`, `verify`, `stream`) | Implemented by five cloud adapters, the custom endpoint adapter, MLX and Foundation Models |39| Orchestration | `InferenceOrchestrator`, `StreamValidator`, `GenerationOutcome` | See §3 |40| Context | `ContextBudget`, `TruncationStrategy`, `TokenEstimator` | Whole-turn truncation; tool results stay with their call; the last user turn is never dropped |41| Cost | `UsageAccounting`, `CostEstimate`, `Pricing` | Reported cost wins; otherwise usage × dated price; otherwise "unavailable", never zero |42| Capabilities | `ParameterNegotiator` | Drops what a model does not accept and says so |43| Errors | `AstraError`, `mapHTTPError` | Typed, user-readable, redacted |44| Secrets | `CredentialStore` (`KeychainCredentialStore`), `Redactor`, `EndpointPolicy` | See `SECURITY.md` |45| Network | `protocol HTTPTransport` (`URLSessionTransport`), `SSEParser` | Adapters never touch `URLSession`; parsers are tested from recorded transcripts |4647## 3. A generation, end to end4849```mermaid50sequenceDiagram51    participant V as ChatScreen52    participant C as ChatController (MainActor)53    participant S as AstraStore (GRDB)54    participant O as InferenceOrchestrator55    participant P as ChatProvider (cloud or local)56    V->>C: send(text, attachments)57    C->>S: appendUserMessage, beginAssistantMessage (status = streaming)58    C->>C: build prompt from the active branch, negotiate parameters, plan context budget59    C->>O: stream(request)60    O->>P: stream(request)61    P-->>O: StreamEvent…62    O-->>C: validated StreamEvent… (exactly one terminal event)63    C->>V: live text, at most ~25 publishes/s64    C->>S: updateStreaming every ~0.4 s (partial answer survives a kill)65    C->>S: finalizeAssistantMessage (usage, cost, timing, reported model)66```6768Guarantees provided by the orchestrator, each covered by a test:6970- **Ordering**: one `messageStarted` first (synthesised if an adapter forgets it), tool deltas only for started calls, nothing after the terminal event.71- **Exactly one terminal event**, whatever the adapter does: a clean `messageCompleted`, or one `error`.72- **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.73- **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`.74- **Cancellation propagates**: cancelling the consuming task cancels the provider stream, which cancels the HTTP request or stops the local decode loop.7576Measurements (`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.7778## 4. Concurrency7980- UI state lives in `@MainActor @Observable` classes: `AppModel`, `ModelLibrary`, `LocalModels`, `ChatController`, and one controller per feature.81- Mutable shared state off the main actor lives in actors: `LocalEngine` (model lifecycle, one generation at a time), `DownloadCoordinator`, the MLX runtime.82- The database is a GRDB pool behind `AstraStore`; every API is `async`, nothing on the main actor waits on disk.83- Image decoding, PDF text extraction, hashing and file measurement run in detached tasks.84- Streams use `AsyncStream` / `AsyncThrowingStream` with `onTermination` wired to task cancellation at every hop.8586## 5. Persistence8788SQLite 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.8990## 6. On-device inference9192- **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.93- **Apple Foundation Models**: `AppleFoundationProvider`, offered only when `SystemLanguageModel` reports availability, with the system's own reason shown otherwise. It is never presented as downloadable.94- **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.95- MLX does not run in the iOS Simulator; the app states this there and offers the other paths.9697## 7. Agents9899`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.100101## 8. App target102103`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.104105## 9. Risk register106107| Risk | Status | Mitigation |108|---|---|---|109| 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` |110| 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 |111| 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 |112| 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` |113| Redistribution terms of some model licences | Managed | Only Apache-2.0 / MIT weights are mirrored; others come from Hugging Face |114| Background execution | By design | No background inference is claimed or attempted |115
Files main
Menu

Theme