Make Codex and Claude Code subscriptions go further: a local model router that gives routine agent work to economical models and keeps your strongest model for the hard parts.
Architecture and ownership
Code map · Agent/Worker map · Decision map · Test map
Web console and Windows host
crates/daemon/src/console owns the separate HTTP listener, origin/asset admission,
credential stores and per-client product contexts. Service startup exclusively
binds configured sockets, including the local companion in network mode; launch
minting selects live state and never enables listening. Linux installer options
and console init persist scope/port in the host-runtime listener store. A wildcard
bind requires a concrete advertised IP for its one-use URL. Launch codes bind that
origin and actual port; the Windows shell explicitly requests the local endpoint.
Request deadlines cover each request independently of connection age; incomplete
headers and bodies have their own bounds. Shared confirmation permits and broker
prompts release on caller cancellation, without approving or affecting another context.
The console transport reserves separate 64-connection pools for loopback and network
peers. Socket writes close after 30 seconds without byte progress; successful writes
reset that deadline, and operation/confirmation waits do not arm it.
Its private in-process Client
Core transport shares Local Control budgets, operation admission and upgrade
drain; external Local Control retains its released-command gate. The frontend
apps/desktop/src/host selects the Tauri, browser or Windows-shell transport and
host capabilities. Browser product requests use explicit Bearer/context headers;
native host actions stay in their host adapter.
apps/shell owns the Windows Tauri window, exact-origin
host IPC, startup/reconnect, tray/login preference and NSIS hooks. The
Rust standalone transaction
owns architecture-matched Task installation and current-schema journal recovery; the shell's separate
inventory/finisher owns its program files and update outcome. Neither owns business
transactions or exposes Local Control to WebView.
The native current-package repair
matches the complete accepted package and owned Task before reapplying a prepared
core journal forward. Generic rollback refuses possible storage writes before any
manager effect. NSIS supplies the candidate to early shell recovery, preserving
the original batch instead of forcing an older-program rollback. The
release catalog emits V3 and the registered
Windows-free V2 projection for supported macOS readers. Public Windows artifacts
are x64 NSIS installers only; headless x64/ARM64 archives stay internal. The
installer and tests invoke __windows-install / __windows-uninstall, with no
Python installer or offered SCM installation entry.
Shared layers
| Responsibility | Production owner | Boundary |
|---|---|---|
| Business types and invariants | Domain | Typed intent, identity, immutable plans and operation checkpoints |
| Local control contract | Application API, client-core | Shared requests/responses for CLI and Desktop; generated schemas come from typed producers |
| Business workflows | Application | Planning and authorization through ports; external effects are supplied by the daemon |
| Composition and process lifecycle | Daemon control, delegation | Concrete adapters, accepted operations, Worker execution and recovery |
| Operating-system primitives | Platform | Cross-platform private filesystem creation/reads and owned cleanup; native handles, ACLs, file identity and local byte streams. Business authority and lifecycle remain with callers |
| Durable state and external effects | Local Storage, Integrations | Store current state; read or conditionally change external Agent configuration through its native leaf |
| Request execution | Gateway, gateway-core | Authenticate against published authority, plan attempts, adapt protocols and enforce execution budgets |
| Business evidence | Observation, authorized queries | Execution facts, managed content, session queries and valuation; diagnostics remain separate |
| Product presentation | Desktop product shell, native host, CLI | The native host projects safe DTOs; frontend state does not grant authority or establish durable success |
CLI JSON request sources (--request-file / --request-stdin) share the bounded
strict input reader. Command codecs retain
typed intent, selector and byte-limit ownership; see the CLI input guide
and production argv regressions.
Connection-test help and native/registered templates come from
Application API; the
installed-example regression
executes the displayed commands with those request documents. The
real-process recipe regression
checks their current-catalog results and protected-input cleanup through CLI/daemon.
Quickstart and Preview convenience inputs compose existing queries and transactions. They use Application authoring options for both initial and reopened editors, also consumed by Desktop. Exact Apply files are ordinary user-selected requests, not another journal or authority. Offline schemas come from shared wire DTOs, including discovery and settings Preview; Application still owns discovery/planning and the daemon supplies adapters.
CLI/Desktop → client-core → daemon control → Application → storage/native adapters is the control path. Published plans and grants feed Gateway execution. Worker admission freezes a plan and run authority before the native client calls Gateway. Observation records what actually ran and supplies authorized reads and continuation.
LocalControlAdapter remains a broad assembly facade. Follow its focused runtime
module before extending it; a local feature does not require a facade-wide rewrite.
Model sources and native configuration
Custom API target normalization is pure for HTTP and HTTPS, retaining the configured hostname until bounded request transport resolves it. Explicit LAN/remote HTTP uses the ordinary check/save flow. The durable target and user-configured Gateway target admit the same explicit transports while retaining exact credential destinations and the separate registered/managed-connector scopes. Control error translation retains closed target reasons in the existing error envelope; the Desktop form owns localized corrections and plaintext notices. The real-process regression covers omitted-directory save/restart/recheck and safe error propagation.
Branch execution keys distinguish reasoning selections. The derived Gateway candidate also retains its original source binding for current credential membership and exact leases; routing, retry and context identities continue using the execution key.
CLI secret entry uses the shared local protected input socket
in both standalone and Desktop-owned role=all processes. The CLI input owner
reads inherited descriptors; ordinary control requests never carry secret bytes.
All current hosts and the CLI resolve its logical hiroute/input.sock endpoint through host-runtime.
Windows maps it to a private named pipe bound to the held runtime directory and account SID;
it does not create a filesystem socket. Follow native ownership.
The name must fit any runtime root that supports hiroute/control.sock, including macOS.
| User step | Owners to follow | Representative guard |
|---|---|---|
| Add an API connection and choose its models | Connection directory, form and draft ownership, registered check | The executable catalog supplies the complete directory. A source name survives check/save; per-product credentials stay in the dialog and protected input. Released public registered probes may omit the name and use the authenticated option label; the current Desktop check requires an explicit label. |
| Discover a native source without executing it | Native model connections, Pi reader, DSH reader, OpenCode reader, Hermes reader | Shared point grouping keeps scope/provider/address/protocol/authentication distinct; static scan never executes helpers |
| Display, prepare and save the selected source | Safe shared product projection, V2 points/catalog qualification, daemon preparation | Exact native/catalog provenance and explicit model selection remain visible; privileged locators stay private; stale facts cannot expand an accepted selection; legacy one-model handles retain their meaning |
| Rename a connection, append models or remove saved configuration | Shared lifecycle planner, transactional reference guards, Desktop lifecycle dialog | Templates do not own credentials. Explicit append preserves saved members; enabled/disabled routes and retained recovery versions block removal. Removing the last model requires explicit connection deletion; owned secrets follow the same recoverable operation. |
| Save Key order or use current Keys with an older plan | Single-save edits, request admission, current pool authority, safe Key masks | A request owns its admitted Key IDs and order; later exact leases enforce current source/Key eligibility and generation. Admission retains closed permission denials in the existing request summary. Shared Plan content stays frozen. Masks are a separate authenticated query; saved plaintext never reaches Desktop. |
| Connect a native Codex or Claude subscription | Source discovery, credential adapters, shared lifecycle, provider runtimes | Native clients retain refresh authority; only access leases enter isolated CPA instances. Claude Keychain interaction is limited to an explicit check; discovery reads metadata only. Codex borrowing reads file storage only and rejects a configured non-file store even if stale auth.json remains. |
| Locate a slow subscription validation condition | Stock discovery/pin loop, pin facts, CPA discovery facts, troubleshooting | Condition regressions and isolated live probe distinguish unmet pins; private metadata admission observes upstream phase, reason and timing from the pinned CPA, retaining the first failure without logging account identities. |
| Sign in independently to a Codex or Claude subscription | Shared login control, protected lifecycle, private sessions, Desktop sign-in | CPA receives browser callbacks on temporary loopback listeners; an unavailable listener uses explicit protected manual input. Login is separate from Check/Save and routing. Daemon maintenance owns pending completion/expiry, and saved revisions own runtime selection. The pinned CPA adapter owns callback admission, authorization and refresh. |
| Lease a subscription credential without blocking Gateway workers | Async adapter, request budget, admission and observations, Claude identity resolution | Bounded provider executors own compatibility I/O. Short admission updates revoke before lifecycle work; identity lookup runs outside the lifecycle owner. Cancellation and saved revisions guard later publication. Follow concurrency regressions for races with disable, replacement and delayed I/O. |
| Inspect saved subscription mode and repair sign-in | V3 query, mode and repair copy | Mode derives from the committed source selection and survives missing credentials. Desktop consumes V3; published V2 queries retain their strict response shape. Existing release-version matching still applies; an external service without V3 requires an update. |
| Configure a subscription connection proxy | Device scan, inline proxy editor, native apply | Scan retains results while editing; cancel restores its actions, and explicit save/restart returns to a fresh scan. Settings has no proxy entry; host policy remains shared by all subscriptions. |
| Make a saved source usable by a plan | Capability qualification, candidate materialization, compiler | Native-observed facts retain source-local authority and budgets; unavailable candidate reasons are read-only and never execution facts. Upstream model values use the shared opaque-ID rule; internal references remain strict |
| Distinguish a missing subscription candidate from a runtime outage | Exact candidate projection, source authorization, provider discovery | Resolve the requested provider from the trusted connection option. Its discovery error remains Unavailable; a best-effort aggregate list cannot establish that a selected source is absent. |
| Configure models and collaboration independently | Shared settings transaction, typed native facts, native provider guide | Native defaults, model grants, installed Skills and conditional restore have distinct owners |
| Project native reasoning settings | Wire types, daemon renderer, Gateway reader and wire normalization | Keep one field/path/toggle definition; materializer → compiler → Gateway tests cover accepted aliases |
Native configuration precedence belongs to each reader. For example, Pi provider
baseUrl overrides inherited catalog addresses, while provider api defaults apply
only to explicit models; filesystem tests
cover that distinction. DSH module replacement and credential-store precedence
are located in the native composition guide.
Do not move either rule into a generic provider merge.
Model settings status joins owned native configuration with the current Gateway endpoint as well as grant/publication evidence. Its opt-in effective-state projection uses existing Observation queries and authenticated receipts with the same current Plan/publication/grant identity. It does not infer loading from saved files, persist new state, restart Agents or send inference requests. CLI listener status uses that read and, for unconfigured/restored targets, the released V1 connection join to request explicit reconfiguration; listener operation history alone does not establish Agent convergence. Port selection belongs to the shared listener store, including Desktop.
Follow discovery through an ordinary request using the saved source. The Pi, DSH and OpenCode acceptance entries cover Scan → Prepare → Save → restart → native use, including stale-source rejection.
The shared product-session layer in crates/product-session owns Preview composition, confirmation permits, retry identity and protected-input lifetime. Desktop supplies its inherited-channel HostAuthority adapter in apps/desktop/src-tauri/src/bootstrap/authority.rs; native startup, updater and window authority stay with the Desktop host.
Native recovery completes
only the exact outstanding acknowledgement on the existing inherited channel,
then transfers the running child to a fresh product session. It never restarts the
daemon or pauses work. Old confirmations and authority remain invalid; malformed
or closed channels fail closed. Status separates reachability from protected authority.
State and lifecycle boundaries
| Boundary | Invariant | Read next |
|---|---|---|
| Agent settings | Configure/Edit seals service state before the file tail. Ordinary Disable conditionally restores files before withdrawing grants; conflicts preserve foreign edits and require the appropriate fresh operation or exact retry. | Transaction, ordering tests |
| Native target registration | An unused discovered target is not access authority or a global startup dependency. Actual access and accepted-operation recovery retain path identity and safe-write checks; OS I/O determines accessibility. | Registration tests, startup journey |
| Operation journal | Domain checkpoints and stored journals agree before publication or native effects; immutable plan bytes and generation/identity guards remain authoritative. JSON member ordering is distinct from a content change. | Checkpoint, verification, transaction guards |
| Managed credential rollback | Authenticate the exact compensated Secret before converging source references under the same writer. Forward generations and source/workspace revisions reject stale authority; the atomic receipt makes restart idempotent. | Coordinator, Secret proof, Control receipt |
| Reference refresh | A checkpoint copies verified installed routing authority at the next revision through the normal publication writer. Preview pins revisions and content; disabled routes, drafts and held versions remain deletion blockers. | Strict checkpoint, shared entry, installed-state facts |
| Profile deletion | Untouched proof binds the current store instance and exact marker; a stage directory alone cannot prove deletion never began. | Profile lifecycle |
| Worker/content lifetime | Result completion, process stop, body availability and permission to Continue are separate facts; cleanup requires exact ownership. | Worker map, managed-text contract |
| Recovery and compatibility | Current producers have one ingestion contract. Startup presenters prefer the current attempt's typed facts over an older writer's report; the Windows shell binds manager-start failures to a diagnostic boot/sequence watermark captured before startup. Registered legacy revoke tails retain their own ordering; frozen fixtures alone do not establish production upgrade support. | Startup admission, upgrade recovery action, host failure facts, daemon failure projection, legacy-tail tests, compatibility registry |
Observation and conversation boundaries
| Concern | Owner | What callers must preserve |
|---|---|---|
| Native Agent session correlation | Gateway identity resolver, native input guide | One identity feeds ContextHold, decision history and observation; native IDs precede content inference, malformed or conflicting claims remain request-scoped |
| Configured Agent attribution | Publication join, persistent grant/session projection | New authenticated writes resolve the exact grant generation to its server-owned Agent; rotation/restoration preserve prior attribution, conflicting Agents stay unlinked, and old receipt rebuilds do not backfill identity. Startup uses verified historical candidates best-effort; missing current proof stays unlinked without blocking journal recovery, and restoration registers completed ownership. Activation stays strict |
| Named tool decision facts and request receipts | Strict Gateway adapter, Product tool choice, receipt writer | Preserve callable kind and name; Product's implicit Function encoding preserves historical digests. Each completed HTTP request closes independently of an unfinished Agent turn; boundary regressions cover all tool choices |
| Lifecycle acceptance of empty response end-stream frames | Transport acceptance capture, Product lifecycle validation, bounded receiver | Successful zero-byte end-stream writes are real operational events with a zero byte count; identity remains strict. Receiver regressions preserve continuous ACK through RequestFinished |
| Capture completeness | Content completeness, session query | Aggregate every required request/direction; a finished stream or readable preview does not prove the session is complete |
| Windows service logs | CLI log reader, held diagnostic directories | Read only the daemon writer's current and newest rotated log through existing held directories; settings, keys, reparse points and hardlinks cannot supply log content |
| Streaming memory | Capture, pending delivery | Decoder, projector and delivery tracker share the stream budget; queue capacity is not capture evidence |
| Reported token usage | Response driver, completion facts, capture tracker | Nonstream completion retains known usage before request termination; capture records content without duplicating it. Follow the Gateway guide for streaming ownership. |
| Upstream fault attribution | Wire projection, attempt association, decision calls | Actual bounded model/control fields, negotiated HTTP protocol, closed error codes, hashed request IDs and separate client headers/body commit facts must preserve the real outcome without prompts or provider error text |
| Source disabled before an upstream attempt | Exact permission gate, product preparation reply, Gateway error guide | Preserve the closed lease denial in the request fact and local JSON response; a frozen route does not grant current source/Key permission, and rejected preparation remains zero attempts |
| Inspect CPA authentication recovery | Private response metadata, pinned CPA adapter | Logical attempts and actual HTTP sends differ; only verified CPA targets can supply recovery counters. Missing evidence remains unknown and does not create token usage. |
| Same-user CLI analysis | Read admission, scoped analysis, CLI codec, installed journey | Conversation, switch/reason, expense ranking and savings paths share retained scopes; control/price composition and indexed content reads keep one 500 ms budget. Supplied grants, current deletion/visibility and legacy calls remain checked. |
| Recorded request estimates | Captured price snapshot, source/execution mapping, Gateway freeze, installed price regression | Resolve exact source identity in one pinned generation; a configured API-equivalent estimate can fill unavailable billing prices while preserving its label, partial usage and frozen history. |
| Current API-equivalent comparison | Analysis price capture, numeric comparison, legacy adapter | Source-matched attempt inputs and immutable scoped prices use the same per-attempt arithmetic as the explicit-reference report. Unknown coverage is not zero; recorded valuation remains unchanged. |
| Native compression and actual transitions | Hermes adapter, private carrier, relationship owner, transition reader | Authenticated bounded ancestry does not change physical session identity or prove adjacent user turns. Shared member resolution and current source/deletion guards apply to content and monetary readers. |
| Analysis upgrades and deleted-history revival | Schema/SQL triggers, native creation proof, joint deletion regression | Core-table triggers also execute for supported released writers; replace dependent triggers/tables atomically. Full deletion cuts historical edges. Fresh native creation evidence can prove a new child after the cut; unknown origins remain gaps. Strict retained native-event bodies exclude the optional creation extension. |
| Search and gaps | Live session search, query contract, keyword lookup | Fresh authorized pages count matching sessions; bounded background backfill and explicit gaps distinguish pending indexes from complete empty results. The released occurrence-search interface remains separate. |
| Business relations and visibility | Relation owner, managed content | query_v2 also writes relations; every content read checks current authorization and visibility |
| Native tool-history continuation | Responses ingress, real continuation journey | Preserve model-generated empty tool names in native history without relaxing declarations/call IDs; unsafe conversion, ContextHold and reasoning cleanup stay disabled for that history |
| Decision and competence attribution | Decision observation map | Attribute scores to the stage that actually ran, with its frozen category/group/candidate and rubric |
Changing boundaries
Compact Observation format admission and fresh-generation initialization belong to
store/upgrade and the
store factory; complete original-source
preservation remains in the existing
startup coordinator.
The sealed-source publisher
uses same-filesystem directory publication without traversing historical contents.
The optional capacity threshold uses the
existing maintenance lifecycle and
bounded retirement owner.
Representative scenarios cover
format admission,
interrupted sealing,
production startup/restart,
and shared survivors and rollback.
Operating and recovery details are in the
Observation guide.
Windows process defaults and private handle validation belong to
native security, with suspended-child
initialization in the Job launcher.
The CPA private-object leaf uses those
primitives for managed files. The borrowed native reader
retains external file identity and permission facts through access-lease admission;
it preserves readable native ACLs instead of adopting managed-file permissions.
Follow these owners for elevated-account defaults or third-party file creation.
The Windows Apps registration exporter
admits a controlled reg.exe export under a held private temporary directory;
the existing child Job gives that process private user-SID defaults. Its explicit
environment binds both temporary-directory variables to the same private stage,
so standard-user export never depends on the Windows-directory scratch fallback. It
then publishes complete bytes with protected private permissions. A repeated
preparation must match the retained export; changed material is preserved and
refused. Unpublished system output never occupies a final recovery filename.
Native client gates select the installed, pinned producer through
Windows acceptance. Ordinary Agent
recipes and official Qoder account recipes have separate inventories; the latter
borrow an explicitly prepared private profile and never obtain account authority
from pull-request environment secrets.
Stopped Windows source snapshots preserve native permissions through
streamed backup copying
and the durable stage owner; the
native descriptor owner
restores creation-recomputed DACL control on the unpublished held stage before
exact permission verification. Native artifact
activation uses a sealed-file transition; it does not reopen read-only payloads
for data writes or clear a target's attributes before replacement.
Windows Agent configuration and restoration reads share the
artifact snapshot reader.
Its read lease retains all
reparse-free ancestors and the regular file while bounded bytes, native identity
and permissions are checked. Native targets keep their existing size limits and
borrowed ACLs; private restore files additionally require their private owner.
Worker New and Continue compare ordinary and verbatim directory spellings through
the existing native workspace identity.
The managed profile and
retained root reader
still require the recorded marker, volume/file identity and complete ancestry.
Keep a change with the owner that can enforce it. Extend a native leaf for a real ecosystem difference; reuse settings, admission, lifecycle and observation owners. Built-in decision models and custom branches are implemented in the decision map; tool selection remains protocol-only.
Before extracting or consolidating code, identify the user scenario, state owner and unique failure assertions. Keep recovery, cancellation, authorization and foreign-file preservation tests. Assign shared contracts and generated registries to one convergence owner. Use the test map to select evidence; neither file size nor test churn alone justifies another abstraction or a broad rewrite.
Trial cost reads use the internal admitted TrustCostScopeV1, joining retained analysis stage identity to Plan/revision/category/group before calling the shared per-attempt comparison engine. Evidence-gap scenarios distinguish partial history from conflicting membership, pending projections from unresolved turns, and conservative coverage from paired subtotals. They preserve the general value query and frozen settlement contracts. The Desktop timeline reconciles absorbed provisional rows using returned request membership; focused presentation checks cover selection, actual focus transfer without stealing focus, and partial monetary subtotals. Live timeline transition presentation adapts the same endpoint/time membership and classifier used by retained analysis; cache mutexes cover only taking and returning snapshots, never SQL or projection. Real reader exhaustion and CLI follow verify the structured failure boundary and retry recovery.
Session detail separately refreshes the selected summary and visible unresolved excerpts; turn-fact digests do not describe body availability. Live refresh scenarios cover delayed content, stale responses and cleanup. Current summary visibility and successful cleanup govern cached titles and request excerpts even when cleanup removes every catalog row; new requests do not revive cleared request content. Timeline presentation scenarios cover exact assessment identities, transient-read recovery and fixed-label geometry. The transition adapter coalesces only redundant intermediate comparisons proven by the same completed turn endpoints; shared retained-analysis classification and recorded facts remain authoritative.
Complete official data and saved default intent
The feed service owns complete snapshot selection, semantic/publication floors and retrieval. Admission qualifies installed execution without discarding descriptive records. The shared capability resolver joins saved intent and exact current endpoint/product facts; price projection uses the same scope with the existing valuation engine. Source preference persistence shares source revisions, effect activation and compensation. The metadata query owner and removal preview provide bounded complete reads. The Desktop directory keeps field inference visible and loads source/rule details against that same captured snapshot. The feed producer checks embedded semantic identity against HEAD and the supplied baseline before release gating. Hosts use product-session; published execution remains in its existing owner.