Repository navigation
Description
Summary
Build one authoritative Omi Agent Runtime Contract for every local agent surface and adapter. Centralize identity, context, lifecycle, authorization, output budgeting, failure semantics, retries, cancellation, and conformance tests in the kernel. Keep Swift/UI code and provider adapters as projections and wire translators.
This is a P1 reliability architecture issue. Recent macOS QA exposed the same structural class repeatedly:
- typed chat and PTT could diverge or lose shared context across turns/barge-ins;
- provider reconnect races could launch a fallback after the realtime turn already owned the commit;
- a routine
list_agent_sessionsresponse grew to roughly 620 KB because it included persisted run input and surface context, then caused Gemini Live to close the voice socket; - provider- and surface-specific paths duplicated tool handling, permission behavior, retry decisions, and result formatting;
- small test stubs passed while production-shaped state failed at runtime.
These are not isolated provider bugs. They are symptoms of agent policy being spread across the Node kernel, Swift surfaces, provider adapters, and individual call sites.
Product fit
- Fits the memory-first loop: Capture → Understand → Remember → Retrieve → Act
- Primary loop layer: Intelligence / Retrieval-Action
- Strengthens the locked agent control-plane invariant
Architecture decision
Centralize contracts and policy, not implementations
Language-neutral Agent Contracts
ContextSnapshot
ToolInvocation / ToolResultEnvelope
PermissionDecision
Session / Run / Attempt / Turn lifecycle
Failure taxonomy
Output / retry / cancellation policies
↓
Authoritative Omi Agent Kernel
identity, journals, authorization, idempotency,
lifecycle, delegation, artifacts, reconciliation
↓
Thin Adapter SDK
pi / ACP / OpenClaw / Hermes
Gemini / OpenAI realtime
↓
Surface projections
typed chat / PTT / task chat / pills
The Node runtime under desktop/macos/agent/src/runtime remains the local authority for now. Contracts that cross into Swift must be generated from a language-neutral schema or validated against shared fixtures.
Do not create a generic Swift AgentManager, move authority into pi, or let every adapter invent its own lifecycle. Pi and other mature harnesses should inform execution ergonomics, but Omi continues to own product identity, continuity, permissions, and durable state.
Non-negotiable rules
- One owner per fact. Session/run/attempt/tool/turn status has one authoritative state machine. UI state is a projection.
- Providers propose; the kernel authorizes. Possessing a tool name, opaque reference, or provider call ID is never execution authority.
- Context is versioned data, not prompt assembly. Typed chat, PTT, task chat, and delegated agents consume kernel-built immutable snapshots with explicit freshness identities.
- Every side effect is idempotent and cancellable. Turn, tool, delegation, permission, journal, and artifact operations carry stable identities.
- All tool output is bounded for the model and preserved for inspection. Full output never rides blindly over a provider transport.
- Adapters translate wire formats only. They do not decide continuity, retry/fallback eligibility, permission policy, or terminal success.
- No silent semantic fallback. Fallbacks use the shared telemetry contract and may only run when the original owner has released the operation.
- Production-shaped fault tests are required. Tiny happy-path stubs are not sufficient coverage.
Priority 1 — Canonical tool-result envelope and artifact retrieval
Create a shared result contract similar to:
interface ToolResultEnvelope {
version: 1;
status: "succeeded" | "failed" | "cancelled";
modelProjection: unknown; // bounded, provider-safe data
fullOutputRef?: string; // kernel-owned opaque artifact reference
originalBytes: number;
projectedBytes: number;
truncated: boolean;
continuation?: {
cursor?: string;
supportsRead: boolean;
supportsSearch: boolean;
};
error?: AgentFailure;
provenance: {
invocationId: string;
runId?: string;
attemptId?: string;
toolName: string;
};
}Required behavior:
- list tools return compact rows and pagination, never full run input, context, result, or metadata;
- detail tools are explicit (
get_agent_run, artifact inspection, etc.); - shell/log/file output returns a bounded head/tail or semantic summary plus a full-output reference;
- add kernel-authorized
read_tool_output(ref, offset, limit)andsearch_tool_output(ref, pattern)operations; - preserve full output locally according to an explicit retention policy;
- provider boundaries enforce an absolute byte ceiling and return a valid error/reference envelope rather than slicing JSON;
- voice receives a short semantic projection; chat can receive a larger projection without changing the canonical result.
Initial budgets should be explicit and centrally configurable:
- voice projection target: 2–4 KiB;
- ordinary model result target: 16–32 KiB;
- absolute provider transport ceiling: 48–64 KiB;
- full output: artifact-backed, subject to storage/retention policy.
Budget by UTF-8 bytes and, where useful, estimated model tokens. Never silently truncate: expose truncated, byte counts, and continuation.
Priority 2 — One continuity and context contract
- Treat the conversation journal as the shared typed-chat/PTT history.
- Build one immutable, versioned
ContextSnapshotper accepted run/turn. - Record source outcome as
available | empty | unavailable | redacted; do not collapse unavailable into empty. - Carry snapshot ID, owner generation, surface, conversation, and recent-turn boundary through every async continuation.
- Barge-in creates or supersedes a typed turn; it must not independently reconstruct context.
- Provider reconnect must preserve the pending turn or terminalize it explicitly.
- Late events from a prior turn/session/generation are dropped by identity, not timing heuristics.
- Context compaction is deterministic and provenance-preserving.
Typed chat and PTT must pass the same continuity fixtures. Surface-specific prompt construction should be deleted as each path migrates.
Priority 3 — Typed lifecycle, failures, retries, and cancellation
Define shared state machines for:
AgentSession;AgentRun;RunAttempt;ToolInvocation;VoiceTurn;Delegation;- permission/grant requests;
- artifact production and delivery.
Define a bounded failure taxonomy used by every adapter and surface:
- authentication;
- quota/rate limit;
- invalid provider request;
- incompatible capability/model;
- transport interruption;
- timeout;
- cancellation;
- stale owner/turn/generation;
- policy rejection;
- malformed or oversized tool result;
- adapter unavailable;
- unknown.
Retry/fallback policy must consume typed failures and lifecycle state. It must specify:
- retryability;
- maximum attempts and elapsed deadline;
- backoff;
- whether context/session may be reused;
- whether the user sees degraded behavior;
- whether fallback is legal;
- terminal state and telemetry.
Cancellation propagates UI turn → run → attempt → adapter → tool/subprocess. Late completion cannot mutate state after revocation.
Priority 4 — Thin adapter SDK and conformance gauntlet
Every local/provider adapter must implement the same narrow interface:
- capability declaration and compatibility handshake;
- open/resume binding;
- execute;
- stream normalized events;
- cancel;
- normalize failures;
- report usage;
- expose transport health.
Create one adapter conformance kit with fake clocks and deterministic fault injection. Run it for pi, ACP, OpenClaw, Hermes, Gemini Realtime, and OpenAI Realtime where applicable.
Required scenarios:
- five or more sequential turns retaining context;
- typed chat → PTT → typed chat continuity;
- barge-in during capture, provider response, playback, and tool execution;
- repeated fast PTT presses during reconnect/session replacement;
- duplicate, reordered, delayed, and missing provider events;
- oversized list, shell, JSON, and artifact results;
- missing/malformed provider tool-call IDs;
- tool timeout and cancellation with late completion;
- permission request/grant/denial from both typed chat and PTT;
- directed delegation to each supported adapter;
- adapter/model incompatibility;
- process crash/restart and prepared/dispatched reconciliation;
- owner sign-out/sign-in generation replacement;
- retry exhaustion and legal fallback;
- successful kernel tool paired with failed provider continuation;
- truthful UI terminal status when underlying work failed.
Fixtures must include production-shaped databases: dozens of sessions/runs, multi-megabyte persisted context, long outputs, slow tools, and concurrent calls.
Priority 5 — Generated cross-language contracts
Create one source of truth for:
- protocol envelopes and versions;
- tool descriptors and input schemas;
- capability/risk/privacy/approval metadata;
- lifecycle enums;
- failure codes;
- result envelopes;
- output policy identifiers.
Generate or validate:
- TypeScript runtime types;
- Swift wire types and provider declarations;
- adapter capability manifests;
- protocol fixtures.
The runtime compatibility handshake must advertise contract version and required capabilities. Unsupported or stale combinations fail closed at startup.
Avoid a code-generation project before the behavioral contracts above exist. Begin with schemas plus golden fixtures; generate progressively where duplication is proven.
Observability requirements
One correlation chain must connect:
surface turn
→ context snapshot
→ provider request/session
→ tool invocation
→ run/attempt
→ artifact/result
→ rendered/spoken response
Record bounded, non-sensitive fields:
- owner generation hash/scope, not raw personal content;
- surface, provider, adapter, model/capability profile;
- turn/run/attempt/invocation correlation IDs;
- state transition and previous state;
- raw/projected byte counts and truncation;
- retry/fallback decision and reason;
- cancellation/revocation phase;
- provider close/failure category;
- outcome and latency.
Do not log prompts, tool output, screen data, memories, or raw provider error bodies.
Tests and CI
Add a manifest-owned, diff-scoped agent contract lane:
- pure state/policy tests;
- protocol and golden-fixture tests;
- adapter conformance tests;
- hermetic cross-surface continuity gauntlet;
- focused named-bundle smoke for changed Desktop agent/PTT paths.
Every regression fix must add a behavioral fixture through a controllable production seam. Source-text assertions may remain only as labeled static ratchets.
Keep fast focused tests available for local QA. Full conformance and production-shaped suites can be CI/PR gates rather than blocking every named-bundle iteration.
Recommended implementation order
- Land
ToolResultEnvelope, compact list contracts, full-output artifacts, read/search continuation, and provider byte backstop. - Route typed chat and PTT through the same kernel context/journal snapshot contract.
- Consolidate lifecycle/failure/retry/cancellation policy behind typed state machines.
- Extract the adapter interface and make existing adapters pass the shared gauntlet one at a time.
- Introduce schema/golden-fixture generation and delete duplicated Swift/provider declarations.
- Make later backend/mobile/cloud work in Deferred agent coordinator expansion after Desktop paradigm lands #8652 consume these proven contracts.
Each phase should be a reviewable PR or child issue with migration coverage. Do not attempt a flag-day runtime rewrite.
Explicit non-goals
- Replacing the Omi kernel with pi or any external harness.
- A new Swift lifecycle authority.
- Rewriting every adapter in one PR.
- Moving the local agent control plane to the cloud.
- General cross-device/backend expansion tracked by Deferred agent coordinator expansion after Desktop paradigm lands #8652.
- Increasing prompt/context size as a substitute for retrieval.
- Returning raw internal IDs or complete tool JSON to users.
- Silent output loss or provider-specific ad hoc truncation.
- Model-assisted routing before deterministic lifecycle/policy tests pass.
Definition of done
- All model-visible tool results use the canonical envelope and central output policy.
- Oversized output is artifact-backed, inspectable, and cannot tear down a provider session.
- Typed chat and PTT share the same journal/context snapshot and pass cross-surface continuity/barge-in tests.
- Lifecycle, retry, fallback, cancellation, and failure semantics have one authoritative typed owner.
- Every supported adapter passes the shared conformance suite for its declared capabilities.
- Swift/provider adapters no longer implement independent semantic policy.
- Cross-language protocol/tool contracts are generated or checked against canonical schemas/fixtures.
- Correlated telemetry makes every provider/tool/run transition diagnosable without sensitive payloads.
- The locked
INV-AGENT-*docs and behavioral guards reflect the final contract. - Deferred agent coordinator expansion after Desktop paradigm lands #8652 references and consumes this contract before backend/mobile/cloud expansion begins.
Activity
Git-on-my-level commentedon Jul 14, 2026
Parent/executor issue: #9688 — binds this issue and its siblings into one PR (Swift shadow-state census, bridge-lifecycle fuzzer, contract fixtures, adapter conformance, anti-regrowth guards) with per-child closure criteria. Sequenced after the PTT stability PR (post-#9660) to reuse its kernel-restore seam and fixture conventions.
hegu-1 commentedon Jul 14, 2026
This is very close to the control-plane boundary I would want: centralize contracts and policy, keep adapters as projections, and enforce one owner per fact.
The acceptance suite is where this becomes durable. I would add cross-adapter negative fixtures for:
Each fixture should assert the same kernel state, receipt, and UI projection across pi, ACP, OpenClaw, Hermes, and realtime providers. That proves adapters translate rather than govern.
I would also make generated Swift/UI state explicitly rebuildable from the authoritative journal so a regression cannot create a second truth surface.
This CI-validated enterprise AI OS adoption kit uses the same pattern: contracts, per-layer acceptance checklists, fictional production fixtures, and executable governance checks: https://github.com/hegu-1/enterprise-ai-os-architecture
fix(macos): converge agent runtime contracts (BasedHardware#9698)