# How the Apache Maka Runtime Package Handles Sessions and Tools

> Discover how the Apache Maka runtime package enforces session boundaries, persists state with SQLite snapshots, and manages tool lifecycles via a scoped ToolRuntime registry for secure execution.

- Repository: [The Apache Software Foundation/maka](https://github.com/apache/maka)
- Tags: internals
- Published: 2026-09-10

---

**The Apache Maka `runtime` package isolates every execution context through session-boundary enforcement, persists state via SQLite-backed snapshots, and manages tool lifecycle through a scoped `ToolRuntime` registry that validates ownership on every read operation.**

The `runtime` package serves as the execution kernel of Apache Maka, orchestrating how AI agents interact with external tools while guaranteeing strict session isolation. By combining immutable session headers, transient execution boundaries, and persistent archiving keyed by `sessionId`, the runtime ensures that concurrent sessions remain completely isolated and that every tool invocation remains traceable to its originating context.

## Session Management Architecture

### Session Identity via SessionHeader

Every execution context in Maka begins with a `SessionHeader` defined in [`packages/core/src/session.ts`](https://github.com/apache/maka/blob/main/packages/core/src/session.ts). This immutable structure carries the canonical session identifier, human-readable metadata, and role-based access flags that persist for the lifetime of the session.

According to the source code, the header contains:

- `id`: The immutable unique identifier for the session
- `name`: A human-readable label for UI display
- `role`: The execution role (e.g., *user*, *assistant*, *deep-research*)
- Status flags including `isArchived` and `status`

In [`packages/core/src/session.ts`](https://github.com/apache/maka/blob/main/packages/core/src/session.ts) (lines 241-262), the `SessionHeader` interface defines the contract that all runtime components use to verify session context:

```typescript
// packages/core/src/session.ts
interface SessionHeader {
  id: string;
  name: string;
  role: 'user' | 'assistant' | 'deep-research';
  isArchived: boolean;
  status: 'active' | 'suspended' | 'terminated';
  createdAt: number;
}

```

### Execution Boundaries with SessionBoundary

When the runtime initiates a new turn (a single unit of work), it creates a `SessionBoundary` object that couples the persistent `SessionHeader` with transient execution identifiers. As implemented in [`packages/core/src/runtime-boundary.ts`](https://github.com/apache/maka/blob/main/packages/core/src/runtime-boundary.ts), this boundary tracks the current `turnId` and `runId`, enabling the runtime to enforce that every read or write operation belongs to the active session.

The boundary acts as a security context passed through the execution stack. Any attempt to access resources outside the boundary triggers a `session_mismatch` error, preventing cross-session contamination during concurrent operations.

### Persistence and Snapshotting

The runtime maintains session state durability through SQLite-backed snapshots defined in [`packages/storage/src/runtime-event-persistence.ts`](https://github.com/apache/maka/blob/main/packages/storage/src/runtime-event-persistence.ts). At periodic intervals and state transitions, the runtime writes a complete snapshot containing:

- Current working directory
- Environment variables
- Active tool registry state
- Pending asynchronous operations

In [`packages/storage/src/runtime-event-persistence.ts`](https://github.com/apache/maka/blob/main/packages/storage/src/runtime-event-persistence.ts) (lines 84-112), the snapshot logic ensures that remote hosts and UI clients can resume exact session states:

```typescript
// packages/storage/src/runtime-event-persistence.ts
async function persistSessionSnapshot(sessionId: string) {
  const snapshot = {
    sessionId,
    workingDirectory: process.cwd(),
    env: process.env,
    activeTools: await getActiveToolsForSession(sessionId),
    timestamp: Date.now()
  };
  await db.run(
    'INSERT INTO session_snapshots (session_id, payload) VALUES (?, ?)',
    [sessionId, JSON.stringify(snapshot)]
  );
}

```

### Session Ownership Enforcement

All artifacts generated during a session—files, tool outputs, and transcript entries—carry the originating `sessionId`. The runtime enforces ownership at the read layer in [`packages/runtime/src/tool-result-archive-capability.ts`](https://github.com/apache/maka/blob/main/packages/runtime/src/tool-result-archive-capability.ts) (lines 94-101), where any read request undergoes validation:

```typescript
// packages/runtime/src/tool-result-archive-capability.ts
async function readToolResult(sessionId: string, resultId: string) {
  const record = await archive.get(resultId);
  if (record.sessionId !== sessionId) {
    throw new Error('session_mismatch: Cannot access result from another session');
  }
  return record.payload;
}

```

This validation guarantees that even if result identifiers were leaked or guessed, sessions cannot access data belonging to other contexts.

### Session Lifecycle Events

The runtime publishes a durable event stream through [`packages/core/src/runtime-event-store.ts`](https://github.com/apache/maka/blob/main/packages/core/src/runtime-event-store.ts), emitting typed events such as `session_start`, `session_end`, `turn_started`, and `turn_completed`. Downstream consumers—including the desktop inspector, TUI interface, and remote runtime hosts—subscribe to these streams to synchronize UI state and persist audit logs.

## Tool Management and Execution

### Tool Registration and Session Binding

Tools in Maka consist of a static `ToolDefinition` and a dynamic `ToolRuntime`. The runtime implementation in [`packages/runtime/src/tool-runtime.ts`](https://github.com/apache/maka/blob/main/packages/runtime/src/tool-runtime.ts) (lines 166-190) binds each tool instance to a specific session during construction:

```typescript
// packages/runtime/src/tool-runtime.ts
class ToolRuntime {
  constructor(
    public readonly definition: ToolDefinition,
    public readonly sessionId: string,
    public readonly mode: 'spawn_session' | 'singleton'
  ) {}
  
  async invoke(params: unknown, turnId: string): Promise<ToolResult> {
    // Execution scoped to this.sessionId
  }
}

```

The `mode` parameter determines whether the tool spawns a sub-session for sandboxed execution or runs as a singleton shared within the parent session boundary.

### Session-Scoped Tool Availability

Not all tools are available to all sessions. The `ToolAvailability` module in [`packages/runtime/src/tool-availability.ts`](https://github.com/apache/maka/blob/main/packages/runtime/src/tool-availability.ts) (lines 58-71) filters the global tool registry to return only tools where `tool.sessionId === currentSession.id` or tools explicitly marked as global utilities.

```typescript
// packages/runtime/src/tool-availability.ts
function getAvailableTools(sessionHeader: SessionHeader): ToolRuntime[] {
  return globalToolRegistry.filter(tool => 
    tool.sessionId === sessionHeader.id || tool.scope === 'global'
  );
}

```

This prevents sessions from discovering or invoking tools intended for other execution contexts.

### Tool Invocation Flow

When a turn requires tool execution, the runtime creates a `ToolInvocation` record that injects the current `sessionId`, `turnId`, and `toolCallId` into the request payload. The [`web-search-tool.ts`](https://github.com/apache/maka/blob/main/web-search-tool.ts) implementation (lines 37-78) demonstrates this pattern:

```typescript
// packages/runtime/src/web-search-tool.ts
async function invokeWebSearch(
  query: string, 
  context: ToolInvocationContext
): Promise<ToolResult> {
  const invocationRecord = {
    sessionId: context.sessionId,
    turnId: context.turnId,
    toolCallId: generateUUID(),
    query,
    timestamp: Date.now()
  };
  
  // Execution occurs within session boundary
  const results = await executeSearch(query);
  
  await archiveToolResult(invocationRecord, results);
  return results;
}

```

### Result Archiving and Supersession

Tool outputs persist in the `tool-result-archive` ([`packages/runtime/src/tool-result-archive.ts`](https://github.com/apache/maka/blob/main/packages/runtime/src/tool-result-archive.ts), lines 130-158), keyed by the composite identifier `{sessionId}:{turnId}:{toolCallId}`. The archive supports *supersession*, allowing new results to replace previous outputs while maintaining an audit trail:

```typescript
// packages/runtime/src/tool-result-archive.ts
async function archiveToolResult(
  key: { sessionId: string; turnId: string; toolCallId: string },
  payload: unknown,
  supersededBy?: string
) {
  await db.run(
    `INSERT INTO tool_results 
     (session_id, turn_id, tool_call_id, payload, superseded_by) 
     VALUES (?, ?, ?, ?, ?)`,
    [key.sessionId, key.turnId, key.toolCallId, JSON.stringify(payload), supersededBy]
  );
}

```

### Runtime Policy Enforcement

Tools requiring elevated capabilities (network access, credential usage) must pass policy validation. The `runtime-policy-proxy` in [`packages/runtime-host/src/server/runtime-policy-proxy.ts`](https://github.com/apache/maka/blob/main/packages/runtime-host/src/server/runtime-policy-proxy.ts) intercepts tool invocations and validates that the session's policy bundle contains required capability tags before allowing execution to proceed.

## Summary

- **Session Isolation**: Apache Maka enforces strict boundaries through `SessionHeader` identities and `SessionBoundary` contexts, preventing cross-session data leakage.
- **Ownership Validation**: Every tool result read operation validates `sessionId` ownership in [`tool-result-archive-capability.ts`](https://github.com/apache/maka/blob/main/tool-result-archive-capability.ts), rejecting unauthorized access with `session_mismatch` errors.
- **Durable State**: The runtime persists session snapshots to SQLite via [`runtime-event-persistence.ts`](https://github.com/apache/maka/blob/main/runtime-event-persistence.ts), enabling exact session replay and remote host synchronization.
- **Scoped Tool Access**: Tools bind to specific sessions during registration, and the `ToolAvailability` module filters tool sets to prevent unauthorized discovery.
- **Policy Enforcement**: The `runtime-policy-proxy` validates capability requirements before allowing tool execution, ensuring security policies govern all external operations.

## Frequently Asked Questions

### How does the runtime package prevent sessions from accessing each other's data?

The runtime enforces session ownership at the persistence layer. In [`packages/runtime/src/tool-result-archive-capability.ts`](https://github.com/apache/maka/blob/main/packages/runtime/src/tool-result-archive-capability.ts) (lines 94-101), every read request compares the requesting `sessionId` against the recorded owner of the artifact. If the identifiers do not match, the system throws a `session_mismatch` error, effectively isolating session data by design rather than by convention.

### What is the difference between a SessionHeader and a SessionBoundary?

The `SessionHeader` (defined in [`packages/core/src/session.ts`](https://github.com/apache/maka/blob/main/packages/core/src/session.ts)) represents the persistent, immutable identity of a session, including its ID and metadata. The `SessionBoundary` (from [`packages/core/src/runtime-boundary.ts`](https://github.com/apache/maka/blob/main/packages/core/src/runtime-boundary.ts)) is a transient object created for each turn that couples the `SessionHeader` with ephemeral identifiers like `turnId` and `runId`, creating a complete security context for a single unit of work.

### How does the runtime handle tool results that need to be updated or corrected?

The runtime implements result supersession in [`packages/runtime/src/tool-result-archive.ts`](https://github.com/apache/maka/blob/main/packages/runtime/src/tool-result-archive.ts). When a tool re-runs within the same session, the new result receives a reference to the previous result's ID in the `superseded_by` field. This creates an immutable audit chain while surfacing only the latest valid result to the consumer, enabling deterministic replay of session histories.

### Can tools be shared across multiple sessions in Apache Maka?

Tools can operate in two modes defined in [`packages/runtime/src/tool-runtime.ts`](https://github.com/apache/maka/blob/main/packages/runtime/src/tool-runtime.ts): `spawn_session` (sandboxed) or `singleton` (shared within a session). However, strict isolation prevents sharing tool instances across different `SessionHeader` IDs. Global utilities must explicitly declare `scope: 'global'` in their definition and still undergo policy validation through the `runtime-policy-proxy` before cross-session execution.