Skip to content

Operations and native-support architecture

This page is the architecture analysis for the hosted-agent-ops module. It complements the implementation pages by focusing on how diagnostics, telemetry, the enterprise gateway, updates, and native helpers are invoked around and alongside the main runtime without owning the local agent loop rather than re-listing each event name.

Scope: debug logs, telemetry/traffic gates, feature flags, the native-only enterprise gateway server, doctor/update tooling, crash and error reporting, hosted review signals, and embedded image/audio native helpers. Implementation specifics live in Diagnostics and debug logs, Telemetry and tracing, Enterprise gateway server, Feature gates reference, Updater and doctor, and Media native modules.

Module purpose

This module owns operational mechanisms outside the local agent turn owner. Some are observational (debug logs and telemetry), some are startup-critical setup (network and sink initialization), one is a standalone auth/inference/policy gateway process, some are foreground maintenance operations (install/update/doctor), and some transform input before it reaches the model loop (image and voice helpers).

It deliberately does not own:

  • Tool execution (owned by the tools/security module).
  • Session persistence (owned by the sessions module).
  • Permission decisions (owned by the trust pipeline).

It can observe those subsystems, but it can also mutate the local installation, write diagnostic state, or produce media-derived input through explicit boundaries.

Architecture thesis

Ops is a mixed control and observation plane: it surfaces structured events, initializes optional exporters, writes local diagnostics, exposes foreground maintenance commands, and provides binary helpers. These surfaces have separate gates and lifecycles; there is no single switch that governs every local log, first-party event, third-party exporter, updater, and media path.

Source anchors

Semantic aliasString or symbolArchitectural meaning
NativeUpdaterStartEventtengu_native_auto_updater_startUpdater entry; runs out-of-band from the model loop.
NativeUpdaterLockEventtengu_native_auto_updater_lock_contentionUpdater lock telemetry; multiple invocations are coordinated.
NativeUpdaterFailureEventtengu_native_auto_updater_failUpdater failure classification (timeout/checksum/not_found).
NativeUpdaterSuccessEventtengu_native_auto_updater_successUpdater success telemetry.
AutoUpdateReleaseChannelauto-update (release channel: latest, stable, rc)Settings-driven release channel selection.
UpdaterPermissionPreflightInsufficient permissions for auto-updatesDoctor-style preflight for updater.
AutoUpdaterStatusMachineautoUpdaterStatus: migrated, installed, disabled, enabledState machine for updater install kind.
DoctorDiagnosticsScreen/doctor diagnostics screenDoctor UX entry.
ShutdownCoordinatorrecordUncaughtAndCheckBreaker, gracefulShutdown, flushAnalyticsSinksOps/shutdown coordinator surface.
EventLoopStallDetectorstartEventLoopStallDetectorOptional diagnostic added at the bootstrap layer.
StartupProfilingMarksimport_time, cli_entry, main_tsx_imports_loaded, cli_before_main_importStartup profiling event groups.
ProviderAndErrorGatesCLAUDE_CODE_USE_VERTEX, CLAUDE_CODE_USE_FOUNDRY, CLAUDE_CODE_USE_ANTHROPIC_AWS, CLAUDE_CODE_USE_MANTLE, DISABLE_ERROR_REPORTINGProvider/error-reporting gates evaluated up front.
TranscriptMirrorFrametranscript_mirrorOps-friendly local mirror of remote transcripts.
StatusLineRuntimesexecuteStatusLineCommand, pNb, fNb, Gyf, SBaMain prompt-line and separate subagent-row command protocols; see Status line runtime and command protocol.
OpsNotificationStateFlagsmarkFirstTeleportMessageLogged, isSessionPersistenceDisabled, isUserActiveForNotificationsCross-cutting state flags observed by ops/notifications.
MediaNativeJsShimsrequire("/$bunfs/root/*.node")JS shims for embedded native helpers; the extraction script also recovers the gitignored .node payloads for inspection.
EnterpriseGatewaycommand("gateway"), startGateway()Native-only OIDC/inference/managed-settings/spend/OTLP server process ~973,797.

Internal decomposition

