# @mono-agent/runtime-adapter

Use this package when a typed host needs mono-agent's stable runtime facade
without importing provider-kernel internals.

## Category

<!-- package-metadata:start -->
<!-- Generated by scripts/generate-package-docs.mjs. Do not edit by hand. -->

Category: `runtime`
Tier: `core`
Catalog responsibility: Wraps @mono-agent/agent-runtime behind runtime contracts and owns sandbox policy/process wrapping.

<!-- package-metadata:end -->

## Responsibility

Typed runtime facade over `@mono-agent/agent-runtime`. It parses and validates canonical `<provider>:<model>` runtime model references, describes the single Pi backend and its capabilities, owns sandbox policy/process wrapping, bridges the kernel's structural process-job controller to a typed neutral host interface, creates a runtime wrapper, and exposes a small structural runtime contract to the harness.

## Install / Usage

```bash
pnpm add @mono-agent/runtime-adapter
```

<!-- doc-test:typescript -->

```ts
import {
  createMonoRuntime,
  parseMonoRuntimeModelReference,
} from "@mono-agent/runtime-adapter";

const model = parseMonoRuntimeModelReference("openai:gpt-5.5");
const runtime = createMonoRuntime({ workspace: process.cwd() });
const result = await runtime.run("You are a concise assistant.", {
  model,
  messages: [{ role: "user", content: "Summarize README.md." }],
  abortSignal: new AbortController().signal,
  cwd: process.cwd(),
  allowedTools: ["Read"],
});

if (result.error) throw new Error(result.error);
console.log(result.text);
```

Use this package when a TypeScript host needs the mono-agent runtime contract.
The process-job start contract carries optional `wakeOnCompletion` (default
true), and `RuntimeRunOptions.processJobsAvailability` carries request lineage
diagnostics independently of the optional start controller.
Use `@mono-agent/agent-runtime` directly only when the host deliberately owns
the lower-level sandbox injection and provider-kernel integration.
Set `RuntimeRunOptions.piToolExecutionMode` to `"sequential"` when every Pi
tool must serialize, or leave the default `"safe-parallel"` mode to overlap
only independent read-only built-ins. Stateful, mutating, and MCP tools remain
sequential in the default mode.

Trusted hosts running with process sandboxing off can extend the managed
filesystem tools beyond `workspace` with `additionalReadRoots` and
`additionalWriteRoots` on `CreateMonoRuntimeOptions`. Writable roots are also
readable. These roots apply to `Read`, `Write`, `Edit`, `Glob`, and `Grep`; they
do not sandbox arbitrary shell commands. Both lexical and resolved real paths
must remain within an additional root, preventing symlink escapes. When a
native sandbox policy is active, its readable and writable roots remain the
authoritative boundary.

Provider-owned project discovery no longer applies: the Pi runtime does not read
another tool's filesystem settings, hooks, or project documents. The five
options that carried that behaviour on the deleted bridges —
`settingSources`, `codexLoadProjectDocs`, `codexSandboxNetworkAccess`,
`fastMode`, and `nativeSubagents` — are declared `?: never` on
`RuntimeRunOptions`, so passing one is a compile error rather than a silently
ignored field. There is no replacement for project-document loading; put
repository instructions in the system prompt the host builds.

The supported equivalents are:

- Filesystem and network containment: `RuntimeRunOptions.sandboxPolicy`
  (with `sandboxEngine`). `sandboxPolicy.network.mode` is `none`, `localhost`,
  `allowlist`, or `all`, and a request-scoped policy can only tighten the
  configured one.
- Delegation: the in-process `Agent` tool, which the host configures through
  the kernel's `subagents` run option that the facade forwards, rather than
  caller-defined native teammate profiles.

For fallback chains, `resolveAttempt().policyOptions` may project only
`allowedTools`, `disallowedTools`, and `permissionMode` for the route actually
being attempted. Every other logical request field remains protected and cannot
be replaced through `resolveAttempt().options`.

`RuntimeRunOptions.providerAttributionSessionId` is a host-owned continuity key
for provider attribution, not permission to resume provider transcript state.
`MonoRuntimeLike.recoverSession(receipt, { appliedInputIds })` forwards optional
host-coordinated durable terminal recovery. `RuntimeRunOptions.sessionRecovery`
opts in with run id and canonical revision; `RuntimeResult.providerSessionRecovery`
proves the exact session/model/tip after successful native close. Recovery appends
nothing and returns false when the tail cannot be proven safe. It does not change
the durable history record format.

