@tangle-network/agent-provider-cli-bridge
Wraps a running cli-bridge server as an AgentEnvironmentProvider.
import { createCliBridgeProvider } from '@tangle-network/agent-provider-cli-bridge'
const provider = createCliBridgeProvider({
baseUrl: 'http://127.0.0.1:8787',
bearerToken: process.env.CLI_BRIDGE_TOKEN,
defaultExecution: {
kind: 'host',
jail: { mode: 'fs-jail' },
},
})
const environment = await provider.create({
profile: {
name: 'researcher',
harness: 'codex',
model: { default: 'gpt-5' },
},
})
const reference = await environment.dispatch({
prompt: 'inspect the repository',
sessionId: 'research-session',
executionId: 'research-turn-1',
})
await saveControlRef(reference.controlRef)
const session = environment.session(reference.id)
for await (const event of session.events({ since: '0' })) {
// Sequence-numbered bridge events, including normalized usage and result data.
}
await session.prompt({
prompt: 'change direction using the evidence already collected',
executionId: 'research-turn-2',
})
Persist the returned controlRef before treating dispatch as accepted.
It contains the exact provider, environment, session, execution, run, and request digest needed after a process restart.
Reconstruct the environment with provider.get(controlRef.environmentId), then call environment.session(controlRef.sessionId, { controlRef }).
The provider rejects any coordinate or digest mismatch instead of attaching to a different run.
If the caller crashes before saving controlRef, call provider.lookupRun() with the planned run coordinates.
The lookup returns the server-issued digest only when all five planned coordinates match the retained run.
Which call adds a turn
Creation, a rebuild by the creating provider, ordinary reconstruction and accepted transfer attachment have different admission authority.
In the process that created the environment, environment.dispatch(), environment.stream(), and session.prompt() all add a turn.
Passing the same sessionId continues the same CLI conversation.
While the environment is not destroyed, provider.get(environmentId) on the provider instance that created it rebuilds the environment from the recorded create input.
The rebuilt environment carries the create metadata and adds a turn through the same three calls, so dispatching a turn identity the Bridge already holds reattaches to that run.
On any other provider instance, and after the environment is destroyed, provider.get(environmentId) reconstructs the environment from its identifier alone, and only session.continueNative(request, { turn }) can add a turn.
It requires the nativeContinuation capability, which the provider publishes only for the Pi harness today, and only when the running Bridge proves the same contract.
The reconstructed environment deliberately refuses every other way to start work: environment.stream(), environment.dispatch() and session.prompt() throw "a reconstructed cli-bridge environment cannot start a turn through" followed by the name of the call.
A reconstructed environment for any other harness therefore controls its existing runs (status, cursor replay, result, cancellation, and interaction responses) but adds no turn.
When the exact deployed route confirms contextTransfer.attach, provider.get(environmentId, { contextTransfer: request }) instead attaches the accepted transfer's first turn. The request must carry its exact profile. The adapter looks up the canonical operation, requires an available matching receipt for that environment, and returns it as environment.contextTransferReceipt. The resulting dispatch, stream and session.prompt accept only that request and its destination identities. They do not allocate another environment or replace a missing one. Changed context or profile fails before dispatch; a missing or uncertain receipt refuses attachment. Destroying this reconstructed handle closes its readers without canceling the accepted destination's runs.
The capability document keeps sessions.continue: true on a reconstructed environment because the Agent Interface couples that flag to retainedControl: a document that reports sessions.continue: false while keeping retained run control fails AgentEnvironmentCapabilitiesSchema with "retained control requires exact run, result, event, cancellation, replay, detach, turn, and session identity together".
nativeContinuation states whether an ordinary reconstructed environment supports continueNative. It does not authorize the first turn of a separate transfer.
A runtime caller continues a retained run with RetainedRunHandle.continueNative, not with startRetainedRunInEnvironment.
startRetainedRunInEnvironment proves ownership through the metadata on the environment provider.get() returns and then calls environment.dispatch(), so it needs the provider instance that created the environment; a reconstructed environment carries no metadata and refuses that dispatch.
The bridge model is selected from run data in this order: the turn, the provider default, or the profile's harness plus model.default.
Execution fails before network use when none is present.
defaultExecution is the existing cli-bridge execution request object.
The provider forwards it unchanged to the Bridge session or chat request.
Host execution accepts jail, netJail, timeoutMs, and acquireTimeoutMs.
acquireTimeoutMs is how long a turn may wait for a Bridge executor slot before the Bridge answers executor_saturated; the Bridge caps it at its own ceiling, and without it a turn waits the Bridge default.
A caller whose work queues behind its own turns, such as a graph map wider than the host's slots, sets it so those turns wait instead of failing; MAX_CLI_BRIDGE_TIMEOUT_MS is the largest value the Bridge accepts.
Sandbox execution accepts repoUrl, gitRef, capability, ttlSeconds, netJail, and timeoutMs.
The Bridge validates the object and applies its operator confinement rules.
Retained native sessions currently require kind: 'host'.
The provider rejects a sandbox default before it creates the retained session; use one-shot execution for kind: 'sandbox'.
The Bridge currently refuses netJail with kind: 'sandbox'; use the sandbox's own egress policy.
Runtime attachments
The create input's runtimeAttachments travel in the Bridge's runtime_attachments field on every one-shot request and on the retained session.
A turn names its own attachments in providerOptions.backend.runtimeAttachments, as Agent Runtime does when it dispatches into an environment it reloaded by id.
The provider sends those in the same runtime_attachments field, with the turn's servers replacing the environment's servers of the same alias.
The rest of the turn's providerOptions goes into metadata on a one-shot request and into provider_options on a retained turn.
The Bridge validates a secret-ref header such as Authorization only in runtime_attachments, and refuses metadata or provider options that contain a credential-bearing key.
A retained turn's attachments apply to the native process that turn starts.
Native workspace cwd
CLI Bridge accepts workspace.cwd only when its base is "host".
Its path is a native host process directory, so it may be absolute or empty.
The adapter rejects a repository-based cwd before it sends a Bridge request.
Tangle Sandbox accepts workspace.cwd with base: "repository" and a portable POSIX path.
The capability document reports these supported cwd bases under workspace.cwdBases.
Passing the same sessionId on later turns continues the same CLI conversation while the creating process still holds the environment.
executionId gives a turn stable bridge identity, and lastEventId reattaches after a reader failure.
dispatch() starts a bridge-owned durable run and returns after detaching its HTTP reader.
The returned AgentSession exposes status, cursor-based event replay, the terminal result, continuation, and cancellation.
Cancellation returns only after cli-bridge confirms the run is terminal.
A direct stream treats a finish frame as provisional until cli-bridge returns the same run's aggregate result.
A retained replay confirms its terminal state from the retained run endpoint.
Terminal results retain the newest 1,024 events and preserve full text and usage totals.
Use session.events() when a caller needs the complete retained event history.
Retained native runs use canonical runtime envelopes and finish with a terminal status event.
Pass any emitted event id back as since to resume after that event.
The canonical envelope identity remains available as event.data.eventId.
Legacy runs keep the OpenAI chunk format and its [DONE] marker.
The provider uses the explicit SSE event field to select the format and rejects mixed streams.
The provider rejects a terminal response when its run id or request digest does not match the accepted stream.
Usage events and terminal result metadata include modelRequests only when the bridge measured an exact non-negative integer count.
Missing, malformed, partial, or estimated request counts remain unknown.
metadata.model and event data.model retain Bridge's compatibility response value; they do not prove which model served a request.
Explicit provider-response observations appear as provider_models in event data and result metadata.
provider_model is present only for one distinct observation, and never on a failed result.
The collector retains disagreements independently of its bounded result event history; overflow or malformed evidence refuses certification.
Requested routes, init records, fingerprints, configured session models and application JSON never establish provider identity.
Opaque native records remain in their existing envelope and cannot promote their own fields into host evidence.
On the qualified OpenAI wire path, raw Bridge usage is retained in event.providerEvent.usage even when a partial receipt cannot form TokenUsage.
metadata.provider_usage folds those receipts outside the bounded event history: a missing count stays unknown across later deltas, and a cumulative receipt replaces counts and coverage.
Events declare this distinction with the existing usageMode field.
Measured usage requires explicit estimated: false and valid reported input and output totals; estimated: true is an estimate, and absent provenance remains unknown.
Observed zero is retained. Missing cache classes and cost remain unknown; cost_scope applies only to cost.
The numeric result.usage compatibility projection alone does not certify complete measured usage.
Old peers and opaque canonical native envelopes remain readable with uncertified provenance; nested native or application records cannot assert host observation authority.
When dispatch() receives no sessionId, it creates one from that turn's stable run id and returns it.
Replay and result reads fail loudly after cli-bridge's configured replay retention expires.
Stopping a session.events() reader detaches only that replay observer.
Stopping a direct environment.stream() reader or destroying the environment cancels its active bridge runs and waits for terminal confirmation.
Destroying an environment does not close a native Bridge session that has reached a terminal result.
For a one-shot Pi session, call closeExactCliBridgeSession(options, controlRef) after reading the result.
The provider verifies the exact run and session before it closes the session.
Repeat cleanup of the same closed session succeeds without sending another close request.
Keep the controlRef from durable admission so a process restart can perform the same cleanup.
Pi retained sessions also expose typed permission interactions and native continuation.
The provider stores the selected harness, exact model route, and canonical create digest inside its opaque environment identifier.
This identifier lets provider.get() reconstruct profile-selected routes after process death without a cache or repeated configuration.
The create digest prevents an altered profile or workspace from reusing the previous retained identity.
An accepted portable-context destination can supply its exact environment identifier through requestedId.
The provider recovers that caller-owned route from cli-bridge's durable transfer receipt.
An unknown caller-owned identifier returns null.
provider.capabilities() queries /v1/capabilities for the configured default route before the Runtime selects retained execution.
provider.create() queries a Pi route and a route provider.capabilities() already queried; any other create sends no query and, without an explicit capability document, publishes no retained control.
provider.get() queries the route of each environment it restores, except that an environment rebuilt by the provider that created it keeps the document create resolved from the Bridge.
The provider shares concurrent discovery requests and refreshes every later query.
It enables retained control only when the running Bridge proves the complete contract.
It enables native interactions only when the running Bridge proves the Pi contract.
Every native turn stays on the model route used for that discovery; another model requires another environment.
An explicit capability document remains available for a caller that already performed the same discovery.
That capability selects cli-bridge's native /v1/sessions and /turns transport; it never sends an interactive turn to /v1/chat/completions.
The environment and session then expose respondToInteraction() for exact response commands.
Each command carries its run, session, execution, request digest, and stable operation identifier.
Native turns require caller-stable turnId and executionId values so an ambiguous admission cannot create another run.
The bridge records repeated operations and rejects a different answer for an existing operation.
Repeating one operation identifier returns its stored acknowledgement; a new operation identifier for an interaction that is already resolved returns already_resolved_same when the answer matches and already_resolved_different when it does not, and answering an interaction that a run cancellation closed returns cancelled.
The expired acknowledgement stays in the contract, but the Bridge never emits it, so only the unit contradiction table covers it.
The provider reports an unconfirmed network result as retryable and never reports it as accepted.
Native replay reads /v1/runs/:runId/events and validates each canonical envelope through Agent Interface before exposing it.
When a turn supplies interactions, the provider carries its exact map, including an explicit {}; an omitted map remains omitted.
Every requested key must be advertised by the selected environment, including keys set to false; an unsupported key fails before transport use.
One-shot requests keep this posture as a top-level interactions field rather than moving it into metadata.
The cli-bridge turn schema must accept that top-level field and include it in its request digest.
Other runners stay disabled until cli-bridge proves the same replay and response behavior for them.
To run the real cross-repository contract, point the test at an installed cli-bridge source checkout:
CLI_BRIDGE_INTEGRATION_ROOT=/path/to/cli-bridge pnpm test -- tests/cli-bridge.integration.test.ts
Use pnpm test:integration for the fail-closed form of this command.
It exits before Vitest when CLI_BRIDGE_INTEGRATION_ROOT is missing.
The regular pnpm test command builds the package and runs every test that needs nothing beyond this checkout, including the integration tests under tests/ that talk to a loopback Bridge peer.
vitest.config.ts names each test that needs a Bridge checkout or a sandbox box image and leaves it out until the variable that supplies it is set, so a run never reports one of them as skipped.