flowchart TD
Runtime[Claude Code runtime] --> Debug[Debug log writers]
Runtime --> Telemetry[Telemetry sinks]
Runtime --> Errors[Error reporter / breaker]
Runtime --> Doctor[/doctor diagnostics]
Runtime --> Updater[Native auto updater]
Runtime --> Gateway[Enterprise gateway server]
Runtime --> Hosted[Hosted review signals]
Runtime --> Statusline[Status line / subagent status line]
Runtime --> Native[Image / audio native helpers]
Debug --> Logs[claude-dir/debug/sessionId.txt]
Telemetry --> Sink[first-party / Datadog / OTel routes]
Errors --> Sink
Updater --> Channel[release channel: latest / stable / rc]
Gateway --> GatewayState[Postgres / OIDC / upstreams / managed policy]
Hosted --> Preflight[/v1/ultrareview/preflight]
Native --> Attach[image / audio attachment inputs]
Policy[managed settings + env gates] --> Telemetry
Policy --> Errors
Policy --> Hosted
Policy --> Updater
Sub-componentResponsibility
Debug log writersAppend-only logs for support; respect debug log gating.
Telemetry sinksRoute sampled first-party events, optional Datadog events, and separately initialized OTel signals; applicable sinks are flushed by shutdown paths.
Error reporterRecord uncaught/breaker state; gated by DISABLE_ERROR_REPORTING.
DoctorUser-facing diagnostics surface for environment, permissions, model selection, integrations.
Native auto updaterVersion lookup, download, checksum, locking, staged install, launcher activation, and old-version cleanup. Foreground commands await this work; periodic checks invoke it outside a model turn.
Hosted review signalsultrareview-adjacent preflight and result hooks; gated by hosted settings/policy.
Status line / subagent status lineOptional command-derived prompt line and JSONL task-row decorations. The focused lifecycle belongs to Status line runtime and command protocol.
Native helpersOriginal payload includes image-processor.node and audio-capture.node loaded via JS shims; local extraction retains gitignored copies of both binaries.
Enterprise gatewayRuns a separate Bun server process that owns OIDC device auth, Postgres state, Messages API routing, managed settings, spend enforcement, and OTLP relay.

Public interface

Inputs

SurfaceEffect
--debug, --debug-to-stderr, --ai-debugEnable debug logging variants.
--add-trace-attribute key=valueAttach OTEL attributes to runtime traces.
DISABLE_TELEMETRY, DISABLE_ERROR_REPORTING, DISABLE_AUTOUPDATERCoarse env gates for telemetry, errors, updater.
OTEL_* envWire OTEL sinks if configured.
claude doctorRun the diagnostics path.
claude update, claude installManual updater entry.
claude gateway --config <path>Starts the native-only enterprise gateway from a strict YAML configuration.
Settings: cleanupPeriodDays, statusLine, subagentStatusLine, auto-update channel/min versionPersistent ops configuration.
Managed policy: disableAllHooks, disableRemoteControl, disableAgentView, disableSkillShellExecutionCapability/policy switches surfaced through ops UX.

Outputs

OutputConsumer
tengu_* event streamTelemetry sink (when enabled).
Debug log filesSupport tooling.
Doctor renderTerminal UX.
Updater state transitionsSettings/state file + telemetry.
Crash/error reportsError sink (when enabled).
Status-line stringsTerminal UX.
Image/audio buffersAttachment paths in the context/model loop.
Gateway OAuth/API/health endpointsEnterprise clients, administrators, and upstream provider adapters.

Internal collaborators

CollaboratorContract
Runtime lifecycleCalls into ops in TopLevelMain (event-loop stall detector, profiling marks) and in preAction (sinks/logs/managed settings refresh).
Settings/policyProvides the gates ops checks before emitting or persisting.
SessionsReceives session_state_changed, transcript-mirror, and bridge-state frames that ops surfaces or logs.
Tools/securityEmits tool decision telemetry; ops aggregates and persists.
Updater backendExternal binary fetch + checksum verification; result is recorded in settings/state.
Hosted review backend/v1/ultrareview/preflight and related routes.
Native helpersBun resolves require("/$bunfs/root/...node") for image/audio addons.