The agent harness supplies the active provider-session epoch automatically for
continuous conversations and protects it from route-attempt overrides. Direct
runtime callers that need attribution continuity across calls must reuse a safe,
opaque value; otherwise Pi-native creates a fresh per-run value.

`RuntimeRunOptions.toolLifecycleSink` is the typed incremental persistence seam
for managed tools. It receives an invocation with stable call id/name,
and redaction-eligible arguments, then exactly one result
with `success`, `rejected`, `error`, `exit_nonzero`, `timeout`, `signal`,
`cancelled`, or `interrupted`, an existing observability failure kind, optional
detail/duration, bounded-content input, and host artifact paths. The awaited
return exposes only stable record/sequence, persistence and truncation/byte
metadata, and opaque artifact references. Hosts should make this sink
idempotent: a retry of an identical phase returns the same record and a
conflicting retry fails rather than overwriting history.

`RuntimeRunOptions.persistArtifact` is the synchronous, host-owned artifact
sink for oversized tool blocks. A per-run value overrides the kernel host
default. Fallback route-attempt resolvers cannot supply or replace it.

## Architecture

`MonitorStartRequest` carries optional `wakeOn`, `dedupe`, and
`minWakeIntervalMs`; `MonitorStartResult` reports the effective values.
`MonitorControllerLimits.maxWakeIntervalMs` publishes the host interval cap.
The bridge rejects malformed policy and nondefault dedupe/interval with exit-only
wakes. Defaults remain batch/none/0.

`runtime-adapter` is the typed boundary between harness code and the JavaScript
provider kernel:

### Data flow

1. Model helpers parse a `<provider>:<model>` reference and assert its parsed
   shape and canonical spelling.
2. `createMonoRuntime()` injects the mono-agent sandbox implementation exactly
   once, then constructs either one runtime or an ordered fallback router.
3. `MonoRuntimeLike` exposes `run()`, consumption-aware live-input messages, an
   awaited incremental tool-lifecycle sink, tool reconfiguration, and bounded
   provider session lifecycle methods to `agent-harness`.
4. Local-provider and MCP helpers translate host config into provider-neutral
   runtime options without importing channel or application code.
5. `bridgeProcessJobsController()` validates host limits and adapts the typed
   process-job controller to the kernel's JSDoc-only structural shape.

Live-input callbacks separate native queue acceptance (`accepted`), exact
transcript consumption (`acknowledge`), uncertain terminal delivery
(`uncertain`), and proved-safe attempt rejection (`reject`). Callback return
types are `unknown` for source compatibility; only exact synchronous
`recorded` and `ignored` literals confirm host handling. Thenables are never
awaited. Stable nonblank IDs enable replay across route attempts; anonymous
input remains legal but is never replayed. A host that independently fences
callback leases may attach one opaque `logicalOwner` object to every fresh
lease of the same message. The runtime keeps the first occurrence's immutable
body and ID, refreshes callbacks only when that exact object matches, and still
suppresses unrelated same-ID callback owners.

### Package structure

| Source file | Responsibility |
| --- | --- |
| `src/runtime-adapter.ts` | Model parsing, backend descriptors, facade construction, and fallback routing |
| `src/types.ts` | Structural runtime, result, event, live-input, approval, and session contracts |
| `src/sandbox*.ts` | Sandbox policy, managed SRT integrity, and command wrapping |
| `src/local-providers.ts` | Ollama, LM Studio, and OpenAI-compatible provider validation/discovery |
| `src/mcp-servers.ts` / `src/runtime-policies.ts` | MCP normalization and legacy-policy migration |
| `src/process-jobs.ts` | Typed host controller, kernel-shape bridge, launch/result contracts, and conformance boundary |

## Public API

### Start here

