# How Maka Manages OAuth Subscriptions and Determines Execution Authority

> Discover how Apache Maka manages OAuth subscriptions and execution authority using its runtime subsystem and Agent Graph Coordinator for efficient session control and token retrieval.

- Repository: [The Apache Software Foundation/maka](https://github.com/apache/maka)
- Tags: how-to-guide
- Published: 2026-08-27

---

**Apache Maka uses a dedicated runtime subsystem to store, refresh, and validate OAuth subscriptions, while a single process-local Agent Graph Coordinator serves as the sole execution authority that decides which sessions run and retrieves fresh tokens via the subscription subsystem.**

Apache Maka treats OAuth-based model access as first-class subscriptions managed independently from execution logic. The runtime maintains these credentials through a secure lifecycle that handles parsing, atomic storage, and automatic refresh, while the **Agent Graph Coordinator** acts as the gatekeeper that determines exactly which Session-backed agent graphs may execute and when they must stop.

## OAuth Subscription Lifecycle

The `@maka/runtime` package isolates all OAuth handling from UI or storage layers, implementing a complete credential lifecycle in [`packages/runtime/src/subscription-credentials.ts`](https://github.com/apache/maka/blob/main/packages/runtime/src/subscription-credentials.ts).

### Parsing and Validation

Raw JSON payloads from providers are parsed into strongly-typed **`OAuthSubscriptionTokens`** objects via the `parseOAuthSubscriptionTokens` function. Invalid payloads are rejected immediately to prevent corrupted credentials from entering the system. The runtime enforces **`OAUTH_MAX_TOKEN_CHARS`** to limit token length for safety.

### Secure Storage and Atomic Updates

Tokens persist in a credential store implementing the **`OAuthSubscriptionCredentialStore`** interface. This store uses `compareAndSetSecret` for atomic updates, ensuring that racing refresh operations cannot corrupt the stored state. Subscriptions are stored with the `oauth_token` kind, allowing the runtime to distinguish them from other secret types.

### Token Resolution and Refresh

When a model request requires authentication, the `resolveOAuthSubscriptionTokens` function retrieves the stored secret and checks expiration against the system clock. If the token is near expiry—defined by the **`TOKEN_REFRESH_SKEW_MS`** grace period—the runtime calls `refreshAndPersistOAuthSubscriptionTokens`. This helper contacts the provider’s token endpoint, validates the response, and atomically swaps the old token for the new one.

The high-level helper **`resolveOAuthSubscriptionAccessToken`** (lines 56–61 in [`subscription-credentials.ts`](https://github.com/apache/maka/blob/main/subscription-credentials.ts)) returns only the `access_token` string to callers, transparently triggering refresh logic when needed.

### Error Handling for Invalid Grants

Deterministic OAuth errors such as `invalid_grant` and `invalid_token` are recognized by the `isDeterministicOAuthCredentialRejection` helper in [`packages/runtime/src/oauth-login.ts`](https://github.com/apache/maka/blob/main/packages/runtime/src/oauth-login.ts). When these errors occur, the runtime clears the stored token from the credential store, forcing a re-login flow rather than retrying with stale credentials.

## Execution Authority and the Agent Graph Coordinator

According to [`ARCHITECTURE.md`](https://github.com/apache/maka/blob/main/ARCHITECTURE.md) (line 24), Maka explicitly declares: *“Maka has one execution authority: Runtime Host.”* This single-authority design eliminates race conditions by ensuring exactly one component decides which Session work executes.

### Single Process-Local Authority Design

The **`AgentGraphCoordinator`** class in [`packages/runtime/src/stream-graph-coordinator.ts`](https://github.com/apache/maka/blob/main/packages/runtime/src/stream-graph-coordinator.ts) serves as the process-local execution authority for Session-backed agent graphs. There is exactly one coordinator per host process, which owns *single-flight wake-ups* and *cancellation handles*. While persistent schedule and topology data belong to the recovery authority, the coordinator is the runtime authority that actually drives execution.

### Integration with OAuth Subscriptions

When dispatching a model request, the coordinator does not manipulate OAuth state directly. Instead, it calls into the subscription subsystem—typically via `runtimePolicy` helpers that invoke `resolveOAuthSubscriptionAccessToken`—to obtain a fresh bearer token. The coordinator then injects this token into request headers using utilities like `openAiCodexHeaders` from [`subscription-auth.js`](https://github.com/apache/maka/blob/main/subscription-auth.js). This separation ensures that the execution authority remains agnostic to credential storage while guaranteeing that every request carries valid authentication.

### Lifecycle Control Methods

The `AgentGraphCoordinatorInput` interface exposes methods that give the authority full control over Session lifecycles:

- **`stopSession`** – Initiates graceful shutdown of a running Session graph.
- **`acquireResidency`** – Claims execution rights for a Session on the current host.
- **`onError`** – Handles error reporting and determines whether to restart or terminate a Session.

These methods ensure that the coordinator alone decides when work starts, stops, or recovers.

## Practical Implementation: Accessing OAuth-Enabled Models

The following pattern demonstrates how the coordinator retrieves tokens and builds authenticated headers for external model calls:

```typescript
import {
  resolveOAuthSubscriptionAccessToken,
  type OAuthSubscriptionProvider,
} from '@maka/runtime/subscription-credentials.js';
import { openAiCodexHeaders } from '@maka/runtime/subscription-auth.js';

async function getHeaders(
  slug: string,
  credentialStore: OAuthSubscriptionCredentialStore,
) {
  // Retrieve and auto-refresh the access token
  const token = await resolveOAuthSubscriptionAccessToken({
    providerType: 'openai-codex' as OAuthSubscriptionProvider,
    slug,
    credentialStore,
  });

  // Build headers with Bearer token
  return token ? openAiCodexHeaders(token) : {};
}

async function callCodexModel(
  payload: unknown,
  slug: string,
  credentialStore: OAuthSubscriptionCredentialStore,
) {
  const headers = await getHeaders(slug, credentialStore);
  // Perform fetch with authenticated headers...
}

```

The `resolveOAuthSubscriptionAccessToken` function guarantees that the returned token is valid, triggering background refresh if the stored credential is within `TOKEN_REFRESH_SKEW_MS` of expiry.

## Key Source Files

- **[`packages/runtime/src/subscription-credentials.ts`](https://github.com/apache/maka/blob/main/packages/runtime/src/subscription-credentials.ts)** – Core OAuth parsing, validation, storage, resolution, and refresh logic.
- **[`packages/runtime/src/oauth-login.ts`](https://github.com/apache/maka/blob/main/packages/runtime/src/oauth-login.ts)** – Token endpoint communication and deterministic error classification.
- **[`packages/runtime/src/stream-graph-coordinator.ts`](https://github.com/apache/maka/blob/main/packages/runtime/src/stream-graph-coordinator.ts)** – Defines the `AgentGraphCoordinator` process-local execution authority.
- **[`packages/runtime/src/subscription-auth.js`](https://github.com/apache/maka/blob/main/packages/runtime/src/subscription-auth.js)** – Header generation utilities like `openAiCodexHeaders`.
- **[`ARCHITECTURE.md`](https://github.com/apache/maka/blob/main/ARCHITECTURE.md)** – High-level authority design documentation.

## Summary

- **OAuth subscriptions** are versioned credentials managed by a dedicated runtime module that handles parsing, atomic storage, and lazy refresh via `refreshAndPersistOAuthSubscriptionTokens`.
- **Execution authority** is centralized in the `AgentGraphCoordinator`, a single process-local component that owns Session lifecycle decisions and never directly mutates OAuth state.
- The coordinator requests fresh tokens from the subscription subsystem when dispatching model calls, ensuring valid authentication without coupling execution logic to credential management.
- This architecture provides **consistency**, **atomicity**, and a **single-source-of-truth** for both credential handling and session execution across the Maka platform.

## Frequently Asked Questions

### How does Maka handle expired OAuth tokens during active sessions?

When the `resolveOAuthSubscriptionAccessToken` helper detects a token nearing expiry (within `TOKEN_REFRESH_SKEW_MS`), it automatically invokes `refreshAndPersistOAuthSubscriptionTokens` to contact the provider’s token endpoint and atomically update the stored credential. Active sessions receive the refreshed token on their next request without interruption.

### What happens when an OAuth provider returns an invalid_grant error?

The `isDeterministicOAuthCredentialRejection` function in [`packages/runtime/src/oauth-login.ts`](https://github.com/apache/maka/blob/main/packages/runtime/src/oauth-login.ts) identifies `invalid_grant` and `invalid_token` as deterministic failures. Upon detection, the runtime clears the stored token from the `OAuthSubscriptionCredentialStore` using `compareAndSetSecret`, forcing the user to re-authenticate rather than retrying with invalid credentials.

### Can multiple processes share execution authority in Maka?

No. According to [`ARCHITECTURE.md`](https://github.com/apache/maka/blob/main/ARCHITECTURE.md), Maka enforces a single execution authority per Runtime Host. The `AgentGraphCoordinator` is process-local and owns exclusive rights to wake-ups and cancellation handles for Session-backed agent graphs, preventing race conditions that would occur if multiple processes claimed authority over the same Session work.

### Where does the Agent Graph Coordinator obtain OAuth tokens for model requests?

The coordinator retrieves tokens indirectly via the subscription subsystem. It calls high-level helpers like `resolveOAuthSubscriptionAccessToken` (defined in [`packages/runtime/src/subscription-credentials.ts`](https://github.com/apache/maka/blob/main/packages/runtime/src/subscription-credentials.ts)), which abstracts the credential store and refresh logic. The coordinator then passes the returned token to utilities like `openAiCodexHeaders` to construct the `Authorization: Bearer` header for the HTTP request.