Design decisions

  1. Ops does not own model-turn policy, but it is not observation-only. The updater changes the installation, diagnostics persist files, and media helpers transform inputs. Turn cancellation and tool authorization still belong elsewhere.
  2. Observability routes are independently controlled. First-party event logging starts during general initialization; third-party/OTel setup has a separate after-trust path; Datadog, debug files, error JSONL, and MCP JSONL each have their own predicates and writers.
  3. Update scheduling and update execution are different. Periodic checks run outside a model turn, while claude update and claude install are foreground commands that await network and filesystem work. Locks prevent a second installer from racing rather than making installation universally nonblocking.
  4. Doctor is the canonical diagnostics surface. Other diagnostic frames (status line, debug logs) are complementary; doctor is the place to converge for support.
  5. Native helpers are isolated behind JavaScript façades. The readable source establishes addon loading, method calls, disposal, recorder selection, and downstream use. Export tables and binary strings alone do not establish native scheduling, cleanup, or error propagation.
  6. Error reporting is opt-in / opt-out at a coarse grain. DISABLE_ERROR_REPORTING short-circuits the reporter rather than reshaping individual call sites.
  7. Profiling marks are part of the lifecycle, not a separate framework. import_time, cli_entry, main_function_start, run_function_start, preAction_* marks all flow through the same logger so support can read a single timeline.
  8. The gateway is an operational server role, not the local agent loop. It proxies provider Messages requests and serves auth/policy/telemetry, but does not assemble or execute a developer’s local tool-using turn.

Operational seams

SeamWhat flows acrossWhy it exists
Early process-exit hookFinal flush / cleanupCatch-all to give sinks one last chance to drain.
process.on("SIGINT", ...)Headless vs interactive shutdown branchingDifferent ops UX for scripted vs human runs.
gracefulShutdown / gracefulShutdownSyncCoordinated flush + analyticsKeep telemetry consistent on planned termination.
recordUncaughtAndCheckBreakerUncaught exception pathCentralize crash classification, avoid noisy duplicates.
tengu_native_auto_updater_* eventsUpdater telemetryExternalize updater health without coupling to UI.
auto-update settings + stateChannel + install kindPersistent state for the updater state machine.

Failure modes

FailureBehavior
Global-package updater lock already heldReturns status: "in_progress"; the contender does not start another install.
Native version lock cannot be acquiredReturns lockFailed: true; no destructive activation is attempted by that invocation.
Download/checksum fails before native activationThe staged candidate is rejected; the active launcher is not replaced by that candidate.
Launcher activation is refused or failsAn unowned launcher is not overwritten. Specific Unix/Windows activation paths preserve or restore the old launcher, but this is not a guarantee for every possible filesystem failure.
Auto-update permission insufficientDoctor preflight reports the fix-up message instead of silently failing.
Third-party telemetry is absent or initialization failsPending OTel events are discarded with not_configured or init_failed; configured providers still receive bounded best-effort flushes on shutdown.
Native helper missing or fails to loadJS call sites either choose a recorder fallback, preserve an already-safe image, or surface a media-specific error. There is no universal native-failure fallback.
Main status-line command errorsThe custom line is suppressed; the loop continues. Subagent-decoration errors instead fall back to built-in task rows.
Event-loop stall detector triggersDiagnostic events emitted; runtime continues.
Hosted review preflight rejectsUX surfaces the result; local workflow is not blocked.
Gateway configuration/store startup failsThe gateway command exits before listening; an already-running local Claude Code session is a separate process.

Extension points

ExtensionHow it plugs in
Additional telemetry sinkRegister through the analytics-sink interface and rely on flushAnalyticsSinks.
Additional debug log channelUse existing logger; do not invent a new file format.
New diagnostic checkAdd to the doctor command rather than scattering checks across the runtime.
Status line customizationUse the statusLine / subagentStatusLine settings; treat them as two command protocols with different input/output contracts, not inline model output.
Custom updater channelAdd to the auto-update settings enum; updater logic should not branch on out-of-band sources.
Native attachment typeAdd a JS shim and a .node addon; attach via the existing attachment surface in the context module.

Caveats

  • The inspected .node modules are stripped Linux x86-64 ELF shared objects. Their exports, linked dependencies, embedded crate/version strings, JS call sites, and selected exact-artifact observations are documented, but their internal control flow was not recovered from disassembly.
  • Many tengu_* strings are runtime evidence; the precise sink schema is implementation-defined.
  • This module touches many other modules but does not own model-turn orchestration. Media preprocessing can affect the input delivered to that orchestration; tool authorization, context assembly, and session semantics remain owned by their respective modules.

Created and maintained by Yingting Huang.