| API | Use it for |
| --- | --- |
| `createMonoRuntime()` | Construct the typed runtime facade and inject mono-agent's sandbox implementation |
| `parseMonoRuntimeModelReference()` | Parse and validate a canonical model string |
| `listMonoRuntimeBackends()` / `describeMonoRuntimeSupport()` / `monoRuntimeSupportsLiveInput()` | Present backend capabilities and compatibility without starting a provider |
| `createSandboxPolicy()` / `failClosedSandboxPolicy()` | Build explicit filesystem and network policy data |
| `discoverLocalProviderModels()` / `runtimeOptionsForLocalProvider()` | Validate and project a configured local Pi provider |
| `parseMcpServers()` | Normalize HTTP, SSE, and stdio MCP server definitions |
| `RuntimeToolLifecycleSink` and event/persistence types | Bind one host-owned durable lifecycle writer without importing provider internals |
| `bridgeProcessJobsController()` / `ProcessJobsController` | Inject a typed host-owned process-job controller without making the kernel import workspace contracts |

The generated inventory below is exhaustive; the table above is the recommended
consumer entry path.

<!-- public-api-inventory:start -->
<!-- Generated by scripts/generate-public-api-docs.mjs. Do not edit by hand. -->

Every symbol exported by each public code entrypoint is listed below.

**`@mono-agent/runtime-adapter`**

```text
AgentRuntimeCustomModel
AgentRuntimeCustomProvider
CodedError
CreateMonoRuntimeOptions
DEFAULT_DENY_WRITE
DiscoverLocalProviderModelsOptions
DiscoverLocalProvidersInput
DiscoveredLocalModel
DiscoveredProvider
LocalProviderCapabilities
LocalProviderDefinition
LocalProviderModelDefinition
LocalProviderPricing
LocalProviderRuntimeOptions
LocalProviderType
MANAGED_SRT_TREE_SHA256
MODEL_REFERENCE_ECHO_MAX_BYTES
MODEL_REFERENCE_REASON_MAX_BYTES
ModelEffortLevels
MonitorControllerLimits
MonitorLaunchOptions
MonitorProcessHandle
MonitorProcessResult
MonitorStartRequest
MonitorStartResult
MonitorStopResult
MonitorsController
MonoRuntimeApprovalDecision
MonoRuntimeApprovalRequest
MonoRuntimeAttemptContext
MonoRuntimeAttemptResolution
MonoRuntimeAttemptResolver
MonoRuntimeBackendCapabilities
MonoRuntimeBackendDescriptor
MonoRuntimeCompactionRecord
MonoRuntimeFallbackChainEntry
MonoRuntimeHostOptions
MonoRuntimeLike
MonoRuntimeParsedPricingModel
MonoRuntimePricing
MonoRuntimeRetryPolicy
MonoRuntimeSandboxEngine
MonoRuntimeSupportDescription
NormalizedMcpServer
NormalizedMcpTransport
PI_TRANSPORTS
PiTransport
PrepareSandboxedCommandInput
PreparedSandboxCommand
ProcessJobLaunchOptions
ProcessJobProcessHandle
ProcessJobProcessResult
ProcessJobStartRequest
ProcessJobStartResult
ProcessJobsController
ProviderDefinition
RuntimeAdapterError
RuntimeAdapterErrorCode
RuntimeAdapterErrorDetails
RuntimeCompactionPolicy
RuntimeEventLike
RuntimeLiveInputCallbackDisposition
RuntimeLiveInputEvidence
RuntimeLiveInputMessage
RuntimeLiveInputUncertainty
RuntimeMcpAppConnection
RuntimeMcpAppHost
RuntimeMcpAppRegistration
RuntimeMessage
RuntimeModelReference
RuntimePolicies
RuntimePromptOverrides
RuntimeResult
RuntimeRunOptions
RuntimeSubagentActivityEvent
RuntimeSubagentActivityPhase
RuntimeSubagentIdentity
RuntimeToolLifecycleEvent
RuntimeToolLifecyclePersistence
RuntimeToolLifecycleSink
RuntimeToolLifecycleTerminalState
RuntimeToolLimits
RuntimeToolOptions
SANDBOX_FALLBACKS
SANDBOX_MODES
SANDBOX_NETWORK_MODES
SandboxCommandSpec
SandboxEffectiveMode
SandboxEffectiveState
SandboxEngine
SandboxEngineId
SandboxErrorCode
SandboxFallback
SandboxMode
SandboxNetworkMode
SandboxNetworkPolicy
SandboxNetworkPolicyInput
SandboxPolicy
SandboxPolicyError
SandboxPolicyInput
SandboxPolicyRuntimeOptions
SandboxUnavailableError
SrtFilesystemSettings
SrtNetworkSettings
SrtSandboxEngineOptions
SrtSettings
assertParsedRuntimeModelReference
bridgeMonitorsController
bridgeProcessJobsController
createMonoRuntime
createPiOAuthApiKeyResolver
createSandboxPolicy
createSrtSandboxEngine
describeMonoRuntimeSupport
describePiBuiltinProvider
describeSandboxEffectiveState
discoverLocalProviderModels
discoverLocalProviders
failClosedSandboxPolicy
inspectCodexSubscriptionSearch
isAutodiscoverableProviderId
isCodedError
isPiBuiltinProvider
isPlainObject
isPrivateBaseUrl
isRuntimeSubagentActivityEvent
isValidMcpServerName
listMonoRuntimeBackends
listPiBuiltinProviders
localProviderDefinitionFor
managedSrtInstallRoot
mergeSandboxPolicies
modelReferenceKey
monoRuntimeSupportsLiveInput
monoRuntimeSupportsMcpApps
monoRuntimeSupportsSessionResume
networkPolicyAllowsUrl
parseMcpServers
parseMonoRuntimeModelReference
prepareSandboxedCommand
protectSandboxRoots
resolveModelEffortLevels
resolveRuntimePolicies
resolveSandboxEffectiveState
runtimeBackendForModel
runtimeOptionsForLocalProvider
sandboxEffectiveStateWarning
sandboxPolicyToRuntimeOptions
sandboxRequired
sanitizeModelReferenceText
srtSettingsForPolicy
validateLocalProviderDefinition
validateProviderBaseUrl
validateProviderDefinition
```

<!-- public-api-inventory:end -->

There is exactly one runtime seam:

| Runtime | Model refs | Boundary |
| --- | --- | --- |
| Pi provider | `<provider>:<model>` | Pi gateway through `@mono-agent/agent-runtime`, including provider ids such as `openai-codex`, `anthropic`, `github-copilot` and `opencode-go` |

The kernel's in-process delegation surface requires `Agent` in an effective
allow-all policy, so restrictive named allowlists fail before provider startup.

Native and in-process delegation paths emit the exact
`RuntimeSubagentActivityEvent` shape: `subagent.id` is the canonical parent
attachment key (normally the initiating parent tool-use id, with a stable
synthetic fallback for orphan lifecycle records), while optional `nativeId` and
`agentPath` retain provider correlation metadata. Its
`RuntimeSubagentActivityPhase` phases are `agent_started`, `started`,
`completed`, `message`, and `agent_completed`; child `message` activity is never
parent answer text or a tool completion. `RuntimeEventLike` remains permissive
for other provider telemetry; use `isRuntimeSubagentActivityEvent()` to narrow
an open event before consuming the required normalized fields.

### ACP

The ACP *client* runtime backend was removed in 0.21.0. `mono-agent bridge acp`
— serving ACP to clients — is unaffected and remains supported.

## Dependency Boundary

This is the only facade package that depends on `@mono-agent/agent-runtime`. Other packages consume its small `MonoRuntimeLike` interface, backend descriptors, and sandbox policy helpers instead of importing provider/runtime internals.

## What This Package Does Not Own

It does not build prompts, manage memory, expose UI, poll communication channels, or persist observability artifacts.

## Related Documentation

- [Runtime and providers](https://mono-agent-docs.vercel.app/runtime/) explains the normal
  config-first path.
- [Backends and model references](https://mono-agent-docs.vercel.app/runtime/backends/)
  documents the five bridge selections surfaced by this facade.
- [Local providers](https://mono-agent-docs.vercel.app/runtime/local-providers/) covers
  Ollama, LM Studio, and compatible gateways.
- [Sandboxing](https://mono-agent-docs.vercel.app/tools/sandbox/) describes the policy that
  this package validates and enforces through managed SRT.
- [`@mono-agent/agent-runtime`](https://github.com/robertsreberski/mono-agent/tree/main/packages/agent-runtime)
  owns the underlying provider kernel.

## Verification

```bash
pnpm --filter @mono-agent/runtime-adapter run build
pnpm --filter @mono-agent/runtime-adapter run typecheck
pnpm --filter @mono-agent/runtime-adapter run test
```
