This file is a merged representation of a subset of the codebase, containing files not matching ignore patterns, combined into a single document by Repomix.
The content has been processed where comments have been removed, empty lines have been removed, content has been compressed (code blocks are separated by ⋮---- delimiter).

<file_summary>
This section contains a summary of this file.

<purpose>
This file contains a packed representation of a subset of the repository's contents that is considered the most important context.
It is designed to be easily consumable by AI systems for analysis, code review,
or other automated processes.
</purpose>

<file_format>
The content is organized as follows:
1. This summary section
2. Repository information
3. Directory structure
4. Repository files (if enabled)
5. Multiple file entries, each consisting of:
  - File path as an attribute
  - Full contents of the file
</file_format>

<usage_guidelines>
- This file should be treated as read-only. Any changes should be made to the
  original repository files, not this packed version.
- When processing this file, use the file path to distinguish
  between different files in the repository.
- Be aware that this file may contain sensitive information. Handle it with
  the same level of security as you would the original repository.
</usage_guidelines>

<notes>
- Some files may have been excluded based on .gitignore rules and Repomix's configuration
- Binary files are not included in this packed representation. Please refer to the Repository Structure section for a complete list of file paths, including binary files
- Files matching these patterns are excluded: **/.git/**, **/.github/**, **/node_modules/**, **/vendor/**, **/third_party/**, **/external/**, **/libs/**, **/lib/**, **/bin/**, **/obj/**, **/build/**, **/dist/**, **/target/**, **/out/**, **/release/**, **/debug/**, **/wwwroot/**, **/public/**, **/assets/**, **/static/**, **/[tT]est/**, **/[tT]ests/**, **/__tests__/**, **/[lL]ogs/**, **/[mM]igrations/**, **/.vs/**, **/.vscode/**, **/.idea/**, **/.pnpm-store/**, **/.yarn/**, **/.npm/**, **/__pycache__/**, **/.pytest_cache/**, **/.mypy_cache/**, **/.gradle/**, **/.mvn/**, **/coverage/**, **/.coverage/**, **/reports/**, **/report/**, **/TestResults/**, **/tmp/**, **/temp/**, **/.tmp/**, **/.cache/**, **/.history/**, **/.DS_Store, **/Thumbs.db, **/*.log, **/*.out, **/*.err, **/*.trace, **/*.trc, **/*.tmp, **/*.cache, **/*.dmp, **/*.dump, **/*.core, **/*.binlog, **/*.ndjson, **/*.jsonl, **/*.csv, **/*.evtx, **/*.etl, **/*.access, **/*.error, **/*.exe, **/*.dll, **/*.so, **/*.dylib, **/*.bin, **/*.app, **/*.msi, **/*.apk, **/*.ipa, **/*.lib, **/*.a, **/*.o, **/*.obj, **/*.lo, **/*.lai, **/*.class, **/*.jar, **/*.war, **/*.ear, **/*.pdb, **/*.idb, **/*.ilk, **/*.nupkg, **/*.snupkg, **/*.gem, **/*.whl, **/*.egg, **/*.deb, **/*.rpm, **/*.zip, **/*.tar, **/*.gz, **/*.tgz, **/*.rar, **/*.bz2, **/*.xz, **/*.7z, **/*.lz, **/*.lzma, **/*.min.js, **/*.min.css, **/*.map, **/*.css, **/*.scss, **/*.sass, **/*.less, **/*.jpg, **/*.jpeg, **/*.png, **/*.gif, **/*.bmp, **/*.tif, **/*.tiff, **/*.webp, **/*.heif, **/*.heic, **/*.svg, **/*.eps, **/*.ai, **/*.raw, **/*.cr2, **/*.cr3, **/*.nef, **/*.arw, **/*.dng, **/*.orf, **/*.rw2, **/*.avif, **/*.apng, **/*.ico, **/*.psd, **/*.psb, **/*.xcf, **/*.hdr, **/*.exr, **/*.dcm, **/*.dicom, **/*.fits, **/*.ppm, **/*.pgm, **/*.pbm, **/*.j2k, **/*.jp2, **/*.pcx, **/*.tga, **/*.iff, **/*.sgi, **/*.ras, **/*.coverage, **/*.lcov, **/*.gcov, **/*.gcda, **/*.gcno, **/*.generated, **/*.g.cs, **/*.designer.cs, **/*.lock, **/*.lock.json, **/*.eot, **/*.ttf, **/*.woff, **/*.woff2, **/*.pfx, **/*.p12, **/*.cer, **/*.crt, **/*.key, **/*.editorconfig, **/*.tool-versions, **/*.onnx, **/*.pt, **/*.pth, **/*.h5, **/*.ckpt, **/*.sln, **/*.csproj, **/*.config, **/*.user, **/*.vsidx, **/*.v2, **/*.db*, **/.*ignore, **/.git*, **/*.config.*, **/*.bzl, **/BUILD, **/BUILD.bazel, **/Makefile, **/CMakeLists.txt, **/pom.xml, **/build.gradle, **/settings.gradle, **/gradlew, **/gradlew.bat, **/mvnw, **/mvnw.cmd, **/.idea/**, **/.vscode/**, **/.eclipse/**, **/.settings/**, **/gen/**, **/generated/**, **/auto/**, **/out/**, **/build/**, **/target/**, **/dist/**, **/.venv/**, **/.cache/**, **/.pytest_cache/**, **/vendor/**, **/third_party/**, **/external/**, **/fixtures/**, **/data/**, **/samples/**, **/seed/**, **/seeds/**, **/proto/**, **/*.proto, **/*.avsc, **/*.thrift, **/*.cddl, **/*.pdl, **/*.smithy, **/*.jsonschema, **/deploy/**, **/e2e/**, **/tests/**, **/.gitignore, **/.gitattributes, **/.dockerignore, **/.helmignore, **/.env, **/.env.*, **/*.lock, **/*.sum, **/*.mod, **/*.nix, **/*.png, **/*.svg, **/*.jpg, **/*.jpeg, **/*.gif
- Files matching patterns in .gitignore are excluded
- Files matching default ignore patterns are excluded
- Code comments have been removed from supported file types
- Empty lines have been removed from all files
- Content has been compressed - code blocks are separated by ⋮---- delimiter
- Files are sorted by Git change count (files with more changes are at the bottom)
</notes>

</file_summary>

<directory_structure>
.agents/
  skills/
    build-from-issue/
      SKILL.md
    build-openshell-mxc-windows/
      reference.md
      SKILL.md
    create-github-issue/
      SKILL.md
    create-github-pr/
      SKILL.md
    create-rfc/
      agents/
        openai.yaml
      SKILL.md
    create-spike/
      SKILL.md
    fix-security-issue/
      SKILL.md
    helm-dev-environment/
      SKILL.md
    launch-openshell-gator/
      SKILL.md
    review-github-pr/
      SKILL.md
    review-security-issue/
      SKILL.md
    sbom/
      SKILL.md
    sync-agent-infra/
      SKILL.md
    test-release-canary/
      SKILL.md
    triage-issue/
      SKILL.md
    tui-development/
      SKILL.md
    update-docs/
      SKILL.md
    watch-github-actions/
      SKILL.md
.cargo/
  config.toml
.claude/
  agent-memory/
    principal-engineer-reviewer/
      MEMORY.md
  agents/
    principal-engineer-reviewer.md
  README.md
.opencode/
  agents/
    principal-engineer-reviewer.md
crates/
  openshell-binary-identity/
    src/
      lib.rs
    Cargo.toml
    README.md
  openshell-bootstrap/
    src/
      edge_token.rs
      jwt.rs
      lib.rs
      metadata.rs
      mtls.rs
      oidc_token.rs
      paths.rs
      pki.rs
    Cargo.toml
  openshell-cli/
    src/
      commands/
        common.rs
        gateway.rs
        mod.rs
        provider_readiness.rs
        provider.rs
      auth.rs
      color.rs
      completers.rs
      edge_tunnel.rs
      lib.rs
      main.rs
      oidc_auth.rs
      output.rs
      policy_update.rs
      run.rs
      ssh.rs
      test_utils.rs
      tls.rs
    Cargo.toml
  openshell-conformance/
    src/
      scenarios/
        file_transfer.rs
        mod.rs
        policy_behavior.rs
        sandbox_lifecycle.rs
        smoke.rs
      executor.rs
      lib.rs
    Cargo.toml
  openshell-conformance-cli/
    src/
      main.rs
    Cargo.toml
  openshell-core/
    src/
      activity.rs
      auth.rs
      config.rs
      container_paths.rs
      denial.rs
      driver_mounts.rs
      driver_utils.rs
      dynamic_string_allowlist.rs
      endpoint_path.rs
      endpoint_status.rs
      error.rs
      extension_protocol.rs
      external_driver_socket.rs
      forward.rs
      google_cloud.rs
      gpu.rs
      grpc_client.rs
      host_pattern.rs
      image.rs
      jwt.rs
      lib.rs
      local_api_socket.rs
      mcp.rs
      metadata.rs
      middleware.rs
      net.rs
      oauth.rs
      paths.rs
      policy_identity.rs
      policy.rs
      progress.rs
      proposals.rs
      proto_struct.rs
      provider_credentials.rs
      resource_admission.rs
      rpc_error.rs
      sandbox_env.rs
      sandbox_generation.rs
      sandbox_session.rs
      secrets_body.rs
      secrets.rs
      settings.rs
      shell.rs
      spiffe.rs
      telemetry.rs
      time.rs
      transport_errors.rs
    build_version.rs
    build.rs
    Cargo.toml
    README.md
  openshell-driver-db-credstore/
    src/
      lib.rs
    Cargo.toml
  openshell-driver-docker/
    src/
      isolation.rs
      lib.rs
      main.rs
      otel_tracing.rs
      tests.rs
    Cargo.toml
    README.md
  openshell-driver-kubernetes/
    src/
      config.rs
      driver.rs
      grpc.rs
      isolation.rs
      lib.rs
      main.rs
      otel_tracing.rs
      resource_admission.rs
      sandbox_runtime.rs
    Cargo.toml
    README.md
  openshell-driver-kubernetes-secrets/
    src/
      lib.rs
      main.rs
    Cargo.toml
  openshell-driver-mxc/
    examples/
      e2e-policies/
        fs-empty.yaml
        fs-readonly.yaml
        fs-rw.yaml
        network-reject.yaml
      demo.yaml
      mxc-gateway.toml
      mxc-ocsf-audit.toml
      ocsf-audit.yaml
      probe-mxc-host.ps1
      README-ocsf-audit.txt
      run-mxc-e2e.ps1
      run-ocsf-audit.ps1
    src/
      policy_map/
        config.rs
        loss.rs
        map.rs
        mod.rs
        report.rs
      driver.rs
      etw_consumer.rs
      grpc.rs
      lib.rs
      mxc.rs
      policy.rs
    Cargo.toml
    README.md
  openshell-driver-podman/
    src/
      client.rs
      config.rs
      container.rs
      driver.rs
      grpc.rs
      isolation.rs
      lib.rs
      main.rs
      otel_tracing.rs
      socket_discovery.rs
      test_utils.rs
      watcher.rs
    Cargo.toml
    NETWORKING.md
    README.md
  openshell-driver-vault/
    src/
      lib.rs
      main.rs
    Cargo.toml
  openshell-driver-vm/
    runtime/
      kernel/
        openshell.kconfig
      pins.env
      README.md
    scripts/
      openshell-vm-sandbox-init.sh
    src/
      extensions/
        mod.rs
      isolation/
        mod.rs
      driver.rs
      embedded_runtime.rs
      ffi.rs
      gpu.rs
      layer_applier.rs
      lib.rs
      lifecycle.rs
      main.rs
      otel_tracing.rs
      procguard.rs
      rootfs.rs
      runtime.rs
    build.rs
    Cargo.toml
    entitlements.plist
    README.md
  openshell-extension-core/
    src/
      auth.rs
      identity.rs
      jwt.rs
      lib.rs
      store.rs
      transport.rs
    Cargo.toml
    README.md
  openshell-gateway/
    src/
      lib.rs
      main.rs
      vm.rs
    Cargo.toml
  openshell-gateway-interceptors/
    src/
      lib.rs
      plan.rs
      profile_source.rs
      proto_json.rs
      routes.rs
      runtime.rs
    Cargo.toml
  openshell-isolation-interface/
    src/
      linux/
        child_seccomp.rs
        landlock.rs
        mod.rs
        proc_fd.rs
        process_signal.rs
        seccomp_notify.rs
        socket_registry.rs
        task_memory.rs
        workload_launcher.rs
      contract.rs
      lib.rs
    Cargo.toml
  openshell-ocsf/
    schemas/
      ocsf/
        v1.7.0/
          classes/
            application_lifecycle.json
            base_event.json
            detection_finding.json
            device_config_state_change.json
            http_activity.json
            network_activity.json
            process_activity.json
            ssh_activity.json
          objects/
            actor.json
            attack.json
            connection_info.json
            container.json
            device.json
            evidences.json
            finding_info.json
            firewall_rule.json
            http_request.json
            http_response.json
            metadata.json
            network_endpoint.json
            network_proxy.json
            process.json
            product.json
            remediation.json
            url.json
          VERSION
        v1.8.0/
          classes/
            api_activity.json
            application_lifecycle.json
            base_event.json
            detection_finding.json
            device_config_state_change.json
            http_activity.json
            network_activity.json
            process_activity.json
            ssh_activity.json
          objects/
            actor.json
            ai_model.json
            api.json
            attack.json
            connection_info.json
            container.json
            device.json
            evidences.json
            finding_info.json
            firewall_rule.json
            http_request.json
            http_response.json
            metadata.json
            network_endpoint.json
            network_proxy.json
            process.json
            product.json
            remediation.json
            url.json
          profiles/
            ai_operation.json
          VERSION
        README.md
    src/
      builders/
        api_activity.rs
        base.rs
        config.rs
        finding.rs
        http.rs
        lifecycle.rs
        mod.rs
        network.rs
        process.rs
        ssh.rs
      enums/
        action.rs
        activity.rs
        auth.rs
        device_type.rs
        disposition.rs
        http_method.rs
        launch.rs
        mod.rs
        security.rs
        severity.rs
        status.rs
      events/
        api_activity.rs
        app_lifecycle.rs
        base_event.rs
        config_state_change.rs
        detection_finding.rs
        http_activity.rs
        mod.rs
        network_activity.rs
        process_activity.rs
        serde_helpers.rs
        ssh_activity.rs
      format/
        downgrade.rs
        jsonl.rs
        mod.rs
        shorthand.rs
      objects/
        ai_model.rs
        api.rs
        attack.rs
        connection.rs
        container.rs
        device.rs
        endpoint.rs
        finding.rs
        firewall_rule.rs
        http.rs
        metadata.rs
        mod.rs
        process.rs
      tracing_layers/
        event_bridge.rs
        jsonl_layer.rs
        mod.rs
        shorthand_layer.rs
      validation/
        mod.rs
        schema.rs
      ctx.rs
      lib.rs
    Cargo.toml
  openshell-otel/
    src/
      driver.rs
      grpc.rs
      lib.rs
      propagation.rs
    Cargo.toml
  openshell-otel-test-support/
    src/
      lib.rs
    Cargo.toml
  openshell-policy/
    src/
      ambiguity.rs
      compose.rs
      l7_validate.rs
      lib.rs
      merge.rs
      middleware.rs
    testdata/
      mcp-version-profiles.yaml
    Cargo.toml
  openshell-policy-schema/
    src/
      lib.rs
    Cargo.toml
  openshell-prover/
    registry/
      apis/
        github.yaml
      binaries/
        claude.yaml
        curl.yaml
        gh.yaml
        git.yaml
        nc.yaml
        node.yaml
        python3.yaml
        ssh.yaml
        wget.yaml
    src/
      containment/
        execution.rs
        ip.rs
      accepted_risks.rs
      containment.rs
      credentials.rs
      finding.rs
      lib.rs
      model.rs
      policy.rs
      queries.rs
      registry.rs
      report.rs
    testdata/
      credentials.yaml
      empty-policy.yaml
      policy.yaml
    Cargo.toml
    README.md
  openshell-prover-cli/
    src/
      main.rs
    Cargo.toml
    README.md
  openshell-providers/
    src/
      providers/
        google_cloud.rs
        mod.rs
        vertex.rs
      context.rs
      discovery.rs
      example_profiles.rs
      lib.rs
      profiles.rs
      test_helpers.rs
    Cargo.toml
    README.md
  openshell-sandbox/
    src/
      sandbox/
        linux/
          landlock.rs
          mod.rs
          seccomp.rs
        mod.rs
      accept_interrupt.rs
      activity_aggregator.rs
      boundary_exec.rs
      boundary_io.rs
      boundary_server.rs
      child_env.rs
      delegated.rs
      denial_aggregator.rs
      lib.rs
      main_session.rs
      main.rs
      managed_children.rs
      mechanistic_mapper.rs
      network_broker.rs
      perf.rs
      process.rs
      provider_files.rs
      pty.rs
      sftp.rs
    Cargo.toml
  openshell-sandbox-backend/
    src/
      boundary_protocol.rs
      lib.rs
      mediation.rs
      runtime.rs
      sandbox_auth.rs
    build.rs
    Cargo.toml
  openshell-sdk/
    src/
      auth.rs
      client.rs
      config.rs
      edge_tunnel.rs
      error.rs
      lib.rs
      oidc.rs
      pagination.rs
      provider_readiness.rs
      raw.rs
      refresh.rs
      transport.rs
      types.rs
    Cargo.toml
    README.md
  openshell-server/
    src/
      auth/
        authenticator.rs
        authz.rs
        compute_driver.rs
        descriptor_authz.rs
        extension_mint_limit.rs
        guard.rs
        http.rs
        identity.rs
        method_authz.rs
        mod.rs
        oidc.rs
        peer.rs
        principal.rs
        sandbox_jwt.rs
        sandbox_methods.rs
        sandbox_session.rs
        workspace_authz.rs
      compute/
        driver_config.rs
        lease.rs
        mod.rs
        provisioning_deadline.rs
        rootfs_tar.rs
      grpc/
        mutation_replay/
          ordinary/
            tests.rs
          streaming/
            tests.rs
          ordinary.rs
          streaming.rs
          tests.rs
        policy/
          endpoint_status_tests.rs
          endpoint_status.rs
          provisioning_clock.rs
        auth_rpc.rs
        interactive_exec_tests.rs
        mod.rs
        mutation_replay.rs
        mutation_tests.rs
        policy.rs
        provider_readiness_tests.rs
        provider_readiness.rs
        provider.rs
        sandbox.rs
        service.rs
        validation.rs
        workspace.rs
      persistence/
        legacy_time_wire.rs
        mod.rs
        postgres.rs
        sqlite.rs
        tests.rs
      certgen.rs
      cli.rs
      config_file.rs
      config_update_operation.rs
      credentials.rs
      defaults.rs
      gateway_listener.rs
      gateway_ocsf.rs
      http.rs
      lib.rs
      middleware.rs
      multiplex.rs
      ocsf_log.rs
      otel_tracing.rs
      pagination.rs
      policy_store.rs
      provider_profile_sources.rs
      provider_refresh.rs
      readiness.rs
      sandbox_index.rs
      sandbox_watch.rs
      service_routing.rs
      ssh_sessions.rs
      storage_proto.rs
      supervisor_owner.rs
      supervisor_session.rs
      telemetry.rs
      test_support.rs
      tls_test_utils.rs
      tls.rs
      tracing_bus.rs
      tracing_setup.rs
      watch_cursor.rs
      ws_tunnel.rs
    build.rs
    Cargo.toml
  openshell-server-macros/
    src/
      lib.rs
    Cargo.toml
  openshell-supervisor/
    src/
      activity_aggregator.rs
      denial_aggregator.rs
      endpoint_status.rs
      lib.rs
      main.rs
      mechanistic_mapper.rs
      provider_readiness.rs
    Cargo.toml
  openshell-supervisor-middleware/
    src/
      response/
        preflight.rs
        validation.rs
      headers.rs
      lib.rs
      remote.rs
      response.rs
      websocket.rs
    Cargo.toml
  openshell-supervisor-middleware-builtins/
    src/
      lib.rs
      regex.rs
    Cargo.toml
  openshell-supervisor-network/
    src/
      l7/
        rest/
          http_response.rs
        graphql.rs
        http.rs
        jsonrpc.rs
        mcp.rs
        middleware.rs
        mod.rs
        path.rs
        provider.rs
        relay.rs
        rest.rs
        tls.rs
        token_grant_injection.rs
        websocket.rs
      opa/
        raw_schema.rs
      policy_dns/
        mod.rs
        name.rs
        resolver.rs
        runtime.rs
        store.rs
        wire.rs
      proxy/
        destination.rs
        egress.rs
        relay.rs
      host.rs
      identity_source.rs
      identity.rs
      lib.rs
      opa.rs
      policy_local.rs
      procfs.rs
      proxy.rs
      run.rs
      sigv4.rs
      spiffe_endpoint.rs
      token_grant.rs
      upstream_proxy.rs
    testdata/
      sandbox-policy.yaml
    Cargo.toml
  openshell-supervisor-process/
    src/
      skills/
        policy-advisor/
          SKILL.md
        policy_advisor.md
      ssh/
        peer_stream.rs
        reconnect_tests.rs
      debug_rpc.rs
      delegated.rs
      lib.rs
      log_push.rs
      main_session.rs
      skills.rs
      ssh.rs
      supervisor_session.rs
      unix_socket.rs
    Cargo.toml
  openshell-tui/
    src/
      ui/
        create_provider.rs
        create_sandbox.rs
        dashboard.rs
        global_settings.rs
        mod.rs
        providers.rs
        sandbox_detail.rs
        sandbox_draft.rs
        sandbox_logs.rs
        sandbox_policy.rs
        sandbox_settings.rs
        sandboxes.rs
        splash.rs
      app.rs
      clipboard.rs
      event.rs
      lib.rs
      theme.rs
    Cargo.toml
  openshell-vfio/
    src/
      bind.rs
      error.rs
      gpu.rs
      lib.rs
      pci.rs
      reconcile.rs
      sysfs.rs
      test_support.rs
    Cargo.toml
docs/
  _components/
    BadgeLinks.tsx
    CommandTerminal.tsx
    jsx.d.ts
  about/
    architecture.mdx
    installation.mdx
    overview.mdx
    run-your-first-agent.mdx
    support-matrix.mdx
  extensibility/
    supervisor-middleware/
      configure.mdx
      index.mdx
      operations.mdx
    drivers.mdx
    gateway-interceptors.mdx
    isolation-backends.mdx
    overview.mdx
  how-it-works/
    gateways/
      authentication.mdx
      configuration.mdx
      container-deployment.mdx
      overview.mdx
    policies/
      advisor.mdx
      default-policy.mdx
      manage-policies.mdx
      network-rules.mdx
      overview.mdx
      prover.mdx
      schema.mdx
    providers/
      aws.mdx
      google.mdx
      overview.mdx
      profiles.mdx
    sandboxes/
      overview.mdx
      runtimes.mdx
      templates.mdx
    inference.mdx
    workspaces.mdx
  kubernetes/
    access-control.mdx
    high-availability.mdx
    ingress.mdx
    managing-certificates.mdx
    openshift.mdx
    setup.mdx
  observability/
    accessing-logs.mdx
    logging.mdx
    ocsf-json-export.mdx
    telemetry.mdx
  resources/
    license.mdx
  sdk/
    api-errors.mdx
    go.mdx
    protobuf-time-types.mdx
    python.mdx
    rust.mdx
    typescript.mdx
  security/
    best-practices.mdx
    verify-image-contents.mdx
  tutorials/
    first-network-policy.mdx
    github-push-access.mdx
    index.mdx
    microsoft-graph-provider-refresh.mdx
    run-pi-with-openrouter.mdx
  upgrade/
    0-1-0.mdx
  .markdownlint-cli2.jsonc
  CONTRIBUTING.mdx
  index.mdx
  index.yml
examples/
  agent-driven-policy-management/
    agent-task.md
    demo.sh
    policy.template.yaml
    README.md
    sandbox-agent.sh
  bring-your-own-container/
    app.py
    Dockerfile
    README.md
  codex-app-server/
    codex.yaml
    Dockerfile
    README.md
    start-codex-app-server
  governance-interceptor/
    profiles/
      github.yaml
      slack.yaml
    src/
      main.rs
      policy_hash.rs
      proto_json.rs
      smoke_client.rs
      tests.rs
    Cargo.toml
    policy.yaml
    README.md
    smoke.sh
  local-inference/
    inference.py
    nvidia-inference.yaml
    README.md
    sandbox-policy.yaml
  multi-agent-notepad/
    prompts/
      synthesis.md
      worker.md
    demo.sh
    policy.template.yaml
    README.md
    runner.sh
  policy-advisor/
    ctf.py
    README.md
    sandbox-policy.yaml
  private-ip-routing/
    Dockerfile
    README.md
    server.py
  provider-managed-files/
    acme-config.yaml
  sandbox-policy-quickstart/
    demo.sh
    policy.yaml
    README.md
  spiffe-token-exchange-demo/
    k8s/
      kustomization.yaml
      protected-service.js
      spiffe-helper.conf
      token-issuer.js
      workloads.yaml
    podman/
      spire/
        agent.conf
        common.sh
        oidc-discovery-provider.conf
        register-gateway.sh
        register-sandbox.sh
        server.conf
        start-agent.sh
        start-server-oidc.sh
      demo.sh
      provider-profile.yaml
      README.md
      start-gateway.sh
    demo.sh
    provider-profile.yaml
    README.md
  spiffe-token-grant-demo/
    k8s/
      kustomization.yaml
      protected-service.js
      token-issuer.js
      workloads.yaml
    demo.sh
    provider-profile.yaml
    README.md
  supervisor-middleware-content-guard/
    src/
      main.rs
    Cargo.toml
    policy.yaml
    README.md
    smoke.sh
    upstream.py
  transparent-tcp-redis/
    demo.sh
    policy.yaml
    README.md
    redis_client.py
  aws-s3-sts.md
  gateway-deploy-connect.md
  sync-files.md
  vscode-remote-sandbox.md
fern/
  components/
    CustomFooter.tsx
  docs.yml
  fern.config.json
  README.md
nix/
  test-guest/
    configuration/
      tasks/
        podman-rootless/
          fedora.yml
          shared.yml
          ubuntu.yml
        podman-common.yml
      docker.yml
      podman-rootful.yml
      podman-rootless.yml
      selinux.yml
      snapd.yml
    provisioners/
      roles/
        gateway-podman/
          tasks/
            development-gateway.yml
            lifecycle.yml
            main.yml
        openshell-development/
          defaults/
            main.yml
          tasks/
            main.yml
        openshell-rpm/
          defaults/
            main.yml
          tasks/
            main.yml
    scripts/
      snap-gateway-repro.sh
    cache-lib.sh
    cache-seal.sh
    cache.sh
    README.md
    run.sh
providers/
  anthropic.yaml
  aws-bedrock.yaml
  aws-s3.yaml
  aws.yaml
  claude-code.yaml
  codex.yaml
  copilot.yaml
  cursor.yaml
  deepinfra.yaml
  github.yaml
  google-cloud.yaml
  google-vertex-ai.yaml
  nvidia.yaml
  oci-genai.yaml
  openai.yaml
  openrouter.yaml
  pypi.yaml
  README.md
python/
  openshell/
    _proto/
      __init__.py
    __init__.py
    errors_test.py
    errors.py
    gateway_config_fixture_test.py
    gateway_schema_v2_capability_parity_test.py
    gateway_schema_v2_compute_boundary_verifier_test.py
    gateway_schema_v2_cross_cutting_dispositions_test.py
    gateway_schema_v2_intentional_changes_test.py
    gateway_schema_v2_kubernetes_option_dispositions_test.py
    gateway_schema_v2_live_results_test.py
    gateway_schema_v2_parity_gap_dispositions_test.py
    mutations.py
    openshell_test.py
    py.typed
    release_formula_test.py
    rpm_gateway_config_migration_test.py
    sandbox_cleanup_test.py
    sandbox_test.py
    sandbox.py
  release_tooling_test.py
  wheel_verifier_test.py
rfc/
  0000-template/
    README.md
  0001-core-architecture/
    README.md
  0002-agent-driven-policy-management/
    README.md
  0003-gateway-configuration/
    README.md
  0004-sandbox-resource-requirements/
    README.md
  0005-sandbox-proxy-egress-adapter/
    current-shape.md
    implementation-plan.md
    README.md
    technical-design.md
  0006-driver-config-passthrough/
    README.md
  0009-supervisor-middleware/
    appendices/
      deployment-options.md
      extension-authentication.md
      protocol-extensions.md
    README.md
  0010-gateway-interceptors/
    appendices/
      extension-authentication.md
    README.md
  0011-multi-player-design/
    README.md
  0012-isolation-backend/
    README.md
  0013-native-windows-mxc/
    README.md
  0014-release-stability/
    build-matrix.md
    README.md
    release-qualification.md
    release-version-selection.md
  README.md
scripts/
  agents/
    gator/
      prompts/
        gator.md
      providers/
        codex-gator.yaml
        github-gator.yaml
      skills/
        gator-gate/
          references/
            review-findings-schema.md
          SKILL.md
      agent.yaml
      Dockerfile
      policy.yaml
      README.md
    runtime/
      harnesses/
        codex/
          exec_test.sh
          exec.sh
          install-codex.sh
          subagent.sh
      entrypoint.sh
      subagent.sh
      supervisor_test.sh
      supervisor.sh
    README.md
    run.sh
  lint-mermaid/
    lint-mermaid.mjs
    package.json
  baseline_workflow_metrics.py
  docker-cleanup.sh
  generate_third_party_notices.py
  junit-to-html.xsl
  keycloak-dev.sh
  keycloak-realm.json
  keycloak-realm.json.license
  smoke-test-network-policy.sh
  test-release-tag.sh
  update_license_headers.py
sdk/
  conformance/
    oauth-client-credentials.json
    oauth-client-credentials.json.license
  go/
    docs/
      src/
        api/
          client.md
          config.md
          edge.md
          exec.md
          fake.md
          files.md
          gateway.md
          health.md
          oidc.md
          overview.md
          policy.md
          profiles.md
          providers.md
          refresh.md
          sandbox-templates.md
          sandboxes.md
          services.md
          ssh.md
          tcp.md
        architecture.md
        error-handling.md
        getting-started.md
        introduction.md
        SUMMARY.md
        testing.md
      book.toml
    openshell/
      v1/
        edge/
          cloudflare_test.go
          cloudflare.go
          doc.go
          options_nil_test.go
          tunnel_test.go
          tunnel.go
        fake/
          broadcaster_test.go
          broadcaster.go
          config_test.go
          config.go
          doc.go
          exec_test.go
          exec.go
          fake_test.go
          fake.go
          file_test.go
          file.go
          health_test.go
          health.go
          mutations.go
          options_nil_test.go
          pager.go
          policy_test.go
          policy.go
          profile_test.go
          profile.go
          provider_test.go
          provider.go
          refresh_test.go
          refresh.go
          sandbox_template_test.go
          sandbox_template.go
          sandbox_test.go
          sandbox.go
          service_test.go
          service.go
          ssh_test.go
          ssh.go
          store_test.go
          store.go
          tcp_test.go
          tcp.go
          workspace_test.go
          workspace.go
        gateway/
          config_test.go
          config.go
          doc.go
          errors_test.go
          errors.go
          gateway_test.go
          gateway.go
          options_nil_test.go
          options.go
          paths_test.go
          paths.go
          token_test.go
          token.go
        internal/
          converter/
            copy.go
            coverage_test.go
            errors_test.go
            errors.go
            exec_test.go
            exec.go
            health_test.go
            health.go
            log_test.go
            log.go
            network_policy_test.go
            network_policy.go
            policy_test.go
            policy.go
            profile_test.go
            profile.go
            provider_test.go
            provider.go
            refresh_test.go
            refresh.go
            sandbox_test.go
            sandbox.go
            service_test.go
            service.go
            setting_test.go
            setting.go
            ssh_test.go
            ssh.go
            time_test.go
            time.go
            workspace_test.go
            workspace.go
          grpc/
            conn_test.go
            conn.go
          options/
            options_test.go
            options.go
        oidc/
          authcode_test.go
          authcode.go
          browser_test.go
          browser.go
          credentials_auth.go
          credentials_test.go
          credentials.go
          device_test.go
          device.go
          discovery_test.go
          discovery.go
          doc.go
          errors_test.go
          errors.go
          example_test.go
          keyboard_test.go
          keyboard.go
          oidc_test.go
          oidc.go
          options_nil_test.go
          options_test.go
          options.go
          token_test.go
          token.go
        types/
          auth.go
          config.go
          doc.go
          errors.go
          exec.go
          health.go
          log.go
          logger.go
          mutations.go
          network_policy.go
          options_nil_test.go
          options.go
          policy.go
          profile.go
          provider.go
          refresh.go
          sandbox.go
          service.go
          setting.go
          ssh.go
          types.go
          watch.go
          workspace.go
        auth_extra_test.go
        auth_extra.go
        auth_refresh_test.go
        auth_refresh.go
        auth_test.go
        auth.go
        client_test.go
        client.go
        config_client_test.go
        config_client.go
        config.go
        context_errors_test.go
        context_errors.go
        doc.go
        errors_test.go
        errors.go
        example_fake_test.go
        example_test.go
        exec_client_test.go
        exec_client.go
        exec_control_test.go
        exec.go
        file_client_test.go
        file_client.go
        file.go
        health_client_test.go
        health_client.go
        health.go
        integration_test.go
        logger.go
        mutations.go
        options_nil_test.go
        options.go
        pager_test.go
        pager.go
        policy_client_test.go
        policy_client.go
        policy.go
        profile_client_test.go
        profile_client.go
        profile.go
        provider_client_test.go
        provider_client.go
        provider.go
        refresh_client_test.go
        refresh_client.go
        refresh.go
        sandbox_client_test.go
        sandbox_client.go
        sandbox_template_client_test.go
        sandbox_template_client.go
        sandbox_template.go
        sandbox.go
        service_client_test.go
        service_client.go
        service.go
        ssh_client_test.go
        ssh_client.go
        ssh.go
        tcp_client_test.go
        tcp_client.go
        tcp.go
        types_reexport.go
        types.go
        watch_test.go
        watch.go
        workspace_client.go
        workspace_scope.go
        workspace_test.go
        workspace.go
    .golangci.yml
    buf.gen.yaml
    mise.toml
    README.md
  typescript/
    src/
      client.test.ts
      client.ts
      errors.test.ts
      errors.ts
      index.ts
      oidc.test.ts
      oidc.ts
      raw.test.ts
      raw.ts
      ssh-validate.ts
      transport.test.ts
      transport.ts
    biome.json
    biome.json.license
    buf.gen.yaml
    package.json
    README.md
    tsconfig.build.json
    tsconfig.build.json.license
    tsconfig.json
    tsconfig.json.license
    vitest.config.ts
skills/
  debug-inference/
    SKILL.md
  debug-openshell-cluster/
    references/
      supervisor-middleware.md
    SKILL.md
  generate-sandbox-policy/
    examples.md
    SKILL.md
  openshell-cli/
    SKILL.md
snap/
  hooks/
    connect-plug-docker
    install
    post-refresh
  local/
    term.desktop
tasks/
  scripts/
    vm/
      _lib.sh
      build-libkrun-macos.sh
      build-libkrun.sh
      build-supervisor-bundle.sh
      compress-vm-runtime.sh
      download-kernel-runtime.sh
      package-vm-runtime.sh
      smoke-orphan-cleanup.sh
      vm-setup.sh
    build-env.sh
    check_docs_nav_test.py
    check_docs_nav.py
    check-cargo-lockfiles.ps1
    check-cargo-lockfiles.sh
    codex_security_range_test.py
    codex_security_range.py
    container-engine.sh
    docker-build-ci.sh
    docker-build-image.sh
    docker-publish-multiarch.sh
    e2e-build-workload.sh
    e2e-gpu-build-images.sh
    gateway-docker.sh
    gateway-podman.sh
    gateway-pull-policy.sh
    gateway-toml.sh
    gateway-vm.sh
    gateway.sh
    generate_python_proto.py
    generate-qualification-summary.sh
    helm-k3s-local.sh
    keycloak-k8s-setup.sh
    package-deb-install.sh
    package-deb.sh
    release.py
    run-git-bash.ps1
    sandbox.sh
    setup-zig-cc-wrapper.sh
    snap-gateway-wrapper.sh
    stage-prebuilt-binaries.sh
    sync_docs_website_test.py
    sync_docs_website.py
    test-build-env.sh
    test-e2e-image-overrides.sh
    test-gateway-config.sh
    test-gateway-pull-policy.sh
    test-install-sh.sh
    test-packaging-assets.sh
    test-qualification-summary.sh
    test-snap-gateway-wrapper.sh
    test-snap-install-hook.sh
    trivy-config-report.jq
    trivy-scan-test.sh
    trivy-scan.sh
    typescript-install.ps1
    typescript-proto.ps1
    verify-defaults-without-telemetry.sh
    verify-glibc-symbols.sh
    verify-image-sbom.sh
    verify-python-wheel.py
    verify-static-binary.sh
    verify-telemetry-compiled-out.sh
    windows-msvc.ps1
  ci.toml
  docker.toml
  docs.toml
  gateway.toml
  go.toml
  helm.toml
  keycloak.toml
  license.toml
  markdown.toml
  notices.toml
  package.toml
  parity.toml
  python.toml
  rust.toml
  sandbox.toml
  sbom.toml
  term.toml
  test.toml
  typescript.toml
  version.toml
  vm.toml
  windows.toml
telemetry/
  2026-07-08.md
  2026-07-26.md
  2026-08-10.md
  README.md
.env.example
.markdownlint-cli2.jsonc
.packit.yaml
.python-version
.trivyignore.yaml
about.toml
AGENTS.md
buf.yaml
Cargo.toml
CI.md
CLAUDE.md
CODE_OF_CONDUCT.md
CONTRIBUTING.md
DCO
deny.toml
GOVERNANCE.md
install.sh
LICENSE
MAINTAINERS.md
mise.toml
openshell.spec
pyproject.toml
README.md
rust-toolchain.toml
SECURITY.md
snapcraft.yaml
STYLEGUIDE.md
TESTING.md
THIRD-PARTY-NOTICES
</directory_structure>

<files>
This section contains the contents of the repository's files.

<file path=".agents/skills/build-from-issue/SKILL.md">
---
name: build-from-issue
description: Given a GitHub issue number, plan and implement the work described in the issue. Supports direct user requests and unattended queue processing through the `agent:*` workflow labels. Includes tests, documentation updates, and PR creation. Trigger keywords - build from issue, implement issue, work on issue, build issue, start issue.
metadata:
  internal: true
---

# Build From Issue

Plan, iterate on feedback, and implement work described in a GitHub issue.

This skill operates as a stateful workflow — it can be run repeatedly against the same issue. Each invocation inspects the issue's labels, plan comment, and conversation history to determine the correct next action.

## Prerequisites

- The `gh` CLI must be authenticated (`gh auth status`)
- You must be in a git repository with a GitHub remote

## Invocation and Authorization

This skill supports two invocation modes:

- **Direct mode:** A user explicitly asks the agent to plan or implement a specific issue. The request itself authorizes the requested phase; the corresponding `agent:*` request label is not required.
- **Queue mode:** An always-on or unattended agent scans for work without a live user directing it to a specific issue. In this mode, `agent:plan-requested` authorizes planning and `agent:implementation-requested` authorizes implementation.

A direct request authorizes only what it says. A request to review or plan does not authorize implementation. A request to build, implement, or work on an issue authorizes both the planning needed to perform the work and implementation unless the user asks to stop after planning.

The two request labels remain human-only queue controls. Under **no circumstances** should this skill or any agent apply them, ask to apply them, or suggest automating their application.

In direct mode, issue lifecycle and `agent:*` workflow labels are advisory rather than gates. Inspect the labels and warn the user about each expected label that is missing or any lifecycle label that indicates the normal workflow is incomplete, then continue with the requested phase. Do not ask the user to fix the labels first. A direct request does not change the issue's disposition or make the labels accurate; it only authorizes the requested work.
... (731 lines truncated)
</file>

<file path=".agents/skills/build-openshell-mxc-windows/reference.md">
# Reference: Windows MSVC maintenance lane

Companion to [SKILL.md](SKILL.md). Use this file for quick lookup while
maintaining the existing build-only Windows MSVC lane.

## Lane Files

| File | Purpose |
|---|---|
| `tasks/windows.toml` | Mise task definitions for `windows:*`. |
| `tasks/scripts/windows-msvc.ps1` | Visual Studio environment discovery, rustup target setup, Cargo invocation, logs, artifact report. |
| `.github/workflows/windows-msvc.yml` | Opt-in PR lint and test plus `windows` branch cache seeding and dependent binary builds on native x64 and ARM64 runners. |

## Commands

Use `--skip-tools` for all Windows mise tasks:

```powershell
mise run --skip-tools windows:check:x64
mise run --skip-tools windows:check:arm64
mise run --skip-tools windows:build:x64
mise run --skip-tools windows:build:arm64
mise run --skip-tools windows:test:x64
mise run --skip-tools windows:test:arm64
mise run --skip-tools windows:test:unsupported:x64
mise run --skip-tools windows:test:unsupported:arm64
mise run --skip-tools windows:ci
```

For host-native full validation, detect architecture first:
... (202 lines truncated)
</file>

<file path=".agents/skills/build-openshell-mxc-windows/SKILL.md">
---
name: build-openshell-mxc-windows
description: Maintain and validate OpenShell's build-only Windows MSVC lane for x64 and ARM64. Use when working on Windows compilation, `windows:*` mise tasks, unsupported Windows compute-driver contracts, or Windows build reports. This skill does not implement Docker, Kubernetes, Podman, VM, MXC driver, policy translation, MSI, service, or supervisor runtime support on Windows.
metadata:
  internal: true
---

# Build OpenShell-MXC for Windows

This skill maintains the existing native Windows MSVC build lane in the
OpenShell repository. The Windows lane is already present in `main`; do not
treat this skill as a first-time porting recipe unless the user explicitly asks
for a new fork or a from-scratch bring-up.

The lane is build-only. It validates that OpenShell can compile and test on
Windows MSVC for the supported deliverables:

- `openshell-gateway.exe`
- `openshell.exe`

It intentionally does not make Windows a Docker, Kubernetes, Podman, or VM
runtime host.

## Current Repository Shape

The Windows build lane is implemented by these tracked files:

| Path | Purpose |
|---|---|
| `tasks/windows.toml` | Mise task entry points for `windows:*` commands. |
... (332 lines truncated)
</file>

<file path=".agents/skills/create-github-issue/SKILL.md">
---
name: create-github-issue
description: Create GitHub issues using the gh CLI. Use when the user wants to create a new issue, report a bug, request a feature, or create a task in GitHub. Trigger keywords - create issue, new issue, file bug, report bug, feature request, github issue.
metadata:
  internal: true
---

# Create GitHub Issue

Create issues on GitHub using the `gh` CLI. Issues must conform to the project's issue templates.

## Prerequisites

The `gh` CLI must be authenticated (`gh auth status`).

## Issue Templates

This project uses YAML form issue templates. When creating issues, match the template structure so the output aligns with what GitHub renders.

### Bug Reports

Do not add a type label automatically. The body must include a **User Story**, **Problem Statement**, **Impact / Why This Matters**, and **Acceptance Criteria**, followed by bug-specific reproduction steps and environment details. Logs are optional and must be concise and redacted. Apply area or topic labels only when they are clearly known.

```bash
gh issue create \
  --title "bug: <concise description>" \
  --body "$(cat <<'EOF'
## User Story

As a <persona>, I want <capability or outcome>, so that <benefit or impact>.
... (125 lines truncated)
</file>

<file path=".agents/skills/create-github-pr/SKILL.md">
---
name: create-github-pr
description: Create GitHub pull requests using the gh CLI. Use when the user wants to create a new PR, submit code for review, or open a pull request. Trigger keywords - create PR, pull request, new PR, submit for review, code review.
metadata:
  internal: true
---

# Create GitHub Pull Request

Create pull requests on GitHub using the `gh` CLI.

## Prerequisites

- The `gh` CLI must be authenticated (`gh auth status`)
- You must have commits on a branch that's pushed to the remote
- For issue-backed work, the branch should follow `<issue-number>-<description>/<username>`. Exempt issue-less changes may use `<description>/<username>`.

## Before Creating a PR

### Check Config Documentation

If the branch changes gateway TOML parsing, `[openshell.gateway]` fields,
`[openshell.drivers.<name>]` fields, driver config defaults, or Helm rendering
of `gateway.toml`, verify that `docs/how-it-works/gateways/configuration.mdx` is updated
in the same branch. If the change affects user-facing compute-driver setup,
also update `docs/how-it-works/sandboxes/runtimes.mdx` or the relevant
deployment docs.

### Check Agent Infrastructure

... (224 lines truncated)
</file>

<file path=".agents/skills/create-rfc/agents/openai.yaml">
interface:
  display_name: "Create RFC"
  short_description: "Create OpenShell RFC proposals"
  default_prompt: "Use $create-rfc to draft an OpenShell RFC from this design."
</file>

<file path=".agents/skills/create-rfc/SKILL.md">
---
name: create-rfc
description: Create OpenShell RFC proposals in rfc/ from a design request. Use when the user asks to write, draft, start, create, or update an RFC, Request for Comments, architecture proposal, API proposal, process proposal, or cross-cutting design proposal that should follow the OpenShell RFC process and template.
metadata:
  internal: true
---

# Create RFC

## Workflow

Create RFCs by following `rfc/README.md` and `rfc/0000-template/README.md`.
Keep the template as the source of truth for section guidance.

1. Read `rfc/README.md` to confirm when an RFC is appropriate, how to choose the
   RFC number, and how the lifecycle works.
2. Read `rfc/0000-template/README.md` before drafting. Follow its section
   guidance, including scope, expected detail, and suggested section length.
3. Choose the next available `NNNN` from the existing `rfc/NNNN-*` directories
   unless the user provided a specific number.
4. Create `rfc/NNNN-short-title/README.md` by copying the template and replacing
   placeholders. Use a short hyphenated folder title.
5. Fill in front matter with the RFC author, `state: draft`, and any related
   links the user provided. If the author is unknown, use the requesting user's
   GitHub handle when available or leave the template placeholder.
6. Draft each section from the user's design context. Keep Summary concise,
   Motivation readable by anyone, Non-goals explicit, Proposal focused on what
   is being proposed, and Alternatives focused on credible competing approaches.
7. Preserve uncertainty in Open questions instead of silently deciding unknowns.
   If a missing decision blocks a coherent RFC, ask the user for that decision.
... (24 lines truncated)
</file>

<file path=".agents/skills/create-spike/SKILL.md">
---
name: create-spike
description: Investigate a plain-language problem description by deeply exploring the codebase, then create a structured GitHub issue with technical findings. Prequel to build-from-issue — maps vague ideas to concrete, buildable issues. Trigger keywords - spike, investigate, explore, research issue, technical investigation, create spike, new spike, feasibility, codebase exploration.
metadata:
  internal: true
---

# Create Spike

Investigate a problem, map it to the codebase, and produce a structured GitHub issue ready for human disposition and roadmap placement.

A **spike** is an exploratory investigation. The user has a vague idea — a feature they want, a bug they've noticed, a performance concern — but hasn't mapped it to code, assessed feasibility, or structured it as a buildable issue. This skill does that mapping.

## Prerequisites

- The `gh` CLI must be authenticated (`gh auth status`)
- You must be in a git repository with a GitHub remote

## Workflow Overview

```
User describes a problem
  │
  ├─ Step 1: Gather the problem statement
  │   └─ Ask ONE round of clarifying questions if genuinely needed
  │
  ├─ Step 2: Deep codebase investigation via principal-engineer-reviewer
  │   └─ Map the problem to code, assess feasibility, identify risks
  │
  ├─ Step 3: Determine labels from the repo
... (289 lines truncated)
</file>

<file path=".agents/skills/fix-security-issue/SKILL.md">
---
name: fix-security-issue
description: Implement a fix for a reviewed security issue. Takes a directly requested issue number or scans for issues labeled `topic:security` and `agent:implementation-requested`. Reads the security review from the issue comments and implements the remediation plan. Trigger keywords - fix security issue, remediate security, implement security fix, patch vulnerability.
metadata:
  internal: true
---

# Fix Security Issue

Implement a code fix for a security issue that has already been reviewed by the `review-security-issue` skill.

## Prerequisites

- The `gh` CLI must be authenticated (`gh auth status`)
- You must be in a git repository with a GitHub remote
- The issue must have `topic:security`. In unattended scan mode it must also have `agent:implementation-requested`; for a direct user request, warn if that workflow label is missing and continue without changing it.
- The issue must have a prior security review comment (posted by `review-security-issue`) with a **Legitimate concern** determination and a remediation plan

## Agent Comment Marker

All PR descriptions and comments posted by this skill **must** begin with the following marker line:

```
> **🔧 security-fix-agent**
```

This distinguishes fix-agent content from review-agent comments (`🔒 security-review-agent`) and human comments.

## Step 1: Identify the Issue

... (293 lines truncated)
</file>

<file path=".agents/skills/helm-dev-environment/SKILL.md">
---
name: helm-dev-environment
description: Start up, tear down, and configure the local Kubernetes development environment for OpenShell. Uses k3d (Docker-backed k3s) + Skaffold + Helm. Covers cluster lifecycle, optional add-ons (Keycloak OIDC, Envoy Gateway), HA testing, and port mappings. Trigger keywords - local k8s, local cluster, k3d, skaffold, helm dev, start cluster, stop cluster, tear down cluster, delete cluster, create cluster, helm:k3s, helm:skaffold, local dev environment, dev cluster, k8s dev, envoy gateway local, keycloak local, high availability, HA.
metadata:
  internal: true
---

# Helm Dev Environment

Set up, run, and tear down the local Kubernetes development environment for OpenShell.
The stack is: **k3d** (Docker-backed k3s) for the cluster, **Skaffold** for image builds and Helm deploys, and the **OpenShell Helm chart** (`deploy/helm/openshell/`).

---

## Prerequisites

- Docker Desktop (macOS) or Docker Engine (Linux) running
- `mise install` completed (provides `k3d`, `kubectl`, `skaffold`, `helm`)

---

## Startup

### 1. Create the cluster

```bash
mise run helm:k3s:create
```

Creates a k3d cluster and merges its kubeconfig into the worktree-local `kubeconfig` file.
... (430 lines truncated)
</file>

<file path=".agents/skills/launch-openshell-gator/SKILL.md">
---
name: launch-openshell-gator
description: Launch and supervise OpenShell gator agents. Use when starting gator on issues or PRs, checking gator sandboxes, building the gator sandbox image, restarting stuck gators, inspecting gator logs, or experimenting with gator harness/model overrides. Trigger keywords - launch gator, start gator, run gator, gator sandbox, supervised gator, gator logs, restart gator.
metadata:
  internal: true
---

# Launch OpenShell Gator

Launch and supervise the repository's headless gator sandbox agent through OpenShell. This skill covers the operator workflow around `scripts/agents/run.sh`; the in-sandbox review and state-machine policy remains the `gator-gate` skill baked into the gator payload.

For gator's PR/issue validation policy, load `gator-gate` inside the launched sandbox. For generic sandbox CLI usage, use `openshell-cli`. For unhealthy gateways or sandbox startup failures, use `debug-openshell-cluster` after the launch preflight identifies a gateway/runtime problem.

## Non-Negotiable Rules

- Keep normal gator launches supervised: use `--watch` and let the in-sandbox supervisor own sleeping and relaunching bounded cycles.
- Do not add passive `sleep` loops in the operator session to watch gator. Check logs or status once, then report the current state or launch a proper watcher outside the model session only when explicitly asked.
- Do not change the default gator model in `scripts/agents/gator/agent.yaml` for experiments. Use `CODEX_MODEL=...` and, if needed, a temporary `--from` Docker context or `--codex-bin` override.
- Do not push to contributor branches, approve, merge, post `/ok to test`, or broaden gator scope unless the operator explicitly authorized that action.
- Scope each launch prompt to the requested issue/PR set. Avoid repo-wide gator scans unless the operator asked for repo-wide processing.
- Leave unrelated local files alone, including `.opencode/` artifacts and old gator logs unless the user asks for cleanup.

## Key Paths

| Path | Purpose |
|---|---|
| `scripts/agents/run.sh` | Manifest-driven OpenShell agent launcher. |
| `scripts/agents/gator/agent.yaml` | Gator manifest: immutable payload version, default gateway, harness, providers, runtime, skills, and subagents. |
| `scripts/agents/gator/Dockerfile` | Gator sandbox image source. Local launches build it in gateway's Docker or Podman image store. |
| `scripts/agents/gator/policy.yaml` | Sandbox policy for the gator agent. |
... (376 lines truncated)
</file>

<file path=".agents/skills/review-github-pr/SKILL.md">
---
name: review-github-pr
description: Review a GitHub pull request by summarizing its diff and key design decisions. Use when the user wants to review a PR, understand changes in a branch, or get a code review summary. Trigger keywords - review PR, review pull request, summarize PR, summarize diff, code review, review branch, PR summary, diff summary.
metadata:
  internal: true
---

# Review GitHub Pull Request

Summarize a GitHub pull request diff, highlighting key design decisions and notable code snippets.

## Prerequisites

- The `gh` CLI must be authenticated (`gh auth status`)
- You must be in a git repository with a GitHub remote

## Step 1: Resolve the PR

The user will provide either a **PR number** (e.g., `#123` or `123`) or a **branch name**. Determine which input was given and resolve it to a PR.

### If a PR number is provided

Strip any leading `#` and use the numeric ID directly. Proceed to Step 2.

### If a branch name is provided

Look up the open PR whose head branch matches:

```bash
gh pr list --head "<branch>" --state open
... (152 lines truncated)
</file>

<file path=".agents/skills/review-security-issue/SKILL.md">
---
name: review-security-issue
description: Given a GitHub issue, review the issue for security implications. You'll make a determination if the claim in the issue is legitimate and should be addressed or will be a "won't fix." Trigger keywords - security issue, review security ticket, review security issue.
metadata:
  internal: true
---

# Review Security Issue

Review an issue that outlines a security, vulnerability, or privacy concern.

## Prerequisites

- The `gh` CLI must be authenticated (`gh auth status`)
- You must be in a git repository with a GitHub remote
- The issue must have `topic:security`. In unattended queue mode it must also have `agent:plan-requested`; for a direct user request, warn if that workflow label is missing and continue without changing it.

## Agent Comment Marker

All comments posted by this skill **must** begin with the following marker line so that prior reviews can be detected and human comments can be distinguished from agent comments:

```
> **🔒 security-review-agent**
```

This marker is used in Step 2 to detect prior reviews and in Step 5 to distinguish agent comments from human comments.

## Step 1: Fetch the Issue

The user will provide an issue ID (e.g., `#42` or `42`). Strip any leading `#` and fetch the issue contents.
... (167 lines truncated)
</file>

<file path=".agents/skills/sbom/SKILL.md">
---
name: sbom
description: Generate and manage Software Bill of Materials (SBOMs) for the OpenShell project. Covers SBOM generation with Syft, license resolution via public registries, and CSV export for compliance review. Trigger keywords - SBOM, sbom, bill of materials, license audit, license resolution, generate sbom, sbom csv, dependency license, supply chain, license scan.
metadata:
  internal: true
---

# SBOM Generation and License Resolution

Generate CycloneDX SBOMs, resolve missing licenses, and export to CSV for compliance review.

## Overview

The OpenShell SBOM tooling produces source-tree CycloneDX JSON SBOMs using Syft, resolves missing or hash-based licenses by querying public registries (crates.io, npm, PyPI), and exports the results to CSV for stakeholder review.

SBOMs are **release artifacts only** -- they are generated on demand and not committed to the repository. Output lands in `deploy/sbom/output/` (gitignored).

Pushed gateway, sandbox, and supervisor images carry an SPDX SBOM and minimal SLSA provenance as OCI attestations. Branch E2E, Release Dev, and Release Tag image binaries embed cargo-auditable metadata, so their image SBOMs include linked Rust crates.

## Prerequisites

- `mise install` has been run (installs Syft and other tools)
- The repository is checked out at the root

## Inspecting an Image SBOM

BuildKit uses its default Syft scanner and attaches one SPDX document per platform. Read one without pulling the image:

```bash
docker buildx imagetools inspect ghcr.io/nvidia/openshell/gateway:latest \
... (115 lines truncated)
</file>

<file path=".agents/skills/sync-agent-infra/SKILL.md">
---
name: sync-agent-infra
description: Detect and fix drift across agent-first infrastructure files. Ensures skill inventories, workflow chains, architecture tables, issue/PR templates, and cross-references stay consistent when skills, crates, or workflows change. Run after adding, removing, or renaming skills or components. Trigger keywords - sync agent infra, sync skills, update agent docs, check agent consistency, agent infra drift, sync contributing, sync agents.
metadata:
  internal: true
---

# Sync Agent Infrastructure

Detect and fix drift across the agent-first infrastructure files. These files reference each other and must stay consistent:

| File | What it tracks |
|------|---------------|
| `AGENTS.md` | Project identity, workflow chains, architecture overview, issue/PR conventions, skill maintenance pointer |
| `CONTRIBUTING.md` | Skills table, workflow chains, "When to Open an Issue" guidance, skill references |
| `CONTRIBUTING.md` issue lifecycle section | Human-facing issue states, roadmap decisions, acceptance signals, and direct-versus-queued agent ownership |
| `README.md` | "Use OpenShell with Your Agent" and "Built With Agents" sections |
| `.github/ISSUE_TEMPLATE/bug_report.yml` | Skill name references in diagnostic guidance |
| `.github/ISSUE_TEMPLATE/feature_request.yml` | Skill name references in investigation guidance |
| `.github/ISSUE_TEMPLATE/config.yml` | Contact link text referencing skills |
| `.github/workflows/issue-triage.yml` | Comment text referencing skills |
| `.agents/skills/triage-issue/SKILL.md` | Skill name references in gate check and diagnosis steps |
| `skills/*/SKILL.md` | Standalone user instructions and links to documentation, included files, and related skills |
| `.agents/skills/create-github-pr/SKILL.md` | Pre-PR agent infrastructure check |
| `.agents/skills/review-github-pr/SKILL.md` | Review-time agent infrastructure check |
| `.agents/skills/build-from-issue/SKILL.md` | Label awareness and pre-commit agent infrastructure check |
| `.claude/agents/principal-engineer-reviewer.md` | Shared review-time agent infrastructure check |

## When to Run

... (185 lines truncated)
</file>

<file path=".agents/skills/test-release-canary/SKILL.md">
---
name: test-release-canary
description: Manually dispatch and iterate on the Release Canary workflow that smoke-tests published OpenShell artifacts (install.sh on macOS/Ubuntu/Fedora, Helm chart on kind) after each Release Dev publish. Use when changing `.github/workflows/release-canary.yml`, validating a release before tagging, debugging a canary failure, or reproducing a canary job locally. Trigger keywords - release canary, release-canary, canary failed, canary dispatch, test release canary, post-release smoke, install.sh canary, helm chart canary, kind canary, dispatch canary.
metadata:
  internal: true
---

# Test Release Canary

The Release Canary (`.github/workflows/release-canary.yml`) smoke-tests the artifacts a `Release Dev` run just published. It is the last automated checkpoint before tagging a public release: if the canary is red, the published `dev` artifacts do not install on a stock environment.

## What the canary verifies

| Job | Runner | Verifies |
|---|---|---|
| `macos` | `macos-latest-xlarge` | Installs the dev Homebrew artifacts, reaches the VM gateway, and creates, executes in, and deletes a sandbox. |
| `ubuntu-deb` | `ubuntu-latest` | Installs the dev Debian package, reaches the Docker gateway, and creates, executes in, and deletes a sandbox. |
| `fedora` | `fedora:latest` container | Installs the dev RPM packages, reaches the Podman gateway, and creates, executes in, and deletes a sandbox. |
| `ubuntu-snap-system-docker` | `ubuntu-latest` | Uses `install.sh` to install the snap from `latest/edge`, reuses system Docker, reaches the Docker gateway, and creates, executes in, and deletes a sandbox, and verifies that the Docker snap is not installed. |
| `ubuntu-snap-docker-preflight` | `ubuntu-latest` | Verifies that `install.sh` rejects the OpenShell Snap path when Docker is absent or supplied by the Docker snap, without installing OpenShell. |
| `kubernetes` | `ubuntu-latest` + kind | Installs the dev Helm chart, reaches the in-cluster gateway, and creates, executes in, and deletes a sandbox using the published runtime images. |

All canary jobs disable anonymous OpenShell telemetry. Host package jobs inject
`OPENSHELL_TELEMETRY_ENABLED=false` through the service environment, and the
Kubernetes job installs with `server.telemetryEnabled=false`, so smoke traffic
does not contribute to product usage metrics.

The workflow sets `OPENSHELL_VERSION=dev` for every `install.sh` job. Positive
jobs consume the rolling dev release produced by the triggering workflow. The
system-Docker Snap lane tracks `latest/edge`; the missing-Docker lane exits
... (122 lines truncated)
</file>

<file path=".agents/skills/triage-issue/SKILL.md">
---
name: triage-issue
description: Assess, validate, and route community-filed issues for human disposition and roadmap placement. Takes a specific issue number or processes a confirmed batch of issues labeled state:triage-needed. Investigates reported behavior, separates objective findings from product decisions, and prepares validated issues for a human yes/no decision. Trigger keywords - triage issue, triage, assess issue, review incoming issue, triage issues.
metadata:
  internal: true
---

# Triage Issue

Establish the facts a human needs to decide whether OpenShell should address an issue and, if so, where it belongs on the roadmap. Triage does not authorize work, sequence it, or produce an implementation plan.

## Prerequisites

- The `gh` CLI must be authenticated (`gh auth status`)
- You must be in a git repository with a GitHub remote
- The workflow labels `state:validated`, `state:accepted`, and `state:needs-info` must exist. Report missing labels to the operator; do not create them implicitly.

## Critical: Disposition and Roadmap Placement Are Human-Only

Triage establishes technical validity; it does not decide whether valid work belongs on the roadmap. Agents must never:

- Decide that OpenShell should or should not invest in otherwise valid work.
- Apply or remove `state:accepted`.
- Add an issue to the roadmap project, apply or remove the `roadmap` label, or recommend a specific roadmap item.
- Apply `agent:plan-requested` or `agent:implementation-requested`.
- Treat technical validity as product acceptance.

OpenShell has no `priority:*` labels. Sequencing comes from association with an item on the OpenShell Roadmap, and that association is a maintainer decision.

`state:validated` means the factual assessment is complete and awaits human disposition. A human declines by closing the issue as not planned with a rationale, or accepts by applying `state:accepted`, placing the issue on the roadmap, or doing both as documented in `CONTRIBUTING.md`. Accepted work may remain human-owned. A maintainer can queue deeper agent investigation or planning with `agent:plan-requested`, or a user can directly ask an agent to work on a specific issue.
... (225 lines truncated)
</file>

<file path=".agents/skills/tui-development/SKILL.md">
---
name: tui-development
description: Guide for developing the OpenShell TUI — a ratatui-based terminal UI for the OpenShell platform. Covers architecture, navigation, data fetching, theming, UX conventions, and development workflow. Trigger keywords - term, TUI, terminal UI, ratatui, openshell-tui, tui development, tui feature, tui bug.
metadata:
  internal: true
---

# OpenShell TUI Development Guide

Comprehensive reference for any agent working on the OpenShell TUI.

## 1. Overview

The OpenShell TUI is a ratatui-based terminal UI for the OpenShell platform. It provides a keyboard-driven interface for managing gateways, sandboxes, and logs — the same operations available via the `openshell` CLI, but with a live, interactive dashboard.

- **Launched via:** `openshell term` or `mise run term`
- **Crate:** `crates/openshell-tui/`
- **Key dependencies:**
  - `ratatui` (workspace version) — uses `frame.size()` (not `frame.area()`)
  - `crossterm` (workspace version) — terminal backend and event polling
  - `tonic` with TLS — gRPC client for the OpenShell gateway
  - `tokio` — async runtime for event loop, spawned tasks, and mpsc channels
  - `openshell-core` — proto-generated types (`OpenShellClient`, request/response structs)
  - `openshell-bootstrap` — gateway discovery (`list_gateways()`)
- **Theme:** Adaptive dark/light via `Theme` struct — NVIDIA-branded green accents. Controlled by `--theme` flag, `OPENSHELL_THEME` env var, or auto-detection.

## 2. Domain Object Hierarchy

The data model follows a strict hierarchy: **Gateway > Workspace > Sandboxes/Providers/Settings > Logs**.

... (620 lines truncated)
</file>

<file path=".agents/skills/update-docs/SKILL.md">
---
name: update-docs-from-commits
description: Scan recent git commits for changes that affect user-facing behavior, then draft or update the corresponding documentation pages. Use when docs have fallen behind code changes, after a batch of features lands, or when preparing a release. Trigger keywords - update docs, draft docs, docs from commits, sync docs, catch up docs, doc debt, docs behind, docs drift.
metadata:
  internal: true
---

# Update Docs from Commits

Scan recent git history for commits that affect user-facing behavior and draft documentation updates for each.

## Prerequisites

- You must be in the OpenShell git repository.
- The published docs tree must exist under `docs/`.
- Read `docs/CONTRIBUTING.mdx` before writing any content. It contains the current style guide and formatting rules.

## When to Use

- After a batch of features or fixes has landed and docs may be stale.
- Before a release, to catch any doc gaps.
- When a contributor asks "what docs need updating?"

## Step 1: Identify Relevant Commits

Determine the commit range. The user may provide one explicitly (e.g., "since v0.2.0" or "last 30 commits"). If not, default to commits since the head of the main branch.

```bash
# Commits since a tag
git log v0.2.0..HEAD --oneline --no-merges
... (159 lines truncated)
</file>

<file path=".agents/skills/watch-github-actions/SKILL.md">
---
name: watch-github-actions
description: Watch and monitor GitHub Actions workflow runs using the gh CLI. Use when the user wants to check workflow status, watch a running workflow, view CI/CD jobs, or monitor build progress. Trigger keywords - watch pipeline, pipeline status, CI status, check build, monitor CI, view pipeline, pipeline progress, workflow status, actions status.
metadata:
  internal: true
---

# Watch GitHub Actions

Monitor GitHub Actions workflow runs using the `gh` CLI.

## Prerequisites

- The `gh` CLI must be authenticated (`gh auth status`)
- You must be in a git repository with a GitHub remote

## Quick Status Check

List recent workflow runs for the current branch:

```bash
gh run list --branch "$(git branch --show-current)"
```

List all recent runs:

```bash
gh run list
```

... (200 lines truncated)
</file>

<file path=".cargo/config.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

[env]
# z3-sys bindgen needs the z3 include path. On some distros (e.g. RHEL/Fedora)
# the header lives in /usr/include/z3/ rather than /usr/include/. The extra -I
# is harmless on systems where the path doesn't exist.
BINDGEN_EXTRA_CLANG_ARGS = "-I/usr/include/z3"
</file>

<file path=".claude/agent-memory/principal-engineer-reviewer/MEMORY.md">
# Principal Engineer Reviewer Memory

## Project Structure
- Proto definitions: `proto/openshell.proto`, `proto/sandbox.proto`, `proto/sandbox_policy.proto`
- Server gRPC handlers: `crates/openshell-server/src/grpc.rs`
- TracingLogBus (log broadcast): `crates/openshell-server/src/tracing_bus.rs`
- Sandbox watch bus: `crates/openshell-server/src/sandbox_watch.rs`
- Server state: `crates/openshell-server/src/lib.rs` (ServerState struct)
- Sandbox main: `crates/openshell-sandbox/src/main.rs`
- Sandbox library: `crates/openshell-sandbox/src/lib.rs`
- Sandbox gRPC client: `crates/openshell-sandbox/src/grpc_client.rs`
- CLI commands: `crates/openshell-cli/src/main.rs` (clap defs), `crates/openshell-cli/src/run.rs` (impl)
- Python SDK: `python/openshell/`
- Plans go in: `plans/`

## Key Patterns
- TracingLogBus: per-sandbox broadcast::channel(1024) + VecDeque tail buffer (200 lines)
- CachedOpenShellClient: reusable mTLS gRPC channel for sandbox->server calls
- SandboxLogLayer: tracing Layer that captures events with sandbox_id field
- Sandbox logging: stdout (ANSI, configurable level) + /var/log/openshell.log (info, no ANSI, non-blocking)
- WatchSandbox: server-streaming with select! loop over status_rx, log_rx, platform_rx
- Proto codegen: `mise run proto`
- Build: `mise run sandbox` for sandbox infra

## Review Preferences (observed)
- Plans stored as markdown in plans/
- Conventional commits required
- No AI attribution in commits
</file>

<file path=".claude/agents/principal-engineer-reviewer.md">
---
name: principal-engineer-reviewer
description: >
  Use this agent to review existing code, audit plans, evaluate product
  requirements, or get architectural guidance that balances pragmatism, user
  experience, and security. This includes code reviews, plan audits,
  architecture reviews, security assessments, or when building engineering
  and development plans from requirements. Use proactively after significant
  code changes or before merging.
tools: Read, Grep, Glob, Bash, WebFetch, WebSearch
model: inherit
memory: project
---

You are a principal engineer reviewing code, plans, and architecture for the
OpenShell project. Your reviews balance three priorities equally:

1. **Pragmatism** — Does the solution match the complexity of the problem? Is
   the simplest viable approach being used? Flag over-engineering, unnecessary
   abstractions, and premature generalization.

2. **User empathy** — How does this affect the people who use, operate, and
   maintain this system? Consider developer ergonomics, operational burden,
   error messages, failure modes, and the debugging experience.

3. **Security** — What are the threat surfaces? Are trust boundaries respected?
   Is input validated at system boundaries? Are secrets, credentials, and
   tokens handled correctly? Evaluate changes against established frameworks:
   **CWE** for code-level weaknesses, **OWASP ASVS** (Level 3 for core
   runtime changes), **OWASP Top 10 for LLM Applications** (especially
... (239 lines truncated)
</file>

<file path=".claude/README.md">
# `.claude/` — Claude Code-specific configuration

Agent skills are canonical in `.agents/skills/` and shared across all harnesses (Claude Code, OpenCode, Cursor, etc.). This directory contains only Claude Code-specific configuration that cannot be made tool-agnostic.

## Contents

- `agents/` — Sub-agent persona definitions with Claude Code-specific frontmatter (`model`, `memory`, `color`, `tools`). The same personas exist in `.opencode/agents/` with OpenCode-specific config.
- `agent-memory/` — Persistent agent memory files. Claude Code runtime state, not portable across tools.
</file>

<file path=".opencode/agents/principal-engineer-reviewer.md">
---
description: >
  Use this agent to review existing code, audit plans, evaluate product
  requirements, or get architectural guidance that balances pragmatism, user
  experience, and security. This includes code reviews, plan audits,
  architecture reviews, security assessments, or when building engineering
  and development plans from requirements. Use proactively after significant
  code changes or before merging.
mode: subagent
tools:
  write: false
  edit: false
---

You are a principal engineer reviewing code, plans, and architecture for the
OpenShell project. Your reviews balance three priorities equally:

1. **Pragmatism** — Does the solution match the complexity of the problem? Is
   the simplest viable approach being used? Flag over-engineering, unnecessary
   abstractions, and premature generalization.

2. **User empathy** — How does this affect the people who use, operate, and
   maintain this system? Consider developer ergonomics, operational burden,
   error messages, failure modes, and the debugging experience.

3. **Security** — What are the threat surfaces? Are trust boundaries respected?
   Is input validated at system boundaries? Are secrets, credentials, and
   tokens handled correctly? Evaluate changes against established frameworks:
   **CWE** for code-level weaknesses, **OWASP ASVS** (Level 3 for core
   runtime changes), **OWASP Top 10 for LLM Applications** (especially
... (129 lines truncated)
</file>

<file path="crates/openshell-binary-identity/src/lib.rs">
use std::collections::HashMap;
⋮----
pub struct ProcfsIdentityResolver {
⋮----
enum AncestryScope {
⋮----
impl Default for ProcfsIdentityResolver {
fn default() -> Self {
⋮----
impl ProcfsIdentityResolver {
⋮----
pub fn for_pid_namespace() -> Self {
⋮----
pub fn for_process_tree(ancestor_root: u32) -> Self {
⋮----
pub fn resolve(&self, pid: u32) -> Result<BinaryIdentity, ResolveError> {
⋮----
AncestryScope::PidNamespace => nested_pid_namespace_init(pid),
AncestryScope::ProcessTree(root) => Some(root),
⋮----
resolve_linux_process(pid, ancestor_root, &self.cache)
⋮----
Err(ResolveError::Failed(
"procfs binary identity is only available on Linux".to_string(),
⋮----
fn resolve_linux_process(
⋮----
let (snapshot, mut executable) = open_process_snapshot(pid)?;
let mut ancestor_processes = collect_ancestor_processes(&snapshot, ancestor_root)?;
⋮----
... (257 lines truncated)
</file>

<file path="crates/openshell-binary-identity/Cargo.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

[package]
name = "openshell-binary-identity"
description = "Trusted executable identity resolution for OpenShell isolation backends"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true

[dependencies]
openshell-isolation-interface = { path = "../openshell-isolation-interface" }
sha2 = { workspace = true }

[lints]
workspace = true
</file>

<file path="crates/openshell-binary-identity/README.md">
# Binary identity

`openshell-binary-identity` provides shared executable-identity resolution for
RFC 0012 isolation backends. Runtime-specific observers remain in their backend:
Docker obtains an authoritative thread ID from seccomp notification, while the
co-located Linux path maps an accepted socket to its owning processes.

Given an authoritative Linux PID and an optional trusted process-tree root, the
crate opens the leaf and bounded ancestor `/proc/<pid>/exe` objects, hashes
those already-open live objects, and returns path-and-digest evidence for the
whole executable chain. It also collects diagnostic command-line paths, which
never authorize network access. Resolution fails without returning a partial
identity if any executable cannot be opened, hashed, or validated after
hashing. The caller receives `ResolveError` and denies the associated
connection.

The crate does not intercept connections, authenticate remote observers, or
evaluate policy. The isolation backend remains responsible for binding the
resolved identity to the active boundary and exact accepted connection before
constructing `PendingTcpOpen`.
</file>

<file path="crates/openshell-bootstrap/src/edge_token.rs">
use crate::paths::user_gateway_dir;
⋮----
use std::path::PathBuf;
⋮----
pub fn edge_token_path(gateway_name: &str) -> Result<PathBuf> {
Ok(user_gateway_dir(gateway_name)?.join("edge_token"))
⋮----
fn legacy_token_path(gateway_name: &str) -> Result<PathBuf> {
Ok(user_gateway_dir(gateway_name)?.join("cf_token"))
⋮----
pub fn store_edge_token(gateway_name: &str, token: &str) -> Result<()> {
let path = edge_token_path(gateway_name)?;
ensure_parent_dir_restricted(&path)?;
⋮----
.into_diagnostic()
.wrap_err_with(|| format!("failed to write edge token to {}", path.display()))?;
⋮----
set_file_owner_only(&path)?;
Ok(())
⋮----
pub fn load_edge_token(gateway_name: &str) -> Option<String> {
⋮----
if let Some(path) = edge_token_path(gateway_name).ok().filter(|p| p.exists()) {
let contents = std::fs::read_to_string(&path).ok()?;
let token = contents.trim().to_string();
if !token.is_empty() {
return Some(token);
⋮----
let legacy_path = legacy_token_path(gateway_name)
.ok()
... (89 lines truncated)
</file>

<file path="crates/openshell-bootstrap/src/jwt.rs">
pub struct JwtKeyMaterial {
⋮----
pub fn generate_jwt_key() -> Result<JwtKeyMaterial> {
⋮----
.into_diagnostic()
.wrap_err("failed to generate Ed25519 JWT signing key")?;
let signing_key_pem = keypair.serialize_pem();
let public_key_pem = keypair.public_key_pem();
let kid = kid_from_public_key_der(&keypair.public_key_der());
Ok(JwtKeyMaterial {
⋮----
fn kid_from_public_key_der(public_key_der: &[u8]) -> String {
⋮----
hex_encode_prefix(&digest, 16)
⋮----
fn hex_encode_prefix(bytes: &[u8], n: usize) -> String {
⋮----
for byte in bytes.iter().take(n) {
let _ = write!(out, "{byte:02x}");
⋮----
mod tests {
⋮----
fn generate_jwt_key_produces_parseable_pem() {
let material = generate_jwt_key().expect("generate_jwt_key");
assert!(material.signing_key_pem.contains("BEGIN PRIVATE KEY"));
assert!(material.public_key_pem.contains("BEGIN PUBLIC KEY"));
assert_eq!(material.kid.len(), 32, "kid is 16 bytes hex-encoded");
assert!(material.kid.chars().all(|c| c.is_ascii_hexdigit()));
⋮----
fn kid_is_stable_for_identical_public_keys() {
... (17 lines truncated)
</file>

<file path="crates/openshell-bootstrap/src/lib.rs">
pub mod edge_token;
pub mod jwt;
pub mod oidc_token;
⋮----
mod metadata;
pub mod mtls;
mod paths;
pub mod pki;
⋮----
use std::sync::Mutex;
</file>

<file path="crates/openshell-bootstrap/src/metadata.rs">
use openshell_core::paths::ensure_parent_dir_restricted;
⋮----
pub struct GatewayMetadata {
⋮----
pub enum GatewayMetadataSource {
⋮----
impl GatewayMetadataSource {
pub const fn label(self) -> &'static str {
⋮----
pub struct ListedGateway {
⋮----
fn user_gateway_metadata_path(name: &str) -> Result<PathBuf> {
Ok(user_gateway_dir(name)?.join("metadata.json"))
⋮----
fn system_gateway_metadata_path(name: &str) -> Result<PathBuf> {
Ok(system_gateway_dir(name)?.join("metadata.json"))
⋮----
fn resolve_gateway_metadata_path(name: &str) -> Result<Option<(PathBuf, GatewayMetadataSource)>> {
let user = user_gateway_metadata_path(name)?;
if user_entry_shadows_system(&user) {
return Ok(Some((user, GatewayMetadataSource::User)));
⋮----
let system = system_gateway_metadata_path(name)?;
if system.exists() {
return Ok(Some((system, GatewayMetadataSource::System)));
⋮----
Ok(None)
⋮----
fn parse_gateway_metadata(path: &Path) -> Result<GatewayMetadata> {
⋮----
... (495 lines truncated)
</file>

<file path="crates/openshell-bootstrap/src/mtls.rs">
use crate::paths::user_gateway_dir;
use crate::pki::PkiBundle;
⋮----
use std::path::PathBuf;
⋮----
pub fn store_pki_bundle(name: &str, bundle: &PkiBundle) -> Result<()> {
let dir = cli_mtls_dir(name)?;
let temp_dir = cli_mtls_temp_dir(name)?;
let backup_dir = cli_mtls_backup_dir(name)?;
⋮----
if temp_dir.exists() {
⋮----
.into_diagnostic()
.map_err(|e| e.wrap_err(format!("failed to remove {}", temp_dir.display())))?;
⋮----
create_dir_restricted(&temp_dir)?;
⋮----
std::fs::write(temp_dir.join("ca.crt"), &bundle.ca_cert_pem)
⋮----
.map_err(|e| e.wrap_err("failed to write ca.crt"))?;
std::fs::write(temp_dir.join("tls.crt"), &bundle.client_cert_pem)
⋮----
.map_err(|e| e.wrap_err("failed to write tls.crt"))?;
std::fs::write(temp_dir.join("tls.key"), &bundle.client_key_pem)
⋮----
.map_err(|e| e.wrap_err("failed to write tls.key"))?;
⋮----
set_file_owner_only(&temp_dir.join("tls.key"))?;
⋮----
validate_cli_mtls_bundle_dir(&temp_dir)?;
... (59 lines truncated)
</file>

<file path="crates/openshell-bootstrap/src/oidc_token.rs">
use crate::paths::user_gateway_dir;
⋮----
use std::path::PathBuf;
⋮----
pub struct OidcTokenBundle {
⋮----
pub fn oidc_token_path(gateway_name: &str) -> Result<PathBuf> {
Ok(user_gateway_dir(gateway_name)?.join("oidc_token.json"))
⋮----
pub fn oidc_login_prompt_required_path(gateway_name: &str) -> Result<PathBuf> {
Ok(user_gateway_dir(gateway_name)?.join("oidc_login_prompt_required"))
⋮----
pub fn store_oidc_token(gateway_name: &str, bundle: &OidcTokenBundle) -> Result<()> {
let path = oidc_token_path(gateway_name)?;
ensure_parent_dir_restricted(&path)?;
⋮----
.into_diagnostic()
.wrap_err("failed to serialize OIDC token bundle")?;
⋮----
.wrap_err_with(|| format!("failed to write OIDC token to {}", path.display()))?;
set_file_owner_only(&path)?;
clear_oidc_login_prompt(gateway_name)?;
Ok(())
⋮----
pub fn load_oidc_token(gateway_name: &str) -> Option<OidcTokenBundle> {
let path = oidc_token_path(gateway_name).ok()?;
if !path.exists() {
⋮----
let contents = std::fs::read_to_string(&path).ok()?;
serde_json::from_str(&contents).ok()
... (74 lines truncated)
</file>

<file path="crates/openshell-bootstrap/src/paths.rs">
use miette::Result;
use openshell_core::paths::openshell_config_dir;
use std::ffi::OsStr;
⋮----
fn system_config_dir_override() -> Option<PathBuf> {
⋮----
if path.as_os_str().is_empty() {
⋮----
if !path.is_absolute() {
⋮----
Some(path)
⋮----
pub fn validated_gateway_name(name: &str) -> Result<&str> {
let mut components = Path::new(name).components();
match (components.next(), components.next()) {
(Some(Component::Normal(component)), None) if component == OsStr::new(name) => Ok(name),
_ => Err(miette::miette!(
⋮----
pub fn user_gateway_dir(name: &str) -> Result<PathBuf> {
Ok(user_gateways_dir()?.join(validated_gateway_name(name)?))
⋮----
pub fn system_gateway_dir(name: &str) -> Result<PathBuf> {
Ok(system_gateways_dir().join(validated_gateway_name(name)?))
⋮----
pub fn user_active_gateway_path() -> Result<PathBuf> {
Ok(openshell_config_dir()?.join("active_gateway"))
⋮----
pub fn user_gateways_dir() -> Result<PathBuf> {
Ok(openshell_config_dir()?.join("gateways"))
⋮----
... (60 lines truncated)
</file>

<file path="crates/openshell-bootstrap/src/pki.rs">
use std::net::IpAddr;
⋮----
pub struct PkiBundle {
⋮----
pub fn generate_pki(extra_sans: &[String]) -> Result<PkiBundle> {
⋮----
.into_diagnostic()
.wrap_err("failed to generate CA key")?;
⋮----
.wrap_err("failed to create CA params")?;
⋮----
ca_params.key_usages = vec![KeyUsagePurpose::KeyCertSign, KeyUsagePurpose::CrlSign];
⋮----
.push(DnType::OrganizationName, "openshell");
⋮----
.push(DnType::CommonName, "openshell-ca");
⋮----
.self_signed(&ca_key)
⋮----
.wrap_err("failed to self-sign CA certificate")?;
⋮----
.wrap_err("failed to generate server key")?;
let server_sans = build_server_sans(extra_sans);
⋮----
.wrap_err("failed to create server cert params")?;
⋮----
.push(DnType::CommonName, "openshell-server");
⋮----
.signed_by(&server_key, &ca_cert, &ca_key)
⋮----
... (100 lines truncated)
</file>

<file path="crates/openshell-bootstrap/Cargo.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

[package]
name = "openshell-bootstrap"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
rust-version.workspace = true

[dependencies]
openshell-core = { path = "../openshell-core", default-features = false }
bytes = { workspace = true }
miette = { workspace = true }
rcgen = { workspace = true }
sha2 = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
tempfile = "3"
tokio = { workspace = true }
tracing = { workspace = true }

[dev-dependencies]
x509-parser = "0.16"

[lints]
workspace = true
</file>

<file path="crates/openshell-cli/src/commands/common.rs">
use crate::color::Colorize;
use chrono::DateTime;
⋮----
use std::collections::HashMap;
use std::io::IsTerminal;
use std::process::Command;
⋮----
pub enum PolicyGetView {
⋮----
impl PolicyGetView {
pub fn from_flags(base: bool, full: bool) -> Self {
⋮----
pub(crate) fn includes_policy(self) -> bool {
matches!(self, Self::Base | Self::Full)
⋮----
pub fn phase_name(phase: i32) -> &'static str {
⋮----
/// Format milliseconds since Unix epoch as a `YYYY-MM-DD HH:MM:SS` UTC string.
pub fn format_epoch_ms(ms: i64) -> String {
⋮----
pub fn format_epoch_ms(ms: i64) -> String {
use std::time::UNIX_EPOCH;
⋮----
return "-".to_string();
⋮----
.checked_add(Duration::from_millis(ms_u64))
.ok_or(())
⋮----
let Ok(dur) = time.duration_since(UNIX_EPOCH) else {
⋮----
... (570 lines truncated)
</file>

<file path="crates/openshell-cli/src/commands/gateway.rs">
use crate::color::Colorize;
⋮----
use bytes::Bytes;
⋮----
use http_body_util::Full;
⋮----
use hyper_rustls::HttpsConnectorBuilder;
⋮----
use std::io::IsTerminal;
use std::path::PathBuf;
⋮----
struct GatewayInfoView {
⋮----
struct ComputeDriverInfoView {
⋮----
struct ComputeDriverCapabilitiesView {
⋮----
struct ExtensionInfoView {
⋮----
/// Show gateway status.
#[allow(clippy::branches_sharing_code)]
pub async fn gateway_status(
⋮----
// Build status data before any output.
let is_bearer = tls.is_bearer_auth();
⋮----
) = match grpc_client(server, tls).await {
Ok(mut client) => match client.health(HealthRequest {}).await {
⋮----
let health = response.into_inner();
... (929 lines truncated)
</file>

<file path="crates/openshell-cli/src/commands/mod.rs">
pub mod common;
pub mod gateway;
pub mod provider;
pub mod provider_readiness;
</file>

<file path="crates/openshell-cli/src/commands/provider_readiness.rs">
use std::collections::HashSet;
use std::time::Duration;
use tokio::time::Instant;
⋮----
pub struct ProviderWaitOptions<'a> {
/// Wait for current runtime installation after saving the desired mutation.
    pub wait: bool,
/// One total deadline for all selected sandbox observations.
    pub timeout: Duration,
/// CLI output format: table, JSON, or YAML.
    pub output: &'a str,
⋮----
impl Default for ProviderWaitOptions<'_> {
fn default() -> Self {
⋮----
pub fn validate(self) -> Result<()> {
provider_wait_deadline(self.timeout).into_diagnostic()?;
if !matches!(self.output, "table" | "json" | "yaml") {
return Err(miette!("unsupported provider status output format"));
⋮----
Ok(())
⋮----
struct DisplayStatus {
⋮----
/// Caller-selected authority that every returned mutation receipt must retain.
#[derive(Clone, Copy)]
pub(super) struct ProviderMutationExpectation<'a> {
⋮----
/// Provider name explicitly selected by the command.
    pub provider_name: &'a str,
... (206 lines truncated)
</file>

<file path="crates/openshell-cli/src/commands/provider.rs">
use crate::color::Colorize;
⋮----
use dialoguer::Confirm;
⋮----
use openshell_core::proto::ProviderProfileCategory;
⋮----
use std::io::IsTerminal;
⋮----
fn provider_mutation_is_uncertain(status: &Status) -> bool {
⋮----
decode_details(status).is_some_and(|details| {
details.error_info().is_some_and(|info| {
⋮----
fn provider_mutation_error(status: &Status, operation: &str) -> miette::Report {
if provider_mutation_is_uncertain(status) {
⋮----
miette!(
⋮----
miette!("provider {operation} failed ({})", status.code())
⋮----
fn proto_timestamp_ms(timestamp: Option<&prost_types::Timestamp>) -> i64 {
⋮----
.and_then(|value| openshell_core::time::timestamp_to_millis(value).ok())
.unwrap_or_default()
⋮----
fn aggregate_delete_failures(resource: &str, failures: &[String]) -> Result<()> {
if failures.is_empty() {
Ok(())
⋮----
Err(miette!(
... (1236 lines truncated)
</file>

<file path="crates/openshell-cli/src/auth.rs">
use bytes::Bytes;
⋮----
use serde::Deserialize;
use std::convert::Infallible;
use std::io::Write;
⋮----
use std::time::Duration;
use tokio::net::TcpListener;
use tokio::sync::oneshot;
use tracing::debug;
⋮----
fn generate_confirmation_code() -> String {
use std::collections::hash_map::RandomState;
⋮----
code.push('-');
⋮----
let mut hasher_a = state_a.build_hasher();
hasher_a.write_usize(i);
hasher_a.write_u64(prev_hash);
let hash_a = hasher_a.finish();
⋮----
let mut hasher_b = state_b.build_hasher();
hasher_b.write_u64(hash_a);
hasher_b.write_usize(i);
let hash_b = hasher_b.finish();
⋮----
let idx = (hash_b as usize) % charset.len();
code.push(charset[idx] as char);
⋮----
pub async fn browser_auth_flow(gateway_endpoint: &str) -> Result<String> {
... (263 lines truncated)
</file>

<file path="crates/openshell-cli/src/color.rs">
use std::ffi::OsStr;
⋮----
use std::io::IsTerminal;
⋮----
pub enum ColorChoice {
⋮----
pub fn init(choice: ColorChoice) {
⋮----
let stdout_enabled = resolve(
⋮----
no_color.as_deref(),
force_color.as_deref(),
terminal_supports_ansi(std::io::stdout().is_terminal(), term.as_deref()),
⋮----
let stderr_enabled = resolve(
⋮----
terminal_supports_ansi(std::io::stderr().is_terminal(), term.as_deref()),
⋮----
STDOUT_ENABLED.store(stdout_enabled, Ordering::Relaxed);
STDERR_ENABLED.store(stderr_enabled, Ordering::Relaxed);
⋮----
.color(stderr_enabled)
.build(),
⋮----
pub fn stdout_enabled() -> bool {
STDOUT_ENABLED.load(Ordering::Relaxed)
⋮----
pub fn stderr_enabled() -> bool {
STDERR_ENABLED.load(Ordering::Relaxed)
⋮----
... (265 lines truncated)
</file>

<file path="crates/openshell-cli/src/completers.rs">
use std::ffi::OsStr;
use std::future::Future;
⋮----
use clap_complete::engine::CompletionCandidate;
use openshell_bootstrap::edge_token::load_edge_token;
⋮----
use openshell_core::ObjectName;
use openshell_core::auth::EdgeAuthInterceptor;
use openshell_core::proto::open_shell_client::OpenShellClient;
⋮----
use tonic::service::interceptor::InterceptedService;
use tonic::transport::Channel;
⋮----
use crate::oidc_auth::oidc_refresh_token;
⋮----
pub fn complete_gateway_names(_prefix: &OsStr) -> Vec<CompletionCandidate> {
let Ok(gateways) = list_gateways() else {
⋮----
.into_iter()
.map(|g| CompletionCandidate::new(g.name))
.collect()
⋮----
pub fn complete_sandbox_names(_prefix: &OsStr) -> Vec<CompletionCandidate> {
blocking_complete(async {
let (endpoint, gateway_name) = resolve_active_gateway()?;
let mut client = completion_grpc_client(&endpoint, &gateway_name).await?;
⋮----
.list_sandboxes(ListSandboxesRequest {
⋮----
workspace_scope: Some(openshell_core::proto::workspace_selector(
... (128 lines truncated)
</file>

<file path="crates/openshell-cli/src/edge_tunnel.rs">
use openshell_core::net::set_tcp_nodelay_best_effort;
use std::net::SocketAddr;
use std::sync::Arc;
⋮----
use tokio_tungstenite::tungstenite::Message;
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
use tokio_tungstenite::tungstenite::http::HeaderValue;
⋮----
pub struct EdgeTunnelProxy {
⋮----
struct TunnelConfig {
⋮----
pub async fn start_tunnel_proxy(
⋮----
let listener = TcpListener::bind("127.0.0.1:0").await.into_diagnostic()?;
let local_addr = listener.local_addr().into_diagnostic()?;
⋮----
let ws_url = format!(
⋮----
edge_token: edge_token.to_string(),
⋮----
debug!(
⋮----
tokio::spawn(accept_loop(listener, config));
⋮----
Ok(EdgeTunnelProxy { local_addr })
⋮----
async fn accept_loop(listener: TcpListener, config: Arc<TunnelConfig>) {
⋮----
match listener.accept().await {
... (72 lines truncated)
</file>

<file path="crates/openshell-cli/src/lib.rs">
pub(crate) mod test_utils;
⋮----
pub mod auth;
pub mod color;
pub(crate) mod commands;
pub mod completers;
pub mod edge_tunnel;
pub mod oidc_auth;
pub mod output;
pub(crate) mod policy_update;
pub mod run;
pub mod ssh;
pub mod tls;
</file>

<file path="crates/openshell-cli/src/main.rs">
use clap_complete::engine::ArgValueCompleter;
use clap_complete::env::CompleteEnv;
use miette::Result;
⋮----
use std::collections::HashMap;
use std::io::Write;
use std::path::PathBuf;
⋮----
use openshell_cli::completers;
use openshell_cli::run;
use openshell_cli::tls::TlsOptions;
⋮----
struct GatewayContext {
⋮----
enum GpuCliRequest {
⋮----
fn from(gpu: GpuCliRequest) -> Self {
⋮----
GpuCliRequest::Count(count) => Self { count: Some(count) },
⋮----
fn normalize_gateway_endpoint(endpoint: &str) -> &str {
endpoint.trim_end_matches('/')
⋮----
fn find_gateway_by_endpoint(endpoint: &str) -> Option<String> {
let endpoint = normalize_gateway_endpoint(endpoint);
⋮----
if let Some(active_name) = load_active_gateway()
&& let Ok(metadata) = load_gateway_metadata(&active_name)
&& normalize_gateway_endpoint(&metadata.gateway_endpoint) == endpoint
⋮----
... (1422 lines truncated)
</file>

<file path="crates/openshell-cli/src/oidc_auth.rs">
use bytes::Bytes;
use http_body_util::Full;
use hyper::service::service_fn;
⋮----
use hyper_util::server::conn::auto::Builder;
⋮----
use openshell_bootstrap::oidc_token::OidcTokenBundle;
use openshell_sdk::oidc::RefreshTokenInput;
use serde::Deserialize;
use std::convert::Infallible;
⋮----
use std::time::Duration;
use tokio::net::TcpListener;
use tokio::sync::oneshot;
use tracing::debug;
⋮----
struct OidcDiscovery {
⋮----
struct DeviceAuthorizationResponse {
⋮----
fn default_interval() -> u64 {
⋮----
struct DeviceTokenErrorResponse {
⋮----
async fn discover(issuer: &str, insecure: bool) -> Result<OidcDiscovery> {
let normalized_issuer = issuer.trim_end_matches('/');
let url = format!("{normalized_issuer}/.well-known/openid-configuration");
let client = http_client(insecure);
⋮----
.get(&url)
... (491 lines truncated)
</file>

<file path="crates/openshell-cli/src/output.rs">
use std::io::Write;
⋮----
pub fn print_next_page_token(next_page_token: &str) {
if !next_page_token.is_empty() {
eprintln!("Next page token: {next_page_token}");
⋮----
fn paginated_collection_value<T, F>(
⋮----
envelope.insert(
collection_name.to_string(),
serde_json::Value::Array(items.iter().map(to_json).collect()),
⋮----
"next_page_token".to_string(),
serde_json::Value::String(next_page_token.to_string()),
⋮----
pub fn print_paginated_output_collection<T, F>(
⋮----
match format.as_ref() {
⋮----
paginated_collection_value(collection_name, items, next_page_token, to_json);
println!(
⋮----
Ok(true)
⋮----
print!("{}", serde_yml::to_string(&envelope).into_diagnostic()?);
⋮----
"table" => Ok(false),
_ => Err(miette::miette!(
⋮----
pub fn print_output_collection<T, F>(
... (145 lines truncated)
</file>

<file path="crates/openshell-cli/src/policy_update.rs">
use openshell_core::proto::policy_merge_operation;
⋮----
pub struct PolicyUpdatePlan {
⋮----
pub fn build_policy_update_plan(
⋮----
let has_l7_append = !add_allow.is_empty() || !add_deny.is_empty();
if binaries.iter().any(|binary| binary.trim().is_empty()) {
return Err(miette!("--binary values must not be empty"));
⋮----
if any_binary && !binaries.is_empty() {
return Err(miette!("--any-binary and --binary are mutually exclusive"));
⋮----
if has_l7_append && !add_endpoints.is_empty() {
return Err(miette!(
⋮----
if rule_name.is_none_or(|name| name.trim().is_empty()) {
⋮----
if binaries.is_empty() && !any_binary {
⋮----
if endpoint_path.is_some() {
⋮----
if !binaries.is_empty() && add_endpoints.is_empty() {
⋮----
if rule_name.is_some() && add_endpoints.is_empty() {
⋮----
if rule_name.is_some() && add_endpoints.len() > 1 {
⋮----
if !paths.contains(path) {
paths.push(path.clone());
... (532 lines truncated)
</file>

<file path="crates/openshell-cli/src/run.rs">
use crate::commands::provider::fetch_provider_profile_catalog;
⋮----
use crate::color::Colorize;
use crate::policy_update::build_policy_update_plan;
⋮----
use futures::StreamExt;
⋮----
use openshell_core::net::set_tcp_nodelay_best_effort;
⋮----
use openshell_core::settings;
⋮----
use prost::Message;
use std::borrow::Cow;
use std::collections::HashMap;
⋮----
use std::process::Command;
⋮----
fn proto_timestamp_ms(timestamp: Option<&prost_types::Timestamp>) -> i64 {
⋮----
.and_then(|value| openshell_core::time::timestamp_to_millis(value).ok())
.unwrap_or_default()
⋮----
fn proto_execution_timeout(timeout_seconds: u32) -> Result<Option<prost_types::Duration>> {
⋮----
return Ok(None);
⋮----
openshell_core::time::duration_from_std(Duration::from_secs(timeout_seconds.into()))
.map(Some)
.into_diagnostic()
⋮----
... (2855 lines truncated)
</file>

<file path="crates/openshell-cli/src/ssh.rs">
use crate::color::Colorize;
⋮----
use openshell_core::driver_mounts;
⋮----
use std::fs;
use std::future::Future;
⋮----
use std::os::unix::process::CommandExt;
⋮----
use tokio::net::TcpStream;
⋮----
use tokio_stream::wrappers::ReceiverStream;
use tonic::Code;
⋮----
pub enum Editor {
⋮----
impl Editor {
fn binary(self) -> &'static str {
⋮----
fn remote_target(host_alias: &str) -> String {
format!("ssh-remote+{host_alias}")
⋮----
fn label(self) -> &'static str {
⋮----
struct SshSessionConfig {
⋮----
async fn ssh_session_config(
⋮----
let mut client = grpc_client(server, tls).await?;
⋮----
... (1365 lines truncated)
</file>

<file path="crates/openshell-cli/src/test_utils.rs">
use std::path::Path;
⋮----
use crate::TEST_ENV_LOCK;
⋮----
pub struct EnvVarGuard {
⋮----
impl EnvVarGuard {
pub fn set(key: &'static str, value: &str) -> Self {
let original = std::env::var(key).ok();
⋮----
pub fn unset(key: &'static str) -> Self {
⋮----
impl Drop for EnvVarGuard {
fn drop(&mut self) {
⋮----
pub fn with_tmp_xdg<F: FnOnce()>(tmp: &Path, f: F) {
⋮----
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
⋮----
tmp.to_str().expect("temp path should be utf-8"),
⋮----
f();
drop(guard);
</file>

<file path="crates/openshell-cli/src/tls.rs">
use openshell_core::auth::EdgeAuthInterceptor;
use openshell_core::net::set_tcp_nodelay_best_effort;
use openshell_core::proto::open_shell_client::OpenShellClient;
⋮----
use std::collections::HashMap;
use std::future::Future;
use std::io::Cursor;
use std::net::SocketAddr;
use std::path::PathBuf;
use std::sync::OnceLock;
use std::time::Duration;
use tokio::sync::Mutex;
use tonic::service::interceptor::InterceptedService;
⋮----
use tracing::debug;
⋮----
pub type GrpcClient = OpenShellClient<InterceptedService<Channel, EdgeAuthInterceptor>>;
⋮----
pub struct TlsOptions {
⋮----
impl TlsOptions {
pub fn new(ca: Option<PathBuf>, cert: Option<PathBuf>, key: Option<PathBuf>) -> Self {
⋮----
pub fn has_any(&self) -> bool {
self.ca.is_some() || self.cert.is_some() || self.key.is_some()
⋮----
pub fn gateway_name(&self) -> Option<&str> {
self.gateway_name.as_deref()
⋮----
pub fn with_gateway_name(&self, name: &str) -> Self {
... (238 lines truncated)
</file>

<file path="crates/openshell-cli/Cargo.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

[package]
name = "openshell-cli"
description = "OpenShell CLI tool"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true

[[bin]]
name = "openshell"
path = "src/main.rs"

[dependencies]
openshell-bootstrap = { path = "../openshell-bootstrap" }
openshell-core = { path = "../openshell-core", default-features = false }
openshell-policy = { path = "../openshell-policy" }
openshell-providers = { path = "../openshell-providers" }
openshell-sdk = { path = "../openshell-sdk" }
openshell-tui = { path = "../openshell-tui" }
serde = { workspace = true }
serde_json = { workspace = true }
serde_yml = { workspace = true }
prost = { workspace = true }
prost-types = { workspace = true }

# Async runtime
... (75 lines truncated)
</file>

<file path="crates/openshell-conformance/src/scenarios/file_transfer.rs">
use std::fs;
use std::path::Path;
use std::process::Stdio;
use std::time::Duration;
⋮----
use tokio::process::Command;
⋮----
fn run_file_transfer(runner: &mut OpenShellRunner) -> ScenarioFuture<'_> {
⋮----
FILE_TRANSFER_ROUND_TRIP_SCENARIO.run(runner).await?;
FILE_TRANSFER_GIT_FILTERING_SCENARIO.run(runner).await?;
FILE_TRANSFER_PATH_SAFETY_SCENARIO.run(runner).await
⋮----
fn run_round_trip(runner: &mut OpenShellRunner) -> ScenarioFuture<'_> {
⋮----
let (sandbox_name, remote_root, local) = prepare_sandbox(runner, "round-trip").await?;
round_trip(runner, &sandbox_name, &remote_root, local.path()).await?;
download_file(runner, &sandbox_name, &remote_root, local.path()).await?;
download_directory(runner, &sandbox_name, &remote_root, local.path()).await?;
delete_sandbox(runner, &sandbox_name).await
⋮----
fn run_git_filtering(runner: &mut OpenShellRunner) -> ScenarioFuture<'_> {
⋮----
let (sandbox_name, remote_root, local) = prepare_sandbox(runner, "git-filtering").await?;
gitignore_filtering(runner, &sandbox_name, &remote_root, local.path()).await?;
single_file_from_git_repo(runner, &sandbox_name, &remote_root, local.path()).await?;
gitignored_directory_fallback(runner, &sandbox_name, &remote_root, local.path()).await?;
⋮----
fn run_path_safety(runner: &mut OpenShellRunner) -> ScenarioFuture<'_> {
⋮----
... (308 lines truncated)
</file>

<file path="crates/openshell-conformance/src/scenarios/mod.rs">
mod file_transfer;
mod policy_behavior;
mod sandbox_lifecycle;
mod smoke;
⋮----
pub use sandbox_lifecycle::SANDBOX_LIFECYCLE_SCENARIO;
pub use smoke::SMOKE_SCENARIO;
</file>

<file path="crates/openshell-conformance/src/scenarios/policy_behavior.rs">
use serde::Deserialize;
use serde_json::Value;
use tempfile::NamedTempFile;
use tokio::time::sleep;
⋮----
struct SandboxState {
⋮----
fn run_policy_local(runner: &mut OpenShellRunner) -> ScenarioFuture<'_> {
⋮----
let name = format!("ct-{}-pl", runner.id());
create_sandbox(runner, &name, None).await?;
enable_proposals(runner, &name).await?;
let binary = sandbox_bash_path(runner, &name).await?;
⋮----
let readiness_path = format!("/v1/proposals/ct-{}-readiness", runner.id());
⋮----
match request_policy_local(runner, &name, "/v1/policy/current").await {
⋮----
.as_str()
.is_some_and(|yaml| yaml.contains("version: 1")) =>
⋮----
match request_policy_local_http(runner, &name, "GET", &readiness_path, "", 404)
⋮----
return Err(format!(
⋮----
Err(error) if started.elapsed() >= READY_TIMEOUT => return Err(error),
⋮----
if started.elapsed() >= READY_TIMEOUT {
return Err(error);
⋮----
... (244 lines truncated)
</file>

<file path="crates/openshell-conformance/src/scenarios/sandbox_lifecycle.rs">
use std::collections::HashSet;
⋮----
use serde::Deserialize;
⋮----
struct SandboxState {
⋮----
struct SandboxListPage {
⋮----
fn run_sandbox_lifecycle(runner: &mut OpenShellRunner) -> ScenarioFuture<'_> {
⋮----
stop_start_preserves_workspace(runner).await?;
stopped_can_be_deleted(runner).await
⋮----
async fn stop_start_preserves_workspace(runner: &mut OpenShellRunner) -> Result<(), String> {
let sandbox_name = format!("ct-{}-ss", runner.id());
let sentinel = format!("openshell-stop-start-{}", runner.id());
⋮----
let main = format!(
⋮----
create_running_sandbox(runner, &sandbox_name, &main, "stop-start").await?;
exec_expect_exact(
⋮----
&format!("printf '%s\\n' '{sentinel}' > '{sentinel_path}' && sync"),
⋮----
run_lifecycle_command(runner, "stop", &sandbox_name, "stop-start/stop").await?;
wait_for_phase(runner, &sandbox_name, "Stopped", "stop-start/stopped").await?;
⋮----
.step("stop-start/exec-while-stopped")
.description(format!(
⋮----
... (119 lines truncated)
</file>

<file path="crates/openshell-conformance/src/scenarios/smoke.rs">
use serde::Deserialize;
use tokio::time::sleep;
⋮----
struct SandboxListEntry {
⋮----
struct SandboxListPage {
⋮----
fn run_smoke(runner: &mut OpenShellRunner) -> ScenarioFuture<'_> {
Box::pin(async move { run_smoke_inner(runner).await })
⋮----
async fn run_smoke_inner(runner: &mut OpenShellRunner) -> Result<(), String> {
⋮----
.step("status")
.description("openshell status succeeds")
.with_timeout(STATUS_TIMEOUT)
.run(&["status"])
⋮----
.map_err(|error| error.to_string())?;
status.require_success()?;
⋮----
let sandbox_name = format!("ct-{}-01", runner.id());
runner.track_sandbox(&sandbox_name);
⋮----
.step("create")
.description("sandbox creation succeeds")
.with_timeout(CREATE_TIMEOUT)
.run(&["sandbox", "create", "--name", &sandbox_name, "--detach"])
⋮----
create.require_success()?;
⋮----
... (73 lines truncated)
</file>

<file path="crates/openshell-conformance/src/executor.rs">
use std::future::Future;
use std::path::PathBuf;
use std::pin::Pin;
⋮----
use std::time::Duration;
⋮----
use tokio::time::timeout;
⋮----
pub type CliExecution<'a> =
⋮----
pub trait CliExecutor: Send + Sync {
⋮----
pub enum CliExecutionError {
⋮----
pub struct ProcessCli {
⋮----
impl ProcessCli {
pub fn new(binary: PathBuf) -> Self {
⋮----
impl CliExecutor for ProcessCli {
fn execute(
⋮----
.args(&args)
.envs(environment)
.env("NO_COLOR", "1")
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true);
⋮----
timeout(command_timeout, process.output())
... (4 lines truncated)
</file>

<file path="crates/openshell-conformance/src/lib.rs">
pub mod executor;
mod scenarios;
⋮----
use std::collections::BTreeSet;
use std::error::Error;
use std::fmt;
use std::future::Future;
use std::path::PathBuf;
use std::pin::Pin;
use std::process::ExitStatus;
use std::sync::Arc;
⋮----
use rand::Rng;
use serde::Deserialize;
use serde::de::DeserializeOwned;
use tokio::time::sleep;
⋮----
pub struct Scenario {
⋮----
pub type ScenarioFuture<'a> = Pin<Box<dyn Future<Output = Result<(), String>> + Send + 'a>>;
⋮----
impl Scenario {
pub async fn run(&self, runner: &mut OpenShellRunner) -> Result<(), String> {
⋮----
/// Returns every scenario compiled into this distribution.
pub fn scenarios() -> &'static [Scenario] {
⋮----
pub fn scenarios() -> &'static [Scenario] {
⋮----
pub fn scenario(name: &str) -> Option<&'static Scenario> {
... (530 lines truncated)
</file>

<file path="crates/openshell-conformance/Cargo.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

[package]
name = "openshell-conformance"
description = "Reusable OpenShell CLI conformance scenarios and runner"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true

[dependencies]
rand.workspace = true
serde.workspace = true
serde_json.workspace = true
tempfile = "3"
tokio.workspace = true

[lints]
workspace = true
</file>

<file path="crates/openshell-conformance-cli/src/main.rs">
use std::path::PathBuf;
use std::process::ExitCode;
⋮----
use serde::Serialize;
⋮----
struct Cli {
⋮----
enum Command {
⋮----
enum OutputFormat {
⋮----
struct ScenarioDescription<'a> {
⋮----
struct ScenarioResult<'a> {
⋮----
struct RunReport<'a> {
⋮----
async fn main() -> ExitCode {
match execute(Cli::parse()).await {
⋮----
eprintln!("openshell-conformance: {error}");
⋮----
async fn execute(cli: Cli) -> Result<(), String> {
⋮----
Command::List { output } => list(output),
⋮----
} => run(&requested, openshell_bin, output).await,
⋮----
fn list(output: OutputFormat) -> Result<(), String> {
⋮----
... (88 lines truncated)
</file>

<file path="crates/openshell-conformance-cli/Cargo.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

[package]
name = "openshell-conformance-cli"
description = "Standalone OpenShell CLI conformance test runner"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true

[[bin]]
name = "openshell-conformance"
path = "src/main.rs"

[dependencies]
clap.workspace = true
openshell-conformance = { path = "../openshell-conformance" }
serde.workspace = true
serde_json.workspace = true
tokio.workspace = true

[lints]
workspace = true
</file>

<file path="crates/openshell-core/src/activity.rs">
use tokio::sync::mpsc;
⋮----
pub struct ActivityEvent {
⋮----
/// Shorthand for the producer side of the activity channel.
pub type ActivitySender = mpsc::Sender<ActivityEvent>;
⋮----
pub type ActivitySender = mpsc::Sender<ActivityEvent>;
⋮----
/// Non-blocking emit. Drops the event if the queue is full.
/// Returns whether the event was enqueued.
⋮----
/// Returns whether the event was enqueued.
pub fn try_record_activity(tx: &ActivitySender, denied: bool, deny_group: &'static str) -> bool {
⋮----
pub fn try_record_activity(tx: &ActivitySender, denied: bool, deny_group: &'static str) -> bool {
tx.try_send(ActivityEvent { denied, deny_group }).is_ok()
⋮----
mod tests {
⋮----
fn activity_send_drops_when_queue_is_full() {
⋮----
assert!(try_record_activity(&tx, false, "unknown"));
assert!(!try_record_activity(&tx, true, "connect_policy"));
</file>

<file path="crates/openshell-core/src/auth.rs">
use miette::Result;
⋮----
pub struct EdgeAuthInterceptor {
⋮----
impl EdgeAuthInterceptor {
⋮----
pub fn new(oidc_token: Option<&str>, edge_token: Option<&str>) -> Result<Self> {
⋮----
format!("Bearer {token}")
.parse()
.map_err(|_| miette::miette!("invalid bearer token value"))?;
return Ok(Self {
bearer_value: Some(bearer),
⋮----
.map_err(|_| miette::miette!("invalid edge token value"))?;
⋮----
format!("CF_Authorization={t}")
⋮----
.map_err(|_| miette::miette!("invalid edge token value for cookie"))?;
(Some(hv), Some(cv))
⋮----
Ok(Self {
⋮----
pub fn noop() -> Self {
⋮----
fn call(
⋮----
req.metadata_mut().insert("authorization", val.clone());
⋮----
req.metadata_mut()
... (6 lines truncated)
</file>

<file path="crates/openshell-core/src/config.rs">
use std::borrow::Cow;
use std::collections::BTreeMap;
use std::fmt;
use std::net::SocketAddr;
⋮----
use std::path::PathBuf;
use std::str::FromStr;
use std::time::Duration;
⋮----
pub fn default_sandbox_pids_limit() -> Option<NonZeroI64> {
⋮----
pub enum PolicyValidationFailureMode {
⋮----
impl PolicyValidationFailureMode {
⋮----
pub const fn as_str(self) -> &'static str {
⋮----
impl FromStr for PolicyValidationFailureMode {
type Err = String;
⋮----
fn from_str(value: &str) -> Result<Self, Self::Err> {
⋮----
"fail_closed" => Ok(Self::FailClosed),
"retain_last_valid" => Ok(Self::RetainLastValid),
_ => Err(format!(
⋮----
/// Default OCI repository for the supervisor image (no tag).
pub const DEFAULT_SUPERVISOR_IMAGE_REPO: &str = "ghcr.io/nvidia/openshell/supervisor";
⋮----
/// Default OCI repository for the sandbox runtime image (no tag).
... (680 lines truncated)
</file>

<file path="crates/openshell-core/src/container_paths.rs">
pub fn netns_path(name: &str) -> PathBuf {
Path::new(NETNS_IPROUTE2_ROOT).join(name)
⋮----
mod tests {
⋮----
fn every_fixed_control_path_is_below_a_reserved_root() {
⋮----
assert!(
⋮----
fn runtime_roots_cover_standard_oci_mount_destinations() {
</file>

<file path="crates/openshell-core/src/denial.rs">
pub struct DenialEvent {
</file>

<file path="crates/openshell-core/src/driver_mounts.rs">
use std::path::Path;
⋮----
pub enum SelinuxLabel {
⋮----
pub fn validate_mount_source(source: &str, field: &str) -> Result<(), String> {
if source.is_empty() {
return Err(format!("{field} must not be empty"));
⋮----
if source != source.trim() {
return Err(format!("{field} must not contain surrounding whitespace"));
⋮----
if source.as_bytes().contains(&0) {
return Err(format!("{field} must not contain NUL bytes"));
⋮----
Ok(())
⋮----
pub fn validate_absolute_mount_source(source: &str, field: &str) -> Result<(), String> {
validate_mount_source(source, field)?;
if !Path::new(source).is_absolute() {
return Err(format!("{field} must be an absolute host path"));
⋮----
pub fn validate_mount_subpath(subpath: &str) -> Result<(), String> {
if subpath.is_empty() {
return Err("mount subpath must not be empty".to_string());
⋮----
if subpath != subpath.trim() {
return Err("mount subpath must not contain surrounding whitespace".to_string());
⋮----
if subpath.as_bytes().contains(&0) {
return Err("mount subpath must not contain NUL bytes".to_string());
... (136 lines truncated)
</file>

<file path="crates/openshell-core/src/driver_utils.rs">
use crate::proto::compute::v1::DriverSandbox;
⋮----
pub fn openshell_sandbox_label_selector() -> String {
format!("{LABEL_MANAGED_BY}={LABEL_MANAGED_BY_VALUE},{LABEL_SANDBOX_ID}")
⋮----
pub struct UpstreamProxyAddr {
⋮----
pub enum UpstreamProxyUrlError {
⋮----
/// Parse and validate a corporate upstream-proxy URL.
///
⋮----
///
/// The accepted grammar is exactly `http://host:port` or `https://host:port`:
⋮----
/// The accepted grammar is exactly `http://host:port` or `https://host:port`:
/// the scheme and the port must both be explicit, only `http://` and
⋮----
/// the scheme and the port must both be explicit, only `http://` and
/// `https://` proxies are accepted, and inline userinfo is rejected. The URL
⋮----
/// `https://` proxies are accepted, and inline userinfo is rejected. The URL
/// must address the proxy only: a path (other than a bare trailing `/`),
⋮----
/// must address the proxy only: a path (other than a bare trailing `/`),
/// query, or fragment is rejected rather than silently discarded. The
⋮----
/// query, or fragment is rejected rather than silently discarded. The
/// returned [`UpstreamProxyAddr::secure`] records whether the `https://`
⋮----
... (812 lines truncated)
</file>

<file path="crates/openshell-core/src/dynamic_string_allowlist.rs">
use std::collections::BTreeSet;
⋮----
pub struct DynamicStringAllowlist {
⋮----
impl DynamicStringAllowlist {
fn read_guard(&self) -> std::sync::RwLockReadGuard<'_, BTreeSet<String>> {
⋮----
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner)
⋮----
fn write_guard(&self) -> std::sync::RwLockWriteGuard<'_, BTreeSet<String>> {
⋮----
.write()
⋮----
pub fn new() -> Self {
⋮----
pub fn from_set(set: BTreeSet<String>) -> Self {
⋮----
pub fn replace(&self, new_set: BTreeSet<String>) {
*self.write_guard() = new_set;
⋮----
pub fn merge(&self, additional: &BTreeSet<String>) {
self.write_guard().extend(additional.iter().cloned());
⋮----
pub fn read(&self) -> std::sync::RwLockReadGuard<'_, BTreeSet<String>> {
self.read_guard()
⋮----
pub fn contains(&self, namespace: &str) -> bool {
self.read_guard().contains(namespace)
⋮----
... (11 lines truncated)
</file>

<file path="crates/openshell-core/src/endpoint_path.rs">
pub struct EndpointPathPattern {
⋮----
enum EndpointPathPatternKind {
⋮----
impl EndpointPathPattern {
⋮----
pub fn new(pattern: &str) -> Self {
let kind = if pattern.is_empty() || pattern == "**" || pattern == "/**" {
⋮----
} else if let Some(prefix) = pattern.strip_suffix("/**") {
EndpointPathPatternKind::Subtree(prefix.to_string())
⋮----
glob::Pattern::new(pattern).map_or(
⋮----
source: pattern.to_string(),
⋮----
pub fn matches(&self, path: &str) -> bool {
⋮----
.strip_prefix(prefix)
.is_some_and(|suffix| suffix.starts_with('/'))
⋮----
EndpointPathPatternKind::Glob(pattern) => pattern.matches(path),
⋮----
pub fn matches(pattern: &str, path: &str) -> bool {
EndpointPathPattern::new(pattern).matches(path)
⋮----
mod tests {
⋮----
fn matches_canonical_endpoint_patterns() {
assert!(matches("", "/v1/messages"));
... (20 lines truncated)
</file>

<file path="crates/openshell-core/src/endpoint_status.rs">
use std::collections::BTreeMap;
⋮----
use std::sync::Arc;
⋮----
pub fn endpoint_id(endpoint: &crate::proto::NetworkEndpoint) -> String {
initial_endpoint_status(endpoint).endpoint_id
⋮----
let host = endpoint.host.to_ascii_lowercase();
let path = match endpoint.path.as_str() {
</file>

<file path="crates/openshell-core/src/error.rs">
use miette::Diagnostic;
use thiserror::Error;
⋮----
pub type Result<T> = std::result::Result<T, Error>;
⋮----
pub enum Error {
⋮----
impl Error {
⋮----
pub fn config(message: impl Into<String>) -> Self {
⋮----
message: message.into(),
⋮----
pub fn tls(message: impl Into<String>) -> Self {
⋮----
pub fn transport(message: impl Into<String>) -> Self {
⋮----
pub fn execution(message: impl Into<String>) -> Self {
⋮----
pub fn process(message: impl Into<String>) -> Self {
⋮----
pub enum ComputeDriverError {
⋮----
fn from(err: ComputeDriverError) -> Self {
</file>

<file path="crates/openshell-core/src/extension_protocol.rs">
use std::collections::BTreeSet;
⋮----
use thiserror::Error;
⋮----
pub enum ExtensionFamily {
⋮----
impl ExtensionFamily {
⋮----
pub const fn as_str(self) -> &'static str {
⋮----
pub fn contract_capability(self) -> String {
format!("openshell.{}.contract", self.as_str())
⋮----
pub struct NegotiatedExtension {
⋮----
pub enum NegotiationError {
⋮----
pub fn gateway_metadata(family: ExtensionFamily) -> PeerMetadata {
let contract = family.contract_capability();
⋮----
protocol_version: Some(ProtocolVersion {
⋮----
implementation_name: "openshell/gateway".to_string(),
implementation_version: crate::VERSION.to_string(),
supported_capabilities: vec![contract.clone()],
required_capabilities: vec![contract],
⋮----
pub fn extension_metadata(
⋮----
let mut supported_capabilities = vec![contract.clone()];
... (152 lines truncated)
</file>

<file path="crates/openshell-core/src/external_driver_socket.rs">
use std::io;
⋮----
use std::pin::Pin;
⋮----
use tokio_stream::Stream;
⋮----
pub fn bind_private(path: &Path) -> Result<UnixListener, String> {
⋮----
.parent()
.ok_or_else(|| format!("driver socket path '{}' has no parent", path.display()))?;
let expected_uid = rustix::process::geteuid().as_raw();
⋮----
.map_err(|err| format!("create socket directory {}: {err}", parent.display()))?;
⋮----
.map_err(|err| format!("stat socket directory {}: {err}", parent.display()))?;
if parent_metadata.file_type().is_symlink() || !parent_metadata.file_type().is_dir() {
return Err(format!(
⋮----
if parent_metadata.uid() != expected_uid {
⋮----
.map_err(|err| format!("chmod socket directory {}: {err}", parent.display()))?;
⋮----
if metadata.file_type().is_socket()
&& !metadata.file_type().is_symlink()
&& metadata.uid() == expected_uid =>
⋮----
.map_err(|err| format!("remove stale socket {}: {err}", path.display()))?;
⋮----
Err(err) if err.kind() == io::ErrorKind::NotFound => {}
Err(err) => return Err(format!("stat driver socket {}: {err}", path.display())),
... (104 lines truncated)
</file>

<file path="crates/openshell-core/src/forward.rs">
use std::borrow::Cow;
use std::net::TcpListener;
⋮----
use std::process::Command;
⋮----
pub fn forward_pid_dir() -> Result<PathBuf> {
Ok(xdg_config_dir()?.join("openshell").join("forwards"))
⋮----
fn safe_path_component(value: &str, kind: &str) -> Result<()> {
if value.is_empty()
|| !matches!(
⋮----
return Err(miette::miette!("invalid {kind} name for forward tracking"));
⋮----
Ok(())
⋮----
pub fn forward_pid_path(workspace: &str, name: &str, port: u16) -> Result<PathBuf> {
safe_path_component(workspace, "workspace")?;
safe_path_component(name, "sandbox")?;
Ok(forward_pid_dir()?
.join(workspace)
.join(format!("{name}-{port}.pid")))
⋮----
pub fn write_forward_pid(
⋮----
let path = forward_pid_path(workspace, name, port)?;
⋮----
.parent()
.ok_or_else(|| miette::miette!("forward PID path has no parent"))?;
create_dir_restricted(dir)?;
... (901 lines truncated)
</file>

<file path="crates/openshell-core/src/google_cloud.rs">
mod tests {
⋮----
use std::collections::HashSet;
⋮----
fn static_config_keys_matches_alias_arrays_and_vertex_vars() {
⋮----
.iter()
.chain(REGION_ENV_VARS)
.chain(SERVICE_ACCOUNT_EMAIL_ENV_VARS)
.copied()
.chain([
⋮----
.collect();
let actual: HashSet<&str> = STATIC_CONFIG_KEYS.iter().copied().collect();
assert_eq!(
</file>

<file path="crates/openshell-core/src/gpu.rs">
use std::collections::HashSet;
use std::fmt;
use std::sync::RwLock;
⋮----
use crate::config::CDI_GPU_DEVICE_ALL;
⋮----
pub fn sandbox_gpu_requested(resources: Option<&SandboxResourceRequirements>) -> bool {
⋮----
.and_then(|resources| resources.gpu.as_ref())
.is_some()
⋮----
pub fn sandbox_gpu_count(resources: Option<&SandboxResourceRequirements>) -> Option<u32> {
⋮----
.and_then(|gpu| gpu.count)
⋮----
pub fn effective_driver_gpu_count(
⋮----
return Ok(None);
⋮----
let count = gpu.count.unwrap_or(1);
⋮----
return Err("gpu count must be greater than 0".to_string());
⋮----
Ok(Some(count))
⋮----
pub fn driver_gpu_requirements(
⋮----
resources.and_then(|resources| resources.gpu.as_ref())
⋮----
pub struct CdiGpuInventory {
... (234 lines truncated)
</file>

<file path="crates/openshell-core/src/grpc_client.rs">
use std::collections::HashMap;
⋮----
use crate::sandbox_env;
⋮----
use tonic::Status;
use tonic::metadata::AsciiMetadataValue;
use tonic::service::interceptor::InterceptedService;
⋮----
pub fn grpc_status_error(status: Status) -> miette::Report {
⋮----
struct GrpcStatusError(#[source] Status);
GrpcStatusError(status).into()
⋮----
pub type AuthedChannel = InterceptedService<Channel, AuthInterceptor>;
⋮----
type TokenSlot = Arc<RwLock<AsciiMetadataValue>>;
⋮----
enum TokenSource {
⋮----
enum RefreshMode {
⋮----
struct AcquiredToken {
⋮----
fn install_token_slot(token: &str) -> Result<TokenSlot> {
let bearer = validate_gateway_bearer(token)?;
Ok(install_validated_token_slot(bearer))
⋮----
fn validate_gateway_bearer(token: &str) -> Result<AsciiMetadataValue> {
AsciiMetadataValue::try_from(format!("Bearer {token}"))
.into_diagnostic()
... (670 lines truncated)
</file>

<file path="crates/openshell-core/src/host_pattern.rs">
pub struct HostPattern {
⋮----
enum HostLabelPattern {
⋮----
pub struct HostSelector {
⋮----
impl HostSelector {
pub fn new(include: &[String], exclude: &[String]) -> Result<Self, String> {
if include.is_empty() {
return Err("endpoint selector must include at least one host pattern".to_string());
⋮----
Ok(Self {
⋮----
.iter()
.map(|pattern| HostPattern::new(pattern))
⋮----
pub fn matches(&self, host: &str) -> bool {
self.includes.iter().any(|pattern| pattern.matches(host))
&& !self.excludes.iter().any(|pattern| pattern.matches(host))
⋮----
pub fn may_match_pattern(&self, candidate: &HostPattern) -> bool {
self.includes.iter().any(|include| {
if !include.overlaps(candidate) {
⋮----
let concrete_intersection = candidate.literal().or_else(|| include.literal());
let excluded = concrete_intersection.map_or_else(
⋮----
self.excludes.iter().any(|excluded| {
excluded.is_universal()
⋮----
... (138 lines truncated)
</file>

<file path="crates/openshell-core/src/image.rs">
pub fn default_sandbox_image() -> String {
DEFAULT_SANDBOX_BASE_IMAGE.to_string()
⋮----
mod tests {
⋮----
fn default_image_is_version_qualified_nvidia_ubuntu() {
assert_eq!(default_sandbox_image(), "nvcr.io/nvidia/base/ubuntu:24.04");
</file>

<file path="crates/openshell-core/src/jwt.rs">
pub fn parse_exp_secs(token: &str) -> Option<i64> {
use base64::Engine;
let raw = token.strip_prefix("Bearer ").unwrap_or(token);
let mut parts = raw.splitn(3, '.');
let _header = parts.next()?;
let payload_b64 = parts.next()?;
⋮----
.decode(payload_b64)
.ok()?;
let value: serde_json::Value = serde_json::from_slice(&decoded).ok()?;
value.get("exp")?.as_i64()
⋮----
mod session {
use std::collections::BTreeMap;
use std::fmt;
use std::sync::Arc;
⋮----
use uuid::Uuid;
use zeroize::Zeroizing;
⋮----
use crate::SandboxSessionId;
use crate::sandbox_generation::SandboxGenerationId;
⋮----
pub struct SandboxId(String);
⋮----
impl SandboxId {
pub fn parse(value: impl Into<String>) -> Result<Self, SessionJwtError> {
let value = value.into();
if value.is_empty() || value.trim() != value || value.chars().any(char::is_whitespace) {
return Err(SessionJwtError::InvalidSandboxId);
... (494 lines truncated)
</file>

<file path="crates/openshell-core/src/lib.rs">
pub mod activity;
pub mod auth;
pub mod config;
pub mod container_paths;
pub mod denial;
pub mod driver_mounts;
pub mod driver_utils;
pub mod dynamic_string_allowlist;
pub mod endpoint_path;
pub mod endpoint_status;
pub mod error;
pub mod extension_protocol;
⋮----
pub mod external_driver_socket;
pub mod forward;
pub mod google_cloud;
pub mod gpu;
pub mod grpc_client;
pub mod host_pattern;
pub mod image;
pub mod jwt;
pub mod local_api_socket;
pub mod mcp;
pub mod metadata;
pub mod middleware;
pub mod net;
⋮----
pub mod oauth;
pub mod paths;
pub mod policy;
... (29 lines truncated)
</file>

<file path="crates/openshell-core/src/local_api_socket.rs">
pub fn first_responsive_socket(
⋮----
.iter()
.find(|path| socket_responds(path, &accepts_response))
.cloned()
⋮----
pub fn contains_ascii(haystack: &[u8], needle: &[u8]) -> bool {
⋮----
.windows(needle.len())
.any(|window| window.eq_ignore_ascii_case(needle))
⋮----
pub fn http_response_is_success(response: &[u8]) -> bool {
response.starts_with(b"HTTP/1.1 200") || response.starts_with(b"HTTP/1.0 200")
⋮----
fn socket_responds(path: &Path, accepts_response: &impl Fn(&[u8]) -> bool) -> bool {
⋮----
use std::time::Duration;
⋮----
.metadata()
.is_ok_and(|metadata| metadata.file_type().is_socket())
⋮----
if stream.set_read_timeout(Some(PROBE_TIMEOUT)).is_err()
|| stream.set_write_timeout(Some(PROBE_TIMEOUT)).is_err()
|| stream.write_all(PING_REQUEST).is_err()
⋮----
while total < response.len() {
let Ok(read) = stream.read(&mut response[total..]) else {
⋮----
if contains_ascii(&response[..total], b"\r\n\r\n") {
⋮----
... (2 lines truncated)
</file>

<file path="crates/openshell-core/src/mcp.rs">
pub fn is_mcp_protocol(protocol: &str) -> bool {
protocol.trim().eq_ignore_ascii_case("mcp")
⋮----
pub fn normalize_provider_profile_mcp_fields(profile: &mut ProviderProfile) {
⋮----
if !is_mcp_protocol(&endpoint.protocol) {
⋮----
let Some(options) = endpoint.mcp.as_mut() else {
endpoint.mcp = Some(McpOptions {
versions: vec![DEFAULT_MCP_PROTOCOL_VERSION.as_str().to_string()],
⋮----
if options.versions.is_empty() {
options.versions = vec![DEFAULT_MCP_PROTOCOL_VERSION.as_str().to_string()];
⋮----
let Ok(versions) = parse_mcp_versions(&options.versions) else {
⋮----
.into_iter()
.map(|version| version.as_str().to_string())
.collect();
⋮----
mod tests {
use prost::Message;
⋮----
fn mcp_protocol_version_all_values_are_in_canonical_order() {
assert_eq!(
⋮----
assert!(
⋮----
fn default_mcp_protocol_version_is_pinned_to_the_2025_11_25_revision() {
⋮----
... (115 lines truncated)
</file>

<file path="crates/openshell-core/src/metadata.rs">
use std::collections::HashMap;
⋮----
pub trait ObjectId {
⋮----
pub trait ObjectName {
⋮----
pub trait ObjectLabels {
⋮----
pub trait SetResourceVersion {
⋮----
pub trait GetResourceVersion {
⋮----
pub trait ObjectWorkspace {
⋮----
impl ObjectId for Sandbox {
fn object_id(&self) -> &str {
self.metadata.as_ref().map_or("", |m| m.id.as_str())
⋮----
impl ObjectName for Sandbox {
fn object_name(&self) -> &str {
self.metadata.as_ref().map_or("", |m| m.name.as_str())
⋮----
impl ObjectLabels for Sandbox {
fn object_labels(&self) -> Option<HashMap<String, String>> {
self.metadata.as_ref().map(|m| m.labels.clone())
⋮----
impl SetResourceVersion for Sandbox {
fn set_resource_version(&mut self, version: u64) {
if let Some(meta) = self.metadata.as_mut() {
⋮----
... (119 lines truncated)
</file>

<file path="crates/openshell-core/src/middleware.rs">
use std::pin::Pin;
use std::time::Duration;
⋮----
use miette::Result;
use tokio::sync::mpsc;
⋮----
pub type HttpResponseResultStream = Pin<
⋮----
/// Transport-neutral response stream for one WebSocket middleware stage.
pub type WebSocketResponseStream = Pin<
⋮----
pub type WebSocketResponseStream = Pin<
⋮----
pub trait SupervisorMiddlewareEndpoint: Send + Sync {
⋮----
async fn open_http_response_pre_return(
⋮----
Err(Status::unimplemented(
⋮----
pub struct HttpRequestView<'a> {
⋮----
/// Create a view over the chain's current request state for one stage.
    #[must_use]
pub fn new(
⋮----
pub fn phase(self) -> SupervisorMiddlewarePhase {
⋮----
pub fn context(self) -> &'a RequestContext {
⋮----
/// Return the validated configuration for this policy-selected stage.
... (130 lines truncated)
</file>

<file path="crates/openshell-core/src/net.rs">
use tokio::net::TcpStream;
⋮----
pub fn is_known_metadata_hostname(host: &str) -> bool {
let normalized = host.trim().trim_end_matches('.').to_ascii_lowercase();
matches!(normalized.as_str(), "metadata.google.internal")
⋮----
pub fn is_link_local_ip(ip: IpAddr) -> bool {
⋮----
IpAddr::V4(v4) => v4.is_link_local(),
⋮----
if (v6.segments()[0] & 0xffc0) == 0xfe80 {
⋮----
if let Some(v4) = v6.to_ipv4_mapped() {
return v4.is_link_local();
⋮----
pub fn is_always_blocked_ip(ip: IpAddr) -> bool {
⋮----
IpAddr::V4(v4) => v4.is_loopback() || v4.is_link_local() || v4.is_unspecified(),
⋮----
if v6.is_loopback() || v6.is_unspecified() {
⋮----
if is_link_local_ip(IpAddr::V6(v6)) {
⋮----
return v4.is_loopback() || v4.is_unspecified();
⋮----
pub fn is_always_blocked_net(net: IpNet) -> bool {
⋮----
let network = v4net.network();
let broadcast = v4net.broadcast();
⋮----
... (295 lines truncated)
</file>

<file path="crates/openshell-core/src/oauth.rs">
use std::net::IpAddr;
⋮----
use serde::Deserialize;
⋮----
pub struct OAuthTokenResponse {
⋮----
struct RawTokenResponse {
⋮----
struct OAuthErrorResponse {
⋮----
async fn post_oauth_token_request(
⋮----
let token_endpoint_url = parse_token_endpoint_url(token_endpoint)?;
⋮----
if !audience.is_empty() {
audience_param = audience.to_string();
form_params.push(("audience", &audience_param));
⋮----
if !scopes.is_empty() {
scope_param = scopes.join(" ");
form_params.push(("scope", &scope_param));
⋮----
.post(token_endpoint_url)
.form(&form_params)
.send()
⋮----
.into_diagnostic()
.wrap_err_with(|| format!("failed to POST to token endpoint {token_endpoint}"))?;
⋮----
if !response.status().is_success() {
... (303 lines truncated)
</file>

<file path="crates/openshell-core/src/paths.rs">
pub fn xdg_config_dir() -> Result<PathBuf> {
⋮----
return Ok(PathBuf::from(path));
⋮----
.into_diagnostic()
.wrap_err("HOME is not set")?;
Ok(PathBuf::from(home).join(".config"))
⋮----
pub fn openshell_config_dir() -> Result<PathBuf> {
Ok(xdg_config_dir()?.join("openshell"))
⋮----
pub fn xdg_state_dir() -> Result<PathBuf> {
⋮----
Ok(PathBuf::from(home).join(".local").join("state"))
⋮----
pub fn openshell_state_dir() -> Result<PathBuf> {
Ok(xdg_state_dir()?.join("openshell"))
⋮----
pub fn xdg_data_dir() -> Result<PathBuf> {
⋮----
Ok(PathBuf::from(home).join(".local").join("share"))
⋮----
pub fn create_dir_restricted(path: &Path) -> Result<()> {
⋮----
.wrap_err_with(|| format!("failed to create {}", path.display()))?;
set_dir_owner_only(path)?;
Ok(())
⋮----
pub fn set_dir_owner_only(path: &Path) -> Result<()> {
⋮----
... (69 lines truncated)
</file>

<file path="crates/openshell-core/src/policy_identity.rs">
use prost::Message;
⋮----
use std::collections::HashMap;
⋮----
const fn canonical_size(value: usize) -> [u8; 8] {
⋮----
(value as u64).to_le_bytes()
⋮----
fn append_canonical_bytes(out: &mut Vec<u8>, value: &[u8]) {
out.extend_from_slice(&canonical_size(value.len()));
out.extend_from_slice(value);
⋮----
fn append_canonical_message<M: Message>(out: &mut Vec<u8>, value: &M) {
append_canonical_bytes(out, &value.encode_to_vec());
⋮----
fn append_sorted_message_map<M: Message>(
⋮----
append_canonical_bytes(out, label);
let mut entries = values.iter().collect::<Vec<_>>();
entries.sort_by_key(|(key, _)| key.as_str());
out.extend_from_slice(&canonical_size(entries.len()));
⋮----
append_canonical_bytes(out, key.as_bytes());
append_canonical_message(out, value);
⋮----
pub fn canonical_rule_bytes(rule: &NetworkPolicyRule) -> Vec<u8> {
let mut map_free = rule.clone();
⋮----
endpoint.graphql_persisted_queries.clear();
⋮----
... (83 lines truncated)
</file>

<file path="crates/openshell-core/src/policy.rs">
use crate::paths::normalize_path;
⋮----
use std::net::SocketAddr;
use std::path::PathBuf;
⋮----
pub struct SandboxPolicy {
⋮----
pub struct FilesystemPolicy {
⋮----
impl Default for FilesystemPolicy {
fn default() -> Self {
⋮----
pub struct NetworkPolicy {
⋮----
impl Default for NetworkPolicy {
⋮----
pub enum NetworkMode {
⋮----
pub struct ProxyPolicy {
⋮----
pub struct LandlockPolicy {
⋮----
pub struct ProcessPolicy {
⋮----
pub enum LandlockCompatibility {
⋮----
pub fn is_valid_landlock_compatibility(value: &str) -> bool {
value.is_empty() || LANDLOCK_COMPATIBILITY_VALUES.contains(&value)
⋮----
type Error = miette::Report;
... (62 lines truncated)
</file>

<file path="crates/openshell-core/src/progress.rs">
use std::collections::HashMap;
use std::hash::BuildHasher;
⋮----
pub fn mark_progress_complete<S: BuildHasher>(
⋮----
metadata.insert(PROGRESS_COMPLETE_STEP_KEY.to_string(), step.to_string());
metadata.insert(PROGRESS_COMPLETE_LABEL_KEY.to_string(), label.into());
⋮----
pub fn mark_progress_active<S: BuildHasher>(
⋮----
metadata.insert(PROGRESS_ACTIVE_STEP_KEY.to_string(), step.to_string());
⋮----
pub fn mark_progress_detail<S: BuildHasher>(
⋮----
metadata.insert(PROGRESS_ACTIVE_DETAIL_KEY.to_string(), detail.into());
⋮----
pub fn format_bytes(bytes: u64) -> String {
⋮----
format!("{gb:.1} GB")
⋮----
format!("{} MB", bytes / MB)
⋮----
format!("{} KB", bytes / KB)
⋮----
format!("{bytes} B")
</file>

<file path="crates/openshell-core/src/proposals.rs">
use std::sync::Arc;
⋮----
pub struct AgentProposals {
⋮----
impl AgentProposals {
⋮----
pub fn new(enabled: bool) -> Self {
⋮----
pub fn enabled(&self) -> bool {
self.enabled.load(Ordering::Relaxed)
⋮----
pub fn set_enabled(&self, enabled: bool) {
self.enabled.store(enabled, Ordering::Relaxed);
⋮----
pub fn swap_enabled(&self, enabled: bool) -> bool {
self.enabled.swap(enabled, Ordering::Relaxed)
⋮----
impl Default for AgentProposals {
fn default() -> Self {
</file>

<file path="crates/openshell-core/src/proto_struct.rs">
pub enum ProtoStructError {
⋮----
pub fn json_object_to_struct(
⋮----
Ok(prost_types::Struct {
⋮----
.into_iter()
.map(|(key, value)| json_value_to_proto(value).map(|value| (key, value)))
⋮----
pub fn json_value_to_proto(
⋮----
serde_json::Value::Number(value) => Kind::NumberValue(number_to_f64_exact(&value)?),
⋮----
.map(json_value_to_proto)
⋮----
serde_json::Value::Object(object) => Kind::StructValue(json_object_to_struct(object)?),
⋮----
Ok(Value { kind: Some(kind) })
⋮----
fn number_to_f64_exact(value: &serde_json::Number) -> Result<f64, ProtoStructError> {
⋮----
.as_f64()
.ok_or_else(|| ProtoStructError::UnrepresentableNumber(value.clone()))?;
⋮----
let exact = value.as_i64().map_or_else(
|| value.as_u64().is_none_or(integer_is_exact_in_f64),
|integer| integer_is_exact_in_f64(integer.unsigned_abs()),
⋮----
.then_some(number)
.ok_or_else(|| ProtoStructError::UnrepresentableNumber(value.clone()))
... (84 lines truncated)
</file>

<file path="crates/openshell-core/src/provider_credentials.rs">
use crate::secrets::SecretResolver;
⋮----
use std::fmt;
⋮----
pub struct ProviderCredentialSnapshot {
⋮----
pub struct ChildEnvironmentSnapshot {
⋮----
struct ProviderCredentialStateInner {
⋮----
struct StaticCredentialIdentityEpoch {
⋮----
struct CompiledStaticCredentialBinding {
⋮----
struct CompiledStaticCredentialEndpointBinding {
⋮----
pub struct ProviderCredentialState {
⋮----
pub struct StaticCredentialBindingError {
⋮----
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.message)
⋮----
impl ProviderCredentialState {
pub fn from_environment(
⋮----
installation_id: uuid::Uuid::new_v4().to_string(),
⋮----
let generations: VecDeque<_> = generation_resolver.map(Arc::new).into_iter().collect();
let current_resolver = current_resolver.map(Arc::new);
... (918 lines truncated)
</file>

<file path="crates/openshell-core/src/resource_admission.rs">
use std::collections::BTreeMap;
⋮----
pub struct ResourceAdmissionConfig {
⋮----
impl Default for ResourceAdmissionConfig {
fn default() -> Self {
⋮----
("openshell.ai/sandbox-attachable".into(), "true".into()),
⋮----
"openshell.ai/sandbox-attachable-workspace".into(),
WORKSPACE_PLACEHOLDER.into(),
⋮----
pub struct DriverAdmissionConfig {
⋮----
impl DriverAdmissionConfig {
pub fn validate(&self) -> Result<(), String> {
self.resource_admission.validate()
⋮----
pub fn acknowledgement(&self) -> String {
⋮----
format!(
⋮----
pub fn verify_acknowledgement(&self, value: &str) -> Result<(), String> {
self.validate()?;
if !self.resource_admission.enabled && value.is_empty() {
⋮----
return Ok(());
⋮----
.strip_prefix("v1:")
.ok_or("compute driver does not acknowledge resource admission v1")
... (170 lines truncated)
</file>

<file path="crates/openshell-core/src/rpc_error.rs">
use std::collections::HashMap;
use std::time::Duration;
⋮----
use prost::Message;
⋮----
pub fn decode_details(status: &Status) -> Option<ErrorDetails> {
let envelope = tonic_types::pb::Status::decode(status.details()).ok()?;
if envelope.code != status.code() as i32 || envelope.message != status.message() {
⋮----
match detail.type_url.rsplit('/').next() {
⋮----
if let Ok(value) = tonic_types::pb::BadRequest::decode(detail.value.as_slice()) {
⋮----
details.add_bad_request_violation(violation.field, violation.description);
⋮----
if let Ok(value) = tonic_types::pb::ErrorInfo::decode(detail.value.as_slice()) {
details.set_error_info(value.reason, value.domain, value.metadata);
⋮----
if let Ok(value) = tonic_types::pb::RetryInfo::decode(detail.value.as_slice())
⋮----
&& (0..=315_576_000_000).contains(&delay.seconds)
&& (0..1_000_000_000).contains(&delay.nanos)
⋮----
details.set_retry_info(Some(Duration::new(
delay.seconds.cast_unsigned(),
delay.nanos.cast_unsigned(),
⋮----
Some(details)
⋮----
pub fn invalid_argument(field: &str, message: impl Into<String>) -> Status {
... (66 lines truncated)
</file>

<file path="crates/openshell-core/src/sandbox_env.rs">
pub struct MainProcessConfig {
⋮----
impl MainProcessConfig {
⋮----
pub fn scratch() -> Self {
⋮----
pub fn from_driver_spec(spec: Option<&crate::proto::compute::v1::DriverSandboxSpec>) -> Self {
⋮----
Some(spec) if !spec.command.is_empty() => Self {
⋮----
command: spec.command.clone(),
⋮----
pub fn decode(encoded: &str) -> Result<Self, String> {
⋮----
let json = if let Some(payload) = encoded.strip_prefix(MAIN_PROCESS_SPEC_BASE64URL_PREFIX) {
⋮----
.decode(payload)
.map_err(|error| format!("invalid {MAIN_PROCESS_SPEC} base64url: {error}"))?;
⋮----
.map_err(|error| format!("invalid {MAIN_PROCESS_SPEC} UTF-8: {error}"))?;
decoded.as_str()
⋮----
.map_err(|error| format!("invalid {MAIN_PROCESS_SPEC}: {error}"))?;
⋮----
return Err(format!(
⋮----
if !config.command.is_empty() && config.command[0].is_empty() {
⋮----
Ok(config)
⋮----
... (54 lines truncated)
</file>

<file path="crates/openshell-core/src/sandbox_generation.rs">
use std::fmt;
⋮----
pub struct SandboxGenerationId(String);
⋮----
pub enum SandboxGenerationIdError {
⋮----
impl SandboxGenerationId {
⋮----
pub fn from_start_resource_version(resource_version: u64) -> Self {
Self(format!("g{resource_version:016x}"))
⋮----
pub fn parse(value: impl Into<String>) -> Result<Self, SandboxGenerationIdError> {
let value = value.into();
if value.is_empty() {
return Err(SandboxGenerationIdError::Empty);
⋮----
if value.len() > Self::MAX_LEN {
return Err(SandboxGenerationIdError::TooLong);
⋮----
.bytes()
.all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')
⋮----
return Err(SandboxGenerationIdError::InvalidCharacter);
⋮----
Ok(Self(value))
⋮----
pub fn as_str(&self) -> &str {
⋮----
pub fn into_string(self) -> String {
⋮----
... (12 lines truncated)
</file>

<file path="crates/openshell-core/src/sandbox_session.rs">
use thiserror::Error;
use uuid::Uuid;
⋮----
pub struct SandboxSessionId(Uuid);
⋮----
impl SandboxSessionId {
⋮----
pub fn new() -> Self {
Self(Uuid::new_v4())
⋮----
pub const fn as_uuid(&self) -> &Uuid {
⋮----
impl Default for SandboxSessionId {
fn default() -> Self {
⋮----
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.hyphenated().fmt(formatter)
⋮----
.debug_tuple("SandboxSessionId")
.field(&self.to_string())
.finish()
⋮----
impl FromStr for SandboxSessionId {
type Err = SandboxSessionIdError;
⋮----
fn from_str(value: &str) -> Result<Self, Self::Err> {
let parsed = Uuid::parse_str(value).map_err(|_| SandboxSessionIdError)?;
if parsed.is_nil() || parsed.hyphenated().to_string() != value {
return Err(SandboxSessionIdError);
⋮----
... (27 lines truncated)
</file>

<file path="crates/openshell-core/src/secrets_body.rs">
use std::fmt;
use std::sync::Arc;
⋮----
pub enum BodyCredentialError {
⋮----
impl BodyCredentialError {
pub const fn reason(self) -> &'static str {
⋮----
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
⋮----
struct ValueStatus {
⋮----
pub struct BodyCredentialClassifier {
⋮----
f.debug_struct("BodyCredentialClassifier")
.finish_non_exhaustive()
⋮----
impl BodyCredentialClassifier {
pub(crate) fn new(
⋮----
if let Some(key) = placeholder_env_key(token) {
result.known.insert(key.to_owned());
⋮----
result.values.insert(
token.clone(),
⋮----
valid: validate_resolved_secret(&value.value).is_ok(),
⋮----
/// Authorize forwarding a complete token unchanged; never resolve it.
... (217 lines truncated)
</file>

<file path="crates/openshell-core/src/secrets.rs">
pub mod body;
⋮----
use crate::time::now_ms;
⋮----
use std::fmt;
use std::sync::Arc;
⋮----
3 * if PLACEHOLDER_PREFIX.len() > PROVIDER_ALIAS_MARKER.len() {
PLACEHOLDER_PREFIX.len()
⋮----
PROVIDER_ALIAS_MARKER.len()
⋮----
fn is_env_key_char(b: u8) -> bool {
b.is_ascii_alphanumeric() || b == b'_'
⋮----
fn is_alias_token_char(b: u8) -> bool {
b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.' | b'~')
⋮----
fn contains_raw_reserved_marker(value: &str) -> bool {
value.contains(PLACEHOLDER_PREFIX) || value.contains(PROVIDER_ALIAS_MARKER)
⋮----
pub fn contains_reserved_credential_marker(value: &str) -> bool {
if contains_raw_reserved_marker(value) {
⋮----
let decoded = percent_decode(value);
contains_raw_reserved_marker(&decoded)
⋮----
/// Return whether an HTTP header value contains syntax reserved for credential
/// placeholder rewriting, including the decoded value of Basic authentication.
⋮----
... (1197 lines truncated)
</file>

<file path="crates/openshell-core/src/settings.rs">
pub enum SettingValueKind {
⋮----
impl SettingValueKind {
⋮----
pub const fn as_str(self) -> &'static str {
⋮----
/// Static descriptor for one registered sandbox setting key.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RegisteredSetting {
⋮----
impl RegisteredSetting {
⋮----
pub fn validate_string_value(&self, value: &str) -> Result<(), &'static [&'static str]> {
⋮----
Some(allowed) if !allowed.contains(&value) => Err(allowed),
_ => Ok(()),
⋮----
allowed_string_values: Some(OCSF_SCHEMA_VERSION_VALUES),
⋮----
allowed_string_values: Some(PROPOSAL_APPROVAL_MODE_VALUES),
⋮----
pub fn setting_for_key(key: &str) -> Option<&'static RegisteredSetting> {
REGISTERED_SETTINGS.iter().find(|entry| entry.key == key)
⋮----
/// Return comma-separated registered keys for CLI/API diagnostics.
#[must_use]
pub fn registered_keys_csv() -> String {
⋮----
.iter()
.map(|entry| entry.key)
... (118 lines truncated)
</file>

<file path="crates/openshell-core/src/shell.rs">
pub fn is_executable(path: &str) -> bool {
⋮----
if !meta.is_file() {
⋮----
use std::os::unix::fs::PermissionsExt;
meta.permissions().mode() & 0o111 != 0
⋮----
pub fn detect_login_shell() -> String {
find_login_shell().unwrap_or_else(|| POSIX_SH.to_string())
⋮----
pub fn find_login_shell() -> Option<String> {
⋮----
.iter()
.find(|candidate| is_executable(candidate))
.map(|candidate| (*candidate).to_string())
⋮----
mod tests {
⋮----
fn posix_sh_exists_on_test_host() {
⋮----
assert!(is_executable(POSIX_SH));
⋮----
fn missing_path_is_not_executable() {
assert!(!is_executable("/nonexistent/definitely/not/here"));
⋮----
fn non_file_is_not_executable() {
⋮----
assert!(!is_executable("/"));
⋮----
fn detect_returns_an_executable_shell() {
... (3 lines truncated)
</file>

<file path="crates/openshell-core/src/spiffe.rs">
use std::path::Path;
⋮----
use serde::Deserialize;
⋮----
pub struct SpiffeJwtClaims {
⋮----
pub enum AudienceClaim {
⋮----
impl AudienceClaim {
pub fn contains(&self, expected: &str) -> bool {
⋮----
Self::Many(values) => values.iter().any(|value| value == expected),
⋮----
pub enum JwtSvidParseError {
⋮----
pub fn workload_api_endpoint(path: &Path) -> String {
let path = path.to_string_lossy();
if path.starts_with("unix:") || path.starts_with("tcp:") {
path.into_owned()
⋮----
format!("unix:{path}")
⋮----
pub fn parse_unverified_jwt_svid_claims(token: &str) -> Result<SpiffeJwtClaims, JwtSvidParseError> {
let segments = token.split('.').collect::<Vec<_>>();
if segments.len() != 3 || segments.iter().any(|segment| segment.is_empty()) {
return Err(JwtSvidParseError::Format);
⋮----
.decode(segments[1])
.map_err(|_| JwtSvidParseError::PayloadEncoding)?;
serde_json::from_slice::<SpiffeJwtClaims>(&decoded).map_err(|_| JwtSvidParseError::Payload)
... (45 lines truncated)
</file>

<file path="crates/openshell-core/src/telemetry.rs">
use reqwest::blocking::Client;
⋮----
use std::collections::BTreeMap;
⋮----
use std::thread;
⋮----
use std::time::Duration;
⋮----
struct TelemetryEvent {
⋮----
enum TelemetrySource {
⋮----
impl TelemetrySource {
const fn as_str(self) -> &'static str {
⋮----
pub enum TelemetryOutcome {
⋮----
impl TelemetryOutcome {
⋮----
pub const fn as_str(self) -> &'static str {
⋮----
pub const fn from_success(success: bool) -> Self {
⋮----
pub enum LifecycleResource {
⋮----
impl LifecycleResource {
⋮----
pub enum LifecycleOperation {
⋮----
impl LifecycleOperation {
... (258 lines truncated)
</file>

<file path="crates/openshell-core/src/time.rs">
use std::cmp::Ordering;
⋮----
use thiserror::Error;
⋮----
pub enum ProtoTimeError {
⋮----
pub fn now_ms() -> i64 {
⋮----
.duration_since(UNIX_EPOCH)
.map_or(0, |d| i64::try_from(d.as_millis()).unwrap_or(i64::MAX))
⋮----
pub fn validate_timestamp(value: &Timestamp) -> Result<(), ProtoTimeError> {
if !(MIN_TIMESTAMP_SECONDS..=MAX_TIMESTAMP_SECONDS).contains(&value.seconds) {
return Err(ProtoTimeError::TimestampOutOfRange);
⋮----
if !(0..1_000_000_000).contains(&value.nanos) {
return Err(ProtoTimeError::InvalidTimestampNanos);
⋮----
Ok(())
⋮----
pub fn compare_timestamps(left: &Timestamp, right: &Timestamp) -> Result<Ordering, ProtoTimeError> {
validate_timestamp(left)?;
validate_timestamp(right)?;
Ok((left.seconds, left.nanos).cmp(&(right.seconds, right.nanos)))
⋮----
pub fn timestamp_from_millis(value: i64) -> Result<Timestamp, ProtoTimeError> {
⋮----
seconds: value.div_euclid(1_000),
nanos: i32::try_from(value.rem_euclid(1_000) * 1_000_000)
.map_err(|_| ProtoTimeError::Overflow)?,
... (99 lines truncated)
</file>

<file path="crates/openshell-core/src/transport_errors.rs">
use std::io::ErrorKind;
⋮----
pub fn is_expected_transport_close_status(status: &tonic::Status) -> bool {
matches!(
⋮----
) && is_expected_transport_close_message(&status.to_string())
⋮----
pub fn is_expected_transport_close_error(error: &(dyn std::error::Error + 'static)) -> bool {
⋮----
return is_expected_transport_close_status(status);
⋮----
return matches!(
⋮----
is_expected_transport_close_message(&error.to_string())
⋮----
pub fn is_expected_transport_close_message(message: &str) -> bool {
let msg = message.to_ascii_lowercase();
msg.contains("h2 protocol error")
|| msg.contains("broken pipe")
|| msg.contains("connection reset")
|| msg.contains("connection aborted")
|| msg.contains("connection closed")
|| msg.contains("connection error")
|| msg.contains("error reading a body from connection")
|| msg.contains("peer closed connection")
|| msg.contains("unexpected eof")
|| msg.contains("cancelled")
|| msg.contains("canceled")
⋮----
mod tests {
... (11 lines truncated)
</file>

<file path="crates/openshell-core/build_version.rs">
type StableVersion = (u32, u32, u32);
type PrereleaseVersion = (u32, u32, u32, u32);
⋮----
fn parse_stable_tag(tag: &str) -> Option<StableVersion> {
let tag = tag.strip_prefix('v').unwrap_or(tag);
let mut parts = tag.split('.');
⋮----
parts.next()?.parse().ok()?,
⋮----
parts.next().is_none().then_some(version)
⋮----
fn parse_prerelease_tag(tag: &str) -> Option<PrereleaseVersion> {
⋮----
let (base, sequence) = tag.rsplit_once("-pre.")?;
let (major, minor, patch) = parse_stable_tag(base)?;
let sequence = sequence.parse().ok()?;
(sequence > 0).then_some((major, minor, patch, sequence))
⋮----
pub fn exact_release_version<'a>(tags: impl Iterator<Item = &'a str>) -> Option<String> {
⋮----
.iter()
.filter_map(|tag| parse_stable_tag(tag).map(|version| (version, tag)))
.max_by_key(|(version, _)| *version)
⋮----
return Some(format!("{major}.{minor}.{patch}"));
⋮----
tags.iter()
.filter_map(|tag| parse_prerelease_tag(tag))
.max()
.map(|(major, minor, patch, sequence)| format!("{major}.{minor}.{patch}-pre.{sequence}"))
... (24 lines truncated)
</file>

<file path="crates/openshell-core/build.rs">
use std::env;
⋮----
mod build_version;
⋮----
fn main() -> Result<(), Box<dyn std::error::Error>> {
⋮----
println!("cargo:rerun-if-changed=../../.git/HEAD");
println!("cargo:rerun-if-changed=../../.git/logs/HEAD");
println!("cargo:rerun-if-changed=../../.git/refs/tags");
println!("cargo:rerun-if-changed=../../.git/packed-refs");
⋮----
if let Some(version) = git_version() {
println!("cargo:rustc-env=OPENSHELL_GIT_VERSION={version}");
⋮----
println!("cargo:rerun-if-changed={PROTO_REL}");
⋮----
let proto_root = manifest_dir.join(PROTO_REL);
⋮----
collect_proto_files(&proto_root, &mut proto_files)?;
proto_files.sort();
⋮----
let descriptor_path = out_dir.join("openshell_descriptor.bin");
⋮----
.build_server(true)
.build_client(true)
.include_file("openshell.rs")
⋮----
.file_descriptor_set_path(&descriptor_path)
.compile_protos(&proto_files, &[proto_root])?;
⋮----
... (36 lines truncated)
</file>

<file path="crates/openshell-core/Cargo.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

[package]
name = "openshell-core"
description = "Shared library for OpenShell - proto definitions, config, and errors"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true

[dependencies]
async-trait = "0.1"
openshell-extension-core = { path = "../openshell-extension-core" }
openshell-policy-schema = { path = "../openshell-policy-schema" }
glob = { workspace = true }
prost = { workspace = true }
prost-types = { workspace = true }
tonic = { workspace = true, features = ["channel", "tls-aws-lc"] }
tonic-prost = { workspace = true }
tonic-types = { workspace = true }
tokio = { workspace = true }
tokio-stream = { workspace = true }
thiserror = { workspace = true }
miette = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
sha2 = { workspace = true }
tracing = { workspace = true }
... (40 lines truncated)
</file>

<file path="crates/openshell-core/README.md">
# openshell-core

Shared types, constants, configuration, and helpers used across OpenShell
crates.

## Object Metadata

Top-level user-facing objects use a Kubernetes-style metadata convention. The
metadata shape provides:

- Stable server-generated ID.
- Human-readable name.
- Creation timestamp.
- Optional labels for filtering and automation.

Code that works with object metadata should use the traits in
`openshell_core::metadata` instead of reaching into protobuf fields directly:

```rust
use openshell_core::{ObjectId, ObjectLabels, ObjectName};

let id = sandbox.object_id();
let name = sandbox.object_name();
let labels = sandbox.object_labels();
```

Trait methods must tolerate missing metadata and return safe empty values rather
than panicking.

## Label Rules
... (37 lines truncated)
</file>

<file path="crates/openshell-driver-db-credstore/src/lib.rs">
use std::collections::HashMap;
⋮----
use std::io::Write;
⋮----
use std::os::unix::fs::OpenOptionsExt;
⋮----
use std::sync::Arc;
⋮----
use async_trait::async_trait;
⋮----
use openshell_core::proto::CredentialHandle;
⋮----
use tonic::Status;
⋮----
pub struct DbCredstoreCredentialDriver {
⋮----
pub trait DbCredstoreObjectStore: std::fmt::Debug + Send + Sync {
⋮----
pub struct StoredCredentialObject {
⋮----
pub struct CredentialObjectWrite {
⋮----
pub enum DbCredstoreWriteCondition {
⋮----
pub struct EncryptedGatewayCredentialStoreCrypto {
⋮----
struct EncryptedGatewayCredentialSettings {
⋮----
struct EncryptedGatewayCredentialState {
⋮----
... (546 lines truncated)
</file>

<file path="crates/openshell-driver-db-credstore/Cargo.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

[package]
name = "openshell-driver-db-credstore"
description = "Encrypted database credential storage driver for OpenShell"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true

[dependencies]
openshell-core = { path = "../openshell-core", default-features = false }

async-trait = "0.1"
base64 = { workspace = true }
futures = { workspace = true }
aws-lc-rs = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
sha2 = { workspace = true }
toml = { workspace = true }
tonic = { workspace = true }

[dev-dependencies]
tempfile = "3"
tokio = { workspace = true }

[lints]
... (2 lines truncated)
</file>

<file path="crates/openshell-driver-docker/src/isolation.rs">
use std::net::IpAddr;
use std::path::PathBuf;
⋮----
use openshell_sandbox_backend::GPU_RESOURCE_CLAIM;
⋮----
use serde::Serialize;
⋮----
struct DockerOuterFenceEvidence<'a> {
⋮----
fn project(&self, generation: &str) -> Result<OuterFenceGuarantees, BackendError> {
if self.container_id.is_empty() {
return Err(BackendError::Descriptor(
"Docker outer fence evidence is incomplete".to_string(),
⋮----
established.extend([
⋮----
if self.unexpected_networks.is_empty() {
established.push(OuterFenceGuarantee::NoUnmanagedEgressPath);
⋮----
let encoded = serde_json::to_vec(self).map_err(|error| {
BackendError::Descriptor(format!("encode Docker outer fence evidence: {error}"))
⋮----
projection.validate(generation)?;
Ok(projection)
⋮----
pub struct DockerBoundarySpec {
⋮----
pub struct DockerBoundaryProvisioning {
⋮----
impl DockerBoundarySpec {
... (54 lines truncated)
</file>

<file path="crates/openshell-driver-docker/src/lib.rs">
mod isolation;
pub mod otel_tracing;
⋮----
use bollard::Docker;
⋮----
use bytes::Bytes;
⋮----
use openshell_core::config::DEFAULT_STOP_TIMEOUT_SECS;
use openshell_core::driver_mounts;
⋮----
use openshell_isolation_interface::contract::ResolvedWorkloadIdentity;
⋮----
use std::pin::Pin;
use std::sync::Arc;
⋮----
use std::time::Duration;
⋮----
use tokio::task::JoinHandle;
use tokio_stream::wrappers::ReceiverStream;
⋮----
use url::Url;
⋮----
fn provisioning_span(
⋮----
let parent_span_context = parent.span().span_context().clone();
if parent_span_context.is_valid() {
let parent = opentelemetry::Context::new().with_remote_span_context(parent_span_context);
let _ = span.set_parent(parent);
⋮----
pub struct DockerComputeConfig {
... (2548 lines truncated)
</file>

<file path="crates/openshell-driver-docker/src/main.rs">
use std::net::SocketAddr;
use std::path::PathBuf;
⋮----
use clap::Parser;
⋮----
use openshell_core::VERSION;
use openshell_core::proto::compute::v1::compute_driver_server::ComputeDriverServer;
⋮----
use tracing::info;
⋮----
struct Args {
⋮----
async fn main() -> Result<()> {
⋮----
endpoint: args.otlp_endpoint.as_deref(),
gateway_name: args.gateway_name.as_deref(),
⋮----
let config_source = std::fs::read_to_string(&args.config).into_diagnostic()?;
⋮----
toml::from_str(&config_source).into_diagnostic()?;
⋮----
.into_diagnostic()?;
⋮----
.map_err(|err| miette::miette!("{err}"))?;
⋮----
openshell_core::external_driver_socket::SocketCleanup::new(args.bind_socket.clone());
info!(socket = %args.bind_socket.display(), "Starting Docker compute driver");
⋮----
.layer(openshell_otel::compute_driver_rpc_layer())
.add_service(ComputeDriverServer::new(ComputeDriverService::new(driver)))
... (12 lines truncated)
</file>

<file path="crates/openshell-driver-docker/src/otel_tracing.rs">
mod tests {
⋮----
async fn driver_spans_reach_otlp_collector_with_resource_identity() {
</file>

<file path="crates/openshell-driver-docker/src/tests.rs">
use std::fs;
⋮----
use std::sync::Arc;
use tempfile::TempDir;
⋮----
fn test_launch_authentication() -> Vec<u8> {
⋮----
.unwrap(),
session_rotation: openshell_core::jwt::SessionRotation::new(1).unwrap(),
auth_epoch: CredentialEpoch::new(1).unwrap(),
gateway_token: SecretJwt::parse("gateway.token.value").unwrap(),
⋮----
sandbox_token: SecretJwt::parse("sandbox.token.value").unwrap(),
⋮----
gateway_id: "gateway-test".to_string(),
verification_keys: vec![SessionVerificationKey {
⋮----
.unwrap()
⋮----
fn test_sandbox() -> DriverSandbox {
⋮----
id: "sbx-123".to_string(),
name: "demo".to_string(),
⋮----
spec: Some(DriverSandboxSpec {
log_level: "debug".to_string(),
environment: HashMap::from([("SPEC_ENV".to_string(), "spec".to_string())]),
template: Some(DriverSandboxTemplate {
image: "nvcr.io/nvidia/base/ubuntu:24.04".to_string(),
⋮----
... (1339 lines truncated)
</file>

<file path="crates/openshell-driver-docker/Cargo.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

[package]
name = "openshell-driver-docker"
description = "Docker compute driver for OpenShell"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true

[[bin]]
name = "openshell-driver-docker"
path = "src/main.rs"

[dependencies]
openshell-core = { path = "../openshell-core", default-features = false, features = ["driver-extraction"] }
openshell-isolation-interface = { path = "../openshell-isolation-interface" }
openshell-sandbox-backend = { path = "../openshell-sandbox-backend" }
openshell-otel = { path = "../openshell-otel" }

opentelemetry = { workspace = true }
opentelemetry_sdk = { workspace = true }
tracing-opentelemetry = { workspace = true }
tokio = { workspace = true }
tonic = { workspace = true, features = ["transport"] }
futures = { workspace = true }
tokio-stream = { workspace = true }
tracing = { workspace = true }
... (30 lines truncated)
</file>

<file path="crates/openshell-driver-docker/README.md">
# openshell-driver-docker

Docker-backed compute driver for local and remote OpenShell gateways.

The driver uses `bollard` to manage sandbox resources through the configured
Docker API socket. When `socket_path` is unset, it selects the first standard
local socket that responds to an API ping. An explicitly selected Docker driver
falls back to `/var/run/docker.sock` when no candidate responds.

When the gateway configures `[openshell.gateway.otlp]`, the in-process driver
exports spans to the same OTLP/gRPC collector as
`openshell-driver-docker`. The standalone driver accepts
`OPENSHELL_OTLP_ENDPOINT`, continues W3C trace context from gateway RPC
metadata, and flushes spans during graceful shutdown.

## Runtime Model

Caller driver config is disabled by default. Existing volumes require
administrator-controlled approval labels; raw bind mounts have no supported
label resolver and are denied under enforcement. GPU devices are temporarily
exempt. Inspect labels again before launch, restart, and during reconciliation.
See [resource admission configuration](../../docs/how-it-works/gateways/configuration.mdx#external-resource-admission).

The driver creates two containers for each sandbox:

- `openshell-sandbox` is PID 1 in the workload container. It owns the workload
  process tree, seccomp notification broker, mandatory Landlock baseline,
  binary identity, exec/signal/wait/PTY operations, and loopback forwarding.
- `openshell-supervisor` runs in a separate companion container. It owns the
  gateway session, policy engine, credentials, interception CA, SSH relay, L7
... (171 lines truncated)
</file>

<file path="crates/openshell-driver-kubernetes/src/driver.rs">
use k8s_openapi::apimachinery::pkg::util::intstr::IntOrString;
⋮----
use kube::core::gvk::GroupVersionKind;
⋮----
use kube::runtime::WatchStreamExt;
use kube::runtime::wait::await_condition;
⋮----
use openshell_core::driver_mounts;
⋮----
use openshell_isolation_interface::contract::ResolvedWorkloadIdentity;
⋮----
use serde::Deserialize;
⋮----
use std::pin::Pin;
use std::sync::Arc;
⋮----
use tokio_stream::wrappers::ReceiverStream;
⋮----
pub type WatchStream =
⋮----
enum SandboxRuntimeBootstrapPhase {
⋮----
impl SandboxRuntimeBootstrapPhase {
const fn as_str(self) -> &'static str {
⋮----
fn parse(value: &str) -> Option<Self> {
⋮----
"preparing" => Some(Self::Preparing),
"released" => Some(Self::Released),
"releasing" => Some(Self::Releasing),
... (4113 lines truncated)
</file>

<file path="crates/openshell-driver-kubernetes/src/grpc.rs">
use std::pin::Pin;
⋮----
use crate::KubernetesComputeDriver;
use crate::WorkspaceMode;
⋮----
type ComputeDriverWatchStream =
⋮----
type TracedWatchStream = openshell_otel::TracedGrpcStream<ComputeDriverWatchStream>;
⋮----
pub struct ComputeDriverService {
⋮----
impl ComputeDriverService {
⋮----
pub fn new(driver: KubernetesComputeDriver) -> Self {
⋮----
pub fn new_in_process(driver: KubernetesComputeDriver) -> Self {
⋮----
impl ComputeDriver for ComputeDriverService {
async fn authenticate_sandbox(
⋮----
.trace(openshell_otel::rpc::AUTHENTICATE_SANDBOX, async {
let credential = request.into_inner().credential;
if credential.is_empty() {
return Err(Status::invalid_argument("credential is required"));
⋮----
self.driver.authenticate_sandbox(&credential).await?;
Ok(Response::new(AuthenticateSandboxResponse {
⋮----
async fn get_capabilities(
⋮----
... (250 lines truncated)
</file>

<file path="crates/openshell-driver-kubernetes/src/isolation.rs">
use std::path::PathBuf;
⋮----
use k8s_openapi::apimachinery::pkg::apis::meta::v1::LabelSelector;
use k8s_openapi::apimachinery::pkg::util::intstr::IntOrString;
use kube::core::ObjectMeta;
⋮----
use serde::Serialize;
⋮----
struct KubernetesOuterFenceEvidence<'a> {
⋮----
fn project(&self, generation: &str) -> Result<OuterFenceGuarantees, BackendError> {
if self.network_policy_uid.is_empty() || self.network_policy_resource_version.is_empty() {
return Err(BackendError::Descriptor(
"Kubernetes outer fence evidence is incomplete".to_string(),
⋮----
established.extend([
⋮----
established.push(OuterFenceGuarantee::NoUnmanagedEgressPath);
⋮----
let encoded = serde_json::to_vec(self).map_err(|error| {
BackendError::Descriptor(format!("encode Kubernetes outer fence evidence: {error}"))
⋮----
projection.validate(generation)?;
Ok(projection)
⋮----
pub struct KubernetesSandboxRuntimeNetworkFenceSpec {
⋮----
pub struct KubernetesSandboxRuntimeNetworkFence {
⋮----
impl KubernetesSandboxRuntimeNetworkFenceSpec {
... (146 lines truncated)
</file>

<file path="crates/openshell-driver-kubernetes/src/lib.rs">
pub mod config;
pub mod driver;
pub mod grpc;
pub mod isolation;
pub mod otel_tracing;
mod resource_admission;
mod sandbox_runtime;
⋮----
pub use grpc::ComputeDriverService;
</file>

<file path="crates/openshell-driver-kubernetes/src/main.rs">
use std::collections::BTreeMap;
use std::net::SocketAddr;
use std::path::PathBuf;
use tracing::info;
⋮----
use openshell_core::VERSION;
use openshell_core::proto::compute::v1::compute_driver_server::ComputeDriverServer;
⋮----
struct Args {
⋮----
async fn shutdown_signal() {
⋮----
signal.recv().await;
⋮----
async fn main() -> Result<()> {
⋮----
endpoint: args.otlp_endpoint.as_deref(),
gateway_name: args.gateway_name.as_deref(),
⋮----
.iter()
.map(|entry| {
⋮----
.split_once('=')
.map(|(key, value)| (key.to_string(), value.to_string()))
.ok_or_else(|| {
⋮----
resource_admission: args.admission_config_json.resource_admission.clone(),
⋮----
default_image: args.sandbox_image.unwrap_or_default(),
⋮----
... (49 lines truncated)
</file>

<file path="crates/openshell-driver-kubernetes/src/otel_tracing.rs">
mod tests {
⋮----
async fn driver_spans_reach_otlp_collector_with_resource_identity() {
</file>

<file path="crates/openshell-driver-kubernetes/src/resource_admission.rs">
use openshell_core::resource_admission::ResourceAdmissionConfig;
use serde_json::Value;
⋮----
use tonic::Status;
⋮----
pub type Identities = BTreeMap<String, String>;
⋮----
enum Scope {
⋮----
struct Reference {
⋮----
fn resource_description(reference: &Reference, namespace: &str, cluster: bool) -> String {
⋮----
format!("{} '{}'", reference.kind, reference.name)
⋮----
format!("{} '{}/{}'", reference.kind, namespace, reference.name)
⋮----
fn contextualize(status: Status, resource: &str) -> Status {
Status::new(status.code(), format!("{resource}: {}", status.message()))
⋮----
fn metadata_lookup_error(error: kube::Error, resource: &str) -> Status {
⋮----
Status::failed_precondition(format!("{resource} does not exist"))
⋮----
kube::Error::Api(response) if response.code == 403 => Status::unavailable(format!(
⋮----
kube::Error::Api(response) if response.code == 401 => Status::unavailable(format!(
⋮----
kube::Error::Api(response) => Status::unavailable(format!(
⋮----
... (178 lines truncated)
</file>

<file path="crates/openshell-driver-kubernetes/src/sandbox_runtime.rs">
use std::collections::BTreeMap;
use std::path::Path;
⋮----
use k8s_openapi::ByteString;
⋮----
use k8s_openapi::apimachinery::pkg::apis::meta::v1::OwnerReference;
use k8s_openapi::apimachinery::pkg::util::intstr::IntOrString;
use kube::core::ObjectMeta;
⋮----
pub struct ClientTlsMaterial {
⋮----
pub enum SupervisorClientTls<'a> {
⋮----
/// A Secret in the sandbox namespace, mounted by name.
    Secret(&'a str),
⋮----
pub struct ProxyCaMaterial {
⋮----
pub fn generate_proxy_ca_material() -> Result<ProxyCaMaterial, String> {
let key = KeyPair::generate().map_err(|error| format!("generate proxy CA key: {error}"))?;
⋮----
.push(DnType::CommonName, "OpenShell Sandbox CA");
⋮----
.push(DnType::OrganizationName, "OpenShell");
params.key_usages = vec![KeyUsagePurpose::KeyCertSign, KeyUsagePurpose::CrlSign];
⋮----
.self_signed(&key)
.map_err(|error| format!("generate proxy CA certificate: {error}"))?;
Ok(ProxyCaMaterial {
certificate_pem: certificate.pem(),
... (504 lines truncated)
</file>

<file path="crates/openshell-driver-kubernetes/Cargo.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

[package]
name = "openshell-driver-kubernetes"
description = "Kubernetes compute driver for OpenShell"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true

[[bin]]
name = "openshell-driver-kubernetes"
path = "src/main.rs"

[dependencies]
openshell-core = { path = "../openshell-core", default-features = false }
openshell-isolation-interface = { path = "../openshell-isolation-interface" }
openshell-sandbox-backend = { path = "../openshell-sandbox-backend" }
openshell-otel = { path = "../openshell-otel" }
openshell-policy = { path = "../openshell-policy" }

opentelemetry = { workspace = true }
tokio = { workspace = true }
tonic = { workspace = true, features = ["transport"] }
prost = { workspace = true }
prost-types = { workspace = true }
futures = { workspace = true }
tokio-stream = { workspace = true }
... (28 lines truncated)
</file>

<file path="crates/openshell-driver-kubernetes/README.md">
# openshell-driver-kubernetes

Kubernetes-backed compute driver for OpenShell cluster deployments.

Caller driver config is disabled by default. External resource references need
administrator-controlled approval labels in every workspace mode, including
before restart and scheduling-gate release. GPU devices are temporarily exempt.
Image-pull Secrets are operator-selected gateway configuration rather than caller
attachments. Managed mode stages an immutable copy for each sandbox runtime
generation.
See [resource admission configuration](../../docs/how-it-works/gateways/configuration.mdx#external-resource-admission).

The driver uses the Kubernetes API to create, delete, fetch, and watch sandbox
custom resources. It runs in-process with the gateway server and supports three
workspace namespace modes via `workspace_mode`:

- **Shared** (default): All sandboxes render into a single static namespace.
  Resource names use `{workspace}--{name}` for collision avoidance.
- **Managed**: The driver auto-creates/deletes a K8s namespace per workspace
  (`openshell-{gateway_id}-{workspace_name}`), creates a ServiceAccount in each,
  and copies OpenShift SCC annotations from the gateway namespace when present.
- **Operator**: Workspace names map 1:1 to pre-provisioned namespaces discovered
  through exactly one source: either a label selector
  (`operator_namespace_label`) or a drop-in allowlist file
  (`operator_namespace_file`). Sandbox creation fails closed if the workspace
  namespace is not in the current allowlist. Workspace deletion only removes
  gateway state; it never deletes or otherwise accesses the operator-managed
  Kubernetes namespace.

When the gateway configures `[openshell.gateway.otlp]`, Kubernetes
... (251 lines truncated)
</file>

<file path="crates/openshell-driver-kubernetes-secrets/src/lib.rs">
use std::collections::BTreeMap;
⋮----
use k8s_openapi::api::core::v1::Secret;
use k8s_openapi::apimachinery::pkg::apis::meta::v1::ObjectMeta;
⋮----
use openshell_core::VERSION;
use openshell_core::proto::CredentialHandle;
⋮----
pub struct KubernetesSecretsCredentialDriver {
⋮----
pub struct CredentialDriverService {
⋮----
impl CredentialDriverService {
⋮----
pub fn new(driver: KubernetesSecretsCredentialDriver) -> Self {
⋮----
struct KubernetesSecretsDriverSettings {
⋮----
impl KubernetesSecretsDriverSettings {
fn resolve_handle(
⋮----
return Err(Status::permission_denied(format!(
⋮----
Ok(reference)
⋮----
struct KubernetesSecretsDriverConfig {
⋮----
struct KubernetesSecretReference {
⋮----
impl KubernetesSecretsCredentialDriver {
... (442 lines truncated)
</file>

<file path="crates/openshell-driver-kubernetes-secrets/src/main.rs">
use std::io;
⋮----
use std::pin::Pin;
⋮----
use clap::Parser;
use futures::Stream;
⋮----
use openshell_core::VERSION;
use openshell_core::proto::credentials::v1::credential_driver_server::CredentialDriverServer;
⋮----
use tracing::info;
use tracing_subscriber::EnvFilter;
⋮----
struct Args {
⋮----
async fn main() -> Result<()> {
⋮----
.with_env_filter(
EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(&args.log_level)),
⋮----
.init();
⋮----
let driver = KubernetesSecretsCredentialDriver::from_config(&driver_config(&args))
⋮----
.into_diagnostic()?;
⋮----
prepare_socket(&args.bind_socket)?;
let listener = UnixListener::bind(&args.bind_socket).into_diagnostic()?;
restrict_socket_permissions(&args.bind_socket)?;
⋮----
... (51 lines truncated)
</file>

<file path="crates/openshell-driver-kubernetes-secrets/Cargo.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

[package]
name = "openshell-driver-kubernetes-secrets"
description = "Kubernetes Secrets credential driver for OpenShell"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true

[[bin]]
name = "openshell-driver-kubernetes-secrets"
path = "src/main.rs"

[dependencies]
openshell-core = { path = "../openshell-core", default-features = false }

clap = { workspace = true }
futures = { workspace = true }
k8s-openapi = { workspace = true }
kube = { workspace = true }
miette = { workspace = true }
serde = { workspace = true }
sha2 = { workspace = true }
tokio = { workspace = true }
toml = { workspace = true }
tonic = { workspace = true }
tracing = { workspace = true }
... (5 lines truncated)
</file>

<file path="crates/openshell-driver-mxc/examples/e2e-policies/fs-empty.yaml">
version: 1
filesystem_policy:
  include_workdir: false
  read_only: []
  read_write: []
</file>

<file path="crates/openshell-driver-mxc/examples/e2e-policies/fs-readonly.yaml">
version: 1
filesystem_policy:
  include_workdir: false
  read_only:
    - "C:/work/openshell-mxc-e2e-ro-src"
  read_write:
    - "C:/work/openshell-mxc-e2e"
</file>

<file path="crates/openshell-driver-mxc/examples/e2e-policies/fs-rw.yaml">
version: 1
filesystem_policy:
  include_workdir: false
  read_only: []
  read_write:
    - "C:/work/openshell-mxc-e2e"
</file>

<file path="crates/openshell-driver-mxc/examples/e2e-policies/network-reject.yaml">
version: 1
filesystem_policy:
  include_workdir: false
  read_only: []
  read_write:
    - "C:/work/openshell-mxc-e2e"
network_policies:
  test_rule:
    name: test-network-reject
    endpoints:
      - host: api.example.com
        port: 443
        protocol: rest
        enforcement: enforce
        access: read-only
</file>

<file path="crates/openshell-driver-mxc/examples/demo.yaml">
version: 1
filesystem_policy:
  include_workdir: false
  read_only: []
  read_write:
    - "C:/work/openshell-mxc-demo"
</file>

<file path="crates/openshell-driver-mxc/examples/mxc-gateway.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

# MXC gateway runtime configuration.
#
# Commands, working directories, and environment variables are sandbox-scoped.
# Supply command and cwd through --driver-config-json when creating a sandbox,
# and environment variables through the standard sandbox --env option.

[openshell.drivers.mxc]
# Path to wxc-exec.exe. Required for live runs. Leave the default for mock-mode
# smoke tests (set OPENSHELL_MXC_MOCK_WXC=1 instead).
wxc_exec_path = "C:\\mxc\\wxc-exec.exe"

# process_container is the default because AppContainer enforces default-deny
# filesystem access. isolation_session is an explicit grant-only compatibility
# mode and does not deny access to paths omitted from the sandbox policy.
backend = "process_container"

# process_container only: request a Less-Privileged AppContainer.
# pc_least_privilege = false
# process_container only: AppContainer capabilities to grant.
# pc_capabilities = []

# isolation_session only. Never use "small" (known OS bug).
default_configuration_id = "composable"

# Enable --debug on wxc-exec invocations.
debug = false
</file>

<file path="crates/openshell-driver-mxc/examples/mxc-ocsf-audit.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

# MXC gateway config for the ETW -> OCSF audit-trail example.
#
# Goal: exercise the in-process ETW consumer (Plane A) end-to-end so that
# creating a sandbox produces a full OCSF audit trail — Application Lifecycle
# [6002], Device Config State Change [5019], Process Activity [1007] and
# Detection Finding [2004] — written to a durable JSONL log, just like the Linux
# OCSF pipeline.
#
# run-ocsf-audit.ps1 patches wxc_exec_path, backend, etw_audit and the
# egress-proxy switch into a disposable copy of this file. Workload command and
# cwd are sandbox-scoped and passed separately through --driver-config-json.

[openshell.drivers.mxc]
# Path to wxc-exec.exe on the box (patched by the run script; default is the
# location observed on the MXC test boxes).
wxc_exec_path = "C:\\mxc-kit\\bin\\wxc-exec.exe"

# One-shot AppContainer. This is the backend whose Sandboxing ETW the consumer
# captures. (isolation_session is "dark" — it emits no provider events.)
backend = "process_container"

default_configuration_id = "composable"

debug = false

# Turn ON the Plane-A ETW -> OCSF audit consumer. This is the core of the example.
etw_audit = true
... (11 lines truncated)
</file>

<file path="crates/openshell-driver-mxc/examples/ocsf-audit.yaml">
version: 1
filesystem_policy:
  include_workdir: false
  read_only: []
  read_write:
    - "C:/work/openshell-mxc-demo"
</file>

<file path="crates/openshell-driver-mxc/examples/probe-mxc-host.ps1">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# probe-mxc-host.ps1 - Operator/CI preflight for a prospective MXC host.
# This diagnostic is not invoked by the driver and does not mutate host state.
# It reports OS, wxc-exec, and backend availability so real tests can skip
# unsupported scenarios with an explicit reason.
#
# PowerShell 5.1-compatible (no && / || / ternary operators).
#
# Usage:
#   powershell -NoProfile -ExecutionPolicy Bypass -File .\probe-mxc-host.ps1
#   powershell -NoProfile -ExecutionPolicy Bypass -File .\probe-mxc-host.ps1 -OutFile caps.json
#
# The script is read-only except for a per-run temp directory. It never enables
# OS features or modifies system state.
#
# Exit codes:
#   0 - report emitted (even if backends are unavailable)
#   1 - unexpected error (should not happen on a healthy box)

[CmdletBinding()]
param(
    [string] $WxcExecPath = "C:\mxc\wxc-exec.exe",
    [string] $OutFile,
    # Emit the complete JSON report to stdout. Default output is a short
    # human-readable summary (the full report still goes to -OutFile if set).
    [switch] $Full
)

... (326 lines truncated)
</file>

<file path="crates/openshell-driver-mxc/examples/README-ocsf-audit.txt">
OpenShell MXC - ETW -> OCSF audit-trail example
===============================================

WHAT THIS PROVES / PRODUCES
  The full Windows OCSF audit path on this box:
    gateway -> MXC driver -> process_container sandbox
      -> the OS "Sandboxing" ETW provider fires as the sandbox is created
      -> the gateway's in-process consumer decodes each event, attributes it to
         an OpenShell sandbox_id, and maps it to OCSF
      -> events are written to a durable JSONL audit log AND printed as
         human-readable shorthand.

  The deliverable is the OCSF log: openshell-ocsf.<date>.log, one OCSF event
  object per line - the same schema and medium the Linux OpenShell pipeline
  produces (Windows is at functional parity).

  OCSF classes you will see:
    [6002] Application Lifecycle        - sandbox created
    [5019] Device Config State Change   - OS policy / hardening / proxy / console
    [1007] Process Activity             - in-sandbox process launch (+ executable identity)
    [2004] Detection Finding            - MXC setup activity errors (informational)

PREREQUISITES (on this test box)
  - wxc-exec.exe present (default expected: C:\mxc-kit\bin\wxc-exec.exe)
  - process_container backend live (it was for our earlier runs)
  - Run ELEVATED (Run as administrator) OR from an account in the
    'Performance Log Users' group. Opening the real-time ETW session needs this;
    without it the run fails fast with a clear message.

HOW TO RUN
... (51 lines truncated)
</file>

<file path="crates/openshell-driver-mxc/examples/run-mxc-e2e.ps1">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# run-mxc-e2e.ps1 - MXC e2e scenario runner.
#
# Runs a table of policy scenarios against the OpenShell MXC driver, emits
# per-scenario PASS/FAIL/SKIP(reason), prints a summary table, and exits non-zero
# only on FAIL.
#
# Every run collects its logs into a timestamped results-e2e-<stamp>\ folder and
# zips it (mirrors the sibling run-*.ps1 scripts). The bundle contains the console
# transcript, the per-scenario gateway stdout/stderr, the exact TOML rendered for
# each scenario, the policy fixture used, and a summary.txt with the verdict table.
#
# The gateway restarts per scenario to keep logs and the in-memory database
# isolated. Workload command/cwd are supplied per sandbox through
# --driver-config-json; they are never patched into gateway configuration.
#
# Scoring (why we do NOT gate on `sandbox create` exit code):
#   The ground truth is the on-disk artifact, so positive scenarios pass on
#   artifact PRESENT and deny scenarios pass on the denied write being ABSENT.
#   A CONTROL write proves the agent ran when the policy grants a writable path;
#   an empty policy instead requires explicit driver-launch evidence.
#
# PowerShell 5.1-compatible (no && / || / ternary operators). ASCII only.
#
# Usage:
#   powershell -NoProfile -ExecutionPolicy Bypass -File .\run-mxc-e2e.ps1 -WxcExecPath C:\mxc-kit\bin\wxc-exec.exe
#   .\run-mxc-e2e.ps1 -Mock                                  # wiring-only, no real backend
#   .\run-mxc-e2e.ps1 -Scenario fs-rw                        # single scenario
... (715 lines truncated)
</file>

<file path="crates/openshell-driver-mxc/examples/run-ocsf-audit.ps1">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# run-ocsf-audit.ps1 - gateway-driven ETW -> OCSF audit-trail example for OpenShell/MXC.
#
# Proves the FULL product path on the test box AND produces a durable OCSF log:
#   start gateway (etw_audit on, OCSF JSONL on) -> register CLI ->
#   create N sandboxes (each drives the OS "Sandboxing" ETW provider) ->
#   the in-process consumer decodes, attributes, and maps every event to OCSF ->
#   tear the sandboxes + gateway down -> collect the OCSF log + every artifact
#   into a results\ folder -> zip it.
#
# The deliverable is the OCSF audit log itself: openshell-ocsf.<date>.log, a
# durable JSONL file with one OCSF event object per line - the same schema and
# medium the Linux OpenShell pipeline produces.
#
# MUST RUN ELEVATED. Opening the real-time ETW session requires an elevated shell
# (Run as administrator) or an account in the 'Performance Log Users' group.
#
# Run from inside the package folder (gateway + cli + mxc-ocsf-audit.toml +
# ocsf-audit.yaml + this script all sit together):
#
#   powershell -NoProfile -ExecutionPolicy Bypass -File .\run-ocsf-audit.ps1 `
#     -WxcExecPath C:\mxc-kit\bin\wxc-exec.exe
#
# By default the per-sandbox egress proxy is ON so the full event set (including
# SandboxProxyConfigured) is produced. Pass -NoProxy to omit only that one event.
#
# The deliverable is the OCSF audit log (openshell-ocsf.<date>.log) inside the
# results-*.zip the script produces. Pass -ShareOut '\\server\share' to also copy
... (415 lines truncated)
</file>

<file path="crates/openshell-driver-mxc/src/policy_map/config.rs">
use openshell_core::proto::SandboxPolicy;
⋮----
pub fn default_enforcement_mode(
⋮----
if allowed_hosts.is_empty() {
⋮----
"processcontainer" | "process" => Some("both"),
⋮----
_ => Some("firewall"),
⋮----
pub fn filesystem_default_deny_message(containment: &str) -> String {
⋮----
.to_owned(),
⋮----
pub fn add_backend_specific_config(
⋮----
"processcontainer" | "process" if !allowed_hosts.is_empty() => {
config["processContainer"] = json!({ "capabilities": ["internetClient"] });
⋮----
config["lxc"] = json!({ "distribution": "alpine", "release": "3.20" });
⋮----
backend @ ("windows_sandbox" | "isolation_session" | "vm") if !allowed_hosts.is_empty() => {
add_loss(
⋮----
&format!("{backend} is not a v0 target for OpenShell network policy mapping."),
⋮----
"microvm" if !allowed_hosts.is_empty() => {
⋮----
pub fn add_backend_network_loss(
⋮----
... (10 lines truncated)
</file>

<file path="crates/openshell-driver-mxc/src/policy_map/loss.rs">
use std::collections::HashSet;
⋮----
use serde::Serialize;
⋮----
pub struct LossItem {
⋮----
pub fn add_loss(
⋮----
items.push(LossItem {
path: path.to_owned(),
severity: severity.to_owned(),
message: message.to_owned(),
openshell_feature: openshell_feature.to_owned(),
mxc_impact: mxc_impact.to_owned(),
⋮----
pub fn summarize_missing_mxc(items: &[LossItem]) -> Vec<String> {
⋮----
&& seen.insert(item.openshell_feature.as_str())
⋮----
summary.push(item.openshell_feature.clone());
</file>

<file path="crates/openshell-driver-mxc/src/policy_map/map.rs">
use std::net::SocketAddr;
⋮----
pub struct MxcMappingOptions {
⋮----
impl Default for MxcMappingOptions {
fn default() -> Self {
⋮----
mxc_version: DEFAULT_MXC_VERSION.to_owned(),
containment: DEFAULT_CONTAINMENT.to_owned(),
command: DEFAULT_COMMAND.to_owned(),
container_id: "openshell-policy".to_owned(),
⋮----
pub struct MxcMappingResult {
⋮----
pub struct SplitPolicyResult {
⋮----
pub fn map_to_mxc(policy: &SandboxPolicy, opts: &MxcMappingOptions) -> MxcMappingResult {
⋮----
let config = build_mxc_config(policy, opts, &mut loss);
⋮----
pub fn split_policy(policy: &SandboxPolicy, opts: &MxcMappingOptions) -> Option<SplitPolicyResult> {
⋮----
let mxc_config = build_split_mxc_config(policy, opts, proxy_addr, &mut loss);
⋮----
network_policies: policy.network_policies.clone(),
network_middlewares: policy.network_middlewares.clone(),
⋮----
Some(SplitPolicyResult {
⋮----
fn build_split_mxc_config(
... (179 lines truncated)
</file>

<file path="crates/openshell-driver-mxc/src/policy_map/mod.rs">
mod config;
mod loss;
mod map;
mod report;
</file>

<file path="crates/openshell-driver-mxc/src/policy_map/report.rs">
pub fn build_loss_report(
⋮----
let count = |severity: &str| items.iter().filter(|i| i.severity == severity).count();
⋮----
json!({
⋮----
pub fn render_readme(source_policy: &str, report: &Value, config: &Value) -> String {
let container_id = config["containerId"].as_str().unwrap_or("");
let containment = config["containment"].as_str().unwrap_or("");
⋮----
.as_bool()
.unwrap_or(false);
⋮----
.as_array()
.map(|a| a.iter().filter_map(Value::as_str).collect())
.unwrap_or_default();
if parts.is_empty() {
"(none)".to_owned()
⋮----
parts.join(", ")
⋮----
let allowed = join_strs(&config["network"]["allowedHosts"]);
let rw = join_strs(&config["filesystem"]["readwritePaths"]);
let ro = join_strs(&config["filesystem"]["readonlyPaths"]);
⋮----
let mut lines: Vec<String> = vec![
⋮----
.map(|a| {
a.iter()
.filter(|item| matches!(item["severity"].as_str(), Some("error" | "warning")))
... (23 lines truncated)
</file>

<file path="crates/openshell-driver-mxc/src/driver.rs">
use futures::Stream;
⋮----
use openshell_core::proto::SandboxPolicy;
⋮----
use openshell_core::proto_struct::struct_to_json_value;
⋮----
use std::collections::HashMap;
use std::net::SocketAddr;
use std::path::PathBuf;
use std::pin::Pin;
use std::sync::Arc;
⋮----
use tokio::task::JoinHandle;
use tokio_stream::wrappers::ReceiverStream;
⋮----
const DRIVER_VERSION: &str = env!("CARGO_PKG_VERSION");
⋮----
pub enum MxcBackend {
⋮----
pub struct MxcComputeConfig {
⋮----
impl Default for MxcComputeConfig {
fn default() -> Self {
⋮----
wxc_exec_path: "wxc-exec.exe".into(),
⋮----
default_configuration_id: crate::mxc::DEFAULT_CONFIGURATION_ID.into(),
⋮----
struct MxcSandboxConfig {
⋮----
... (788 lines truncated)
</file>

<file path="crates/openshell-driver-mxc/src/etw_consumer.rs">
use std::ffi::c_void;
⋮----
use std::sync::mpsc;
⋮----
use std::thread::JoinHandle;
⋮----
struct RawEtwEvent {
⋮----
unsafe impl Send for RawEtwEvent {}
⋮----
pub(crate) struct DecodedEtwEvent {
⋮----
impl DecodedEtwEvent {
⋮----
pub fn get(&self, key: &str) -> Option<&str> {
⋮----
.iter()
.find(|(k, _)| k == key)
.map(|(_, v)| v.as_str())
⋮----
pub fn get_unquoted(&self, key: &str) -> Option<String> {
self.get(key)
.map(|v| v.trim_matches('"').to_string())
.filter(|s| !s.is_empty())
⋮----
pub fn identity(&self) -> Option<String> {
self.get_unquoted("identity")
⋮----
pub fn cv_base(&self) -> Option<String> {
self.get_unquoted("__TlgCV__")
... (976 lines truncated)
</file>

<file path="crates/openshell-driver-mxc/src/grpc.rs">
use crate::driver::MxcComputeBackend;
⋮----
use std::pin::Pin;
⋮----
pub struct ComputeDriverService {
⋮----
impl ComputeDriverService {
pub fn new(backend: MxcComputeBackend) -> Self {
⋮----
impl ComputeDriver for ComputeDriverService {
async fn get_capabilities(
⋮----
let capabilities = self.backend.capabilities();
⋮----
capabilities.extension.as_ref(),
request.into_inner().gateway,
⋮----
.map_err(|error| Status::failed_precondition(error.to_string()))?;
Ok(Response::new(capabilities))
⋮----
async fn authenticate_sandbox(
⋮----
Err(Status::unimplemented(
⋮----
async fn validate_sandbox_create(
⋮----
let request = request.into_inner();
⋮----
.ok_or_else(|| Status::invalid_argument("sandbox is required"))?;
self.backend.validate_sandbox_create(&sandbox)?;
... (90 lines truncated)
</file>

<file path="crates/openshell-driver-mxc/src/lib.rs">
mod driver;
⋮----
mod grpc;
⋮----
mod mxc;
⋮----
mod policy;
⋮----
mod policy_map;
⋮----
mod etw_consumer;
⋮----
pub use grpc::ComputeDriverService;
</file>

<file path="crates/openshell-driver-mxc/src/mxc.rs">
use std::collections::HashMap;
use std::net::SocketAddr;
use std::path::PathBuf;
⋮----
use thiserror::Error;
use tokio::process::Command;
use tracing::debug;
⋮----
fn mock_enabled() -> bool {
std::env::var(MOCK_ENV_VAR).is_ok_and(|value| value == "1")
⋮----
fn mock_normalize(s: &str) -> String {
s.replace('/', "\\").to_lowercase()
⋮----
/// Per-process mock state: `iso:` sandbox id → granted read-write paths
/// (normalized). Populated by the mock provision, consumed by the mock exec to
⋮----
/// (normalized). Populated by the mock provision, consumed by the mock exec to
/// decide whether the agent's write target is in-policy.
⋮----
/// decide whether the agent's write target is in-policy.
fn mock_grants() -> &'static Mutex<HashMap<String, Vec<String>>> {
⋮----
fn mock_grants() -> &'static Mutex<HashMap<String, Vec<String>>> {
⋮----
GRANTS.get_or_init(|| Mutex::new(HashMap::new()))
⋮----
// ── Request types ─────────────────────────────────────────────────────────────
⋮----
/// Filesystem shares for the sandbox.
... (329 lines truncated)
</file>

<file path="crates/openshell-driver-mxc/src/policy.rs">
use std::net::SocketAddr;
⋮----
use openshell_core::proto::SandboxPolicy;
use thiserror::Error;
⋮----
pub struct MappedConfig {
⋮----
pub struct MapCtx {
⋮----
pub struct LossItem {
⋮----
pub enum MapError {
⋮----
fn format_loss(items: &[LossItem]) -> String {
⋮----
.iter()
.map(|i| format!("{}: {}", i.rule_kind, i.detail))
⋮----
.join("; ")
⋮----
pub trait PolicyMapper: Send + Sync {
⋮----
fn normalize_path(p: &str) -> String {
p.replace('/', "\\")
⋮----
// ── Embedded mapper (primary impl) ──────────────────────────────────────────
⋮----
/// Primary `PolicyMapper`: calls the embedded `policy_map` module (the source of
/// truth) directly on the typed `SandboxPolicy` proto.
⋮----
... (133 lines truncated)
</file>

<file path="crates/openshell-driver-mxc/Cargo.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

[package]
name = "openshell-driver-mxc"
description = "MXC (Windows isolation session) compute driver for OpenShell"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true

[lib]
name = "openshell_driver_mxc"

[dependencies]
openshell-core = { path = "../openshell-core", default-features = false }
openshell-policy = { path = "../openshell-policy" }
# OCSF builders + emit target used by the Windows ETW audit consumer. OS-agnostic
# crate (no windows deps), so safe to depend on from all targets; only the
# windows-gated `etw_consumer` module actually uses it.
openshell-ocsf = { path = "../openshell-ocsf" }
tokio = { workspace = true }
tonic = { workspace = true }
futures = { workspace = true }
tokio-stream = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
base64 = { workspace = true }
tracing = { workspace = true }
... (26 lines truncated)
</file>

<file path="crates/openshell-driver-mxc/README.md">
# openshell-driver-mxc

OpenShell compute driver backed by **Microsoft MXC** (`wxc-exec`) on Windows.

## Design

Caller driver config is disabled by default, so command-based MXC workflows
need explicit administrator opt-in. Host filesystem grants have no trusted
label resolver and are rejected while resource admission is enabled.
See [resource admission configuration](../../docs/how-it-works/gateways/configuration.mdx#external-resource-admission)
for the independent controls and the security consequences of opting out.

This driver implements the gateway's ordinary in-process `ComputeDriver`
contract and is linked into `openshell-gateway`. It sets
`driver_reports_runtime_readiness`, so the gateway accepts driver-reported
readiness without a supervisor session. The canonical create-time
`SandboxPolicy` is carried by `DriverSandboxSpec.policy`. `process_container` launches a one-shot
AppContainer and is the default. The opt-in `isolation_session` backend uses the
state-aware `provision` → `start` → `exec` → `stop` → `deprovision` lifecycle.
The driver launches and monitors the configured workload itself and self-reports
readiness; there is no in-sandbox supervisor or `ConnectSupervisor` relay.

## Capability Matrix

| Capability | MXC driver | Closing it requires |
|---|---|---|
| Filesystem policy (read-write / read-only grants) | ✅ provision-time AppContainer shares | — |
| Governed egress (CONNECT proxy + OPA + L7) | Available behind `egress_proxy` on `process_container`; the driver starts a per-sandbox host CONNECT proxy, generates HTTPS MITM trust material, and injects the CA bundle into the sandbox process env | Gateway event-bus wiring follow-on |
| Network policy | Split into MXC `network.proxy` + trimmed OpenShell policy on `process_container`; `isolation_session` still rejects network config | MXC feedback item M1 for persistent sessions |
| Network middleware | ❌ rejected before launch because the MXC host proxy does not receive the gateway middleware registry | Gateway middleware-registry injection |
... (171 lines truncated)
</file>

<file path="crates/openshell-driver-podman/src/client.rs">
use hyper::Request;
use hyper::body::Bytes;
use hyper_util::rt::TokioIo;
use serde::de::DeserializeOwned;
use serde_json::Value;
use std::collections::HashMap;
use std::path::PathBuf;
use std::pin::Pin;
use std::time::Duration;
use tokio::net::UnixStream;
use tokio::sync::mpsc;
use tracing::debug;
⋮----
pub enum PodmanApiError {
⋮----
pub fn validate_name(name: &str) -> Result<(), PodmanApiError> {
⋮----
if name.is_empty() {
return Err(PodmanApiError::InvalidInput(
"name must not be empty".to_string(),
⋮----
if name.len() > MAX_NAME_LEN {
return Err(PodmanApiError::InvalidInput(format!(
⋮----
let bytes = name.as_bytes();
if !bytes[0].is_ascii_alphanumeric() {
⋮----
.iter()
.all(|&b| b.is_ascii_alphanumeric() || b == b'.' || b == b'_' || b == b'-')
⋮----
... (559 lines truncated)
</file>

<file path="crates/openshell-driver-podman/src/container.rs">
use crate::config::PodmanComputeConfig;
use openshell_core::ComputeDriverError;
use openshell_core::driver_mounts::SelinuxLabel;
⋮----
use openshell_core::proto_struct::deserialize_optional_non_empty_string_list;
⋮----
use serde::Serialize;
use serde_json::Value;
⋮----
use std::path::Path;
⋮----
fn is_selinux_enabled() -> bool {
Path::new("/sys/fs/selinux").is_dir()
⋮----
pub struct PodmanSandboxDriverConfig {
⋮----
impl PodmanSandboxDriverConfig {
pub(crate) fn admit_mount_types(
⋮----
if matches!(
⋮----
.reject_unlabelable("host bind or image mount")
.map_err(|error| ComputeDriverError::Precondition(error.message().into()))?;
⋮----
Ok(())
⋮----
pub fn from_sandbox(sandbox: &DriverSandbox) -> Result<Self, ComputeDriverError> {
⋮----
.as_ref()
.and_then(|spec| spec.template.as_ref())
... (1235 lines truncated)
</file>

<file path="crates/openshell-driver-podman/src/driver.rs">
use openshell_core::ComputeDriverError;
use openshell_core::config::CDI_GPU_DEVICE_ALL;
⋮----
use std::collections::HashMap;
⋮----
use std::sync::Arc;
use std::time::Duration;
⋮----
enum PodmanEndpointEnvironment {
⋮----
impl PodmanEndpointEnvironment {
const fn current() -> Self {
if cfg!(target_os = "linux") {
⋮----
const fn gateway_host(self) -> &'static str {
⋮----
fn select_grpc_endpoint(
⋮----
if !config.grpc_endpoint.is_empty() {
return config.grpc_endpoint.clone();
⋮----
let scheme = if config.tls_enabled() {
⋮----
format!(
⋮----
fn decode_launch_authentication(
⋮----
.map_err(|error| {
ComputeDriverError::Precondition(format!(
⋮----
... (1511 lines truncated)
</file>

<file path="crates/openshell-driver-podman/src/grpc.rs">
use std::pin::Pin;
⋮----
use crate::PodmanComputeDriver;
⋮----
type ComputeDriverWatchStream =
⋮----
type TracedWatchStream = openshell_otel::TracedGrpcStream<ComputeDriverWatchStream>;
⋮----
pub struct ComputeDriverService {
⋮----
impl ComputeDriverService {
⋮----
pub fn new(driver: PodmanComputeDriver) -> Self {
⋮----
pub fn new_in_process(driver: PodmanComputeDriver) -> Self {
⋮----
impl ComputeDriver for ComputeDriverService {
async fn authenticate_sandbox(
⋮----
.trace(openshell_otel::rpc::AUTHENTICATE_SANDBOX, async {
Err(Status::unimplemented(
⋮----
async fn get_capabilities(
⋮----
.trace(openshell_otel::rpc::GET_CAPABILITIES, async {
let capabilities = self.driver.capabilities().map_err(Status::from)?;
⋮----
capabilities.extension.as_ref(),
request.into_inner().gateway,
⋮----
... (289 lines truncated)
</file>

<file path="crates/openshell-driver-podman/src/isolation.rs">
use std::io::Read;
use std::path::PathBuf;
⋮----
use openshell_core::ComputeDriverError;
use openshell_core::proto::compute::v1::DriverSandbox;
⋮----
use openshell_sandbox_backend::ALLOW_EXTRA_SUPPLEMENTARY_GROUPS_RESOURCE_CLAIM;
⋮----
struct PodmanOuterFenceEvidence<'a> {
⋮----
fn project(&self, generation: &str) -> Result<OuterFenceGuarantees, ComputeDriverError> {
if self.container_id.is_empty() {
return Err(invalid("Podman outer fence evidence is incomplete"));
⋮----
// With no container network namespace attachment, workload egress
// remains denied both after revocation and if the supervisor exits.
established.extend([
⋮----
if self.unexpected_networks.is_empty() {
established.push(OuterFenceGuarantee::NoUnmanagedEgressPath);
⋮----
let encoded = serde_json::to_vec(self).map_err(invalid)?;
⋮----
.map_err(invalid)?;
projection.validate(generation).map_err(invalid)?;
Ok(projection)
⋮----
pub fn supervisor_name(id: &str) -> String {
format!("openshell-supervisor-{id}")
⋮----
... (290 lines truncated)
</file>

<file path="crates/openshell-driver-podman/src/lib.rs">
pub(crate) mod client;
pub mod config;
pub(crate) mod container;
pub mod driver;
pub mod grpc;
mod isolation;
pub mod otel_tracing;
mod socket_discovery;
⋮----
pub(crate) mod test_utils;
pub(crate) mod watcher;
⋮----
pub use config::PodmanComputeConfig;
pub use driver::PodmanComputeDriver;
pub use grpc::ComputeDriverService;
</file>

<file path="crates/openshell-driver-podman/src/main.rs">
use clap::Parser;
⋮----
use std::future::Future;
use std::net::SocketAddr;
⋮----
use std::path::PathBuf;
use tracing::info;
⋮----
use openshell_core::proto::compute::v1::compute_driver_server::ComputeDriverServer;
⋮----
struct Args {
⋮----
async fn main() -> Result<()> {
⋮----
endpoint: args.otlp_endpoint.as_deref(),
gateway_name: args.gateway_name.as_deref(),
⋮----
resource_admission: args.admission_config_json.resource_admission.clone(),
⋮----
default_image: args.sandbox_image.unwrap_or_default(),
⋮----
grpc_endpoint: args.grpc_endpoint.unwrap_or_default(),
⋮----
.unwrap_or_else(PodmanComputeConfig::default_host_gateway_ip),
⋮----
.unwrap_or_else(openshell_core::config::default_sandbox_runtime_image),
⋮----
.unwrap_or_else(openshell_core::config::default_supervisor_image),
⋮----
.into_diagnostic()?;
... (55 lines truncated)
</file>

<file path="crates/openshell-driver-podman/src/otel_tracing.rs">
mod tests {
⋮----
async fn driver_spans_reach_otlp_collector_with_resource_identity() {
</file>

<file path="crates/openshell-driver-podman/src/socket_discovery.rs">
use std::path::PathBuf;
⋮----
pub fn detect_socket() -> Option<PathBuf> {
openshell_core::local_api_socket::first_responsive_socket(&socket_candidates(), |response| {
⋮----
.or_else(discover_socket)
⋮----
fn socket_candidates() -> Vec<PathBuf> {
⋮----
if let Some(path) = env_var_nonempty("OPENSHELL_PODMAN_SOCKET") {
candidates.push(PathBuf::from(path));
⋮----
candidates.push(PathBuf::from(runtime_dir).join("podman/podman.sock"));
⋮----
candidates.push(PathBuf::from(format!(
⋮----
.push(PathBuf::from(home).join(".local/share/containers/podman/machine/podman.sock"));
⋮----
fn discover_socket() -> Option<PathBuf> {
let stdout = run_podman_capture(&["info", "--format", "json"])?;
⋮----
if env_var_nonempty("CONTAINER_CONNECTION").is_none()
&& let Some(path) = env_var_nonempty("CONTAINER_HOST")
.as_deref()
.and_then(unix_url_socket_path)
⋮----
return Some(path);
⋮----
let info: serde_json::Value = serde_json::from_slice(&stdout).ok()?;
if !info["host"]["serviceIsRemote"].as_bool().unwrap_or(false) {
... (156 lines truncated)
</file>

<file path="crates/openshell-driver-podman/src/test_utils.rs">
use hyper::StatusCode;
use hyper::body::Bytes;
use hyper::server::conn::http1;
use hyper::service::service_fn;
use hyper_util::rt::TokioIo;
use std::collections::VecDeque;
use std::convert::Infallible;
use std::path::PathBuf;
⋮----
use tokio::net::UnixListener;
⋮----
pub struct StubResponse {
⋮----
impl StubResponse {
pub fn new(status: StatusCode, body: impl Into<Bytes>) -> Self {
⋮----
body: body.into(),
⋮----
pub fn with_delay(mut self, delay: Duration) -> Self {
⋮----
pub fn with_archive_members(mut self, members: &[&str]) -> Self {
self.archive_members = Some(members.iter().map(PathBuf::from).collect());
⋮----
pub fn unique_socket_path(test_name: &str) -> PathBuf {
⋮----
.duration_since(UNIX_EPOCH)
.expect("clock should be after unix epoch")
.as_nanos();
PathBuf::from(format!(
⋮----
... (47 lines truncated)
</file>

<file path="crates/openshell-driver-podman/src/watcher.rs">
use futures::Stream;
use openshell_core::ComputeDriverError;
⋮----
use std::collections::HashMap;
use std::pin::Pin;
⋮----
use tokio::sync::mpsc;
use tokio_stream::wrappers::ReceiverStream;
⋮----
pub type WatchStream =
⋮----
pub struct LifecycleEventFences {
⋮----
impl LifecycleEventFences {
pub fn record_previous_exit(&self, sandbox_id: &str, finished_at: Option<&str>) {
⋮----
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
match finished_at.filter(|finished_at| !finished_at.is_empty()) {
⋮----
fences.insert(sandbox_id.to_string(), finished_at.to_string());
⋮----
fences.remove(sandbox_id);
⋮----
pub fn remove(&self, sandbox_id: &str) {
⋮----
.unwrap_or_else(std::sync::PoisonError::into_inner)
.remove(sandbox_id);
⋮----
fn matches_previous_exit(
... (361 lines truncated)
</file>

<file path="crates/openshell-driver-podman/Cargo.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

[package]
name = "openshell-driver-podman"
description = "Podman compute driver for OpenShell"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true

[[bin]]
name = "openshell-driver-podman"
path = "src/main.rs"

[dependencies]
openshell-core = { path = "../openshell-core", default-features = false, features = ["driver-extraction"] }
openshell-otel = { path = "../openshell-otel" }
openshell-isolation-interface = { path = "../openshell-isolation-interface" }
openshell-sandbox-backend = { path = "../openshell-sandbox-backend" }
tar = "0.4"
uuid = { workspace = true }

tokio = { workspace = true }
tonic = { workspace = true, features = ["transport"] }
futures = { workspace = true }
tokio-stream = { workspace = true }
hyper = { workspace = true }
hyper-util = { workspace = true }
... (29 lines truncated)
</file>

<file path="crates/openshell-driver-podman/NETWORKING.md">
# Podman Networking

Only the external supervisor has external network connectivity. The workload
container uses `network=none`; its loopback DNS relay and TCP socket mediation
reach the supervisor through a protected Unix socket, not a veth or proxy
environment variable.

```text
workload container                       supervisor container
agent -> sandbox -- private UDS / gRPC -> policy proxy -> host network -> destination
                                            |
                                            +-- authenticated gateway session
```

## Outer network fence

The driver creates the workload without networks, host aliases, published
ports, or added capabilities. It checks the Podman inspect response before
launch and restart. The sandbox installs seccomp mediation and Landlock before
executing the agent. It does not create network namespaces, configure nftables,
or require `CAP_NET_ADMIN`.

TCP opens, TCP byte streams, DNS requests/replies, and lifecycle operations
share the authenticated gRPC channel. DNS is resolved and authorized by the
supervisor. General UDP is unsupported.

The driver mounts a read-only, driver-owned `/etc/resolv.conf` into the
workload with `nameserver 127.0.0.53`. This prevents the disconnected Podman
network namespace from replacing the policy-DNS relay with a runtime resolver.
The supervisor answers `host.openshell.internal` with a trusted concrete
... (37 lines truncated)
</file>

<file path="crates/openshell-driver-podman/README.md">
# openshell-driver-podman

The Podman compute driver runs inside the gateway and uses the native libpod
REST API over a Unix socket. Each sandbox has two independent containers:

- `openshell-sandbox` owns the agent process in the workload container.
- `openshell-supervisor` evaluates policy, holds gateway credentials, and
  proxies approved egress in a separate companion container.

The driver provisions placement, identity, credentials, transport, and lifecycle.
The shared isolation interface supplies exec, attach, signal, terminate, binary
identity, DNS, TCP, and loopback-forwarding semantics.

## Runtime posture

Caller driver config is disabled by default. Existing volumes require
administrator-controlled approval labels; bind and supplemental image mounts
are denied under enforcement. Private-volume names alone do not prove
ownership. GPU devices are temporarily exempt. Admission runs before launch,
restart, and periodically for running workloads.
See [resource admission configuration](../../docs/how-it-works/gateways/configuration.mdx#external-resource-admission).

| Property | Workload | Supervisor |
|---|---|---|
| UID/GID | Pinned non-root workload identity | Same mapped identity |
| Capabilities | Drop all; add none | Drop all; add none |
| Seccomp | Runtime default plus sandbox-installed filters | Runtime default |
| Network | `none`; loopback only | Podman host network |
| Gateway JWT and upstream credentials | Never mounted | Podman secrets |
| User volumes and CDI devices | Workload only | Never mounted |
... (102 lines truncated)
</file>

<file path="crates/openshell-driver-vault/src/lib.rs">
use std::sync::Arc;
⋮----
use openshell_core::VERSION;
use openshell_core::proto::CredentialHandle;
⋮----
pub struct VaultCredentialDriver {
⋮----
struct CachedVaultToken {
⋮----
pub struct CredentialDriverService {
⋮----
impl CredentialDriverService {
⋮----
pub fn new(driver: VaultCredentialDriver) -> Self {
⋮----
struct VaultDriverSettings {
⋮----
enum VaultAuthSettings {
⋮----
enum KvVersion {
⋮----
struct VaultDriverConfig {
⋮----
struct VaultSecretReference {
⋮----
struct KubernetesLoginRequest<'a> {
⋮----
struct KubernetesLoginResponse {
⋮----
struct KubernetesLoginAuth {
... (730 lines truncated)
</file>

<file path="crates/openshell-driver-vault/src/main.rs">
use std::io;
⋮----
use std::pin::Pin;
⋮----
use clap::Parser;
use futures::Stream;
⋮----
use openshell_core::VERSION;
use openshell_core::proto::credentials::v1::credential_driver_server::CredentialDriverServer;
⋮----
use tracing::info;
use tracing_subscriber::EnvFilter;
⋮----
struct Args {
⋮----
async fn main() -> Result<()> {
⋮----
.with_env_filter(
EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(&args.log_level)),
⋮----
.init();
⋮----
let driver = VaultCredentialDriver::from_config(&driver_config(&args)).into_diagnostic()?;
⋮----
prepare_socket(&args.bind_socket)?;
let listener = UnixListener::bind(&args.bind_socket).into_diagnostic()?;
restrict_socket_permissions(&args.bind_socket)?;
⋮----
info!(socket = %args.bind_socket.display(), "Starting Vault credential driver");
⋮----
... (73 lines truncated)
</file>

<file path="crates/openshell-driver-vault/Cargo.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

[package]
name = "openshell-driver-vault"
description = "Vault credential driver for OpenShell"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true

[[bin]]
name = "openshell-driver-vault"
path = "src/main.rs"

[dependencies]
openshell-core = { path = "../openshell-core", default-features = false }

clap = { workspace = true }
futures = { workspace = true }
miette = { workspace = true }
reqwest = { workspace = true }
rustls = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
sha2 = { workspace = true }
tokio = { workspace = true }
toml = { workspace = true }
tonic = { workspace = true }
... (13 lines truncated)
</file>

<file path="crates/openshell-driver-vm/runtime/kernel/openshell.kconfig">
# Custom kernel config fragment for libkrunfw (OpenShell VM)
#
# This fragment is applied on top of libkrunfw's base kernel config. VM
# sandboxes have no virtual NIC; the base loopback, TCP/UDP, Unix-socket,
# route-netlink, and vsock support is enough for the capability-free sandbox.
#
# Apply with: scripts/merge-kconfig.sh <base_config> <this_file>
#
# See also: check-vm-capabilities.sh for runtime verification.

# Root disk transport and filesystem.
CONFIG_BLOCK=y
CONFIG_BLK_DEV=y
CONFIG_VIRTIO_BLK=y
CONFIG_EXT4_FS=y
CONFIG_EXT4_USE_FOR_EXT2=y

# Cgroups used for process supervision and resource limits.
CONFIG_CGROUPS=y
CONFIG_CGROUP_DEVICE=y
CONFIG_CGROUP_CPUACCT=y
CONFIG_CGROUP_PIDS=y
CONFIG_MEMCG=y

# Disable the kernel headers archive to avoid cpio issues in CI.
# CONFIG_IKHEADERS is not set

# POSIX message queues used by OCI workloads.
CONFIG_POSIX_MQUEUE=y
CONFIG_POSIX_MQUEUE_SYSCTL=y
... (16 lines truncated)
</file>

<file path="crates/openshell-driver-vm/runtime/pins.env">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

# Pinned dependency versions for the openshell-driver-vm runtime.
#
# This file is sourced by VM runtime packaging scripts. It centralises version
# pins so that builds are reproducible and auditable.
#
# Environment variables override these defaults — CI and local dev workflows
# can still set the runtime dependency versions below.
#
# To update a dependency:
#   1. Change the version/digest below.
#   2. Run the relevant build script to verify.
#   3. Commit pins.env alongside any script changes.

# SERVER_IMAGE is intentionally NOT pinned here — it changes frequently
# during local development. Override via IMAGE_REPO_BASE and IMAGE_TAG
# environment variables (defaults: openshell/gateway:dev).

# ── umoci (guest OCI unpacker) ───────────────────────────────────────
# Repo: https://github.com/opencontainers/umoci
UMOCI_VERSION="${UMOCI_VERSION:-v0.6.0}"

# ── libkrunfw upstream (commit-pinned) ────────────────────────────────
# Repo: https://github.com/libkrun/libkrunfw
# Pinned: v5.6.1 (Linux 6.12.109, 2026-09-16)
LIBKRUNFW_REF="${LIBKRUNFW_REF:-617938cf2ae9a3a0e5696d23a5d6252cd7a1ef4f}"

# ── libkrun upstream (commit-pinned) ─────────────────────────────────
... (4 lines truncated)
</file>

<file path="crates/openshell-driver-vm/runtime/README.md">
# VM Driver Runtime

> Status: Experimental. VM support is under active development and may change.

This directory owns the pinned runtime inputs for `openshell-driver-vm`:

```text
runtime/
  pins.env
  kernel/
    openshell.kconfig
```

`openshell-driver-vm` embeds libkrun, libkrunfw, umoci for guest-side OCI image
unpacking, and the portable capability-free `openshell-sandbox` role.
VMs do not attach a guest NIC. The boundary carries control, mediated network,
and DNS streams over the authenticated vsock channel.

## Why

The stock `libkrunfw` kernel does not include every cgroup, seccomp, and
Landlock feature the sandbox needs inside each microVM.
`kernel/openshell.kconfig` extends the libkrunfw kernel so VM sandboxes retain
guest-local process, network-syscall, and filesystem enforcement while the
supervisor runs on the host.

## Build Scripts

| Script | Platform | Purpose |
|---|---|---|
... (48 lines truncated)
</file>

<file path="crates/openshell-driver-vm/scripts/openshell-vm-sandbox-init.sh">
set -euo pipefail
unset KRUN_INIT_PID1
BOOT_START=$(date +%s%3N 2>/dev/null || date +%s)
SANDBOX_OWNER_NORMALIZED_MARKER="/opt/openshell/.sandbox-owner-normalized"
GPU_ENABLED="${GPU_ENABLED:-false}"
ts() {
    local now
    now=$(date +%s%3N 2>/dev/null || date +%s)
    local elapsed=$((now - BOOT_START))
    printf "[%d.%03ds] %s\n" $((elapsed / 1000)) $((elapsed % 1000)) "$*"
}
mount_initial_fs() {
    mount -t proc proc /proc 2>/dev/null || true
    mount -t sysfs sysfs /sys 2>/dev/null || true
    mount -t tmpfs tmpfs /tmp 2>/dev/null || true
    mount -t tmpfs tmpfs /run 2>/dev/null || true
    mount -t devtmpfs devtmpfs /dev 2>/dev/null || true
}
bind_mount_into_newroot() {
    local source="$1"
    local target="/newroot${source}"
    mkdir -p "$target" 2>/dev/null || true
    mount --rbind "$source" "$target" 2>/dev/null \
        || mount --bind "$source" "$target" 2>/dev/null \
        || true
}
root_path() {
    local path="$1"
    printf '%s%s\n' "${ROOT_PREFIX:-}" "$path"
}
... (486 lines truncated)
</file>

<file path="crates/openshell-driver-vm/src/extensions/mod.rs">

</file>

<file path="crates/openshell-driver-vm/src/isolation/mod.rs">
use openshell_sandbox_backend::GPU_RESOURCE_CLAIM;
⋮----
use serde::Serialize;
⋮----
struct VmOuterFenceEvidence<'a> {
⋮----
fn project(&self) -> Result<OuterFenceGuarantees, BackendError> {
if self.generation.is_empty() {
return Err(BackendError::Descriptor(
"VM outer fence evidence is incomplete".to_string(),
⋮----
let established = (self.network_device_count == 0).then_some([
⋮----
let encoded = serde_json::to_vec(self).map_err(|error| {
BackendError::Descriptor(format!("encode VM outer fence evidence: {error}"))
⋮----
established.into_iter().flatten(),
⋮----
projection.validate(self.generation)?;
Ok(projection)
⋮----
pub struct VmBoundarySpec {
⋮----
pub struct VmBoundaryProvisioning {
⋮----
impl VmBoundarySpec {
⋮----
pub fn provision(self) -> Result<VmBoundaryProvisioning, BackendError> {
⋮----
"vm-config".to_string(),
... (51 lines truncated)
</file>

<file path="crates/openshell-driver-vm/src/embedded_runtime.rs">
use std::fs;
⋮----
mod resources {
pub const LIBKRUN: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/libkrun.dylib.zst"));
pub const LIBKRUNFW: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/libkrunfw.5.dylib.zst"));
⋮----
pub const LIBKRUN: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/libkrun.so.zst"));
pub const LIBKRUNFW: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/libkrunfw.so.5.zst"));
⋮----
const VERSION: &str = env!("CARGO_PKG_VERSION");
⋮----
pub fn ensure_runtime_extracted() -> Result<PathBuf, String> {
if resources::LIBKRUN.is_empty() {
return Err(
⋮----
.to_string(),
⋮----
let cache_dir = runtime_cache_dir()?;
let version_marker = cache_dir.join(".version");
let cache_key = runtime_cache_key();
⋮----
if version_marker.exists()
⋮----
&& cached_key.trim() == cache_key
&& validate_runtime_dir(&cache_dir).is_ok()
⋮----
return Ok(cache_dir);
⋮----
cleanup_old_versions(&cache_dir)?;
⋮----
... (74 lines truncated)
</file>

<file path="crates/openshell-driver-vm/src/ffi.rs">
use std::sync::OnceLock;
⋮----
use libc::c_char;
use libloading::Library;
⋮----
use crate::runtime::validate_runtime_dir;
⋮----
type KrunInitLog =
⋮----
type KrunCreateCtx = unsafe extern "C" fn() -> i32;
type KrunFreeCtx = unsafe extern "C" fn(ctx_id: u32) -> i32;
type KrunSetVmConfig = unsafe extern "C" fn(ctx_id: u32, num_vcpus: u8, ram_mib: u32) -> i32;
type KrunAddDisk = unsafe extern "C" fn(
⋮----
type KrunSetRootDiskRemount = unsafe extern "C" fn(
⋮----
type KrunSetWorkdir = unsafe extern "C" fn(ctx_id: u32, workdir_path: *const c_char) -> i32;
type KrunSetExec = unsafe extern "C" fn(
⋮----
type KrunSetConsoleOutput = unsafe extern "C" fn(ctx_id: u32, filepath: *const c_char) -> i32;
type KrunStartEnter = unsafe extern "C" fn(ctx_id: u32) -> i32;
type KrunDisableImplicitVsock = unsafe extern "C" fn(ctx_id: u32) -> i32;
type KrunAddVsock = unsafe extern "C" fn(ctx_id: u32, tsi_features: u32) -> i32;
type KrunAddVsockPort2 =
⋮----
pub struct LibKrun {
⋮----
pub fn libkrun(runtime_dir: &Path) -> Result<&'static LibKrun, String> {
if let Some(lib) = LIBKRUN.get() {
return Ok(lib);
... (75 lines truncated)
</file>

<file path="crates/openshell-driver-vm/src/gpu.rs">
pub struct GpuInventory {
⋮----
struct GpuSlot {
⋮----
impl GpuInventory {
pub fn new(sysfs: SysfsRoot, state_dir: &Path) -> Self {
let state_path = state_dir.join("gpu-bindings.json");
⋮----
let restored = reconcile_stale_bindings(&sysfs, &state_path);
⋮----
let gpus = probe_host_nvidia_vfio_readiness(&sysfs);
⋮----
.into_iter()
.map(|info| GpuSlot {
⋮----
.collect();
⋮----
pub fn gpu_count(&self) -> u32 {
u32::try_from(self.slots.len()).unwrap_or(u32::MAX)
⋮----
pub fn available_count(&self) -> u32 {
⋮----
.iter()
.filter(|s| s.assigned_to.is_none())
.count(),
⋮----
.unwrap_or(u32::MAX)
⋮----
pub fn assign(&mut self, sandbox_id: &str, gpu_device: &str) -> Result<GpuAssignment, String> {
let slot_idx = if gpu_device.is_empty() {
... (59 lines truncated)
</file>

<file path="crates/openshell-driver-vm/src/layer_applier.rs">
use std::collections::VecDeque;
use std::ffi::OsString;
use std::fs;
⋮----
use std::os::unix::fs::PermissionsExt;
⋮----
pub fn apply_layer_dir_to_rootfs(layer_root: &Path, rootfs: &Path) -> Result<(), String> {
LayerApplier::new(rootfs)?.apply(layer_root)
⋮----
struct LayerApplier {
⋮----
enum DirectoryMergePlan {
⋮----
impl DirectoryMergePlan {
fn path(&self) -> &Path {
⋮----
fn applies_directory_metadata(&self) -> bool {
!matches!(self, Self::FollowLowerLayerSymlink { .. })
⋮----
struct ResolvedDirectory {
⋮----
impl LayerApplier {
fn new(rootfs: &Path) -> Result<Self, String> {
fs::create_dir_all(rootfs).map_err(|err| format!("create {}: {err}", rootfs.display()))?;
⋮----
.map_err(|err| format!("canonicalize rootfs {}: {err}", rootfs.display()))?;
⋮----
.map_err(|err| format!("open rootfs {}: {err}", rootfs.display()))?;
Ok(Self {
⋮----
... (328 lines truncated)
</file>

<file path="crates/openshell-driver-vm/src/lib.rs">
compile_error!(
⋮----
pub mod driver;
⋮----
mod embedded_runtime;
⋮----
mod ffi;
⋮----
pub mod gpu;
⋮----
mod isolation;
⋮----
mod layer_applier;
⋮----
pub mod lifecycle;
⋮----
pub mod otel_tracing;
⋮----
pub mod procguard;
⋮----
mod rootfs;
⋮----
mod runtime;
</file>

<file path="crates/openshell-driver-vm/src/lifecycle.rs">
use std::collections::HashSet;
⋮----
use std::sync::Arc;
⋮----
use openshell_core::settings::parse_bool_like;
⋮----
use crate::runtime::VmBackend;
⋮----
pub enum LaunchAbortReason {
⋮----
pub struct LifecycleError {
⋮----
impl LifecycleError {
pub fn new(message: impl Into<String>) -> Self {
⋮----
message: message.into(),
⋮----
pub fn resource_exhausted(message: impl Into<String>) -> Self {
⋮----
pub fn message(&self) -> &str {
⋮----
pub fn is_resource_exhausted(&self) -> bool {
⋮----
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.message)
⋮----
pub type LifecycleResult<T> = Result<T, LifecycleError>;
⋮----
/// A capability an extension can require from the VM backend.
///
... (535 lines truncated)
</file>

<file path="crates/openshell-driver-vm/src/main.rs">
use clap::Parser;
use futures::Stream;
⋮----
use openshell_core::VERSION;
use openshell_core::proto::compute::v1::compute_driver_server::ComputeDriverServer;
⋮----
use std::io;
use std::net::SocketAddr;
⋮----
use std::pin::Pin;
⋮----
use tracing::info;
⋮----
struct Args {
⋮----
async fn main() -> Result<()> {
⋮----
maybe_reexec_internal_vm_with_runtime_env()?;
let config = build_vm_launch_config(&args).map_err(|err| miette::miette!("{err}"))?;
run_vm(&config).map_err(|err| miette::miette!("{err}"))?;
return Ok(());
⋮----
endpoint: args.otlp_endpoint.as_deref(),
gateway_name: args.gateway_name.as_deref(),
⋮----
let listen_mode = compute_driver_listen_mode(&args).map_err(|err| miette::miette!("{err}"))?;
⋮----
resource_admission: args.admission_config_json.resource_admission.clone(),
⋮----
.ok_or_else(|| miette::miette!("OPENSHELL_GRPC_ENDPOINT is required"))?,
... (290 lines truncated)
</file>

<file path="crates/openshell-driver-vm/src/otel_tracing.rs">
mod tests {
⋮----
async fn driver_spans_reach_otlp_collector_with_resource_identity() {
</file>

<file path="crates/openshell-driver-vm/src/procguard.rs">
pub fn die_with_parent() -> Result<(), String> {
die_with_parent_cleanup(|| ())
⋮----
pub fn die_with_parent_cleanup<F>(cleanup: F) -> Result<(), String>
⋮----
// Linux has no opportunity for a cleanup hook — the kernel
// delivers SIGKILL directly. Callers that need pre-exit cleanup
// must combine this with a `pre_exec` PR_SET_PDEATHSIG on their
// children (so the kernel cascades) or rely on process-group
// killpg from a signal handler in the parent.
let _ = cleanup; // intentionally dropped
install_linux_pdeathsig()
⋮----
install_bsd_kqueue_watcher(cleanup)
⋮----
Ok(())
⋮----
fn install_linux_pdeathsig() -> Result<(), String> {
use nix::sys::signal::Signal;
use nix::unistd::getppid;
⋮----
// Race: if the parent already died between fork/exec and this call,
// `getppid()` now returns 1 and PR_SET_PDEATHSIG will never fire.
// Read the current parent first so we can detect that case and exit.
let original_ppid = getppid();
⋮----
return Err("process was already orphaned before procguard armed".to_string());
⋮----
.map_err(|err| format!("prctl(PR_SET_PDEATHSIG) failed: {err}"))?;
⋮----
... (27 lines truncated)
</file>

<file path="crates/openshell-driver-vm/src/rootfs.rs">
use flate2::read::MultiGzDecoder;
⋮----
use std::fs;
use std::fs::File;
⋮----
use std::io::BufWriter;
⋮----
use std::process::Command;
use std::sync::OnceLock;
⋮----
use crate::driver::DEFAULT_SANDBOX_UID;
⋮----
const SANDBOX: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/openshell-sandbox.zst"));
const SUPERVISOR: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/openshell-supervisor.zst"));
const VM_INIT: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/openshell-vm-init.zst"));
const UMOCI: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/umoci.zst"));
⋮----
pub const fn sandbox_guest_init_path() -> &'static str {
⋮----
/// Identity of every embedded artifact materialized into a bootstrap rootfs.
///
⋮----
///
/// Including this in the image-cache key makes local, uncommitted guest-sandbox
⋮----
/// Including this in the image-cache key makes local, uncommitted guest-sandbox
/// changes invalidate the cache even when the `OpenShell` version is unchanged.
⋮----
/// changes invalidate the cache even when the `OpenShell` version is unchanged.
pub fn sandbox_guest_runtime_identity() -> String {
... (924 lines truncated)
</file>

<file path="crates/openshell-driver-vm/src/runtime.rs">
use std::ffi::CString;
⋮----
use std::ptr;
⋮----
use std::time::Duration;
⋮----
pub enum VmBackend {
⋮----
pub struct VsockPortMap {
⋮----
pub struct VmLaunchConfig {
⋮----
pub fn run_vm(config: &VmLaunchConfig) -> Result<(), String> {
⋮----
VmBackend::Qemu => run_qemu_vm(config),
VmBackend::Libkrun => run_libkrun_vm(config),
⋮----
fn run_qemu_vm(config: &VmLaunchConfig) -> Result<(), String> {
⋮----
.as_deref()
.ok_or("gpu_bdf is required for QEMU backend")?;
⋮----
.ok_or("vsock_cid is required for QEMU backend")?;
⋮----
if !config.root_disk.is_file() {
return Err(format!(
⋮----
if !config.overlay_disk.is_file() {
⋮----
&& !image_disk.is_file()
... (446 lines truncated)
</file>

<file path="crates/openshell-driver-vm/build.rs">
fn main() {
if env::var_os("CARGO_FEATURE_COMPUTE_DRIVER").is_none() {
⋮----
println!("cargo:rerun-if-env-changed=OPENSHELL_VM_RUNTIME_COMPRESSED_DIR");
⋮----
println!("cargo:rerun-if-changed={dir}");
⋮----
println!("cargo:rerun-if-changed={dir}/{name}");
⋮----
let out_dir = PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR not set"));
let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap_or_default();
let target_arch = env::var("CARGO_CFG_TARGET_ARCH").unwrap_or_default();
⋮----
let (libkrun_name, libkrunfw_name) = match target_os.as_str() {
⋮----
println!("cargo:warning=VM runtime not available for {target_os}-{target_arch}");
generate_stub_resources(
⋮----
println!("cargo:warning=OPENSHELL_VM_RUNTIME_COMPRESSED_DIR not set");
println!("cargo:warning=Run: mise run vm:setup && mise run vm:supervisor");
⋮----
&format!("{libkrun_name}.zst"),
&format!("{libkrunfw_name}.zst"),
⋮----
assert!(
⋮----
(format!("{libkrun_name}.zst"), format!("{libkrun_name}.zst")),
⋮----
format!("{libkrunfw_name}.zst"),
⋮----
... (28 lines truncated)
</file>

<file path="crates/openshell-driver-vm/Cargo.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

[package]
name = "openshell-driver-vm"
description = "MicroVM compute driver for OpenShell"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true

[lib]
name = "openshell_driver_vm"
path = "src/lib.rs"

[[bin]]
name = "openshell-driver-vm"
path = "src/main.rs"
required-features = ["compute-driver"]

[[bin]]
name = "openshell-vm-init"
path = "src/bin/openshell-vm-init.rs"

[dependencies]
openshell-core = { path = "../openshell-core", default-features = false }
openshell-isolation-interface = { path = "../openshell-isolation-interface" }
openshell-sandbox-backend = { path = "../openshell-sandbox-backend" }
openshell-otel = { path = "../openshell-otel", optional = true }
... (102 lines truncated)
</file>

<file path="crates/openshell-driver-vm/entitlements.plist">
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>com.apple.security.hypervisor</key>
    <true/>
</dict>
</plist>
</file>

<file path="crates/openshell-driver-vm/README.md">
# openshell-driver-vm

> Status: Experimental. The VM compute driver is under active development.

Standalone libkrun-backed [`ComputeDriver`](../../proto/compute_driver.proto) for OpenShell. The gateway spawns this binary as a subprocess and talks to it over the `openshell.compute.v1.ComputeDriver` Unix-socket surface. `openshell-supervisor` runs as a native host process, while `openshell-sandbox` runs as capability-free PID 1 inside each microVM and applies guest-local isolation over virtio-vsock.

The driver embeds libkrun, libkrunfw, the guest OCI unpacker, the portable guest sandbox, and the custom kernel runtime. Each sandbox boots from a cached immutable bootstrap ext4 root disk plus a per-sandbox writable overlay disk. When the requested sandbox image differs from the bootstrap image, the driver prepares a read-only image ext4 disk inside a bootstrap VM and mounts that unpacked rootfs as the sandbox lowerdir.

## How it fits together

Caller driver config is disabled by default, including upload workflows
encoded in driver JSON. GPU devices and their trusted VFIO plumbing are
temporarily exempt from approval labels; existing GPU selection validation
still applies. Private rootfs staging does not authorize arbitrary host paths.
The gateway passes its common policy to its managed VM subprocess.
See [resource admission configuration](../../docs/how-it-works/gateways/configuration.mdx#external-resource-admission).

```mermaid
flowchart LR
    subgraph host["Host"]
        gateway["openshell-gateway<br/>(vm::spawn)"]
        driver["openshell-driver-vm<br/>libkrun"]
        supervisor["openshell-supervisor<br/>host policy supervisor"]
        gateway <-->|"gRPC over UDS<br/>compute-driver.sock"| driver
        supervisor <-->|"authenticated gRPC<br/>policy + relay"| gateway
    end

    subgraph guest["Per-sandbox microVM"]
        init["/srv/openshell-vm-<br/>sandbox-init.sh"]
        sandbox["openshell-sandbox<br/>capability-free guest PID 1"]
... (294 lines truncated)
</file>

<file path="crates/openshell-extension-core/src/auth.rs">
use std::fmt;
⋮----
use tonic::metadata::AsciiMetadataValue;
⋮----
pub struct BearerTokenSlot {
⋮----
struct Token {
⋮----
pub enum TokenSlotError {
⋮----
impl BearerTokenSlot {
⋮----
pub fn empty() -> Self {
⋮----
pub fn new(token: &str, expires_at_ms: i64) -> Result<Self, TokenSlotError> {
⋮----
slot.update(token, expires_at_ms)?;
Ok(slot)
⋮----
pub fn update(&self, token: &str, expires_at_ms: i64) -> Result<(), TokenSlotError> {
⋮----
return Err(TokenSlotError::InvalidExpiry);
⋮----
if token.is_empty() || token.bytes().any(|byte| byte.is_ascii_whitespace()) {
return Err(TokenSlotError::InvalidToken);
⋮----
let authorization = AsciiMetadataValue::try_from(format!("Bearer {token}"))
.map_err(|_| TokenSlotError::InvalidToken)?;
⋮----
.write()
... (103 lines truncated)
</file>

<file path="crates/openshell-extension-core/src/identity.rs">
use std::fmt;
use std::str::FromStr;
⋮----
pub enum ExtensionKind {
⋮----
impl ExtensionKind {
pub const fn as_str(self) -> &'static str {
⋮----
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
⋮----
pub struct ExtensionIdentity(String);
⋮----
pub struct ExtensionAudience(String);
⋮----
pub enum IdentityError {
⋮----
macro_rules! opaque_value {
⋮----
opaque_value!(ExtensionIdentity, "identity");
opaque_value!(ExtensionAudience, "audience");
⋮----
impl ExtensionAudience {
/// Build the deterministic fallback audience for a validated registration.
    ///
⋮----
///
    /// Explicit operator-configured audiences remain opaque and take precedence.
⋮----
/// Explicit operator-configured audiences remain opaque and take precedence.
... (36 lines truncated)
</file>

<file path="crates/openshell-extension-core/src/jwt.rs">
use std::time::Duration;
⋮----
pub enum ExtensionCallerKind {
⋮----
pub struct ExtensionJwtClaims {
⋮----
mod tests {
⋮----
fn caller_kind_uses_stable_snake_case_wire_values() {
assert_eq!(
⋮----
fn gateway_claims_omit_sandbox_id() {
⋮----
iss: "openshell-gateway:test".to_string(),
aud: "urn:openshell:extension:interceptor:test".to_string(),
sub: "openshell-gateway:test".to_string(),
⋮----
jti: "unique".to_string(),
⋮----
let json = serde_json::to_value(claims).unwrap();
assert!(json.get("sandbox_id").is_none());
assert_eq!(json["caller_kind"], "gateway");
</file>

<file path="crates/openshell-extension-core/src/lib.rs">
mod auth;
mod identity;
mod jwt;
mod store;
mod transport;
⋮----
pub use store::ExtensionCredentialStore;
</file>

<file path="crates/openshell-extension-core/src/store.rs">
struct Entry {
⋮----
pub struct ExtensionCredentialStore {
⋮----
impl ExtensionCredentialStore {
⋮----
pub fn new() -> Self {
⋮----
fn read(&self) -> std::sync::RwLockReadGuard<'_, HashMap<String, Entry>> {
⋮----
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner)
⋮----
fn write(&self) -> std::sync::RwLockWriteGuard<'_, HashMap<String, Entry>> {
⋮----
.write()
⋮----
pub fn install(
⋮----
let refresh_after_ms = refresh_deadline_ms(expires_at_ms, now_ms);
let mut slots = self.write();
if let Some(entry) = slots.get_mut(name) {
entry.slot.update(token, expires_at_ms)?;
⋮----
return Ok(entry.slot.clone());
⋮----
slots.insert(
name.to_string(),
⋮----
slot: slot.clone(),
... (127 lines truncated)
</file>

<file path="crates/openshell-extension-core/src/transport.rs">
use std::path::PathBuf;
use std::time::Duration;
⋮----
use hyper_util::rt::TokioIo;
⋮----
use tokio::net::UnixStream;
⋮----
use tonic::transport::Uri;
⋮----
use tower::service_fn;
⋮----
pub enum ExtensionServerTrust {
⋮----
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
⋮----
Self::PlatformRoots => formatter.write_str("PlatformRoots"),
Self::CustomCaPem(_) => formatter.write_str("CustomCaPem(<redacted>)"),
⋮----
/// Configuration for an outbound extension gRPC channel.
#[derive(Clone, PartialEq, Eq)]
pub struct ExtensionChannelConfig {
⋮----
impl ExtensionChannelConfig {
pub fn new(endpoint: impl Into<String>) -> Self {
⋮----
endpoint: endpoint.into(),
⋮----
/// Select how the remote extension service is authenticated.
    #[must_use]
pub fn with_server_trust(mut self, server_trust: ExtensionServerTrust) -> Self {
... (174 lines truncated)
</file>

<file path="crates/openshell-extension-core/Cargo.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

[package]
name = "openshell-extension-core"
description = "Shared extension identity, authentication, and transport primitives for OpenShell"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true

[dependencies]
hyper-util = { workspace = true, features = ["tokio"] }
serde = { workspace = true, features = ["derive"] }
thiserror = { workspace = true }
tokio = { workspace = true }
tonic = { workspace = true, features = ["channel", "tls-native-roots"] }
tower = { workspace = true }

[dev-dependencies]
http = { workspace = true }
rcgen = { workspace = true }
rustls = { workspace = true }
serde_json = { workspace = true }
tokio-stream = { workspace = true, features = ["net"] }
tonic = { workspace = true, features = ["server", "tls-native-roots"] }

[lints]
workspace = true
... (1 lines truncated)
</file>

<file path="crates/openshell-extension-core/README.md">
# OpenShell extension core

`openshell-extension-core` contains protocol-neutral primitives shared by two or
more OpenShell extension mechanisms. It currently owns extension identity and
audience values, the extension JWT claim contract, refreshable bearer
credentials and the per-service store that holds them, and outbound gRPC
transport construction for HTTP, HTTPS, and Unix sockets.

`ExtensionKind` is non-exhaustive so additional extension points can join the
shared identity and audience model without breaking consumers. A new kind must
still define its own registration, transport, and authorization semantics
before gateway wiring accepts it.

Outbound HTTPS authentication is selected through the shared
`ExtensionServerTrust` policy. Platform roots and operator-provided CA bundles
are implemented today. The non-exhaustive policy boundary allows future
SPIFFE X.509-SVID or public-key pinning support to be added once without
changing middleware and interceptor clients independently. Unix sockets retain
their local operating-system access boundary.

Middleware- or interceptor-specific protobuf clients, policy selection,
orchestration, and lifecycle management stay in their owning crates. Gateway
signing authority also stays in `openshell-server`. This ownership rule keeps
this crate from becoming a general-purpose dumping ground as extension support
grows.
</file>

<file path="crates/openshell-gateway/src/lib.rs">
compile_error!(
⋮----
mod vm;
⋮----
use openshell_core::telemetry::TelemetryComputeDriver;
⋮----
use openshell_server::ComputeDriverRegistration;
use openshell_server::ComputeDriverRegistry;
⋮----
pub fn install_default_compute_drivers() -> ComputeDriverRegistry {
⋮----
install_in_tree_compute_drivers(&mut registry);
⋮----
install_mxc_compute_driver(&mut registry);
⋮----
install_unsupported_windows_compute_drivers(&mut registry);
⋮----
fn install_mxc_compute_driver(registry: &mut ComputeDriverRegistry) {
⋮----
.expect("first-party driver name is valid")
.with_telemetry_category(TelemetryComputeDriver::anonymous_category("mxc"))
.with_local_singleplayer();
⋮----
.install(registration)
.expect("first-party driver names are unique");
⋮----
fn install_unsupported_windows_compute_drivers(registry: &mut ComputeDriverRegistry) {
⋮----
.expect("first-party driver name is valid");
⋮----
... (178 lines truncated)
</file>

<file path="crates/openshell-gateway/src/main.rs">
async fn main() -> miette::Result<()> {
</file>

<file path="crates/openshell-gateway/src/vm.rs">
use hyper_util::rt::TokioIo;
⋮----
use openshell_otel::TraceContextInterceptor;
use openshell_server::AcquiredRemoteDriverEndpoint;
⋮----
use openshell_server::ManagedDriverProcess;
use openshell_server::config_file::OtlpConfig;
⋮----
use std::path::Path;
use std::path::PathBuf;
⋮----
use tokio::net::UnixStream;
⋮----
use tokio::process::Command;
use tonic::transport::Channel;
⋮----
use tonic::transport::Endpoint;
⋮----
use tower::service_fn;
⋮----
pub struct VmComputeConfig {
⋮----
impl VmComputeConfig {
⋮----
pub fn default_state_dir() -> PathBuf {
openshell_core::paths::openshell_state_dir().map_or_else(
⋮----
|dir| dir.join("vm-driver"),
⋮----
pub const fn default_krun_log_level() -> u32 {
... (537 lines truncated)
</file>

<file path="crates/openshell-gateway/Cargo.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

[package]
name = "openshell-gateway"
description = "OpenShell gateway binary composition"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true

[[bin]]
name = "openshell-gateway"
path = "src/main.rs"

[dependencies]
serde_json = { workspace = true }
openshell-core = { path = "../openshell-core", default-features = false }
openshell-server = { path = "../openshell-server", default-features = false }
openshell-otel = { path = "../openshell-otel", optional = true }
async-trait = "0.1"
miette = { workspace = true }
tokio = { workspace = true }

[target.'cfg(not(target_os = "windows"))'.dependencies]
openshell-driver-docker = { path = "../openshell-driver-docker", optional = true }
openshell-driver-kubernetes = { path = "../openshell-driver-kubernetes", optional = true }
openshell-driver-podman = { path = "../openshell-driver-podman", optional = true }
openshell-policy = { path = "../openshell-policy", optional = true }
... (54 lines truncated)
</file>

<file path="crates/openshell-gateway-interceptors/src/lib.rs">
use std::collections::BTreeMap;
⋮----
use openshell_core::config::GatewayInterceptorConfig;
⋮----
use tonic::service::interceptor::InterceptedService;
use tonic::transport::Channel;
⋮----
pub(crate) mod plan;
pub(crate) mod profile_source;
pub(crate) mod proto_json;
pub mod routes;
pub(crate) mod runtime;
⋮----
pub use proto_json::ProtoJsonCodec;
⋮----
pub enum InterceptorError {
⋮----
pub type Result<T> = std::result::Result<T, InterceptorError>;
⋮----
pub fn validate_configs(configs: &[GatewayInterceptorConfig]) -> Result<()> {
⋮----
pub(crate) type ExtensionChannel = InterceptedService<Channel, BearerTokenInterceptor>;
⋮----
pub async fn initialize(
⋮----
initialize_configured(configs, None).await
⋮----
pub async fn initialize_authenticated(
⋮----
initialize_configured(configs, Some(token_slots)).await
... (8 lines truncated)
</file>

<file path="crates/openshell-gateway-interceptors/src/plan.rs">
use std::time::Duration;
⋮----
use tonic::Request;
⋮----
use crate::profile_source::GatewayInterceptorProfileSource;
use crate::routes::OpenShellRouteIndex;
⋮----
pub enum Phase {
⋮----
impl Phase {
⋮----
pub const fn as_str(self) -> &'static str {
⋮----
type Error = InterceptorError;
⋮----
fn try_from(value: GatewayInterceptorPhase) -> Result<Self> {
⋮----
GatewayInterceptorPhase::ModifyOperation => Ok(Self::ModifyOperation),
GatewayInterceptorPhase::Validate => Ok(Self::Validate),
GatewayInterceptorPhase::PostCommit => Ok(Self::PostCommit),
GatewayInterceptorPhase::Unspecified => Err(InterceptorError::Config(
"binding phase must not be unspecified".to_string(),
⋮----
fn from(value: GatewayInterceptorPhaseConfig) -> Self {
⋮----
pub enum FailurePolicy {
⋮----
impl FailurePolicy {
⋮----
fn from(value: GatewayInterceptorFailurePolicy) -> Self {
... (586 lines truncated)
</file>

<file path="crates/openshell-gateway-interceptors/src/profile_source.rs">
use std::time::Duration;
⋮----
use openshell_core::mcp::normalize_provider_profile_mcp_fields;
use openshell_core::proto::ProviderProfile;
⋮----
use tonic::Request;
⋮----
pub struct ProviderProfileSourceSnapshot {
⋮----
pub struct GatewayInterceptorProfileSource {
⋮----
impl GatewayInterceptorProfileSource {
pub(crate) fn new(
⋮----
pub fn source_id(&self) -> &str {
⋮----
pub async fn snapshot(&self) -> Result<ProviderProfileSourceSnapshot> {
let mut client = self.client.clone();
⋮----
client.snapshot_provider_profiles(Request::new(ProviderProfileSnapshotRequest {})),
⋮----
.map_err(|_| {
InterceptorError::Transport(format!(
⋮----
.map_err(|status| {
⋮----
.into_inner();
⋮----
resolve_provider_profile_snapshot_revision(response.revision, &response.profiles);
Ok(ProviderProfileSourceSnapshot {
... (61 lines truncated)
</file>

<file path="crates/openshell-gateway-interceptors/src/proto_json.rs">
use std::collections::HashSet;
use std::sync::Arc;
⋮----
use serde_json::Value;
⋮----
pub struct ProtoJsonCodec {
⋮----
impl ProtoJsonCodec {
pub fn from_descriptor_set(bytes: &[u8]) -> Result<Self> {
let pool = DescriptorPool::decode(bytes).map_err(|err| {
InterceptorError::Config(format!("decode protobuf descriptor set: {err}"))
⋮----
let secret_option = pool.get_extension_by_name(SECRET_OPTION);
Ok(Self {
⋮----
pub fn openshell() -> Result<Self> {
⋮----
pub fn decode_message_to_json<M>(&self, type_name: &str, message: &M) -> Result<Value>
⋮----
self.decode_bytes_to_json(type_name, &message.encode_to_vec())
⋮----
pub fn encode_json_to_message(&self, type_name: &str, value: &Value) -> Result<Vec<u8>> {
let descriptor = self.message_descriptor(type_name)?;
let encoded_json = serde_json::to_vec(value).map_err(|err| {
InterceptorError::Transcode(format!(
⋮----
.map_err(|err| {
InterceptorError::Transcode(format!("encode {type_name} from ProtoJSON: {err}"))
⋮----
deserializer.end().map_err(|err| {
... (288 lines truncated)
</file>

<file path="crates/openshell-gateway-interceptors/src/routes.rs">
use prost_reflect::DescriptorPool;
⋮----
pub struct OpenShellRouteIndex {
⋮----
impl OpenShellRouteIndex {
pub fn from_descriptor_set(bytes: &[u8]) -> Result<Self> {
⋮----
.map_err(|e| InterceptorError::Config(format!("decode descriptor set: {e}")))?;
⋮----
pub(crate) fn from_descriptor_pool(pool: &DescriptorPool) -> Result<Self> {
⋮----
.get_service_by_name(SERVICE_OPEN_SHELL)
.ok_or_else(|| {
InterceptorError::Config(format!(
⋮----
for method in service.methods() {
let name = method.name().to_string();
all_methods.insert(name.clone());
if !method.is_client_streaming() && !method.is_server_streaming() {
unary_methods.insert(name.clone());
input_types.insert(name.clone(), method.input().full_name().to_string());
output_types.insert(name, method.output().full_name().to_string());
⋮----
index.validate_interceptable_list()?;
Ok(index)
⋮----
pub fn is_interceptable(&self, service: &str, method: &str) -> bool {
⋮----
&& self.unary_methods.contains(method)
&& INTERCEPTABLE_METHODS.contains(&method)
... (39 lines truncated)
</file>

<file path="crates/openshell-gateway-interceptors/src/runtime.rs">
use std::collections::BTreeMap;
use std::sync::Arc;
use std::time::Instant;
⋮----
use openshell_core::config::GatewayInterceptorConfig;
use openshell_core::extension_protocol::NegotiatedExtension;
⋮----
use openshell_extension_core::BearerTokenSlot;
⋮----
use prost_types::Struct;
⋮----
use crate::profile_source::GatewayInterceptorProfileSource;
⋮----
pub struct GatewayInterceptorRuntime {
⋮----
pub struct EvaluationContext {
⋮----
pub struct InterceptedRequest {
⋮----
struct ValidatedOperation {
⋮----
impl ValidatedOperation {
fn new(codec: &ProtoJsonCodec, type_name: &str, json: Value) -> Result<Self> {
let encoded = codec.encode_json_to_message(type_name, &json)?;
let json = codec.decode_bytes_to_json(type_name, &encoded)?;
Ok(Self { json, encoded })
⋮----
fn apply_patches(
⋮----
let json = apply_json_patches(&self.json, patches).map_err(|err| {
... (603 lines truncated)
</file>

<file path="crates/openshell-gateway-interceptors/Cargo.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

[package]
name = "openshell-gateway-interceptors"
description = "Gateway interceptor framework for OpenShell"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true

[dependencies]
openshell-core = { path = "../openshell-core", default-features = false }
openshell-extension-core = { path = "../openshell-extension-core" }

json-patch = "1.4"
metrics = { workspace = true }
prost = { workspace = true }
prost-reflect = { workspace = true }
prost-types = { workspace = true }
serde_json = { workspace = true }
sha2 = { workspace = true }
thiserror = { workspace = true }
tokio = { workspace = true }
tonic = { workspace = true, features = ["channel", "tls-native-roots"] }
tracing = { workspace = true }

[dev-dependencies]
tracing-subscriber = { workspace = true }
... (4 lines truncated)
</file>

<file path="crates/openshell-isolation-interface/src/linux/child_seccomp.rs">
use std::io;
⋮----
pub struct ChildHardeningProgram {
⋮----
impl ChildHardeningProgram {
⋮----
pub fn install(&mut self) -> io::Result<()> {
set_no_new_privileges()?;
let len = u16::try_from(self.instructions.len()).map_err(|_| {
⋮----
filter: self.instructions.as_mut_ptr(),
⋮----
Err(io::Error::last_os_error())
⋮----
Ok(())
⋮----
pub fn instruction_count(&self) -> usize {
self.instructions.len()
⋮----
pub fn prepare(sandbox_tgid: u32) -> io::Result<ChildHardeningProgram> {
⋮----
return Err(io::Error::new(
⋮----
let mut instructions = vec![
⋮----
instructions.extend([
jump(BPF_JMP_JSET_K, X32_SYSCALL_BIT, 0, 1),
stmt(BPF_RET_K, SECCOMP_RET_KILL_PROCESS),
⋮----
append_unconditional_deny(&mut instructions, syscall)?;
... (115 lines truncated)
</file>

<file path="crates/openshell-isolation-interface/src/linux/landlock.rs">
use std::collections::BTreeSet;
⋮----
use std::io;
use std::os::fd::OwnedFd;
use std::os::unix::ffi::OsStrExt;
use std::path::Path;
⋮----
pub fn abi_version() -> io::Result<u32> {
⋮----
Err(io::Error::last_os_error())
⋮----
u32::try_from(result).map_err(|_| io::Error::other("Landlock ABI does not fit u32"))
⋮----
pub struct RootEntryHandle {
⋮----
impl RootEntryHandle {
⋮----
pub fn name(&self) -> &OsStr {
⋮----
pub fn fd(&self) -> &OwnedFd {
⋮----
pub fn device(&self) -> u64 {
⋮----
pub fn inode(&self) -> u64 {
⋮----
pub fn open_root_allowlist(
⋮----
validate_component(private_name)?;
if allowed_names.contains(private_name) {
return Err(io::Error::new(
... (57 lines truncated)
</file>

<file path="crates/openshell-isolation-interface/src/linux/mod.rs">
pub mod child_seccomp;
pub mod landlock;
pub mod proc_fd;
pub mod process_signal;
pub mod seccomp_notify;
pub mod socket_registry;
pub mod task_memory;
pub mod workload_launcher;
</file>

<file path="crates/openshell-isolation-interface/src/linux/proc_fd.rs">
use std::fs;
use std::io;
use std::os::fd::RawFd;
⋮----
pub fn installed_socket_inodes_excluding(
⋮----
let Some(name) = process.file_name().to_str().map(str::to_owned) else {
⋮----
let Ok(descriptors) = fs::read_dir(process.path().join("fd")) else {
⋮----
for descriptor in descriptors.flatten() {
let Ok(target) = fs::read_link(descriptor.path()) else {
⋮----
let Some(target) = target.to_str() else {
⋮----
.strip_prefix("socket:[")
.and_then(|value| value.strip_suffix(']'))
⋮----
inodes.insert(inode);
⋮----
Ok(inodes)
⋮----
pub fn socket_inode(tid: u32, fd: RawFd) -> io::Result<u64> {
⋮----
return Err(io::Error::new(
⋮----
let target = fs::read_link(format!("/proc/{tid}/fd/{fd}"))?;
let target = target.to_str().ok_or_else(|| {
⋮----
.ok_or_else(|| {
... (27 lines truncated)
</file>

<file path="crates/openshell-isolation-interface/src/linux/process_signal.rs">
use std::io;
⋮----
use crate::linux::task_memory;
⋮----
pub fn mediate_process_signal(
⋮----
listener.validate_id(notification.id)?;
let target = scalar_int(notification.args[0]);
let signal = scalar_int(notification.args[1]);
if target <= 0 || !(0..=64).contains(&signal) {
return Err(io::Error::from_raw_os_error(if target <= 0 {
⋮----
let target = u32::try_from(target).map_err(|_| io::Error::from_raw_os_error(libc::ESRCH))?;
let retained = retain_signal_target(target, sandbox_tgid)?;
⋮----
return Err(io::Error::from_raw_os_error(libc::EPERM));
⋮----
_ => return Err(io::Error::from_raw_os_error(libc::ENOSYS)),
⋮----
retained.as_raw_fd(),
⋮----
return Err(io::Error::last_os_error());
⋮----
listener.respond_value(notification.id, 0)
⋮----
pub fn mediate_thread_signal(
⋮----
let target_group = thread_group_id(target)?;
⋮----
listener.respond_continue(notification.id)
... (70 lines truncated)
</file>

<file path="crates/openshell-isolation-interface/src/linux/seccomp_notify.rs">
use std::io;
use std::mem::size_of;
⋮----
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
⋮----
const fn ioc(direction: u32, number: u32, size: usize) -> libc::c_ulong {
⋮----
const fn iowr<T>(number: u32) -> libc::c_ulong {
ioc(IOC_READ | IOC_WRITE, number, size_of::<T>())
⋮----
const fn iow<T>(number: u32) -> libc::c_ulong {
ioc(IOC_WRITE, number, size_of::<T>())
⋮----
struct SeccompData {
⋮----
struct RawNotification {
⋮----
struct RawResponse {
⋮----
struct RawAddFd {
⋮----
struct RawNotificationSizes {
⋮----
/// One validated seccomp user-notification request.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Notification {
/// Kernel-unique notification identifier.
    pub id: u64,
... (430 lines truncated)
</file>

<file path="crates/openshell-isolation-interface/src/linux/socket_registry.rs">
use std::collections::BTreeMap;
use std::io;
use std::mem::size_of;
use std::net::SocketAddr;
⋮----
use rustix::fs::fstat;
⋮----
use crate::linux::proc_fd;
⋮----
pub struct SocketIdentity {
⋮----
pub enum InetFamily {
⋮----
pub enum InetKind {
⋮----
pub struct SocketMetadata {
⋮----
pub enum SocketState {
⋮----
pub struct SocketEntry {
⋮----
impl SocketEntry {
⋮----
pub fn identity(&self) -> SocketIdentity {
⋮----
pub fn metadata(&self) -> SocketMetadata {
⋮----
pub fn state(&self) -> &SocketState {
⋮----
pub fn retained_preconnect(&self) -> io::Result<&OwnedFd> {
... (163 lines truncated)
</file>

<file path="crates/openshell-isolation-interface/src/linux/task_memory.rs">
use std::io;
use std::mem::size_of;
⋮----
pub fn read_exact(tid: u32, address: u64, destination: &mut [u8]) -> io::Result<()> {
validate_request(tid, address, destination.len())?;
⋮----
.map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "TID does not fit pid_t"))?;
let remote_address = usize::try_from(address).map_err(|_| {
⋮----
iov_base: destination.as_mut_ptr().cast(),
iov_len: destination.len(),
⋮----
let copied = retry_eintr(|| unsafe {
⋮----
Ok(copied) => require_exact(copied, destination.len(), "task-memory read"),
Err(error) if syscall_profile_denied(&error) => {
read_exact_from_proc_mem(tid, address, destination)
.map_err(|fallback| fallback_error("read", &error, fallback))
⋮----
Err(error) => Err(error),
⋮----
pub fn write_exact(tid: u32, address: u64, source: &[u8]) -> io::Result<()> {
validate_request(tid, address, source.len())?;
⋮----
iov_base: source.as_ptr().cast_mut().cast(),
iov_len: source.len(),
⋮----
Ok(copied) => require_exact(copied, source.len(), "task-memory write"),
⋮----
write_exact_to_proc_mem(tid, address, source)
... (136 lines truncated)
</file>

<file path="crates/openshell-isolation-interface/src/linux/workload_launcher.rs">
use std::io;
use std::sync::Arc;
⋮----
use std::sync::mpsc;
use std::thread;
⋮----
type LaunchJob = Box<dyn FnOnce() + Send + 'static>;
⋮----
/// Serialized child-launch executor whose thread owns the inherited listener
/// filter.
⋮----
/// filter.
#[derive(Clone)]
pub struct WorkloadLauncher {
⋮----
impl WorkloadLauncher {
/// Execute one prebuilt spawn operation on the filtered launcher thread.
    ///
⋮----
///
    /// The closure must only perform audited launch work. It must not open an
⋮----
/// The closure must only perform audited launch work. It must not open an
    /// INET socket itself: the launcher is trusted and deliberately has no
⋮----
/// INET socket itself: the launcher is trusted and deliberately has no
    /// notification broker.
⋮----
/// notification broker.
    pub fn execute<T: Send + 'static>(
... (86 lines truncated)
</file>

<file path="crates/openshell-isolation-interface/src/contract.rs">
use std::fmt;
⋮----
use std::path::PathBuf;
use std::str::FromStr;
use std::sync::Arc;
⋮----
use async_trait::async_trait;
⋮----
use tokio::sync::oneshot;
⋮----
pub use openshell_core::SandboxSessionId;
pub use openshell_core::policy::SandboxPolicy;
⋮----
pub enum BackendError {
⋮----
pub enum BackendErrorKind {
⋮----
impl BackendError {
⋮----
pub fn kind(&self) -> BackendErrorKind {
⋮----
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
⋮----
Self::Descriptor(m) => write!(f, "descriptor error: {m}"),
Self::NotRegistered(m) => write!(f, "backend not registered: {m}"),
Self::Denied(m) => write!(f, "attachment denied: {m}"),
Self::Unavailable(m) => write!(f, "boundary unavailable: {m}"),
Self::Unsupported(m) => write!(f, "operation unsupported: {m}"),
Self::Attach(m) => write!(f, "attachment failed: {m}"),
Self::Confirm(m) => write!(f, "confirmation failed: {m}"),
... (305 lines truncated)
</file>

<file path="crates/openshell-isolation-interface/src/lib.rs">
pub struct AgentSpec {
⋮----
pub mod contract;
⋮----
pub mod linux;
</file>

<file path="crates/openshell-isolation-interface/Cargo.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

[package]
name = "openshell-isolation-interface"
description = "OpenShell Isolation Backend interface (RFC 0012)"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true

[dependencies]
openshell-core = { path = "../openshell-core", default-features = false }
async-trait = "0.1"
serde = { workspace = true }
serde_json = { workspace = true }
sha2 = { workspace = true }
tokio = { workspace = true }

[target.'cfg(unix)'.dependencies]
libc = "0.2"

[target.'cfg(target_os = "linux")'.dependencies]
rustix = { workspace = true, features = ["fs", "process"] }

[dev-dependencies]
tokio = { workspace = true }

[lints]
... (2 lines truncated)
</file>

<file path="crates/openshell-ocsf/schemas/ocsf/v1.7.0/classes/application_lifecycle.json">
{
    "attributes": [
        {
            "severity": {
                "type": "string_t",
                "description": "The event/finding severity, normalized to the caption of the <code>severity_id</code> value. In the case of 'Other', it is defined by the source.",
                "group": "classification",
                "requirement": "optional",
                "caption": "Severity",
                "type_name": "String",
                "_source": "base_event",
                "_sibling_of": "severity_id"
            }
        },
        {
            "risk_level": {
                "profile": "security_control",
                "type": "string_t",
                "description": "The risk level, normalized to the caption of the risk_level_id value.",
                "group": "context",
                "requirement": "optional",
                "caption": "Risk Level",
                "type_name": "String",
                "_source": "base_event",
                "_sibling_of": "risk_level_id"
            }
        },
        {
            "status_code": {
                "type": "string_t",
... (1018 lines truncated)
</file>

<file path="crates/openshell-ocsf/schemas/ocsf/v1.7.0/classes/base_event.json">
{
    "attributes": [
        {
            "severity": {
                "type": "string_t",
                "description": "The event/finding severity, normalized to the caption of the <code>severity_id</code> value. In the case of 'Other', it is defined by the source.",
                "group": "classification",
                "requirement": "optional",
                "caption": "Severity",
                "type_name": "String",
                "_source": "base_event",
                "_sibling_of": "severity_id"
            }
        },
        {
            "risk_level": {
                "profile": "security_control",
                "type": "string_t",
                "description": "The risk level, normalized to the caption of the risk_level_id value.",
                "group": "context",
                "requirement": "optional",
                "caption": "Risk Level",
                "type_name": "String",
                "_source": "base_event",
                "_sibling_of": "risk_level_id"
            }
        },
        {
            "status_code": {
                "type": "string_t",
... (935 lines truncated)
</file>

<file path="crates/openshell-ocsf/schemas/ocsf/v1.7.0/classes/detection_finding.json">
{
    "attributes": [
        {
            "severity": {
                "type": "string_t",
                "description": "The event/finding severity, normalized to the caption of the <code>severity_id</code> value. In the case of 'Other', it is defined by the source.",
                "group": "classification",
                "requirement": "optional",
                "caption": "Severity",
                "type_name": "String",
                "_source": "base_event",
                "_sibling_of": "severity_id"
            }
        },
        {
            "risk_level": {
                "profile": null,
                "type": "string_t",
                "description": "The risk level, normalized to the caption of the risk_level_id value.",
                "group": "context",
                "requirement": "optional",
                "caption": "Risk Level",
                "type_name": "String",
                "_source": "detection_finding",
                "_sibling_of": "risk_level_id"
            }
        },
        {
            "status_code": {
                "type": "string_t",
... (1368 lines truncated)
</file>

<file path="crates/openshell-ocsf/schemas/ocsf/v1.7.0/classes/device_config_state_change.json">
{
    "attributes": [
        {
            "severity": {
                "type": "string_t",
                "description": "The event/finding severity, normalized to the caption of the <code>severity_id</code> value. In the case of 'Other', it is defined by the source.",
                "group": "classification",
                "requirement": "optional",
                "caption": "Severity",
                "type_name": "String",
                "_source": "base_event",
                "_sibling_of": "severity_id"
            }
        },
        {
            "risk_level": {
                "profile": "security_control",
                "type": "string_t",
                "description": "The risk level, normalized to the caption of the risk_level_id value.",
                "group": "context",
                "requirement": "optional",
                "caption": "Risk Level",
                "type_name": "String",
                "_source": "base_event",
                "_sibling_of": "risk_level_id"
            }
        },
        {
            "status_code": {
                "type": "string_t",
... (1108 lines truncated)
</file>

<file path="crates/openshell-ocsf/schemas/ocsf/v1.7.0/classes/http_activity.json">
{
    "attributes": [
        {
            "proxy_http_request": {
                "profile": "network_proxy",
                "type": "object_t",
                "description": "The HTTP Request from the proxy server to the remote server.",
                "group": "context",
                "requirement": "optional",
                "caption": "Proxy HTTP Request",
                "object_name": "HTTP Request",
                "object_type": "http_request",
                "_source": "network"
            }
        },
        {
            "proxy_endpoint": {
                "profile": "network_proxy",
                "type": "object_t",
                "description": "The proxy (server) in a network connection.",
                "group": "context",
                "requirement": "optional",
                "caption": "Proxy Endpoint",
                "object_name": "Network Proxy Endpoint",
                "object_type": "network_proxy",
                "_source": "network"
            }
        },
        {
            "severity": {
... (1351 lines truncated)
</file>

<file path="crates/openshell-ocsf/schemas/ocsf/v1.7.0/classes/network_activity.json">
{
    "attributes": [
        {
            "proxy_http_request": {
                "profile": "network_proxy",
                "type": "object_t",
                "description": "The HTTP Request from the proxy server to the remote server.",
                "group": "context",
                "requirement": "optional",
                "caption": "Proxy HTTP Request",
                "object_name": "HTTP Request",
                "object_type": "http_request",
                "_source": "network"
            }
        },
        {
            "proxy_endpoint": {
                "profile": "network_proxy",
                "type": "object_t",
                "description": "The proxy (server) in a network connection.",
                "group": "context",
                "requirement": "optional",
                "caption": "Proxy Endpoint",
                "object_name": "Network Proxy Endpoint",
                "object_type": "network_proxy",
                "_source": "network"
            }
        },
        {
            "severity": {
... (1280 lines truncated)
</file>

<file path="crates/openshell-ocsf/schemas/ocsf/v1.7.0/classes/process_activity.json">
{
    "attributes": [
        {
            "severity": {
                "type": "string_t",
                "description": "The event/finding severity, normalized to the caption of the <code>severity_id</code> value. In the case of 'Other', it is defined by the source.",
                "group": "classification",
                "requirement": "optional",
                "caption": "Severity",
                "type_name": "String",
                "_source": "base_event",
                "_sibling_of": "severity_id"
            }
        },
        {
            "risk_level": {
                "profile": "security_control",
                "type": "string_t",
                "description": "The risk level, normalized to the caption of the risk_level_id value.",
                "group": "context",
                "requirement": "optional",
                "caption": "Risk Level",
                "type_name": "String",
                "_source": "base_event",
                "_sibling_of": "risk_level_id"
            }
        },
        {
            "status_code": {
                "type": "string_t",
... (1164 lines truncated)
</file>

<file path="crates/openshell-ocsf/schemas/ocsf/v1.7.0/classes/ssh_activity.json">
{
    "attributes": [
        {
            "proxy_http_request": {
                "profile": "network_proxy",
                "type": "object_t",
                "description": "The HTTP Request from the proxy server to the remote server.",
                "group": "context",
                "requirement": "optional",
                "caption": "Proxy HTTP Request",
                "object_name": "HTTP Request",
                "object_type": "http_request",
                "_source": "network"
            }
        },
        {
            "proxy_endpoint": {
                "profile": "network_proxy",
                "type": "object_t",
                "description": "The proxy (server) in a network connection.",
                "group": "context",
                "requirement": "optional",
                "caption": "Proxy Endpoint",
                "object_name": "Network Proxy Endpoint",
                "object_type": "network_proxy",
                "_source": "network"
            }
        },
        {
            "server_hassh": {
... (1362 lines truncated)
</file>

<file path="crates/openshell-ocsf/schemas/ocsf/v1.7.0/objects/actor.json">
{
    "attributes": [
        {
            "process": {
                "type": "object_t",
                "description": "The process that initiated the activity.",
                "requirement": "recommended",
                "caption": "Process",
                "object_name": "Process",
                "object_type": "process",
                "_source": "actor"
            }
        },
        {
            "session": {
                "type": "object_t",
                "description": "The user session from which the activity was initiated.",
                "requirement": "optional",
                "caption": "Session",
                "object_name": "Session",
                "object_type": "session",
                "_source": "actor"
            }
        },
        {
            "user": {
                "type": "object_t",
                "description": "The user that initiated the activity or the user context from which the activity was initiated.",
                "requirement": "recommended",
                "caption": "User",
... (89 lines truncated)
</file>

<file path="crates/openshell-ocsf/schemas/ocsf/v1.7.0/objects/attack.json">
{
    "attributes": [
        {
            "version": {
                "type": "string_t",
                "description": "The ATT&CK\u00ae or ATLAS\u2122 Matrix version.",
                "requirement": "recommended",
                "caption": "Version",
                "type_name": "String",
                "_source": "attack"
            }
        },
        {
            "tactics": {
                "type": "object_t",
                "description": "The Tactic object describes the tactic ID and/or tactic name that are associated with the attack technique, as defined by <a target='_blank' href='https://attack.mitre.org/wiki/ATT&CK_Matrix'>ATT&CK\u00ae Matrix</a>.",
                "is_array": true,
                "requirement": "optional",
                "caption": "Tactics",
                "object_name": "MITRE Tactic",
                "object_type": "tactic",
                "@deprecated": {
                    "message": "Use the <code>tactic</code> attribute instead.",
                    "since": "1.1.0"
                },
                "_source": "attack"
            }
        },
        {
            "technique": {
... (106 lines truncated)
</file>

<file path="crates/openshell-ocsf/schemas/ocsf/v1.7.0/objects/connection_info.json">
{
    "error": "Object connection_info not found"
}
</file>

<file path="crates/openshell-ocsf/schemas/ocsf/v1.7.0/objects/container.json">
{
    "attributes": [
        {
            "name": {
                "type": "string_t",
                "description": "The container name.",
                "requirement": "recommended",
                "caption": "Name",
                "type_name": "String",
                "_source": "container"
            }
        },
        {
            "runtime": {
                "type": "string_t",
                "description": "The backend running the container, such as containerd or cri-o.",
                "requirement": "optional",
                "caption": "Runtime",
                "type_name": "String",
                "_source": "container"
            }
        },
        {
            "size": {
                "type": "long_t",
                "description": "The size of the container image.",
                "requirement": "recommended",
                "caption": "Size",
                "type_name": "Long",
                "_source": "container"
... (121 lines truncated)
</file>

<file path="crates/openshell-ocsf/schemas/ocsf/v1.7.0/objects/device.json">
{
    "attributes": [
        {
            "boot_time_dt": {
                "profile": "datetime",
                "type": "datetime_t",
                "description": "The time the system was booted.",
                "requirement": "optional",
                "caption": "Boot Time",
                "type_name": "Datetime",
                "_source": "device"
            }
        },
        {
            "risk_level": {
                "type": "string_t",
                "description": "The risk level, normalized to the caption of the risk_level_id value.",
                "requirement": "optional",
                "caption": "Risk Level",
                "type_name": "String",
                "_source": "device",
                "_sibling_of": "risk_level_id"
            }
        },
        {
            "vendor_name": {
                "type": "string_t",
                "description": "The vendor for the device. For example <code>Dell</code> or <code>Lenovo</code>.",
                "requirement": "recommended",
                "caption": "Vendor Name",
... (769 lines truncated)
</file>

<file path="crates/openshell-ocsf/schemas/ocsf/v1.7.0/objects/evidences.json">
{
    "attributes": [
        {
            "data": {
                "type": "json_t",
                "description": "Additional evidence data that is not accounted for in the specific evidence attributes.<code> Use only when absolutely necessary.</code>",
                "requirement": "optional",
                "caption": "Data",
                "type_name": "JSON",
                "_source": "evidences"
            }
        },
        {
            "http_response": {
                "type": "object_t",
                "description": "Describes details about the http response associated to the activity that triggered the detection.",
                "requirement": "recommended",
                "caption": "HTTP Response",
                "object_name": "HTTP Response",
                "object_type": "http_response",
                "_source": "evidences"
            }
        },
        {
            "http_request": {
                "type": "object_t",
                "description": "Describes details about the http request associated to the activity that triggered the detection.",
                "requirement": "recommended",
                "caption": "HTTP Request",
                "object_name": "HTTP Request",
... (399 lines truncated)
</file>

<file path="crates/openshell-ocsf/schemas/ocsf/v1.7.0/objects/finding_info.json">
{
    "attributes": [
        {
            "title": {
                "type": "string_t",
                "description": "A title or a brief phrase summarizing the reported finding.",
                "requirement": "recommended",
                "caption": "Title",
                "type_name": "String",
                "_source": "finding_info"
            }
        },
        {
            "desc": {
                "type": "string_t",
                "description": "The description of the reported finding.",
                "requirement": "optional",
                "caption": "Description",
                "type_name": "String",
                "_source": "finding_info"
            }
        },
        {
            "product": {
                "type": "object_t",
                "description": "Details about the product that reported the finding.",
                "requirement": "optional",
                "caption": "Product",
                "object_name": "Product",
                "object_type": "product",
... (289 lines truncated)
</file>

<file path="crates/openshell-ocsf/schemas/ocsf/v1.7.0/objects/firewall_rule.json">
{
    "attributes": [
        {
            "name": {
                "type": "string_t",
                "description": "The name of the rule that generated the event.",
                "requirement": "recommended",
                "caption": "Name",
                "type_name": "String",
                "_source": "rule"
            }
        },
        {
            "type": {
                "type": "string_t",
                "description": "The rule type.",
                "requirement": "optional",
                "caption": "Type",
                "type_name": "String",
                "_source": "rule"
            }
        },
        {
            "version": {
                "type": "string_t",
                "description": "The rule version. For example: <code>1.1</code>.",
                "requirement": "optional",
                "caption": "Version",
                "type_name": "String",
                "_source": "rule"
... (106 lines truncated)
</file>

<file path="crates/openshell-ocsf/schemas/ocsf/v1.7.0/objects/http_request.json">
{
    "attributes": [
        {
            "args": {
                "type": "string_t",
                "description": "The arguments sent along with the HTTP request.",
                "requirement": "optional",
                "caption": "HTTP Arguments",
                "type_name": "String",
                "_source": "http_request"
            }
        },
        {
            "version": {
                "type": "string_t",
                "description": "The Hypertext Transfer Protocol (HTTP) version.",
                "requirement": "recommended",
                "caption": "HTTP Version",
                "type_name": "String",
                "_source": "http_request"
            }
        },
        {
            "length": {
                "type": "integer_t",
                "description": "The length of the entire HTTP request, in number of bytes.",
                "requirement": "optional",
                "caption": "Request Length",
                "type_name": "Integer",
                "_source": "http_request"
... (138 lines truncated)
</file>

<file path="crates/openshell-ocsf/schemas/ocsf/v1.7.0/objects/http_response.json">
{
    "attributes": [
        {
            "code": {
                "type": "integer_t",
                "description": "The Hypertext Transfer Protocol (HTTP) status code returned from the web server to the client. For example, 200.",
                "requirement": "required",
                "caption": "Response Code",
                "type_name": "Integer",
                "_source": "http_response"
            }
        },
        {
            "message": {
                "type": "string_t",
                "description": "The description of the event/finding, as defined by the source.",
                "requirement": "optional",
                "caption": "Message",
                "type_name": "String",
                "_source": "http_response"
            }
        },
        {
            "status": {
                "type": "string_t",
                "description": "The response status. For example: A successful HTTP status of 'OK' which corresponds to a code of 200.",
                "requirement": "optional",
                "caption": "Status",
                "type_name": "String",
                "_source": "http_response"
... (67 lines truncated)
</file>

<file path="crates/openshell-ocsf/schemas/ocsf/v1.7.0/objects/metadata.json">
{
    "attributes": [
        {
            "untruncated_size": {
                "type": "integer_t",
                "description": "The original size of the OCSF event data in kilobytes before any truncation occurred. This field is typically populated when <code>is_truncated</code> is <code>true</code> to indicate the full size of the original event.",
                "requirement": "optional",
                "caption": "Untruncated Size",
                "type_name": "Integer",
                "_source": "metadata"
            }
        },
        {
            "profiles": {
                "type": "string_t",
                "description": "The list of profiles used to create the event.  Profiles should be referenced by their <code>name</code> attribute for core profiles, or <code>extension/name</code> for profiles from extensions.",
                "is_array": true,
                "requirement": "optional",
                "caption": "Profiles",
                "type_name": "String",
                "_source": "metadata"
            }
        },
        {
            "loggers": {
                "type": "object_t",
                "description": "An array of Logger objects that describe the pipeline of devices and logging products between the event source and its eventual destination. Note, this attribute can be used when there is a complex end-to-end path of event flow and/or to track the chain of custody of the data.",
                "is_array": true,
                "requirement": "optional",
                "caption": "Loggers",
... (402 lines truncated)
</file>

<file path="crates/openshell-ocsf/schemas/ocsf/v1.7.0/objects/network_endpoint.json">
{
    "attributes": [
        {
            "name": {
                "type": "string_t",
                "description": "The short name of the endpoint.",
                "requirement": "recommended",
                "caption": "Name",
                "type_name": "String",
                "_source": "endpoint"
            }
        },
        {
            "owner": {
                "type": "object_t",
                "description": "The identity of the service or user account that owns the endpoint or was last logged into it.",
                "requirement": "recommended",
                "caption": "Owner",
                "object_name": "User",
                "object_type": "user",
                "_source": "endpoint"
            }
        },
        {
            "port": {
                "type": "port_t",
                "description": "The port used for communication within the network connection.",
                "requirement": "recommended",
                "caption": "Port",
                "type_name": "Port",
... (419 lines truncated)
</file>

<file path="crates/openshell-ocsf/schemas/ocsf/v1.7.0/objects/network_proxy.json">
{
    "attributes": [
        {
            "name": {
                "type": "string_t",
                "description": "The short name of the endpoint.",
                "requirement": "recommended",
                "caption": "Name",
                "type_name": "String",
                "_source": "endpoint"
            }
        },
        {
            "owner": {
                "type": "object_t",
                "description": "The identity of the service or user account that owns the endpoint or was last logged into it.",
                "requirement": "recommended",
                "caption": "Owner",
                "object_name": "User",
                "object_type": "user",
                "_source": "endpoint"
            }
        },
        {
            "port": {
                "type": "port_t",
                "description": "The port used for communication within the network connection.",
                "requirement": "recommended",
                "caption": "Port",
                "type_name": "Port",
... (419 lines truncated)
</file>

<file path="crates/openshell-ocsf/schemas/ocsf/v1.7.0/objects/process.json">
{
    "attributes": [
        {
            "name": {
                "type": "process_name_t",
                "description": "The friendly name of the process, for example: <code>Notepad++</code>.",
                "requirement": "recommended",
                "caption": "Name",
                "type_name": "String",
                "_source": "process_entity"
            }
        },
        {
            "pid": {
                "type": "integer_t",
                "description": "The process identifier, as reported by the operating system. Process ID (PID) is a number used by the operating system to uniquely identify an active process.",
                "requirement": "recommended",
                "caption": "Process ID",
                "type_name": "Integer",
                "observable": 15,
                "_source": "process_entity"
            }
        },
        {
            "session": {
                "type": "object_t",
                "description": "The user session under which this process is running.",
                "requirement": "optional",
                "caption": "Session",
                "object_name": "Session",
... (417 lines truncated)
</file>

<file path="crates/openshell-ocsf/schemas/ocsf/v1.7.0/objects/product.json">
{
    "attributes": [
        {
            "name": {
                "type": "string_t",
                "description": "The name of the product.",
                "requirement": "recommended",
                "caption": "Name",
                "type_name": "String",
                "_source": "product"
            }
        },
        {
            "version": {
                "type": "string_t",
                "description": "The version of the product, as defined by the event source. For example: <code>2013.1.3-beta</code>.",
                "requirement": "recommended",
                "caption": "Version",
                "type_name": "String",
                "_source": "product"
            }
        },
        {
            "path": {
                "type": "string_t",
                "description": "The installation path of the product.",
                "requirement": "optional",
                "caption": "Path",
                "type_name": "String",
                "_source": "product"
... (110 lines truncated)
</file>

<file path="crates/openshell-ocsf/schemas/ocsf/v1.7.0/objects/remediation.json">
{
    "attributes": [
        {
            "desc": {
                "type": "string_t",
                "description": "The description of the remediation strategy.",
                "requirement": "required",
                "caption": "Description",
                "type_name": "String",
                "_source": "remediation"
            }
        },
        {
            "references": {
                "type": "string_t",
                "description": "A list of supporting URL/s, references that help describe the remediation strategy.",
                "is_array": true,
                "requirement": "optional",
                "caption": "References",
                "type_name": "String",
                "_source": "remediation"
            }
        },
        {
            "cis_controls": {
                "type": "object_t",
                "description": "An array of Center for Internet Security (CIS) Controls that can be optionally mapped to provide additional remediation details.",
                "is_array": true,
                "references": [
                    {
... (45 lines truncated)
</file>

<file path="crates/openshell-ocsf/schemas/ocsf/v1.7.0/objects/url.json">
{
    "attributes": [
        {
            "port": {
                "type": "port_t",
                "description": "The URL port. For example: <code>80</code>.",
                "requirement": "recommended",
                "caption": "Port",
                "type_name": "Port",
                "_source": "url"
            }
        },
        {
            "scheme": {
                "type": "string_t",
                "description": "The scheme portion of the URL. For example: <code>http</code>, <code>https</code>, <code>ftp</code>, or <code>sftp</code>.",
                "requirement": "recommended",
                "caption": "Scheme",
                "type_name": "String",
                "_source": "url"
            }
        },
        {
            "path": {
                "type": "string_t",
                "description": "The URL path as extracted from the URL. For example: <code>/download/trouble</code> from <code>www.example.com/download/trouble</code>.",
                "requirement": "recommended",
                "caption": "Path",
                "type_name": "String",
                "_source": "url"
... (375 lines truncated)
</file>

<file path="crates/openshell-ocsf/schemas/ocsf/v1.7.0/VERSION">
1.7.0
</file>

<file path="crates/openshell-ocsf/schemas/ocsf/v1.8.0/classes/api_activity.json">
{
    "attributes": {
        "status_code": {
            "type": "string_t",
            "description": "The event status code, as reported by the event source.<br /><br />For example, in a Windows Failed Authentication event, this would be the value of 'Failure Code', e.g. 0x18.",
            "group": "primary",
            "requirement": "recommended",
            "caption": "Status Code",
            "type_name": "String"
        },
        "risk_score": {
            "type": "integer_t",
            "description": "The risk score as reported by the event source.",
            "group": "context",
            "requirement": "optional",
            "caption": "Risk Score",
            "profiles": [
                "security_control"
            ],
            "type_name": "Integer"
        },
        "time": {
            "type": "timestamp_t",
            "description": "The normalized event occurrence time or the finding creation time.",
            "group": "occurrence",
            "requirement": "required",
            "caption": "Event Time",
            "type_name": "Timestamp"
        },
        "observables": {
... (935 lines truncated)
</file>

<file path="crates/openshell-ocsf/schemas/ocsf/v1.8.0/classes/application_lifecycle.json">
{
    "attributes": {
        "status_code": {
            "type": "string_t",
            "description": "The event status code, as reported by the event source.<br /><br />For example, in a Windows Failed Authentication event, this would be the value of 'Failure Code', e.g. 0x18.",
            "group": "primary",
            "requirement": "recommended",
            "caption": "Status Code",
            "type_name": "String"
        },
        "risk_score": {
            "type": "integer_t",
            "description": "The risk score as reported by the event source.",
            "group": "context",
            "requirement": "optional",
            "caption": "Risk Score",
            "profiles": [
                "security_control"
            ],
            "type_name": "Integer"
        },
        "time": {
            "type": "timestamp_t",
            "description": "The normalized event occurrence time or the finding creation time.",
            "group": "occurrence",
            "requirement": "required",
            "caption": "Event Time",
            "type_name": "Timestamp"
        },
        "observables": {
... (902 lines truncated)
</file>

<file path="crates/openshell-ocsf/schemas/ocsf/v1.8.0/classes/base_event.json">
{
    "attributes": {
        "status_code": {
            "type": "string_t",
            "description": "The event status code, as reported by the event source.<br /><br />For example, in a Windows Failed Authentication event, this would be the value of 'Failure Code', e.g. 0x18.",
            "group": "primary",
            "requirement": "recommended",
            "caption": "Status Code",
            "type_name": "String"
        },
        "risk_score": {
            "type": "integer_t",
            "description": "The risk score as reported by the event source.",
            "group": "context",
            "requirement": "optional",
            "caption": "Risk Score",
            "profiles": [
                "security_control"
            ],
            "type_name": "Integer"
        },
        "time": {
            "type": "timestamp_t",
            "description": "The normalized event occurrence time or the finding creation time.",
            "group": "occurrence",
            "requirement": "required",
            "caption": "Event Time",
            "type_name": "Timestamp"
        },
        "observables": {
... (819 lines truncated)
</file>

<file path="crates/openshell-ocsf/schemas/ocsf/v1.8.0/classes/detection_finding.json">
{
    "attributes": {
        "verdict": {
            "type": "string_t",
            "description": "The verdict assigned to an Incident finding.",
            "group": "primary",
            "requirement": "recommended",
            "caption": "Verdict",
            "profiles": [
                "incident"
            ],
            "type_name": "String"
        },
        "vendor_attributes": {
            "type": "object_t",
            "description": "The Vendor Attributes object can be used to represent values of attributes populated by the Vendor/Finding Provider. It can help distinguish between the vendor-provided values and consumer-updated values, of key attributes like <code>severity_id</code>.<br>The original finding producer should not populate this object. It should be populated by consuming systems that support data mutability.",
            "group": "context",
            "requirement": "optional",
            "caption": "Vendor Attributes",
            "object_type": "vendor_attributes",
            "object_name": "Vendor Attributes"
        },
        "priority_id": {
            "type": "integer_t",
            "enum": {
                "3": {
                    "description": "Critical functionality or network access is interrupted, degraded or unusable, having a severe impact on services availability. No acceptable alternative is possible.",
                    "caption": "High"
                },
                "0": {
... (1181 lines truncated)
</file>

<file path="crates/openshell-ocsf/schemas/ocsf/v1.8.0/classes/device_config_state_change.json">
{
    "attributes": {
        "state_id": {
            "type": "integer_t",
            "enum": {
                "0": {
                    "description": "The Config Change state is unknown.",
                    "caption": "Unknown"
                },
                "1": {
                    "description": "Config State Changed to Disabled.",
                    "caption": "Disabled"
                },
                "2": {
                    "description": "Config State Changed to Enabled.",
                    "caption": "Enabled"
                },
                "99": {
                    "description": "The Config Change is not mapped. See the <code>state</code> attribute, which contains data source specific values.",
                    "caption": "Other"
                }
            },
            "description": "The Config Change State of the managed entity.",
            "requirement": "recommended",
            "caption": "Config Change State ID",
            "sibling": "state",
            "type_name": "Integer"
        },
        "status_code": {
            "type": "string_t",
... (958 lines truncated)
</file>

<file path="crates/openshell-ocsf/schemas/ocsf/v1.8.0/classes/http_activity.json">
{
    "attributes": {
        "status_code": {
            "type": "string_t",
            "description": "The event status code, as reported by the event source.<br /><br />For example, in a Windows Failed Authentication event, this would be the value of 'Failure Code', e.g. 0x18.",
            "group": "primary",
            "requirement": "recommended",
            "caption": "Status Code",
            "type_name": "String"
        },
        "proxy_http_response": {
            "type": "object_t",
            "description": "The HTTP Response from the remote server to the proxy server.",
            "group": "context",
            "requirement": "optional",
            "caption": "Proxy HTTP Response",
            "object_type": "http_response",
            "profiles": [
                "network_proxy"
            ],
            "object_name": "HTTP Response"
        },
        "risk_score": {
            "type": "integer_t",
            "description": "The risk score as reported by the event source.",
            "group": "context",
            "requirement": "optional",
            "caption": "Risk Score",
            "profiles": [
                "security_control"
... (1214 lines truncated)
</file>

<file path="crates/openshell-ocsf/schemas/ocsf/v1.8.0/classes/network_activity.json">
{
    "attributes": {
        "is_src_dst_assignment_known": {
            "type": "boolean_t",
            "description": "<code>true</code> denotes that <code>src_endpoint</code> and <code>dst_endpoint</code> correctly identify the initiator and responder respectively. <code>false</code> denotes that the event source has arbitrarily assigned one peer to <code>src_endpoint</code> and the other to <code>dst_endpoint</code>, in other words that initiator and responder are not being asserted. This can occur, for example, when the event source is a network appliance that has not observed the initiation of a given connection. In the absence of this attribute, interpretation of the initiator and responder is implementation-specific.",
            "group": "primary",
            "requirement": "recommended",
            "caption": "Source/Destination Assignment Known",
            "type_name": "Boolean"
        },
        "status_code": {
            "type": "string_t",
            "description": "The event status code, as reported by the event source.<br /><br />For example, in a Windows Failed Authentication event, this would be the value of 'Failure Code', e.g. 0x18.",
            "group": "primary",
            "requirement": "recommended",
            "caption": "Status Code",
            "type_name": "String"
        },
        "proxy_http_response": {
            "type": "object_t",
            "description": "The HTTP Response from the remote server to the proxy server.",
            "group": "context",
            "requirement": "optional",
            "caption": "Proxy HTTP Response",
            "object_type": "http_response",
            "profiles": [
                "network_proxy"
            ],
            "object_name": "HTTP Response"
        },
... (1153 lines truncated)
</file>

<file path="crates/openshell-ocsf/schemas/ocsf/v1.8.0/classes/process_activity.json">
{
    "attributes": {
        "exit_code": {
            "type": "integer_t",
            "description": "The exit code reported by a process when it terminates. The convention is that zero indicates success and any non-zero exit code indicates that some error occurred.",
            "group": "primary",
            "requirement": "recommended",
            "caption": "Exit Code",
            "type_name": "Integer"
        },
        "status_code": {
            "type": "string_t",
            "description": "The event status code, as reported by the event source.<br /><br />For example, in a Windows Failed Authentication event, this would be the value of 'Failure Code', e.g. 0x18.",
            "group": "primary",
            "requirement": "recommended",
            "caption": "Status Code",
            "type_name": "String"
        },
        "risk_score": {
            "type": "integer_t",
            "description": "The risk score as reported by the event source.",
            "group": "context",
            "requirement": "optional",
            "caption": "Risk Score",
            "profiles": [
                "security_control"
            ],
            "type_name": "Integer"
        },
        "time": {
... (1043 lines truncated)
</file>

<file path="crates/openshell-ocsf/schemas/ocsf/v1.8.0/classes/ssh_activity.json">
{
    "attributes": {
        "status_code": {
            "type": "string_t",
            "description": "The event status code, as reported by the event source.<br /><br />For example, in a Windows Failed Authentication event, this would be the value of 'Failure Code', e.g. 0x18.",
            "group": "primary",
            "requirement": "recommended",
            "caption": "Status Code",
            "type_name": "String"
        },
        "proxy_http_response": {
            "type": "object_t",
            "description": "The HTTP Response from the remote server to the proxy server.",
            "group": "context",
            "requirement": "optional",
            "caption": "Proxy HTTP Response",
            "object_type": "http_response",
            "profiles": [
                "network_proxy"
            ],
            "object_name": "HTTP Response"
        },
        "risk_score": {
            "type": "integer_t",
            "description": "The risk score as reported by the event source.",
            "group": "context",
            "requirement": "optional",
            "caption": "Risk Score",
            "profiles": [
                "security_control"
... (1222 lines truncated)
</file>

<file path="crates/openshell-ocsf/schemas/ocsf/v1.8.0/objects/actor.json">
{
    "attributes": {
        "process": {
            "type": "object_t",
            "description": "The process that initiated the activity.",
            "requirement": "recommended",
            "caption": "Process",
            "object_type": "process",
            "object_name": "Process"
        },
        "session": {
            "type": "object_t",
            "description": "The user session from which the activity was initiated.",
            "requirement": "optional",
            "caption": "Session",
            "object_type": "session",
            "object_name": "Session"
        },
        "user": {
            "type": "object_t",
            "description": "The user that initiated the activity or the user context from which the activity was initiated.",
            "requirement": "recommended",
            "caption": "User",
            "object_type": "user",
            "object_name": "User"
        },
        "app_name": {
            "type": "string_t",
            "description": "The client application or service that initiated the activity. This can be in conjunction with the <code>user</code> if present.  Note that <code>app_name</code> is distinct from the <code>process</code> if present.",
            "requirement": "optional",
... (67 lines truncated)
</file>

<file path="crates/openshell-ocsf/schemas/ocsf/v1.8.0/objects/ai_model.json">
{
    "attributes": {
        "name": {
            "type": "string_t",
            "description": "Human-readable model name. For example: <code>gpt-4o</code>, <code>claude-3-sonnet</code>, or <code>text-embedding-ada-002</code>.",
            "requirement": "required",
            "caption": "Name",
            "type_name": "String"
        },
        "version": {
            "type": "string_t",
            "description": "Model version identifier. For example: <code>2024-05-13</code>, <code>v2.1.0</code>, or <code>beta</code>.",
            "requirement": "recommended",
            "caption": "Version",
            "type_name": "String"
        },
        "uid": {
            "type": "string_t",
            "description": "The unique identifier of the AI model.",
            "requirement": "recommended",
            "caption": "Unique ID",
            "type_name": "String"
        },
        "ai_provider": {
            "type": "string_t",
            "description": "AI service provider or organization name. For example: <code>OpenAI</code>, <code>Anthropic</code>, <code>Google</code>, or <code>Internal</code>.",
            "requirement": "required",
            "caption": "AI Provider",
            "type_name": "String"
        }
... (23 lines truncated)
</file>

<file path="crates/openshell-ocsf/schemas/ocsf/v1.8.0/objects/api.json">
{
    "attributes": {
        "version": {
            "type": "string_t",
            "description": "The version of the API service.",
            "requirement": "optional",
            "caption": "Version",
            "type_name": "String"
        },
        "request": {
            "type": "object_t",
            "description": "Details pertaining to the API request.",
            "requirement": "recommended",
            "caption": "API Request Details",
            "object_type": "request",
            "object_name": "Request Elements"
        },
        "service": {
            "type": "object_t",
            "description": "The information pertaining to the API service.",
            "requirement": "optional",
            "caption": "Service",
            "object_type": "service",
            "object_name": "Service"
        },
        "group": {
            "type": "object_t",
            "description": "The information pertaining to the API group.",
            "requirement": "optional",
            "caption": "Group",
... (33 lines truncated)
</file>

<file path="crates/openshell-ocsf/schemas/ocsf/v1.8.0/objects/attack.json">
{
    "attributes": {
        "version": {
            "type": "string_t",
            "description": "The ATT&CK\u00ae or ATLAS\u2122 Matrix version.",
            "requirement": "recommended",
            "caption": "Version",
            "type_name": "String"
        },
        "tactics": {
            "type": "object_t",
            "description": "The Tactic object describes the tactic ID and/or tactic name that are associated with the attack technique, as defined by <a target='_blank' href='https://attack.mitre.org/wiki/ATT&CK_Matrix'>ATT&CK\u00ae Matrix</a>.",
            "is_array": true,
            "requirement": "optional",
            "caption": "Tactics",
            "object_type": "tactic",
            "@deprecated": {
                "message": "Use the <code>tactic</code> attribute instead.",
                "since": "1.1.0"
            },
            "object_name": "MITRE Tactic"
        },
        "technique": {
            "type": "object_t",
            "description": "The Technique object describes the MITRE ATT&CK\u00ae or ATLAS\u2122 Technique ID and/or name associated to an attack.",
            "references": [
                {
                    "description": "ATT&CK\u00ae Matrix",
                    "url": "https://attack.mitre.org"
                },
... (88 lines truncated)
</file>

<file path="crates/openshell-ocsf/schemas/ocsf/v1.8.0/objects/connection_info.json">
{
    "error": "Object connection_info not found"
}
</file>

<file path="crates/openshell-ocsf/schemas/ocsf/v1.8.0/objects/container.json">
{
    "attributes": {
        "name": {
            "type": "string_t",
            "description": "The container name.",
            "requirement": "recommended",
            "caption": "Name",
            "type_name": "String"
        },
        "runtime": {
            "type": "string_t",
            "description": "The backend running the container, such as containerd or cri-o.",
            "requirement": "optional",
            "caption": "Runtime",
            "type_name": "String"
        },
        "size": {
            "type": "long_t",
            "description": "The size of the container image.",
            "requirement": "recommended",
            "caption": "Size",
            "type_name": "Long"
        },
        "tag": {
            "type": "string_t",
            "description": "The tag used by the container. It can indicate version, format, OS.",
            "requirement": "optional",
            "caption": "Image Tag",
            "type_name": "String",
            "@deprecated": {
... (85 lines truncated)
</file>

<file path="crates/openshell-ocsf/schemas/ocsf/v1.8.0/objects/device.json">
{
    "attributes": {
        "imei": {
            "type": "string_t",
            "description": "The International Mobile Equipment Identity that is associated with the device.",
            "requirement": "optional",
            "caption": "IMEI",
            "type_name": "String",
            "@deprecated": {
                "message": "Use the <code>imei_list</code> attribute instead.",
                "since": "1.4.0"
            }
        },
        "org": {
            "type": "object_t",
            "description": "Organization and org unit related to the device.",
            "requirement": "optional",
            "caption": "Organization",
            "object_type": "organization",
            "object_name": "Organization"
        },
        "last_seen_time_dt": {
            "type": "datetime_t",
            "description": "The most recent discovery time of the device.",
            "requirement": "optional",
            "caption": "Last Seen",
            "profiles": [
                "datetime"
            ],
            "type_name": "Datetime"
... (613 lines truncated)
</file>

<file path="crates/openshell-ocsf/schemas/ocsf/v1.8.0/objects/evidences.json">
{
    "attributes": {
        "data": {
            "type": "json_t",
            "description": "Additional evidence data that is not accounted for in the specific evidence attributes.<code> Use only when absolutely necessary.</code>",
            "requirement": "optional",
            "caption": "Data",
            "type_name": "JSON"
        },
        "http_response": {
            "type": "object_t",
            "description": "Describes details about the http response associated to the activity that triggered the detection.",
            "requirement": "recommended",
            "caption": "HTTP Response",
            "object_type": "http_response",
            "object_name": "HTTP Response"
        },
        "http_request": {
            "type": "object_t",
            "description": "Describes details about the http request associated to the activity that triggered the detection.",
            "requirement": "recommended",
            "caption": "HTTP Request",
            "object_type": "http_request",
            "object_name": "HTTP Request"
        },
        "name": {
            "type": "string_t",
            "description": "The naming convention or type identifier of the evidence associated with the security detection. For example, the <code>@odata.type</code> from Microsoft Graph Alerts V2 or <code>display_name</code> from CrowdStrike Falcon Incident Behaviors.",
            "requirement": "optional",
            "caption": "Name",
... (304 lines truncated)
</file>

<file path="crates/openshell-ocsf/schemas/ocsf/v1.8.0/objects/finding_info.json">
{
    "attributes": {
        "title": {
            "type": "string_t",
            "description": "A title or a brief phrase summarizing the reported finding.",
            "requirement": "recommended",
            "caption": "Title",
            "type_name": "String"
        },
        "product": {
            "type": "object_t",
            "description": "Details about the product that reported the finding.",
            "requirement": "optional",
            "caption": "Product",
            "object_type": "product",
            "object_name": "Product"
        },
        "desc": {
            "type": "string_t",
            "description": "The description of the reported finding.",
            "requirement": "optional",
            "caption": "Description",
            "type_name": "String"
        },
        "uid": {
            "type": "string_t",
            "description": "The unique identifier of the reported finding.",
            "requirement": "required",
            "caption": "Unique ID",
            "type_name": "String"
... (219 lines truncated)
</file>

<file path="crates/openshell-ocsf/schemas/ocsf/v1.8.0/objects/firewall_rule.json">
{
    "attributes": {
        "name": {
            "type": "string_t",
            "description": "The name of the rule that generated the event.",
            "requirement": "recommended",
            "caption": "Name",
            "type_name": "String"
        },
        "type": {
            "type": "string_t",
            "description": "The rule type.",
            "requirement": "optional",
            "caption": "Type",
            "type_name": "String"
        },
        "version": {
            "type": "string_t",
            "description": "The rule version. For example: <code>1.1</code>.",
            "requirement": "optional",
            "caption": "Version",
            "type_name": "String"
        },
        "desc": {
            "type": "string_t",
            "description": "The description of the rule that generated the event.",
            "requirement": "optional",
            "caption": "Description",
            "type_name": "String"
        },
... (70 lines truncated)
</file>

<file path="crates/openshell-ocsf/schemas/ocsf/v1.8.0/objects/http_request.json">
{
    "attributes": {
        "args": {
            "type": "string_t",
            "description": "The arguments sent along with the HTTP request.",
            "requirement": "optional",
            "caption": "HTTP Arguments",
            "type_name": "String"
        },
        "version": {
            "type": "string_t",
            "description": "The Hypertext Transfer Protocol (HTTP) version.",
            "requirement": "recommended",
            "caption": "HTTP Version",
            "type_name": "String"
        },
        "length": {
            "type": "integer_t",
            "description": "The length of the entire HTTP request, in number of bytes.",
            "requirement": "optional",
            "caption": "Request Length",
            "type_name": "Integer"
        },
        "uid": {
            "type": "string_t",
            "description": "The unique identifier of the http request.",
            "requirement": "optional",
            "caption": "Unique ID",
            "type_name": "String"
        },
... (105 lines truncated)
</file>

<file path="crates/openshell-ocsf/schemas/ocsf/v1.8.0/objects/http_response.json">
{
    "attributes": {
        "code": {
            "type": "integer_t",
            "description": "The Hypertext Transfer Protocol (HTTP) status code returned from the web server to the client. For example, 200.",
            "requirement": "required",
            "caption": "Response Code",
            "type_name": "Integer"
        },
        "message": {
            "type": "string_t",
            "description": "The description of the event/finding, as defined by the source.",
            "requirement": "optional",
            "caption": "Message",
            "type_name": "String"
        },
        "status": {
            "type": "string_t",
            "description": "The response status. For example: A successful HTTP status of 'OK' which corresponds to a code of 200.",
            "requirement": "optional",
            "caption": "Status",
            "type_name": "String"
        },
        "length": {
            "type": "integer_t",
            "description": "The length of the entire HTTP response, in number of bytes.",
            "requirement": "optional",
            "caption": "Response Length",
            "type_name": "Integer"
        },
... (43 lines truncated)
</file>

<file path="crates/openshell-ocsf/schemas/ocsf/v1.8.0/objects/metadata.json">
{
    "attributes": {
        "tenant_uid": {
            "type": "string_t",
            "description": "The unique tenant identifier.",
            "requirement": "recommended",
            "caption": "Tenant UID",
            "type_name": "String"
        },
        "log_version": {
            "type": "string_t",
            "description": "The event log schema version of the original event. For example the syslog version or the Cisco Log Schema version",
            "requirement": "optional",
            "caption": "Log Version",
            "type_name": "String"
        },
        "labels": {
            "type": "string_t",
            "description": "The list of labels attached to the event. For example: <code>[\"sample\", \"dev\"]</code>",
            "is_array": true,
            "requirement": "optional",
            "caption": "Labels",
            "type_name": "String"
        },
        "original_time": {
            "type": "string_t",
            "description": "The original event time as reported by the event source. For example, the time in the original format from system event log such as Syslog on Unix/Linux and the System event file on Windows. Omit if event is generated instead of collected via logs.",
            "requirement": "recommended",
            "caption": "Original Time",
            "type_name": "String"
... (309 lines truncated)
</file>

<file path="crates/openshell-ocsf/schemas/ocsf/v1.8.0/objects/network_endpoint.json">
{
    "attributes": {
        "vpc_uid": {
            "type": "string_t",
            "description": "The unique identifier of the Virtual Private Cloud (VPC).",
            "requirement": "optional",
            "caption": "VPC UID",
            "type_name": "String"
        },
        "os": {
            "type": "object_t",
            "description": "The endpoint operating system.",
            "requirement": "optional",
            "caption": "OS",
            "object_type": "os",
            "object_name": "Operating System (OS)"
        },
        "type_id": {
            "type": "integer_t",
            "enum": {
                "3": {
                    "description": "A <a target='_blank' href='https://d3fend.mitre.org/dao/artifact/d3f:LaptopComputer/'>laptop computer</a>.",
                    "caption": "Laptop"
                },
                "6": {
                    "description": "A <a target='_blank' href='https://d3fend.mitre.org/dao/artifact/d3f:VirtualizationSoftware/'>virtual machine</a>.",
                    "caption": "Virtual"
                },
                "0": {
                    "description": "The type is unknown.",
... (358 lines truncated)
</file>

<file path="crates/openshell-ocsf/schemas/ocsf/v1.8.0/objects/network_proxy.json">
{
    "attributes": {
        "vpc_uid": {
            "type": "string_t",
            "description": "The unique identifier of the Virtual Private Cloud (VPC).",
            "requirement": "optional",
            "caption": "VPC UID",
            "type_name": "String"
        },
        "os": {
            "type": "object_t",
            "description": "The endpoint operating system.",
            "requirement": "optional",
            "caption": "OS",
            "object_type": "os",
            "object_name": "Operating System (OS)"
        },
        "type_id": {
            "type": "integer_t",
            "enum": {
                "3": {
                    "description": "A <a target='_blank' href='https://d3fend.mitre.org/dao/artifact/d3f:LaptopComputer/'>laptop computer</a>.",
                    "caption": "Laptop"
                },
                "6": {
                    "description": "A <a target='_blank' href='https://d3fend.mitre.org/dao/artifact/d3f:VirtualizationSoftware/'>virtual machine</a>.",
                    "caption": "Virtual"
                },
                "0": {
                    "description": "The type is unknown.",
... (358 lines truncated)
</file>

<file path="crates/openshell-ocsf/schemas/ocsf/v1.8.0/objects/process.json">
{
    "attributes": {
        "name": {
            "type": "process_name_t",
            "description": "The friendly name of the process, for example: <code>Notepad++</code>.",
            "requirement": "recommended",
            "caption": "Name",
            "type_name": "Process Name"
        },
        "pid": {
            "type": "integer_t",
            "description": "The process identifier, as reported by the operating system. Process ID (PID) is a number used by the operating system to uniquely identify an active process.",
            "requirement": "recommended",
            "caption": "Process ID",
            "type_name": "Integer",
            "observable": 15
        },
        "session": {
            "type": "object_t",
            "description": "The user session under which this process is running.",
            "requirement": "optional",
            "caption": "Session",
            "object_type": "session",
            "object_name": "Session"
        },
        "file": {
            "type": "object_t",
            "description": "The process file object.",
            "requirement": "recommended",
            "caption": "File",
... (328 lines truncated)
</file>

<file path="crates/openshell-ocsf/schemas/ocsf/v1.8.0/objects/product.json">
{
    "attributes": {
        "name": {
            "type": "string_t",
            "description": "The name of the product.",
            "requirement": "recommended",
            "caption": "Name",
            "type_name": "String"
        },
        "version": {
            "type": "string_t",
            "description": "The version of the product, as defined by the event source. For example: <code>2013.1.3-beta</code>.",
            "requirement": "recommended",
            "caption": "Version",
            "type_name": "String"
        },
        "path": {
            "type": "string_t",
            "description": "The installation path of the product.",
            "requirement": "optional",
            "caption": "Path",
            "type_name": "String"
        },
        "uid": {
            "type": "string_t",
            "description": "The unique identifier of the product.",
            "requirement": "recommended",
            "caption": "Unique ID",
            "type_name": "String"
        },
... (81 lines truncated)
</file>

<file path="crates/openshell-ocsf/schemas/ocsf/v1.8.0/objects/remediation.json">
{
    "attributes": {
        "desc": {
            "type": "string_t",
            "description": "The description of the remediation strategy.",
            "requirement": "required",
            "caption": "Description",
            "type_name": "String"
        },
        "references": {
            "type": "string_t",
            "description": "A list of supporting URL/s, references that help describe the remediation strategy.",
            "is_array": true,
            "requirement": "optional",
            "caption": "References",
            "type_name": "String"
        },
        "cis_controls": {
            "type": "object_t",
            "description": "An array of Center for Internet Security (CIS) Controls that can be optionally mapped to provide additional remediation details.",
            "is_array": true,
            "references": [
                {
                    "description": "Center For Internet Security Controls",
                    "url": "https://www.cisecurity.org/controls/"
                }
            ],
            "requirement": "optional",
            "caption": "CIS Controls",
            "object_type": "cis_control",
... (33 lines truncated)
</file>

<file path="crates/openshell-ocsf/schemas/ocsf/v1.8.0/objects/url.json">
{
    "attributes": {
        "port": {
            "type": "port_t",
            "description": "The URL port. For example: <code>80</code>.",
            "requirement": "recommended",
            "caption": "Port",
            "type_name": "Port"
        },
        "scheme": {
            "type": "string_t",
            "description": "The scheme portion of the URL. For example: <code>http</code>, <code>https</code>, <code>ftp</code>, or <code>sftp</code>.",
            "requirement": "recommended",
            "caption": "Scheme",
            "type_name": "String"
        },
        "path": {
            "type": "string_t",
            "description": "The URL path as extracted from the URL. For example: <code>/download/trouble</code> from <code>www.example.com/download/trouble</code>.",
            "requirement": "recommended",
            "caption": "Path",
            "type_name": "String"
        },
        "domain": {
            "type": "string_t",
            "description": "The domain portion of the URL. For example: <code>example.com</code> in <code>https://sub.example.com</code>.",
            "requirement": "optional",
            "caption": "Domain",
            "type_name": "String"
        },
... (341 lines truncated)
</file>

<file path="crates/openshell-ocsf/schemas/ocsf/v1.8.0/profiles/ai_operation.json">
{
    "attributes": {
        "ai_model": {
            "type": "object_t",
            "description": "The AI Model object describes the characteristics of an AI/ML model. Examples include language models like GPT-4, embedding models like text-embedding-ada-002, and computer vision models like CLIP.",
            "group": "context",
            "requirement": "recommended",
            "caption": "AI Model",
            "object_type": "ai_model",
            "object_name": "AI Model"
        },
        "message_context": {
            "type": "object_t",
            "description": "Communication context for AI system interactions including protocols, roles, clients, and session information for MCP and other AI communication systems.",
            "group": "context",
            "requirement": "optional",
            "caption": "Message Context",
            "object_type": "message_context",
            "object_name": "Message Context"
        }
    },
    "meta": "profile",
    "name": "ai_operation",
    "description": "AI-specific attributes for model operations, retrieval systems, and agent activities. e.g. model_name, total_token_counts etc.",
    "caption": "AI Operation"
}
</file>

<file path="crates/openshell-ocsf/schemas/ocsf/v1.8.0/VERSION">
1.8.0
</file>

<file path="crates/openshell-ocsf/schemas/ocsf/README.md">
# Vendored OCSF Schemas

These schemas are vendored from the [OCSF Schema Server](https://schema.ocsf.io/)
for offline test validation.

## Version

- **OCSF v1.8.0** — fetched from `https://schema.ocsf.io/api/1.8.0/`

## Contents

### Classes (8)

- `network_activity` [4001]
- `http_activity` [4002]
- `ssh_activity` [4007]
- `process_activity` [1007]
- `detection_finding` [2004]
- `application_lifecycle` [6002]
- `device_config_state_change` [5019]
- `base_event` [0]

### Objects (17)

- `metadata`, `network_endpoint`, `network_proxy`, `process`, `actor`
- `device`, `container`, `product`, `firewall_rule`, `finding_info`
- `evidences`, `http_request`, `http_response`, `url`, `attack`
- `remediation`, `connection_info`, `ai_model`

### Profiles (1)
... (28 lines truncated)
</file>

<file path="crates/openshell-ocsf/src/builders/api_activity.rs">
use crate::builders::EventContext;
⋮----
use crate::events::base_event::BaseEventData;
⋮----
fn sanitize_model_name(name: &str) -> String {
let truncated = if name.len() > MAX_MODEL_LEN {
⋮----
while end > 0 && !name.is_char_boundary(end) {
⋮----
format!("{}...", &name[..end])
⋮----
name.to_string()
⋮----
truncated.replace(['\n', '\r', '\t'], " ")
⋮----
pub struct ApiActivityBuilder<'a> {
⋮----
pub fn new(ctx: &'a EventContext, operation: impl Into<String>) -> Self {
⋮----
api_operation: operation.into(),
⋮----
pub fn severity(mut self, severity: SeverityId) -> Self {
⋮----
pub fn status(mut self, status: StatusId) -> Self {
self.status = Some(status);
⋮----
pub fn message(mut self, message: impl Into<String>) -> Self {
self.message = Some(message.into());
⋮----
pub fn http_request(mut self, req: HttpRequest) -> Self {
... (91 lines truncated)
</file>

<file path="crates/openshell-ocsf/src/builders/base.rs">
use crate::builders::EventContext;
⋮----
use crate::events::base_event::BaseEventData;
⋮----
pub struct BaseEventBuilder<'a> {
⋮----
pub fn new(ctx: &'a EventContext) -> Self {
⋮----
pub fn activity_name(mut self, name: impl Into<String>) -> Self {
self.activity_name = Some(name.into());
⋮----
pub fn unmapped(mut self, key: &str, value: impl Into<serde_json::Value>) -> Self {
self.unmapped.insert(key.to_string(), value.into());
⋮----
pub fn build(self) -> OcsfEvent {
let activity_name = self.activity_name.as_deref().unwrap_or("Other");
⋮----
self.ctx.metadata(&["container", "host"]),
⋮----
if !self.unmapped.is_empty() {
base.unmapped = Some(serde_json::Value::Object(self.unmapped));
⋮----
.apply_common_fields(&mut base, self.status, self.message);
⋮----
impl_builder_setters!(BaseEventBuilder);
⋮----
mod tests {
⋮----
use crate::builders::test_sandbox_context;
⋮----
... (17 lines truncated)
</file>

<file path="crates/openshell-ocsf/src/builders/config.rs">
use crate::builders::EventContext;
⋮----
use crate::events::base_event::BaseEventData;
⋮----
pub struct ConfigStateChangeBuilder<'a> {
⋮----
pub fn new(ctx: &'a EventContext) -> Self {
⋮----
pub fn state(mut self, id: StateId, label: &str) -> Self {
self.state_id = Some(id);
self.state_label = Some(label.to_string());
⋮----
pub fn security_level(mut self, id: SecurityLevelId) -> Self {
self.security_level = Some(id);
⋮----
pub fn prev_security_level(mut self, id: SecurityLevelId) -> Self {
self.prev_security_level = Some(id);
⋮----
pub fn unmapped(mut self, key: &str, value: impl Into<serde_json::Value>) -> Self {
self.unmapped.insert(key.to_string(), value.into());
⋮----
pub fn build(self) -> OcsfEvent {
⋮----
.metadata(&["security_control", "container", "host"]),
⋮----
if !self.unmapped.is_empty() {
base.unmapped = Some(serde_json::Value::Object(self.unmapped));
⋮----
.apply_common_fields(&mut base, self.status, self.message);
⋮----
... (25 lines truncated)
</file>

<file path="crates/openshell-ocsf/src/builders/finding.rs">
use crate::builders::EventContext;
⋮----
use crate::events::base_event::BaseEventData;
⋮----
pub struct DetectionFindingBuilder<'a> {
⋮----
pub fn new(ctx: &'a EventContext) -> Self {
⋮----
pub fn finding_info(mut self, info: FindingInfo) -> Self {
self.finding_info = Some(info);
⋮----
pub fn is_alert(mut self, alert: bool) -> Self {
self.is_alert = Some(alert);
⋮----
pub fn confidence(mut self, id: ConfidenceId) -> Self {
self.confidence = Some(id);
⋮----
pub fn risk_level(mut self, id: RiskLevelId) -> Self {
self.risk_level = Some(id);
⋮----
pub fn log_source(mut self, source: impl Into<String>) -> Self {
self.log_source = Some(source.into());
⋮----
pub fn unmapped(mut self, key: &str, value: impl Into<serde_json::Value>) -> Self {
self.unmapped.insert(key.to_string(), value.into());
⋮----
pub fn remediation(mut self, desc: &str) -> Self {
self.remediation = Some(Remediation::new(desc));
⋮----
pub fn evidence(mut self, key: &str, value: &str) -> Self {
... (67 lines truncated)
</file>

<file path="crates/openshell-ocsf/src/builders/http.rs">
use crate::builders::EventContext;
⋮----
use crate::events::base_event::BaseEventData;
⋮----
pub struct HttpActivityBuilder<'a, Context = MissingHttpContext> {
⋮----
pub struct MissingHttpContext;
⋮----
pub struct HasHttpContext;
⋮----
pub fn new(ctx: &'a EventContext) -> Self {
⋮----
pub fn http_request(self, req: HttpRequest) -> HttpActivityBuilder<'a, HasHttpContext> {
self.with_http_request(req)
⋮----
pub fn http_response(self, resp: HttpResponse) -> HttpActivityBuilder<'a, HasHttpContext> {
self.with_http_response(resp)
⋮----
pub fn http_request(mut self, req: HttpRequest) -> Self {
self.http_request = Some(req);
⋮----
pub fn http_response(mut self, resp: HttpResponse) -> Self {
self.http_response = Some(resp);
⋮----
fn with_http_request(self, req: HttpRequest) -> HttpActivityBuilder<'a, HasHttpContext> {
⋮----
http_request: Some(req),
⋮----
fn with_http_response(self, resp: HttpResponse) -> HttpActivityBuilder<'a, HasHttpContext> {
⋮----
... (96 lines truncated)
</file>

<file path="crates/openshell-ocsf/src/builders/lifecycle.rs">
use crate::builders::EventContext;
⋮----
use crate::events::base_event::BaseEventData;
⋮----
use crate::objects::Product;
⋮----
pub struct AppLifecycleBuilder<'a> {
⋮----
pub fn new(ctx: &'a EventContext) -> Self {
⋮----
pub fn build(self) -> OcsfEvent {
let activity_name = self.activity.lifecycle_label().to_string();
⋮----
self.activity.as_u8(),
⋮----
self.ctx.metadata(&["container", "host"]),
⋮----
.apply_common_fields(&mut base, self.status, self.message);
⋮----
impl_activity_setter!(AppLifecycleBuilder);
impl_builder_setters!(AppLifecycleBuilder);
⋮----
mod tests {
⋮----
use crate::builders::test_sandbox_context;
⋮----
fn test_app_lifecycle_builder() {
let ctx = test_sandbox_context();
⋮----
.activity(ActivityId::Reset)
... (11 lines truncated)
</file>

<file path="crates/openshell-ocsf/src/builders/mod.rs">
macro_rules! impl_builder_setters {
⋮----
macro_rules! impl_activity_setter {
⋮----
macro_rules! impl_action_disposition_setters {
⋮----
macro_rules! impl_actor_process_setter {
⋮----
macro_rules! impl_dst_endpoint_setter {
⋮----
macro_rules! impl_src_endpoint_addr_setter {
⋮----
mod api_activity;
mod base;
mod config;
mod finding;
mod http;
mod lifecycle;
mod network;
mod process;
mod ssh;
⋮----
pub use api_activity::ApiActivityBuilder;
pub use base::BaseEventBuilder;
pub use config::ConfigStateChangeBuilder;
pub use finding::DetectionFindingBuilder;
pub use http::HttpActivityBuilder;
pub use lifecycle::AppLifecycleBuilder;
pub use network::NetworkActivityBuilder;
pub use process::ProcessActivityBuilder;
... (89 lines truncated)
</file>

<file path="crates/openshell-ocsf/src/builders/network.rs">
use crate::builders::EventContext;
⋮----
use crate::events::base_event::BaseEventData;
⋮----
pub struct NetworkActivityBuilder<'a, EndpointState = MissingNetworkEndpoint> {
⋮----
pub struct MissingNetworkEndpoint;
⋮----
pub struct HasNetworkEndpoint;
⋮----
pub fn new(ctx: &'a EventContext) -> Self {
⋮----
pub fn src_endpoint_addr(
⋮----
self.with_src_endpoint(Endpoint::from_ip(ip, port))
⋮----
pub fn dst_endpoint(
⋮----
self.with_dst_endpoint(endpoint)
⋮----
pub fn src_endpoint_addr(mut self, ip: std::net::IpAddr, port: u16) -> Self {
self.src_endpoint = Some(Endpoint::from_ip(ip, port));
⋮----
pub fn dst_endpoint(mut self, endpoint: Endpoint) -> Self {
self.dst_endpoint = Some(endpoint);
⋮----
fn with_src_endpoint(
⋮----
src_endpoint: Some(endpoint),
⋮----
... (98 lines truncated)
</file>

<file path="crates/openshell-ocsf/src/builders/process.rs">
use crate::builders::EventContext;
⋮----
use crate::events::base_event::BaseEventData;
⋮----
pub struct ProcessActivityBuilder<'a> {
⋮----
pub fn new(ctx: &'a EventContext) -> Self {
⋮----
pub fn process(mut self, proc: Process) -> Self {
self.process = Some(proc);
⋮----
pub fn launch_type(mut self, lt: LaunchTypeId) -> Self {
self.launch_type = Some(lt);
⋮----
pub fn exit_code(mut self, code: i32) -> Self {
self.exit_code = Some(code);
⋮----
pub fn build(self) -> OcsfEvent {
let activity_name = self.activity.process_label().to_string();
⋮----
self.activity.as_u8(),
⋮----
.metadata(&["security_control", "container", "host"]),
⋮----
.apply_common_fields(&mut base, self.status, self.message);
⋮----
process: self.process.unwrap_or_else(|| Process::new("unknown", 0)),
⋮----
impl_activity_setter!(ProcessActivityBuilder);
impl_action_disposition_setters!(ProcessActivityBuilder);
... (35 lines truncated)
</file>

<file path="crates/openshell-ocsf/src/builders/ssh.rs">
use crate::builders::EventContext;
⋮----
use crate::events::base_event::BaseEventData;
⋮----
pub struct SshActivityBuilder<'a> {
⋮----
pub fn new(ctx: &'a EventContext) -> Self {
⋮----
pub fn auth_type(mut self, id: AuthTypeId, label: &str) -> Self {
self.auth_type_id = Some(id);
self.auth_type_label = Some(label.to_string());
⋮----
pub fn protocol_ver(mut self, ver: &str) -> Self {
self.protocol_ver = Some(ver.to_string());
⋮----
pub fn build(self) -> OcsfEvent {
let activity_name = self.activity.network_label().to_string();
⋮----
self.activity.as_u8(),
⋮----
.metadata(&["security_control", "container", "host"]),
⋮----
.apply_common_fields(&mut base, self.status, self.message);
⋮----
impl_activity_setter!(SshActivityBuilder);
impl_action_disposition_setters!(SshActivityBuilder);
impl_actor_process_setter!(SshActivityBuilder);
impl_dst_endpoint_setter!(SshActivityBuilder);
impl_src_endpoint_addr_setter!(SshActivityBuilder);
impl_builder_setters!(SshActivityBuilder);
... (23 lines truncated)
</file>

<file path="crates/openshell-ocsf/src/enums/action.rs">
pub enum ActionId {
⋮----
impl ActionId {
⋮----
pub fn label(self) -> &'static str {
⋮----
pub fn as_u8(self) -> u8 {
⋮----
mod tests {
⋮----
fn test_action_labels() {
assert_eq!(ActionId::Unknown.label(), "Unknown");
assert_eq!(ActionId::Allowed.label(), "Allowed");
assert_eq!(ActionId::Denied.label(), "Denied");
assert_eq!(ActionId::Observed.label(), "Observed");
assert_eq!(ActionId::Modified.label(), "Modified");
assert_eq!(ActionId::Other.label(), "Other");
⋮----
fn test_action_json_roundtrip() {
⋮----
let json = serde_json::to_value(action).unwrap();
assert_eq!(json, serde_json::json!(2));
let deserialized: ActionId = serde_json::from_value(json).unwrap();
assert_eq!(deserialized, ActionId::Denied);
</file>

<file path="crates/openshell-ocsf/src/enums/activity.rs">
pub enum ActivityId {
⋮----
impl ActivityId {
⋮----
pub fn for_http_method(method: &str) -> Self {
match method.to_ascii_uppercase().as_str() {
⋮----
pub fn network_label(self) -> &'static str {
⋮----
/// Returns a human-readable label for HTTP activity context.
    #[must_use]
pub fn http_label(self) -> &'static str {
⋮----
pub fn finding_label(self) -> &'static str {
⋮----
_ => self.network_label(),
⋮----
/// Returns a human-readable label for Application Lifecycle activity context.
    #[must_use]
pub fn lifecycle_label(self) -> &'static str {
⋮----
pub fn config_label(self) -> &'static str {
⋮----
/// Returns a human-readable label for Process Activity context.
    #[must_use]
pub fn process_label(self) -> &'static str {
⋮----
pub fn as_u8(self) -> u8 {
⋮----
mod tests {
... (31 lines truncated)
</file>

<file path="crates/openshell-ocsf/src/enums/auth.rs">
pub enum AuthTypeId {
⋮----
impl AuthTypeId {
⋮----
pub fn label(self) -> &'static str {
⋮----
pub fn as_u8(self) -> u8 {
⋮----
mod tests {
⋮----
fn test_auth_type_labels() {
assert_eq!(AuthTypeId::Unknown.label(), "Unknown");
assert_eq!(AuthTypeId::CertificateBased.label(), "Certificate Based");
assert_eq!(AuthTypeId::PublicKey.label(), "Public Key");
assert_eq!(AuthTypeId::Other.label(), "Other");
⋮----
fn test_auth_type_integer_values() {
assert_eq!(AuthTypeId::Unknown.as_u8(), 0);
assert_eq!(AuthTypeId::CertificateBased.as_u8(), 1);
assert_eq!(AuthTypeId::PublicKey.as_u8(), 6);
assert_eq!(AuthTypeId::Other.as_u8(), 99);
⋮----
fn test_auth_type_json_roundtrip() {
⋮----
let json = serde_json::to_value(auth).unwrap();
assert_eq!(json, serde_json::json!(99));
let deserialized: AuthTypeId = serde_json::from_value(json).unwrap();
assert_eq!(deserialized, AuthTypeId::Other);
</file>

<file path="crates/openshell-ocsf/src/enums/device_type.rs">
pub enum DeviceTypeId {
⋮----
impl DeviceTypeId {
⋮----
pub fn as_u8(self) -> u8 {
⋮----
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str(match self {
⋮----
mod tests {
⋮----
fn device_type_display_uses_schema_labels() {
⋮----
assert_eq!(device_type.to_string(), expected);
assert_eq!(format!("{device_type}"), expected);
⋮----
fn device_type_json_roundtrip() {
⋮----
let json = serde_json::to_value(device_type).unwrap();
assert_eq!(json, serde_json::json!(expected));
let decoded: DeviceTypeId = serde_json::from_value(json).unwrap();
assert_eq!(decoded, device_type);
</file>

<file path="crates/openshell-ocsf/src/enums/disposition.rs">
pub enum DispositionId {
⋮----
impl DispositionId {
⋮----
pub fn label(self) -> &'static str {
⋮----
pub fn as_u8(self) -> u8 {
⋮----
mod tests {
⋮----
fn test_disposition_labels() {
assert_eq!(DispositionId::Unknown.label(), "Unknown");
assert_eq!(DispositionId::Allowed.label(), "Allowed");
assert_eq!(DispositionId::Blocked.label(), "Blocked");
assert_eq!(DispositionId::Detected.label(), "Detected");
assert_eq!(DispositionId::Logged.label(), "Logged");
assert_eq!(DispositionId::Rejected.label(), "Rejected");
assert_eq!(DispositionId::Error.label(), "Error");
assert_eq!(DispositionId::Other.label(), "Other");
⋮----
fn test_disposition_integer_values() {
assert_eq!(DispositionId::Unknown.as_u8(), 0);
assert_eq!(DispositionId::Allowed.as_u8(), 1);
assert_eq!(DispositionId::Blocked.as_u8(), 2);
assert_eq!(DispositionId::Rejected.as_u8(), 25);
assert_eq!(DispositionId::Error.as_u8(), 27);
assert_eq!(DispositionId::Other.as_u8(), 99);
⋮----
fn test_disposition_json_roundtrip() {
⋮----
... (5 lines truncated)
</file>

<file path="crates/openshell-ocsf/src/enums/http_method.rs">
pub enum HttpMethod {
⋮----
impl HttpMethod {
⋮----
pub fn as_str(&self) -> &str {
⋮----
type Err = std::convert::Infallible;
⋮----
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(match s.to_uppercase().as_str() {
⋮----
_ => Self::Other(s.to_string()),
⋮----
impl Serialize for HttpMethod {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(self.as_str())
⋮----
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
⋮----
Ok(s.parse().unwrap())
⋮----
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
⋮----
mod tests {
⋮----
fn test_from_str_standard_methods() {
assert_eq!("GET".parse::<HttpMethod>().unwrap(), HttpMethod::Get);
assert_eq!("get".parse::<HttpMethod>().unwrap(), HttpMethod::Get);
assert_eq!("Post".parse::<HttpMethod>().unwrap(), HttpMethod::Post);
... (25 lines truncated)
</file>

<file path="crates/openshell-ocsf/src/enums/launch.rs">
pub enum LaunchTypeId {
⋮----
impl LaunchTypeId {
⋮----
pub fn label(self) -> &'static str {
⋮----
pub fn as_u8(self) -> u8 {
⋮----
mod tests {
⋮----
fn test_launch_type_labels() {
assert_eq!(LaunchTypeId::Unknown.label(), "Unknown");
assert_eq!(LaunchTypeId::Spawn.label(), "Spawn");
assert_eq!(LaunchTypeId::Fork.label(), "Fork");
assert_eq!(LaunchTypeId::Exec.label(), "Exec");
assert_eq!(LaunchTypeId::Other.label(), "Other");
⋮----
fn test_launch_type_json_roundtrip() {
⋮----
let json = serde_json::to_value(launch).unwrap();
assert_eq!(json, serde_json::json!(1));
let deserialized: LaunchTypeId = serde_json::from_value(json).unwrap();
assert_eq!(deserialized, LaunchTypeId::Spawn);
</file>

<file path="crates/openshell-ocsf/src/enums/mod.rs">
mod action;
mod activity;
mod auth;
mod device_type;
mod disposition;
mod http_method;
mod launch;
mod security;
mod severity;
mod status;
⋮----
pub use action::ActionId;
pub use activity::ActivityId;
pub use auth::AuthTypeId;
pub use device_type::DeviceTypeId;
pub use disposition::DispositionId;
pub use http_method::HttpMethod;
pub use launch::LaunchTypeId;
⋮----
pub use severity::SeverityId;
⋮----
pub trait OcsfEnum: Copy + Clone + PartialEq + Eq + std::fmt::Debug {
⋮----
/// Implement [`OcsfEnum`] for a type that already has `as_u8()` and `label()` methods.
macro_rules! impl_ocsf_enum {
⋮----
macro_rules! impl_ocsf_enum {
⋮----
impl_ocsf_enum!(
</file>

<file path="crates/openshell-ocsf/src/enums/security.rs">
pub enum SecurityLevelId {
⋮----
impl SecurityLevelId {
⋮----
pub fn label(self) -> &'static str {
⋮----
pub fn as_u8(self) -> u8 {
⋮----
/// OCSF Confidence ID (0-3, 99).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize_repr, Deserialize_repr)]
⋮----
pub enum ConfidenceId {
/// 0 — Unknown
    Unknown = 0,
/// 1 — Low
    Low = 1,
/// 2 — Medium
    Medium = 2,
/// 3 — High
    High = 3,
/// 99 — Other
    Other = 99,
⋮----
impl ConfidenceId {
⋮----
pub enum RiskLevelId {
⋮----
impl RiskLevelId {
⋮----
mod tests {
... (32 lines truncated)
</file>

<file path="crates/openshell-ocsf/src/enums/severity.rs">
pub enum SeverityId {
⋮----
impl SeverityId {
⋮----
pub fn label(self) -> &'static str {
⋮----
/// Returns the single-character shorthand for log display.
    #[must_use]
pub fn shorthand_char(self) -> char {
⋮----
pub fn as_u8(self) -> u8 {
⋮----
mod tests {
⋮----
fn test_severity_labels() {
assert_eq!(SeverityId::Unknown.label(), "Unknown");
assert_eq!(SeverityId::Informational.label(), "Informational");
assert_eq!(SeverityId::Low.label(), "Low");
assert_eq!(SeverityId::Medium.label(), "Medium");
assert_eq!(SeverityId::High.label(), "High");
assert_eq!(SeverityId::Critical.label(), "Critical");
assert_eq!(SeverityId::Fatal.label(), "Fatal");
assert_eq!(SeverityId::Other.label(), "Other");
⋮----
fn test_severity_shorthand_chars() {
assert_eq!(SeverityId::Unknown.shorthand_char(), ' ');
assert_eq!(SeverityId::Informational.shorthand_char(), 'I');
assert_eq!(SeverityId::Low.shorthand_char(), 'L');
assert_eq!(SeverityId::Medium.shorthand_char(), 'M');
assert_eq!(SeverityId::High.shorthand_char(), 'H');
... (21 lines truncated)
</file>

<file path="crates/openshell-ocsf/src/enums/status.rs">
pub enum StatusId {
⋮----
impl StatusId {
⋮----
pub fn label(self) -> &'static str {
⋮----
pub fn as_u8(self) -> u8 {
⋮----
/// OCSF State ID (0-2, 99) — used by Device Config State Change.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize_repr, Deserialize_repr)]
⋮----
pub enum StateId {
/// 0 — Unknown
    Unknown = 0,
/// 1 — Disabled
    Disabled = 1,
/// 2 — Enabled
    Enabled = 2,
/// 99 — Other
    Other = 99,
⋮----
impl StateId {
⋮----
mod tests {
⋮----
fn test_status_labels() {
assert_eq!(StatusId::Unknown.label(), "Unknown");
assert_eq!(StatusId::Success.label(), "Success");
assert_eq!(StatusId::Failure.label(), "Failure");
assert_eq!(StatusId::Other.label(), "Other");
... (21 lines truncated)
</file>

<file path="crates/openshell-ocsf/src/events/api_activity.rs">
use serde::Deserialize;
⋮----
use super::base_event::BaseEventData;
⋮----
pub struct ApiActivityEvent {
⋮----
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
⋮----
let mut base_val = serde_json::to_value(&self.base).map_err(serde::ser::Error::custom)?;
⋮----
.as_object_mut()
.ok_or_else(|| serde::ser::Error::custom("expected object"))?;
⋮----
obj.insert(
"api".to_string(),
serde_json::to_value(&self.api).map_err(serde::ser::Error::custom)?,
⋮----
"actor".to_string(),
serde_json::to_value(&self.actor).map_err(serde::ser::Error::custom)?,
⋮----
"src_endpoint".to_string(),
serde_json::to_value(&self.src_endpoint).map_err(serde::ser::Error::custom)?,
⋮----
insert_optional!(obj, "http_request", self.http_request);
insert_optional!(obj, "http_response", self.http_response);
insert_optional!(obj, "dst_endpoint", self.dst_endpoint);
insert_enum_pair!(obj, "action", self.action);
insert_enum_pair!(obj, "disposition", self.disposition);
⋮----
base_val.serialize(serializer)
... (32 lines truncated)
</file>

<file path="crates/openshell-ocsf/src/events/app_lifecycle.rs">
use crate::events::base_event::BaseEventData;
use crate::objects::Product;
⋮----
pub struct ApplicationLifecycleEvent {
⋮----
mod tests {
⋮----
use crate::enums::SeverityId;
use crate::objects::Metadata;
⋮----
fn test_app_lifecycle_serialization() {
⋮----
version: "1.8.0".to_string(),
⋮----
profiles: vec!["container".to_string()],
uid: Some("sandbox-abc123".to_string()),
⋮----
base.set_message("Starting sandbox");
⋮----
let json = serde_json::to_value(&event).unwrap();
assert_eq!(json["class_uid"], 6002);
assert_eq!(json["type_uid"], 600_203);
assert_eq!(json["app"]["name"], "OpenShell Sandbox Supervisor");
assert_eq!(json["message"], "Starting sandbox");
</file>

<file path="crates/openshell-ocsf/src/events/base_event.rs">
pub struct BaseEventData {
⋮----
impl Serialize for BaseEventData {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
use serde::ser::SerializeMap;
⋮----
let mut map = serializer.serialize_map(None)?;
⋮----
map.serialize_entry("class_uid", &self.class_uid)?;
map.serialize_entry("class_name", &self.class_name)?;
map.serialize_entry("category_uid", &self.category_uid)?;
map.serialize_entry("category_name", &self.category_name)?;
map.serialize_entry("activity_id", &self.activity_id)?;
map.serialize_entry("activity_name", &self.activity_name)?;
map.serialize_entry("type_uid", &self.type_uid)?;
map.serialize_entry("type_name", &self.type_name)?;
map.serialize_entry("time", &self.time)?;
⋮----
map.serialize_entry("severity_id", &self.severity.as_u8())?;
map.serialize_entry("severity", self.severity.label())?;
⋮----
map.serialize_entry("status_id", &status.as_u8())?;
map.serialize_entry("status", status.label())?;
⋮----
map.serialize_entry("message", msg)?;
⋮----
map.serialize_entry("status_detail", detail)?;
⋮----
map.serialize_entry("metadata", &self.metadata)?;
⋮----
... (91 lines truncated)
</file>

<file path="crates/openshell-ocsf/src/events/config_state_change.rs">
use crate::events::base_event::BaseEventData;
⋮----
pub struct DeviceConfigStateChangeEvent {
⋮----
impl Serialize for DeviceConfigStateChangeEvent {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
⋮----
let mut base_val = serde_json::to_value(&self.base).map_err(serde::ser::Error::custom)?;
⋮----
.as_object_mut()
.ok_or_else(|| serde::ser::Error::custom("expected object"))?;
⋮----
insert_enum_pair_custom!(obj, "state", self.state, self.state_custom_label);
insert_enum_pair!(obj, "security_level", self.security_level);
insert_enum_pair!(obj, "prev_security_level", self.prev_security_level);
⋮----
base_val.serialize(serializer)
⋮----
mod tests {
⋮----
fn test_config_state_change_serialization() {
⋮----
version: "1.8.0".to_string(),
⋮----
profiles: vec!["security_control".to_string()],
uid: Some("sandbox-abc123".to_string()),
⋮----
base.set_message("Policy reloaded successfully");
base.add_unmapped("policy_version", serde_json::json!("v3"));
base.add_unmapped("policy_hash", serde_json::json!("sha256:abc123def456"));
... (13 lines truncated)
</file>

<file path="crates/openshell-ocsf/src/events/detection_finding.rs">
use crate::events::base_event::BaseEventData;
⋮----
pub struct DetectionFindingEvent {
⋮----
impl Serialize for DetectionFindingEvent {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
⋮----
let mut base_val = serde_json::to_value(&self.base).map_err(serde::ser::Error::custom)?;
⋮----
.as_object_mut()
.ok_or_else(|| serde::ser::Error::custom("expected object"))?;
⋮----
insert_required!(obj, "finding_info", self.finding_info);
insert_optional!(obj, "evidences", self.evidences);
insert_optional!(obj, "attacks", self.attacks);
insert_optional!(obj, "remediation", self.remediation);
insert_optional!(obj, "is_alert", self.is_alert);
insert_enum_pair!(obj, "confidence", self.confidence);
insert_enum_pair!(obj, "risk_level", self.risk_level);
insert_enum_pair!(obj, "action", self.action);
insert_enum_pair!(obj, "disposition", self.disposition);
⋮----
base_val.serialize(serializer)
⋮----
mod tests {
⋮----
fn test_detection_finding_serialization() {
⋮----
version: "1.8.0".to_string(),
⋮----
... (21 lines truncated)
</file>

<file path="crates/openshell-ocsf/src/events/http_activity.rs">
use crate::events::base_event::BaseEventData;
⋮----
pub struct HttpActivityEvent {
⋮----
impl Serialize for HttpActivityEvent {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
⋮----
let mut base_val = serde_json::to_value(&self.base).map_err(serde::ser::Error::custom)?;
⋮----
.as_object_mut()
.ok_or_else(|| serde::ser::Error::custom("expected object"))?;
⋮----
insert_optional!(obj, "http_request", self.http_request);
insert_optional!(obj, "http_response", self.http_response);
insert_optional!(obj, "src_endpoint", self.src_endpoint);
insert_optional!(obj, "dst_endpoint", self.dst_endpoint);
insert_optional!(obj, "proxy_endpoint", self.proxy_endpoint);
insert_optional!(obj, "actor", self.actor);
insert_optional!(obj, "firewall_rule", self.firewall_rule);
insert_enum_pair!(obj, "action", self.action);
insert_enum_pair!(obj, "disposition", self.disposition);
insert_optional!(obj, "observation_point_id", self.observation_point_id);
insert_optional!(
⋮----
base_val.serialize(serializer)
⋮----
mod tests {
⋮----
fn test_http_activity_serialization() {
⋮----
... (17 lines truncated)
</file>

<file path="crates/openshell-ocsf/src/events/mod.rs">
mod api_activity;
mod app_lifecycle;
pub(crate) mod base_event;
mod config_state_change;
mod detection_finding;
mod http_activity;
mod network_activity;
mod process_activity;
pub(crate) mod serde_helpers;
mod ssh_activity;
⋮----
pub use api_activity::ApiActivityEvent;
pub use app_lifecycle::ApplicationLifecycleEvent;
⋮----
pub use config_state_change::DeviceConfigStateChangeEvent;
pub use detection_finding::DetectionFindingEvent;
pub use http_activity::HttpActivityEvent;
pub use network_activity::NetworkActivityEvent;
pub use process_activity::ProcessActivityEvent;
pub use ssh_activity::SshActivityEvent;
⋮----
pub enum OcsfEvent {
⋮----
impl Serialize for OcsfEvent {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
⋮----
Self::NetworkActivity(e) => e.serialize(serializer),
Self::HttpActivity(e) => e.serialize(serializer),
Self::SshActivity(e) => e.serialize(serializer),
Self::ProcessActivity(e) => e.serialize(serializer),
... (131 lines truncated)
</file>

<file path="crates/openshell-ocsf/src/events/network_activity.rs">
use crate::events::base_event::BaseEventData;
⋮----
pub struct NetworkActivityEvent {
⋮----
impl Serialize for NetworkActivityEvent {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
⋮----
let mut base_val = serde_json::to_value(&self.base).map_err(serde::ser::Error::custom)?;
⋮----
.as_object_mut()
.ok_or_else(|| serde::ser::Error::custom("expected object"))?;
⋮----
insert_optional!(obj, "src_endpoint", self.src_endpoint);
insert_optional!(obj, "dst_endpoint", self.dst_endpoint);
insert_optional!(obj, "proxy_endpoint", self.proxy_endpoint);
insert_optional!(obj, "actor", self.actor);
insert_optional!(obj, "firewall_rule", self.firewall_rule);
insert_optional!(obj, "connection_info", self.connection_info);
insert_enum_pair!(obj, "action", self.action);
insert_enum_pair!(obj, "disposition", self.disposition);
insert_optional!(obj, "observation_point_id", self.observation_point_id);
insert_optional!(
⋮----
base_val.serialize(serializer)
⋮----
mod tests {
⋮----
fn test_network_activity_serialization() {
⋮----
version: "1.8.0".to_string(),
... (26 lines truncated)
</file>

<file path="crates/openshell-ocsf/src/events/process_activity.rs">
use crate::events::base_event::BaseEventData;
⋮----
pub struct ProcessActivityEvent {
⋮----
impl Serialize for ProcessActivityEvent {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
⋮----
let mut base_val = serde_json::to_value(&self.base).map_err(serde::ser::Error::custom)?;
⋮----
.as_object_mut()
.ok_or_else(|| serde::ser::Error::custom("expected object"))?;
⋮----
insert_required!(obj, "process", self.process);
insert_optional!(obj, "actor", self.actor);
insert_enum_pair!(obj, "launch_type", self.launch_type);
insert_optional!(obj, "exit_code", self.exit_code);
insert_enum_pair!(obj, "action", self.action);
insert_enum_pair!(obj, "disposition", self.disposition);
⋮----
base_val.serialize(serializer)
⋮----
mod tests {
⋮----
fn test_process_activity_serialization() {
⋮----
version: "1.8.0".to_string(),
⋮----
profiles: vec!["container".to_string()],
uid: Some("sandbox-abc123".to_string()),
⋮----
... (14 lines truncated)
</file>

<file path="crates/openshell-ocsf/src/events/serde_helpers.rs">
macro_rules! insert_enum_pair {
⋮----
macro_rules! insert_enum_pair_custom {
⋮----
macro_rules! insert_optional {
⋮----
macro_rules! insert_required {
⋮----
pub(crate) use insert_enum_pair;
pub(crate) use insert_enum_pair_custom;
pub(crate) use insert_optional;
pub(crate) use insert_required;
</file>

<file path="crates/openshell-ocsf/src/events/ssh_activity.rs">
use crate::events::base_event::BaseEventData;
⋮----
pub struct SshActivityEvent {
⋮----
impl Serialize for SshActivityEvent {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
⋮----
let mut base_val = serde_json::to_value(&self.base).map_err(serde::ser::Error::custom)?;
⋮----
.as_object_mut()
.ok_or_else(|| serde::ser::Error::custom("expected object"))?;
⋮----
insert_optional!(obj, "src_endpoint", self.src_endpoint);
insert_optional!(obj, "dst_endpoint", self.dst_endpoint);
insert_optional!(obj, "actor", self.actor);
insert_enum_pair_custom!(
⋮----
insert_optional!(obj, "protocol_ver", self.protocol_ver);
insert_enum_pair!(obj, "action", self.action);
insert_enum_pair!(obj, "disposition", self.disposition);
⋮----
base_val.serialize(serializer)
⋮----
mod tests {
⋮----
fn test_ssh_activity_serialization() {
⋮----
version: "1.8.0".to_string(),
⋮----
profiles: vec!["security_control".to_string()],
... (17 lines truncated)
</file>

<file path="crates/openshell-ocsf/src/format/downgrade.rs">
use serde_json::Value;
⋮----
pub fn downgrade_event(event: &mut Value, target_version: &str) -> bool {
let target = parse_version(target_version);
⋮----
if target >= parse_version(crate::OCSF_VERSION) {
⋮----
let Some(obj) = event.as_object_mut() else {
⋮----
if obj.remove(*field).is_some() {
⋮----
.get_mut("metadata")
.and_then(Value::as_object_mut)
.and_then(|m| m.get_mut("profiles"))
.and_then(Value::as_array_mut)
⋮----
let before = profiles.len();
profiles.retain(|p| !p.as_str().is_some_and(|s| STRIP_PROFILES_V1_3.contains(&s)));
if profiles.len() != before {
⋮----
if let Some(metadata) = obj.get_mut("metadata").and_then(Value::as_object_mut) {
⋮----
.get("version")
.and_then(Value::as_str)
.unwrap_or(crate::OCSF_VERSION)
.to_string();
metadata.insert(
"version".to_string(),
Value::String(target_version.to_string()),
⋮----
... (75 lines truncated)
</file>

<file path="crates/openshell-ocsf/src/format/jsonl.rs">
use crate::events::OcsfEvent;
⋮----
impl OcsfEvent {
⋮----
pub fn to_json(&self) -> Result<serde_json::Value, serde_json::Error> {
⋮----
pub fn to_json_line(&self) -> Result<String, serde_json::Error> {
⋮----
line.push('\n');
Ok(line)
⋮----
mod tests {
use crate::enums::SeverityId;
use crate::events::base_event::BaseEventData;
⋮----
fn test_event() -> OcsfEvent {
⋮----
version: "1.8.0".to_string(),
⋮----
profiles: vec!["container".to_string()],
uid: Some("sandbox-abc123".to_string()),
⋮----
base.set_time(1_742_054_400_000);
base.set_message("Test event");
⋮----
fn test_to_json_has_required_fields() {
let event = test_event();
let json = event.to_json().unwrap();
⋮----
assert_eq!(json["class_uid"], 0);
... (26 lines truncated)
</file>

<file path="crates/openshell-ocsf/src/format/mod.rs">
pub mod downgrade;
pub mod jsonl;
pub mod shorthand;
</file>

<file path="crates/openshell-ocsf/src/format/shorthand.rs">
use crate::events::OcsfEvent;
use crate::events::base_event::BaseEventData;
use crate::objects::Url;
⋮----
pub fn format_ts(time_ms: i64) -> String {
⋮----
match Utc.timestamp_millis_opt(time_ms) {
MappedLocalTime::Single(dt) => dt.format("%H:%M:%S%.3f").to_string(),
_ => "??:??:??.???".to_string(),
⋮----
pub fn severity_char(severity_id: u8) -> char {
⋮----
pub fn severity_tag(severity_id: u8) -> &'static str {
⋮----
/// Max length for the reason text in `[reason:...]` before truncation. A
/// denial reason carries the full destination endpoint plus the rejecting
⋮----
/// denial reason carries the full destination endpoint plus the rejecting
/// policy name (e.g. `endpoint host.example:443 not in policy <name>`), so the
⋮----
/// policy name (e.g. `endpoint host.example:443 not in policy <name>`), so the
/// budget has to be wide enough to keep the port and policy name readable in
⋮----
/// budget has to be wide enough to keep the port and policy name readable in
/// the shorthand denial logs; 80 chars cut a typical reason mid-endpoint.
⋮----
/// the shorthand denial logs; 80 chars cut a typical reason mid-endpoint.
const MAX_REASON_LEN: usize = 256;
⋮----
/// Truncate `text` to at most `max` bytes at a UTF-8 char boundary, appending
... (513 lines truncated)
</file>

<file path="crates/openshell-ocsf/src/objects/ai_model.rs">
pub struct AiModel {
⋮----
impl AiModel {
⋮----
pub fn new(name: impl Into<String>, ai_provider: impl Into<String>) -> Self {
⋮----
name: name.into(),
ai_provider: ai_provider.into(),
⋮----
mod tests {
⋮----
fn test_ai_model_serialization() {
⋮----
let json = serde_json::to_value(&model).unwrap();
assert_eq!(json["name"], "claude-3-haiku");
assert_eq!(json["ai_provider"], "anthropic");
assert!(json.get("version").is_none());
assert!(json.get("uid").is_none());
⋮----
fn test_ai_model_roundtrip() {
⋮----
name: "gpt-4o".to_string(),
ai_provider: "openai".to_string(),
version: Some("2024-05-13".to_string()),
uid: Some("model-123".to_string()),
⋮----
let json = serde_json::to_string(&model).unwrap();
let deserialized: AiModel = serde_json::from_str(&json).unwrap();
assert_eq!(deserialized.name, "gpt-4o");
assert_eq!(deserialized.ai_provider, "openai");
... (3 lines truncated)
</file>

<file path="crates/openshell-ocsf/src/objects/api.rs">
pub struct Api {
⋮----
impl Api {
⋮----
pub fn new(operation: impl Into<String>) -> Self {
⋮----
operation: operation.into(),
⋮----
mod tests {
⋮----
fn test_api_serialization() {
⋮----
let json = serde_json::to_value(&api).unwrap();
assert_eq!(json["operation"], "POST /v1/messages");
assert!(json.get("version").is_none());
</file>

<file path="crates/openshell-ocsf/src/objects/attack.rs">
pub struct Attack {
⋮----
pub struct Technique {
⋮----
pub struct Tactic {
⋮----
impl Attack {
⋮----
pub fn mitre(
⋮----
uid: technique_uid.to_string(),
name: technique_name.to_string(),
⋮----
tactic: Some(Tactic {
uid: tactic_uid.to_string(),
name: tactic_name.to_string(),
⋮----
mod tests {
⋮----
fn test_attack_mitre() {
⋮----
let json = serde_json::to_value(&attack).unwrap();
assert_eq!(json["technique"]["uid"], "T1550");
assert_eq!(
⋮----
assert_eq!(json["tactic"]["uid"], "TA0008");
assert_eq!(json["tactic"]["name"], "Lateral Movement");
</file>

<file path="crates/openshell-ocsf/src/objects/connection.rs">
pub struct ConnectionInfo {
⋮----
impl ConnectionInfo {
⋮----
pub fn new(protocol: &str) -> Self {
⋮----
protocol_name: protocol.to_string(),
⋮----
mod tests {
⋮----
fn test_connection_info() {
⋮----
let json = serde_json::to_value(&info).unwrap();
assert_eq!(json["protocol_name"], "tcp");
</file>

<file path="crates/openshell-ocsf/src/objects/container.rs">
pub struct Container {
⋮----
pub struct Image {
⋮----
mod tests {
⋮----
fn test_container_serialization() {
⋮----
name: "my-sandbox".to_string(),
uid: Some("sandbox-abc123".to_string()),
image: Some(Image {
name: "ghcr.io/openshell/sandbox:latest".to_string(),
⋮----
let json = serde_json::to_value(&container).unwrap();
assert_eq!(json["name"], "my-sandbox");
assert_eq!(json["uid"], "sandbox-abc123");
assert_eq!(json["image"]["name"], "ghcr.io/openshell/sandbox:latest");
⋮----
fn test_container_minimal() {
⋮----
name: "test".to_string(),
⋮----
assert!(json.get("uid").is_none());
assert!(json.get("image").is_none());
</file>

<file path="crates/openshell-ocsf/src/objects/device.rs">
use crate::enums::DeviceTypeId;
⋮----
pub struct Device {
⋮----
pub struct OsInfo {
⋮----
impl OsInfo {
⋮----
pub fn pretty_name(os: &str) -> &str {
⋮----
impl Device {
⋮----
pub fn linux(hostname: &str) -> Self {
⋮----
hostname: hostname.to_string(),
⋮----
type_label: "Sandbox".to_string(),
os: Some(OsInfo {
name: "Linux".to_string(),
⋮----
pub fn windows(hostname: &str) -> Self {
⋮----
name: "Windows".to_string(),
⋮----
pub fn for_current_os(hostname: &str) -> Self {
⋮----
pub fn gateway(hostname: &str, name: &str) -> Self {
⋮----
type_label: DeviceTypeId::Server.to_string(),
name: Some(name.to_string()),
... (57 lines truncated)
</file>

<file path="crates/openshell-ocsf/src/objects/endpoint.rs">
use std::net::IpAddr;
⋮----
pub struct Endpoint {
⋮----
impl Endpoint {
⋮----
pub fn from_domain(name: &str, port: u16) -> Self {
⋮----
domain: Some(name.to_string()),
⋮----
port: Some(port),
⋮----
pub fn from_ip(addr: IpAddr, port: u16) -> Self {
⋮----
ip: Some(addr.to_string()),
⋮----
pub fn from_ip_str(addr: &str, port: u16) -> Self {
⋮----
pub fn domain_or_ip(&self) -> &str {
⋮----
.as_deref()
.or(self.ip.as_deref())
.unwrap_or("unknown")
⋮----
mod tests {
⋮----
fn test_endpoint_domain() {
⋮----
assert_eq!(ep.domain_or_ip(), "api.example.com");
let json = serde_json::to_value(&ep).unwrap();
... (11 lines truncated)
</file>

<file path="crates/openshell-ocsf/src/objects/finding.rs">
pub struct FindingInfo {
⋮----
impl FindingInfo {
⋮----
pub fn new(uid: &str, title: &str) -> Self {
⋮----
uid: uid.to_string(),
title: title.to_string(),
⋮----
pub fn with_desc(mut self, desc: &str) -> Self {
self.desc = Some(desc.to_string());
⋮----
pub struct Evidence {
⋮----
impl Evidence {
⋮----
pub fn from_pairs(pairs: &[(&str, &str)]) -> Self {
⋮----
map.insert(
(*key).to_string(),
serde_json::Value::String((*value).to_string()),
⋮----
data: Some(serde_json::Value::Object(map)),
⋮----
pub struct Remediation {
⋮----
impl Remediation {
⋮----
pub fn new(desc: &str) -> Self {
⋮----
... (23 lines truncated)
</file>

<file path="crates/openshell-ocsf/src/objects/firewall_rule.rs">
pub struct FirewallRule {
⋮----
impl FirewallRule {
⋮----
pub fn new(name: &str, rule_type: &str) -> Self {
⋮----
name: name.to_string(),
rule_type: rule_type.to_string(),
⋮----
mod tests {
⋮----
fn test_firewall_rule_serialization() {
⋮----
let json = serde_json::to_value(&rule).unwrap();
assert_eq!(json["name"], "default-egress");
assert_eq!(json["type"], "mechanistic");
</file>

<file path="crates/openshell-ocsf/src/objects/http.rs">
use crate::enums::HttpMethod;
⋮----
pub struct HttpRequest {
⋮----
pub struct HttpResponse {
⋮----
pub struct Url {
⋮----
impl Url {
⋮----
pub fn new(scheme: &str, hostname: &str, path: &str, port: u16) -> Self {
⋮----
scheme: Some(scheme.to_string()),
hostname: Some(hostname.to_string()),
path: Some(path.to_string()),
port: Some(port),
⋮----
pub fn to_display_string(&self) -> String {
let scheme = self.scheme.as_deref().unwrap_or("https");
let hostname = self.hostname.as_deref().unwrap_or("unknown");
let path = self.path.as_deref().unwrap_or("/");
⋮----
Some(p) => format!(":{p}"),
⋮----
format!("{scheme}://{hostname}{port_suffix}{path}")
⋮----
impl HttpRequest {
⋮----
pub fn new(method: &str, url: Url) -> Self {
⋮----
... (41 lines truncated)
</file>

<file path="crates/openshell-ocsf/src/objects/metadata.rs">
pub struct Metadata {
⋮----
pub struct Product {
⋮----
impl Product {
⋮----
pub fn openshell_sandbox(version: &str) -> Self {
⋮----
name: "OpenShell Sandbox Supervisor".to_string(),
vendor_name: "OpenShell".to_string(),
version: Some(version.to_string()),
⋮----
pub fn openshell_gateway(version: &str) -> Self {
⋮----
name: "OpenShell Gateway".to_string(),
⋮----
mod tests {
⋮----
fn test_metadata_serialization() {
⋮----
version: "1.8.0".to_string(),
⋮----
profiles: vec!["security_control".to_string(), "container".to_string()],
uid: Some("sandbox-abc123".to_string()),
⋮----
let json = serde_json::to_value(&metadata).unwrap();
assert_eq!(json["version"], "1.8.0");
assert_eq!(json["product"]["name"], "OpenShell Sandbox Supervisor");
assert_eq!(json["product"]["vendor_name"], "OpenShell");
assert!(json.get("log_source").is_none());
... (11 lines truncated)
</file>

<file path="crates/openshell-ocsf/src/objects/mod.rs">
mod ai_model;
mod api;
mod attack;
mod connection;
mod container;
mod device;
mod endpoint;
mod finding;
mod firewall_rule;
mod http;
mod metadata;
mod process;
⋮----
pub use ai_model::AiModel;
pub use api::Api;
⋮----
pub use connection::ConnectionInfo;
⋮----
pub use endpoint::Endpoint;
⋮----
pub use firewall_rule::FirewallRule;
</file>

<file path="crates/openshell-ocsf/src/objects/process.rs">
pub struct Process {
⋮----
impl Process {
⋮----
pub fn new(name: &str, pid: i64) -> Self {
⋮----
name: name.to_string(),
⋮----
pub fn with_cmd_line(mut self, cmd_line: &str) -> Self {
self.cmd_line = Some(cmd_line.to_string());
⋮----
pub fn with_parent(mut self, parent: Self) -> Self {
self.parent_process = Some(Box::new(parent));
⋮----
pub fn from_bypass(binary: &str, pid: &str, ancestors: &str) -> Self {
let pid = pid.parse::<i64>().unwrap_or(0);
⋮----
let parts: Vec<&str> = ancestors.split(" -> ").collect();
if parts.len() >= 2 {
let mut parent = Self::new(parts[parts.len() - 1], 0);
for ancestor in parts[..parts.len() - 1].iter().rev() {
parent = Self::new(ancestor, 0).with_parent(parent);
⋮----
proc.parent_process = Some(Box::new(parent));
} else if !ancestors.is_empty() && ancestors != binary {
proc.parent_process = Some(Box::new(Self::new(ancestors, 0)));
⋮----
pub struct Actor {
⋮----
mod tests {
... (37 lines truncated)
</file>

<file path="crates/openshell-ocsf/src/tracing_layers/event_bridge.rs">
use crate::events::OcsfEvent;
⋮----
pub fn clone_current_event() -> Option<OcsfEvent> {
CURRENT_EVENT.with(|cell| cell.borrow().clone())
⋮----
pub fn emit_ocsf_event(event: OcsfEvent) {
⋮----
set_current_event(event);
⋮----
clear_current_event();
⋮----
pub fn set_current_event(event: OcsfEvent) {
CURRENT_EVENT.with(|cell| {
*cell.borrow_mut() = Some(event);
⋮----
pub fn clear_current_event() {
⋮----
cell.borrow_mut().take();
⋮----
pub fn emit_ocsf_event_routed(sandbox_id: &str, event: OcsfEvent) {
let message = event.format_shorthand();
⋮----
macro_rules! ocsf_emit {
⋮----
mod tests {
⋮----
use crate::enums::SeverityId;
use crate::events::base_event::BaseEventData;
⋮----
fn test_event() -> OcsfEvent {
... (59 lines truncated)
</file>

<file path="crates/openshell-ocsf/src/tracing_layers/jsonl_layer.rs">
use std::io::Write;
use std::sync::Arc;
use std::sync::Mutex;
⋮----
use tracing::Subscriber;
use tracing_subscriber::Layer;
use tracing_subscriber::layer::Context;
⋮----
use crate::format::downgrade::downgrade_event;
⋮----
pub struct OcsfJsonlLayer<W: Write + Send + 'static> {
⋮----
pub fn new(writer: W) -> Self {
⋮----
pub fn with_enabled_flag(mut self, flag: Arc<AtomicBool>) -> Self {
self.enabled = Some(flag);
⋮----
pub fn with_target_version(mut self, version: Arc<Mutex<String>>) -> Self {
self.target_version = Some(version);
⋮----
fn on_event(&self, event: &tracing::Event<'_>, _ctx: Context<'_, S>) {
if event.metadata().target() != OCSF_TARGET {
⋮----
// If an enabled flag is set and it reads `false`, skip writing.
⋮----
&& !flag.load(Ordering::Relaxed)
⋮----
if let Some(ocsf_event) = clone_current_event()
&& let Ok(mut w) = self.writer.lock()
⋮----
... (15 lines truncated)
</file>

<file path="crates/openshell-ocsf/src/tracing_layers/mod.rs">
pub(crate) mod event_bridge;
mod jsonl_layer;
mod shorthand_layer;
⋮----
pub use jsonl_layer::OcsfJsonlLayer;
pub use shorthand_layer::OcsfShorthandLayer;
</file>

<file path="crates/openshell-ocsf/src/tracing_layers/shorthand_layer.rs">
use std::io::Write;
use std::sync::Mutex;
⋮----
use chrono::Utc;
use tracing::Subscriber;
use tracing_subscriber::Layer;
use tracing_subscriber::layer::Context;
⋮----
pub struct OcsfShorthandLayer<W: Write + Send + 'static> {
⋮----
/// Whether to include non-OCSF events in the output.
    include_non_ocsf: bool,
⋮----
pub fn new(writer: W) -> Self {
⋮----
pub fn with_non_ocsf(mut self, include: bool) -> Self {
⋮----
fn on_event(&self, event: &tracing::Event<'_>, _ctx: Context<'_, S>) {
let meta = event.metadata();
⋮----
let ts = Utc::now().format("%Y-%m-%dT%H:%M:%S%.3fZ");
⋮----
if meta.target() == OCSF_TARGET {
// This is an OCSF event — clone from thread-local (non-consuming)
if let Some(ocsf_event) = clone_current_event() {
let line = ocsf_event.format_shorthand();
if let Ok(mut w) = self.writer.lock() {
let _ = writeln!(w, "{ts} OCSF {line}");
⋮----
// Fallback: format non-OCSF events with basic format
... (54 lines truncated)
</file>

<file path="crates/openshell-ocsf/src/validation/mod.rs">
pub mod schema;
</file>

<file path="crates/openshell-ocsf/src/validation/schema.rs">
use serde_json::Value;
use std::fs;
⋮----
pub fn load_class_schema(class: &str) -> Value {
let path = format!(
⋮----
fs::read_to_string(&path).unwrap_or_else(|_| panic!("Missing vendored schema: {path}"));
serde_json::from_str(&data).unwrap_or_else(|e| panic!("Invalid JSON in {path}: {e}"))
⋮----
pub fn load_object_schema(object: &str) -> Value {
⋮----
pub fn validate_required_fields(event: &Value, schema: &Value) {
let attrs = match schema.get("attributes") {
⋮----
.iter()
.map(|(k, v)| (k.clone(), v.clone()))
⋮----
.filter_map(|item| item.as_object())
.flat_map(|obj| obj.iter().map(|(k, v)| (k.clone(), v.clone())))
⋮----
.get("constraints")
.and_then(|constraints| constraints.get("at_least_one"))
.and_then(Value::as_array)
⋮----
assert!(
⋮----
let is_required = def.get("requirement").and_then(|r| r.as_str()) == Some("required");
let is_profile_field = def.get("profile").is_some() || def.get("profiles").is_some();
⋮----
pub fn validate_enum_value(event: &Value, field: &str, schema: &Value) {
... (27 lines truncated)
</file>

<file path="crates/openshell-ocsf/src/ctx.rs">
hostname: "test".to_string(),
product_version: env!("CARGO_PKG_VERSION").to_string(),
⋮----
pub fn set_ctx(ctx: EventContext) -> bool {
OCSF_CTX.set(ctx).is_ok()
⋮----
pub fn ctx() -> &'static EventContext {
OCSF_CTX.get().unwrap_or(&OCSF_CTX_FALLBACK)
</file>

<file path="crates/openshell-ocsf/src/lib.rs">
pub mod builders;
pub mod ctx;
pub mod enums;
pub mod events;
pub mod format;
pub mod objects;
pub mod tracing_layers;
⋮----
pub mod validation;
</file>

<file path="crates/openshell-ocsf/Cargo.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

[package]
name = "openshell-ocsf"
description = "OCSF v1.8.0 event types, formatters, and tracing layers for OpenShell sandbox logging"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true

[features]
# Share vendored-schema assertions with producer regression tests.
test-support = []

[dependencies]
chrono = { version = "0.4", features = ["serde"] }
serde = { workspace = true }
serde_json = { workspace = true }
serde_repr = "0.1"
tracing = { workspace = true }
uuid = { workspace = true }
tracing-subscriber = { workspace = true }

[dev-dependencies]
tracing-subscriber = { workspace = true, features = ["env-filter", "json"] }

[lints]
workspace = true
... (1 lines truncated)
</file>

<file path="crates/openshell-otel/src/driver.rs">
use std::future::Future;
use std::pin::Pin;
⋮----
use futures::Stream;
⋮----
use tracing_subscriber::EnvFilter;
⋮----
use tracing_subscriber::registry::LookupSpan;
⋮----
macro_rules! compute_driver_tracing {
⋮----
pub struct ComputeDriverTracing {
⋮----
impl ComputeDriverTracing {
⋮----
pub const fn new(service_name: &'static str, crate_target_prefix: &'static str) -> Self {
⋮----
pub const fn service_name(self) -> &'static str {
⋮----
/// Canonical compute-driver name derived from `service.name`.
    #[must_use]
pub fn compute_driver(self) -> &'static str {
⋮----
.strip_prefix("openshell-driver-")
.unwrap_or(self.service_name)
⋮----
pub const fn in_process_target(self) -> &'static str {
⋮----
/// Targets routed to this driver's provider when it runs in-process.
    #[must_use]
... (89 lines truncated)
</file>

<file path="crates/openshell-otel/src/grpc.rs">
use futures::Stream;
use http::Request;
⋮----
use opentelemetry_sdk::propagation::TraceContextPropagator;
use tower_http::classify::GrpcFailureClass;
⋮----
use tracing::Span;
⋮----
pub struct TracedGrpcStream<S> {
⋮----
pub fn new(inner: S, span: Span) -> Self {
⋮----
impl<S, T> Stream for TracedGrpcStream<S>
⋮----
type Item = Result<T, tonic::Status>;
⋮----
fn poll_next(
⋮----
let this = self.get_mut();
let span = this.span.clone();
let _entered = span.enter();
let result = std::pin::Pin::new(&mut this.inner).poll_next(cx);
⋮----
record_grpc_status(&this.span, status.code());
⋮----
record_grpc_status(&this.span, tonic::Code::Ok);
⋮----
/// Low-cardinality semantic-convention identity for a compute-driver RPC.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ComputeDriverRpc {
... (121 lines truncated)
</file>

<file path="crates/openshell-otel/src/lib.rs">
mod driver;
mod grpc;
mod propagation;
⋮----
use opentelemetry::KeyValue;
⋮----
use opentelemetry_sdk::Resource;
use opentelemetry_sdk::trace::SdkTracer;
pub use opentelemetry_sdk::trace::SdkTracerProvider;
use tracing::Subscriber;
use tracing_opentelemetry::OpenTelemetryLayer;
⋮----
use tracing_subscriber::registry::LookupSpan;
⋮----
pub fn gateway_resource_attributes(
⋮----
if let Some(name) = gateway_name.map(str::trim).filter(|name| !name.is_empty()) {
attributes.push(KeyValue::new("openshell.gateway.name", name.to_string()));
⋮----
.map(str::trim)
.filter(|driver| !driver.is_empty())
⋮----
attributes.push(KeyValue::new(
⋮----
driver.to_string(),
⋮----
pub fn mark_error(span: &tracing::Span) {
span.record("otel.status_code", "ERROR");
⋮----
pub fn record_error_result<T, E>(result: Result<T, E>) -> Result<T, E> {
... (227 lines truncated)
</file>

<file path="crates/openshell-otel/src/propagation.rs">
use std::collections::BTreeMap;
⋮----
use http::HeaderMap;
⋮----
use opentelemetry_sdk::propagation::TraceContextPropagator;
⋮----
pub struct HeaderMapExtractor<'a>(&'a HeaderMap);
⋮----
pub fn new(headers: &'a HeaderMap) -> Self {
Self(headers)
⋮----
impl Extractor for HeaderMapExtractor<'_> {
fn get(&self, key: &str) -> Option<&str> {
self.0.get(key).and_then(|value| value.to_str().ok())
⋮----
fn keys(&self) -> Vec<&str> {
self.0.keys().map(http::HeaderName::as_str).collect()
⋮----
pub struct MetadataMapInjector<'a>(&'a mut tonic::metadata::MetadataMap);
⋮----
pub fn new(metadata: &'a mut tonic::metadata::MetadataMap) -> Self {
Self(metadata)
⋮----
impl Injector for MetadataMapInjector<'_> {
fn set(&mut self, key: &str, value: String) {
⋮----
let Ok(value) = value.parse() else {
⋮----
self.0.insert(key, value);
⋮----
... (39 lines truncated)
</file>

<file path="crates/openshell-otel/Cargo.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

[package]
name = "openshell-otel"
description = "Shared OpenTelemetry trace export support for OpenShell services"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true

[dependencies]
futures = { workspace = true }
http = { workspace = true }
opentelemetry = { workspace = true }
opentelemetry_sdk = { workspace = true }
opentelemetry-otlp = { workspace = true }
thiserror = { workspace = true }
tracing = { workspace = true }
tracing-opentelemetry = { workspace = true }
tracing-subscriber = { workspace = true }
tonic = { workspace = true }
tower-http = { workspace = true }

[dev-dependencies]
opentelemetry_sdk = { workspace = true, features = ["testing"] }
tokio = { workspace = true }

[lints]
... (2 lines truncated)
</file>

<file path="crates/openshell-otel-test-support/src/lib.rs">
use std::time::Duration;
⋮----
use opentelemetry_proto::tonic::trace::v1::Span;
⋮----
pub async fn tracing_test_lock() -> tokio::sync::MutexGuard<'static, ()> {
⋮----
.expect("test tracing subscriber installs once");
⋮----
let guard = LOCK.lock().await;
⋮----
/// Verify one compute-driver descriptor exports spans and shared resources.
pub async fn assert_compute_driver_tracing(
⋮----
pub async fn assert_compute_driver_tracing(
⋮----
let _tracing_lock = tracing_test_lock().await;
⋮----
let (provider, error) = descriptor.provider_for(
Some(collector.endpoint()),
⋮----
Some("test-gateway"),
Some(descriptor.compute_driver()),
⋮----
assert!(error.is_none(), "valid OTLP endpoint should configure");
let provider = provider.expect("provider");
let subscriber = tracing_subscriber::registry().with(descriptor.layer(&provider));
⋮----
drop(span.enter());
drop(span);
⋮----
... (64 lines truncated)
</file>

<file path="crates/openshell-otel-test-support/Cargo.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

[package]
name = "openshell-otel-test-support"
description = "Shared OTLP collector fixture for OpenShell tracing tests"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true

[dependencies]
openshell-otel = { path = "../openshell-otel" }
opentelemetry-proto = { version = "0.32", default-features = false, features = ["gen-tonic", "trace"] }
tokio = { workspace = true }
tokio-stream = { workspace = true }
tonic = { workspace = true }
tracing = { workspace = true }
tracing-subscriber = { workspace = true }

[lints]
workspace = true
</file>

<file path="crates/openshell-policy/src/ambiguity.rs">
use std::fmt;
⋮----
pub struct EndpointAmbiguity {
⋮----
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
⋮----
struct EndpointRef<'a> {
⋮----
pub fn find_endpoint_ambiguities(policy: &SandboxPolicy) -> Vec<EndpointAmbiguity> {
⋮----
.iter()
.flat_map(|(key, rule)| {
let policy_name = if rule.name.is_empty() {
key.as_str()
⋮----
rule.name.as_str()
⋮----
.enumerate()
.map(move |(index, endpoint)| EndpointRef {
⋮----
for left_index in 0..endpoints.len() {
for right_index in (left_index + 1)..endpoints.len() {
⋮----
let overlapping_ports = overlapping_ports(left.endpoint, right.endpoint);
if overlapping_ports.is_empty()
|| !host_patterns_overlap(&left.endpoint.host, &right.endpoint.host)
⋮----
let mut conflicts = connection_conflicts(left.endpoint, right.endpoint);
if endpoint_contributes_request_pipeline_metadata(left.endpoint)
... (479 lines truncated)
</file>

<file path="crates/openshell-policy/src/compose.rs">
pub struct ProviderPolicyLayer {
⋮----
pub fn is_provider_rule_name(rule_name: &str) -> bool {
rule_name.starts_with(PROVIDER_RULE_NAME_PREFIX)
⋮----
pub fn provider_rule_name(provider_name: &str) -> String {
⋮----
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || c == '_' {
c.to_ascii_lowercase()
⋮----
.trim_matches('_')
.to_string();
⋮----
if sanitized.is_empty() {
format!("{PROVIDER_RULE_NAME_PREFIX}unnamed")
⋮----
format!("{PROVIDER_RULE_NAME_PREFIX}{sanitized}")
⋮----
pub fn strip_provider_rule_names(policy: &mut SandboxPolicy) -> bool {
let original_len = policy.network_policies.len();
⋮----
.retain(|key, _| !is_provider_rule_name(key));
policy.network_policies.len() != original_len
⋮----
pub fn compose_effective_policy(
⋮----
let mut effective = source_policy.clone();
⋮----
... (71 lines truncated)
</file>

<file path="crates/openshell-policy/src/l7_validate.rs">
pub fn network_tls_mode_from_str(value: &str) -> Option<NetworkTlsMode> {
⋮----
"" => Some(NetworkTlsMode::Unspecified),
"skip" => Some(NetworkTlsMode::Skip),
"terminate" => Some(NetworkTlsMode::Terminate),
"passthrough" => Some(NetworkTlsMode::Passthrough),
⋮----
pub fn network_tls_mode_to_str(value: i32) -> Option<&'static str> {
match NetworkTlsMode::try_from(value).ok()? {
NetworkTlsMode::Unspecified => Some(""),
NetworkTlsMode::Skip => Some("skip"),
NetworkTlsMode::Terminate => Some("terminate"),
NetworkTlsMode::Passthrough => Some("passthrough"),
⋮----
pub fn network_enforcement_mode_from_str(value: &str) -> Option<NetworkEnforcementMode> {
⋮----
"" => Some(NetworkEnforcementMode::Unspecified),
"enforce" => Some(NetworkEnforcementMode::Enforce),
"audit" => Some(NetworkEnforcementMode::Audit),
⋮----
pub fn network_enforcement_mode_to_str(value: i32) -> Option<&'static str> {
match NetworkEnforcementMode::try_from(value).ok()? {
NetworkEnforcementMode::Unspecified => Some(""),
NetworkEnforcementMode::Enforce => Some("enforce"),
NetworkEnforcementMode::Audit => Some("audit"),
⋮----
pub fn network_access_preset_from_str(value: &str) -> Option<NetworkAccessPreset> {
⋮----
"" => Some(NetworkAccessPreset::Unspecified),
"read-only" => Some(NetworkAccessPreset::ReadOnly),
... (290 lines truncated)
</file>

<file path="crates/openshell-policy/src/lib.rs">
mod compose;
mod l7_validate;
mod merge;
mod middleware;
⋮----
use std::fmt;
use std::net::IpAddr;
use std::path::Path;
⋮----
mod ambiguity;
⋮----
use hickory_proto::rr::Name;
⋮----
pub use middleware::middleware_host_matches;
⋮----
fn json_rpc_config_from_proto(max_body_bytes: u32) -> Option<JsonRpcConfigDef> {
(max_body_bytes > 0).then_some(JsonRpcConfigDef { max_body_bytes })
⋮----
fn mcp_config_from_proto(max_body_bytes: u32, mcp: Option<&McpOptions>) -> Option<McpConfigDef> {
⋮----
.map(|config| config.versions.clone())
.unwrap_or_default();
canonicalize_mcp_versions(&mut versions);
let strict_tool_names = mcp.and_then(|config| config.strict_tool_names);
let allow_all_known_mcp_methods = mcp.and_then(|config| config.allow_all_known_mcp_methods);
(!versions.is_empty()
⋮----
|| strict_tool_names.is_some()
|| allow_all_known_mcp_methods.is_some())
.then_some(McpConfigDef {
... (1810 lines truncated)
</file>

<file path="crates/openshell-policy/src/merge.rs">
pub fn canonicalize_advisor_add_rule(
⋮----
if incoming_rule.endpoints.len() != 1 || incoming_rule.binaries.is_empty() {
return Ok((requested_rule_name.to_string(), incoming_rule.clone()));
⋮----
let incoming_ports = canonical_ports(incoming_endpoint);
if incoming_endpoint.host.trim().is_empty() || incoming_ports.len() != 1 {
⋮----
.values()
.flat_map(|rule| &rule.endpoints)
.filter(|endpoint| {
endpoint.host.eq_ignore_ascii_case(&incoming_endpoint.host)
&& canonical_ports(endpoint).contains(&port)
⋮----
.cloned()
.map(|mut endpoint| {
⋮----
endpoint.ports = vec![port];
normalize_endpoint(&mut endpoint);
⋮----
if !unique_contracts.contains(&contract) {
unique_contracts.push(contract);
⋮----
let Some(contract) = unique_contracts.first().cloned() else {
⋮----
if unique_contracts.len() != 1 {
return Err(format!(
⋮----
.iter()
.filter(|(name, _)| !is_provider_rule_name(name))
... (2089 lines truncated)
</file>

<file path="crates/openshell-policy/src/middleware.rs">
use serde::Deserialize;
⋮----
use super::PolicyViolation;
⋮----
struct SupervisorRuntimePolicyJson {
⋮----
struct SupervisorRuntimeNetworkPolicyJson {
⋮----
struct SupervisorRuntimeEndpointJson {
⋮----
pub fn into_proto(
⋮----
.into_iter()
.map(|(key, definition)| {
Ok((
key.clone(),
⋮----
name: if definition.name.is_empty() {
⋮----
config: Some(json_object_to_struct(
definition.config.into_iter().collect(),
⋮----
.map(|selector| MiddlewareEndpointSelector {
⋮----
.collect()
⋮----
pub fn from_proto(
⋮----
.iter()
.map(|(name, middleware)| {
... (103 lines truncated)
</file>

<file path="crates/openshell-policy/testdata/mcp-version-profiles.yaml">
version: 1
network_policies:
  versioned_mcp:
    name: versioned_mcp
    endpoints:
      - host: mcp.example.com
        port: 443
        protocol: mcp
        enforcement: enforce
        mcp:
          versions:
            - "2026-07-28"
            - "2025-11-25"
            - "2025-03-26"
            - "2025-06-18"
        rules:
          - allow:
              method: initialize
    binaries:
      - path: /usr/bin/mcp-client
</file>

<file path="crates/openshell-policy/Cargo.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

[package]
name = "openshell-policy"
description = "Shared sandbox policy parsing and defaults for OpenShell"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true

[dependencies]
hickory-proto = { workspace = true }
openshell-core = { path = "../openshell-core", default-features = false }
openshell-policy-schema = { path = "../openshell-policy-schema" }
serde = { workspace = true }
serde_json = { workspace = true }
miette = { workspace = true }
prost-types = { workspace = true }

[lints]
workspace = true
</file>

<file path="crates/openshell-policy-schema/src/lib.rs">
use std::fmt;
use std::fs::File;
use std::io::Read;
⋮----
use std::str::FromStr;
⋮----
pub enum McpProtocolVersion {
⋮----
impl McpProtocolVersion {
⋮----
/// Return the exact MCP protocol identifier accepted in policy.
    #[must_use]
pub const fn as_str(self) -> &'static str {
⋮----
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
⋮----
impl FromStr for McpProtocolVersion {
type Err = ParseMcpProtocolVersionError;
⋮----
fn from_str(value: &str) -> std::result::Result<Self, Self::Err> {
⋮----
"2025-03-26" => Ok(Self::V2025_03_26),
"2025-06-18" => Ok(Self::V2025_06_18),
"2025-11-25" => Ok(Self::V2025_11_25),
"2026-07-28" => Ok(Self::V2026_07_28),
_ => Err(ParseMcpProtocolVersionError {
value: value.to_owned(),
⋮----
/// Error returned for a revision outside the exact policy vocabulary.
... (459 lines truncated)
</file>

<file path="crates/openshell-policy-schema/Cargo.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

[package]
name = "openshell-policy-schema"
description = "Canonical authored policy schema for OpenShell"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true

[dependencies]
miette = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
serde_yml = { workspace = true }
thiserror = { workspace = true }

[lints]
workspace = true
</file>

<file path="crates/openshell-prover/registry/apis/github.yaml">
api: github
host: api.github.com
port: 443
credential_type: github-pat
scope_capabilities:
  repo:
    - { method: GET, path: "/repos/**", action: read_repo }
    - { method: GET, path: "/user/repos", action: list_repos }
    - { method: POST, path: "/repos/*/issues", action: create_issue }
    - { method: POST, path: "/repos/*/issues/*/comments", action: comment_issue }
    - { method: POST, path: "/repos/*/pulls", action: create_pr }
    - { method: PUT, path: "/repos/*/contents/**", action: write_file }
    - { method: DELETE, path: "/repos/*/contents/**", action: delete_file }
    - { method: DELETE, path: "/repos/*/*", action: delete_repo }
    - { method: POST, path: "/repos/*/git/**", action: write_git_data }
    - { method: POST, path: "/repos/*/forks", action: fork_repo }
    - { method: PATCH, path: "/repos/*/*", action: update_repo }
    - { method: POST, path: "/repos/*/releases", action: create_release }
    - { method: POST, path: "/repos/*/dispatches", action: trigger_workflow }
  "read:org":
    - { method: GET, path: "/orgs/**", action: read_org }
    - { method: GET, path: "/user/orgs", action: list_orgs }
  "write:org":
    - { method: GET, path: "/orgs/**", action: read_org }
    - { method: POST, path: "/orgs/*/repos", action: create_org_repo }
    - { method: PUT, path: "/orgs/*/memberships/**", action: manage_members }
  gist:
    - { method: GET, path: "/gists/**", action: read_gists }
    - { method: POST, path: "/gists", action: create_gist }
    - { method: PATCH, path: "/gists/*", action: update_gist }
... (31 lines truncated)
</file>

<file path="crates/openshell-prover/registry/binaries/claude.yaml">
binary: /usr/local/bin/claude
description: "Claude Code CLI — AI coding agent"
protocols:
  - name: anthropic-api
    transport: https
    description: "Anthropic API calls for inference"
    bypasses_l7: false
    actions:
      - { name: inference, type: write, description: "Send prompts and receive completions" }
  - name: http-via-tools
    transport: https
    description: "Claude can make HTTP requests via tool use (Bash, WebFetch)"
    bypasses_l7: false
    actions:
      - { name: get, type: read }
      - { name: post, type: write }
      - { name: put, type: write }
spawns:
  - /usr/local/bin/node
  - /usr/local/bin/python3.13
  - /usr/bin/git
  - /usr/bin/curl
  - /usr/bin/ssh
  - /usr/bin/nc
can_exfiltrate: true
exfil_mechanism: "Can read files and send contents via tool use, API calls, or spawned subprocesses"
can_construct_http: true
</file>

<file path="crates/openshell-prover/registry/binaries/curl.yaml">
binary: /usr/bin/curl
description: "Command-line HTTP client"
protocols:
  - name: http
    transport: https
    description: "HTTP/HTTPS requests — can construct arbitrary method, path, headers, body"
    bypasses_l7: false
    actions:
      - { name: get, type: read, description: "HTTP GET request" }
      - { name: post, type: write, description: "HTTP POST with arbitrary body" }
      - { name: put, type: write, description: "HTTP PUT with arbitrary body" }
      - { name: delete, type: destructive, description: "HTTP DELETE request" }
      - { name: upload, type: write, description: "File upload via multipart POST" }
spawns: []
can_exfiltrate: true
exfil_mechanism: "POST/PUT file contents to any reachable endpoint, or encode in URL query parameters"
can_construct_http: true
</file>

<file path="crates/openshell-prover/registry/binaries/gh.yaml">
binary: /usr/bin/gh
description: "GitHub CLI — REST API client for GitHub"
protocols:
  - name: github-rest
    transport: https
    description: "GitHub REST API via gh cli — uses standard HTTP, subject to L7 inspection"
    bypasses_l7: false
    actions:
      - { name: api_read, type: read, description: "GET requests to GitHub API" }
      - { name: api_write, type: write, description: "POST/PUT/PATCH requests (create issues, PRs, etc.)" }
      - { name: api_delete, type: destructive, description: "DELETE requests (delete repos, branches, etc.)" }
spawns:
  - /usr/bin/git
can_exfiltrate: true
exfil_mechanism: "Create gists, issues, or PRs with file contents"
can_construct_http: true
</file>

<file path="crates/openshell-prover/registry/binaries/git.yaml">
binary: /usr/bin/git
description: "Distributed version control system"
protocols:
  - name: git-smart-http
    transport: https
    description: "Git smart HTTP protocol over HTTPS CONNECT tunnel — not REST, bypasses L7 HTTP inspection"
    bypasses_l7: true
    actions:
      - { name: clone, type: read, description: "Clone/fetch repository" }
      - { name: push, type: write, description: "Push commits to remote" }
      - { name: force_push, type: destructive, description: "Force push, rewriting remote history" }
  - name: git-ssh
    transport: ssh
    description: "Git over SSH"
    bypasses_l7: true
    actions:
      - { name: clone, type: read }
      - { name: push, type: write }
      - { name: force_push, type: destructive }
spawns:
  - /usr/lib/git-core/git-remote-https
  - /usr/bin/ssh
can_exfiltrate: true
exfil_mechanism: "Commit data to repo and push, or encode in branch/tag names"
can_construct_http: false
</file>

<file path="crates/openshell-prover/registry/binaries/nc.yaml">
binary: /usr/bin/nc
description: "Netcat — arbitrary TCP/UDP connections"
protocols:
  - name: raw-tcp
    transport: tcp
    description: "Raw TCP connection — can send/receive arbitrary data"
    bypasses_l7: true
    actions:
      - { name: connect, type: read, description: "Establish TCP connection" }
      - { name: send, type: write, description: "Send arbitrary data over TCP" }
      - { name: listen, type: read, description: "Listen for incoming connections" }
spawns: []
can_exfiltrate: true
exfil_mechanism: "Stream arbitrary data over raw TCP connection"
can_construct_http: false
</file>

<file path="crates/openshell-prover/registry/binaries/node.yaml">
binary: /usr/local/bin/node
description: "Node.js runtime — general-purpose JavaScript runtime"
protocols:
  - name: http-programmatic
    transport: https
    description: "Node can construct arbitrary HTTP requests via fetch, axios, http module"
    bypasses_l7: false
    actions:
      - { name: get, type: read }
      - { name: post, type: write }
      - { name: put, type: write }
      - { name: delete, type: destructive }
spawns:
  - /usr/bin/curl
  - /usr/bin/git
can_exfiltrate: true
exfil_mechanism: "Construct arbitrary HTTP requests, spawn subprocesses"
can_construct_http: true
</file>

<file path="crates/openshell-prover/registry/binaries/python3.yaml">
binary: /usr/local/bin/python3.13
description: "Python interpreter — general-purpose runtime"
protocols:
  - name: http-programmatic
    transport: https
    description: "Python can construct arbitrary HTTP requests via urllib, httpx, requests"
    bypasses_l7: false
    actions:
      - { name: get, type: read }
      - { name: post, type: write }
      - { name: put, type: write }
      - { name: delete, type: destructive }
spawns:
  - /usr/bin/curl
  - /usr/bin/git
  - /usr/bin/ssh
  - /usr/bin/nc
  - /usr/bin/wget
can_exfiltrate: true
exfil_mechanism: "Construct arbitrary HTTP requests, write to files, spawn subprocesses"
can_construct_http: true
</file>

<file path="crates/openshell-prover/registry/binaries/ssh.yaml">
binary: /usr/bin/ssh
description: "OpenSSH client"
protocols:
  - name: ssh
    transport: ssh
    description: "SSH protocol — encrypted tunnel, can forward ports and transfer files"
    bypasses_l7: true
    actions:
      - { name: connect, type: read, description: "SSH shell connection" }
      - { name: tunnel, type: write, description: "Port forwarding / tunnel" }
      - { name: scp, type: write, description: "File transfer via SCP" }
spawns: []
can_exfiltrate: true
exfil_mechanism: "SCP files or pipe data through SSH tunnel"
can_construct_http: false
</file>

<file path="crates/openshell-prover/registry/binaries/wget.yaml">
binary: /usr/bin/wget
description: "Non-interactive network downloader"
protocols:
  - name: http
    transport: https
    description: "HTTP/HTTPS downloads — can also POST with --post-data"
    bypasses_l7: false
    actions:
      - { name: download, type: read }
      - { name: post, type: write, description: "POST via --post-data or --post-file" }
spawns: []
can_exfiltrate: true
exfil_mechanism: "POST file contents via --post-file to any reachable endpoint"
can_construct_http: true
</file>

<file path="crates/openshell-prover/src/containment/execution.rs">
use openshell_policy_schema::LandlockCompatibility;
⋮----
pub(super) fn unsupported_reason(policy: &ContainmentPolicy) -> Option<String> {
⋮----
if !identity.is_empty()
&& !matches!(identity.as_str(), "sandbox" | "root" | "0")
⋮----
.is_ok_and(|id| (1..u32::MAX).contains(&id))
⋮----
return Some(format!("uses unsupported process identity '{identity}'"));
⋮----
pub(super) fn check(
⋮----
.as_ref()
.map_or("", |process| process.run_as_user.as_str());
⋮----
.map_or("", |process| process.run_as_group.as_str());
⋮----
let root = |identity: &str| matches!(identity, "root" | "0");
if root(boundary) && root(candidate) {
⋮----
if !boundary.is_empty() && !root(boundary) && root(candidate) {
return Some(CheckResult::Exceeds(ExceedsEvidence(
⋮----
boundary: boundary.to_owned(),
candidate: candidate.to_owned(),
⋮----
unresolved_change.get_or_insert_with(|| {
unsupported(
⋮----
... (40 lines truncated)
</file>

<file path="crates/openshell-prover/src/containment/ip.rs">
pub(super) struct SymbolicIp {
⋮----
impl SymbolicIp {
pub(super) fn new(name: &str) -> Self {
⋮----
bits: BV::new_const(format!("{name}_destination_ip"), 128),
v6: Bool::new_const(format!("{name}_ipv6")),
⋮----
pub(super) fn concrete(ip: IpAddr) -> Self {
⋮----
bits: bits(net.address),
⋮----
pub(super) fn assert_domain(&self, solver: &Solver) {
solver.assert(
⋮----
.not()
.implies(self.bits.extract(127, 32).eq(BV::from_u64(0, 96))),
⋮----
pub(super) fn decode(&self, model: &Model) -> Option<IpAddr> {
let high = model.eval(&self.bits.extract(127, 64), true)?.as_u64()?;
let low = model.eval(&self.bits.extract(63, 0), true)?.as_u64()?;
Some(if model.eval(&self.v6, true)?.as_bool()? {
⋮----
IpAddr::V4(Ipv4Addr::from(u32::try_from(low).ok()?))
⋮----
fn matches(&self, net: Network) -> Bool {
⋮----
self.v6.eq(Bool::from_bool(net.v6)),
⋮----
.bvand(bits(net.mask()))
... (194 lines truncated)
</file>

<file path="crates/openshell-prover/src/accepted_risks.rs">
use std::path::Path;
⋮----
use serde::Deserialize;
⋮----
struct AcceptedRisksFile {
⋮----
struct AcceptedRiskDef {
⋮----
pub struct AcceptedRisk {
⋮----
pub fn load_accepted_risks(path: &Path) -> Result<Vec<AcceptedRisk>> {
⋮----
.into_diagnostic()
.wrap_err_with(|| format!("reading accepted risks {}", path.display()))?;
⋮----
.wrap_err("parsing accepted risks YAML")?;
⋮----
Ok(raw
⋮----
.into_iter()
.map(|r| AcceptedRisk {
⋮----
.collect())
⋮----
fn path_matches_risk(path: &FindingPath, risk: &AcceptedRisk) -> bool {
⋮----
if !risk.binary.is_empty() && p.binary != risk.binary {
⋮----
if !risk.endpoint.is_empty() && p.endpoint_host != risk.endpoint {
⋮----
... (26 lines truncated)
</file>

<file path="crates/openshell-prover/src/containment.rs">
use std::collections::BTreeMap;
use std::fmt;
use std::net::IpAddr;
use std::str::FromStr;
⋮----
mod execution;
mod ip;
⋮----
pub struct ParsePolicyError(String);
⋮----
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(&self.0)
⋮----
/// Policy representation used by boundary checking, projected from the canonical
/// authored schema. Construction always goes through the shared bounded parser.
⋮----
/// authored schema. Construction always goes through the shared bounded parser.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ContainmentPolicy {
⋮----
trait ContainmentEndpoint {
⋮----
impl ContainmentEndpoint for Endpoint {
fn protocol_kind(&self) -> Protocol {
if self.is_l4() {
⋮----
/// Parse one captured YAML or JSON input using the canonical authored schema.
pub fn parse_policy_str(source: &str) -> Result<ContainmentPolicy, ParsePolicyError> {
⋮----
pub fn parse_policy_str(source: &str) -> Result<ContainmentPolicy, ParsePolicyError> {
... (1451 lines truncated)
</file>

<file path="crates/openshell-prover/src/credentials.rs">
use std::collections::HashMap;
use std::path::Path;
⋮----
use serde::Deserialize;
⋮----
struct CredentialsFile {
⋮----
struct CredentialDef {
⋮----
struct ApiRegistryDef {
⋮----
struct ApiActionDef {
⋮----
pub struct Credential {
⋮----
pub struct ApiAction {
⋮----
pub struct ApiCapability {
⋮----
impl ApiCapability {
⋮----
pub fn actions_for_scopes(&self, scopes: &[String]) -> Vec<&ApiAction> {
⋮----
if let Some(actions) = self.scope_capabilities.get(scope) {
result.extend(actions.iter());
⋮----
pub fn write_actions_for_scopes(&self, scopes: &[String]) -> Vec<&ApiAction> {
self.actions_for_scopes(scopes)
.into_iter()
.filter(|a| {
... (195 lines truncated)
</file>

<file path="crates/openshell-prover/src/finding.rs">
pub mod category {
⋮----
pub struct ExfilPath {
⋮----
pub enum FindingPath {
⋮----
pub struct Finding {
</file>

<file path="crates/openshell-prover/src/lib.rs">
pub mod accepted_risks;
pub mod containment;
pub mod credentials;
pub mod finding;
pub mod model;
pub mod policy;
pub mod queries;
pub mod registry;
pub mod report;
⋮----
use std::path::Path;
⋮----
use miette::Result;
⋮----
use model::build_model;
use policy::parse_policy;
use queries::run_all_queries;
⋮----
pub fn prove(
⋮----
let policy = parse_policy(Path::new(policy_path))?;
⋮----
let z3_model = build_model(policy, credential_set, binary_registry);
let mut findings = run_all_queries(&z3_model);
⋮----
let accepted = load_accepted_risks(Path::new(ar_path))?;
findings = apply_accepted_risks(findings, &accepted);
⋮----
render_compact(&findings, policy_path, credentials_path)
⋮----
... (109 lines truncated)
</file>

<file path="crates/openshell-prover/src/model.rs">
use z3::ast::Bool;
⋮----
use crate::credentials::CredentialSet;
⋮----
use crate::registry::BinaryRegistry;
⋮----
pub struct EndpointId {
⋮----
impl EndpointId {
⋮----
pub fn key(&self) -> String {
format!("{}:{}:{}", self.policy_name, self.host, self.port)
⋮----
pub struct ReachabilityModel {
⋮----
impl ReachabilityModel {
⋮----
pub fn new(
⋮----
model.build();
⋮----
fn build(&mut self) {
self.index_endpoints();
self.index_binaries();
self.encode_policy_allows();
self.encode_l7_enforcement();
self.encode_binary_capabilities();
self.encode_credentials();
self.encode_filesystem();
⋮----
... (146 lines truncated)
</file>

<file path="crates/openshell-prover/src/policy.rs">
use std::path::Path;
⋮----
pub enum PolicyIntent {
⋮----
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str(match self {
⋮----
pub struct L7Rule {
⋮----
pub struct Endpoint {
⋮----
impl Endpoint {
⋮----
pub fn is_l7_enforced(&self) -> bool {
!self.protocol.is_empty() && !self.protocol.eq_ignore_ascii_case("tcp")
⋮----
pub fn intent(&self) -> PolicyIntent {
if !self.is_l7_enforced() {
⋮----
if self.rules.is_empty() {
⋮----
self.rules.iter().map(|r| r.method.to_uppercase()).collect();
⋮----
.iter()
.map(|s| (*s).to_owned())
.collect();
if methods.is_subset(&read_only) {
⋮----
} else if !methods.contains("DELETE") {
⋮----
... (87 lines truncated)
</file>

<file path="crates/openshell-prover/src/queries.rs">
use std::collections::HashSet;
use std::net::IpAddr;
⋮----
use z3::SatResult;
⋮----
use crate::model::ReachabilityModel;
⋮----
pub(crate) fn is_link_local(host: &str) -> bool {
⋮----
Ok(IpAddr::V4(v4)) => v4.is_link_local(),
Ok(IpAddr::V6(v6)) => v6.is_unicast_link_local(),
⋮----
pub(crate) fn is_known_metadata_hostname(host: &str) -> bool {
let normalized = host.trim().trim_end_matches('.').to_ascii_lowercase();
matches!(normalized.as_str(), "metadata.google.internal")
⋮----
fn is_link_local_or_metadata_host(host: &str) -> bool {
is_link_local(host) || is_known_metadata_hostname(host)
⋮----
pub fn check_credential_safety(model: &ReachabilityModel) -> Vec<Finding> {
⋮----
let cap = model.binary_registry.get_or_unknown(bpath);
⋮----
let expr = model.can_exfil_via_endpoint(bpath, eid);
if model.check_sat(&expr) != SatResult::Sat {
⋮----
let host_is_link_local = is_link_local_or_metadata_host(&eid.host);
let has_credential = !model.credentials.credentials_for_host(&eid.host).is_empty();
⋮----
link_local_paths.push(ExfilPath {
... (85 lines truncated)
</file>

<file path="crates/openshell-prover/src/registry.rs">
use std::collections::HashMap;
⋮----
use serde::Deserialize;
⋮----
static EMBEDDED_REGISTRY: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/registry");
⋮----
// ---------------------------------------------------------------------------
// Serde types
⋮----
struct BinaryCapabilityDef {
⋮----
struct BinaryProtocolDef {
⋮----
struct BinaryActionDef {
⋮----
// Public types
⋮----
/// Type of action a binary can perform.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ActionType {
⋮----
impl ActionType {
fn from_str(s: &str) -> Self {
⋮----
/// A single action a binary protocol supports.
#[derive(Debug, Clone)]
pub struct BinaryAction {
⋮----
/// A protocol supported by a binary.
#[derive(Debug, Clone)]
... (119 lines truncated)
</file>

<file path="crates/openshell-prover/src/report.rs">
use std::path::Path;
⋮----
use owo_colors::OwoColorize;
⋮----
fn category_label(query: &str) -> &str {
⋮----
pub fn finding_shorthand(finding: &Finding) -> String {
⋮----
lines.push(format_path_line(&finding.query, p));
⋮----
lines.join("\n  ")
⋮----
fn format_path_line(query: &str, p: &crate::finding::ExfilPath) -> String {
let endpoint = format!("{}:{}", p.endpoint_host, p.endpoint_port);
⋮----
format!("link_local_reach: {endpoint} via {}", p.binary)
⋮----
format!("l7_bypass_credentialed: {endpoint} via {}", p.binary)
⋮----
format!("credential_reach_expansion: {endpoint} via {}", p.binary)
⋮----
format!(
⋮----
_ => format!("{query}: {endpoint} via {}", p.binary),
⋮----
pub fn render_compact(findings: &[Finding], _policy_path: &str, _credentials_path: &str) -> i32 {
let active: Vec<&Finding> = findings.iter().filter(|f| !f.accepted).collect();
let accepted: Vec<&Finding> = findings.iter().filter(|f| f.accepted).collect();
⋮----
println!("  {} {}", "•".yellow(), format_path_line(&finding.query, p));
... (98 lines truncated)
</file>

<file path="crates/openshell-prover/testdata/credentials.yaml">
credentials:
  - name: github-pat
    type: github-pat
    scopes:
      - repo
    injected_via: GITHUB_TOKEN
    target_hosts:
      - api.github.com
      - github.com
</file>

<file path="crates/openshell-prover/testdata/empty-policy.yaml">
version: 1
</file>

<file path="crates/openshell-prover/testdata/policy.yaml">
version: 1
filesystem_policy:
  include_workdir: true
  read_only:
    - /usr
    - /lib
    - /proc
    - /dev/urandom
    - /app
    - /etc
    - /var/log
  read_write:
    - /sandbox
    - /tmp
    - /dev/null
landlock:
  compatibility: best_effort
process:
  run_as_user: sandbox
  run_as_group: sandbox
network_policies:
  github_api:
    name: github-api
    endpoints:
      - host: api.github.com
        port: 443
        protocol: rest
        enforcement: enforce
        access: read-only
      - host: github.com
... (8 lines truncated)
</file>

<file path="crates/openshell-prover/Cargo.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

[package]
name = "openshell-prover"
description = "Formal policy verification for OpenShell sandboxes"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true

[features]
bundled-z3 = ["z3/bundled"]
prebuilt-z3 = ["z3/gh-release"]

[dependencies]
z3 = { workspace = true }
openshell-policy-schema = { path = "../openshell-policy-schema" }
serde = { workspace = true }
serde_yml = { workspace = true }
miette = { workspace = true }
owo-colors = { workspace = true }
include_dir = { workspace = true }
glob = { workspace = true }

[dev-dependencies]
openshell-core = { path = "../openshell-core" }
regorus = { version = "0.9", default-features = false, features = ["std", "arc", "glob"] }
serde_json = { workspace = true }
... (4 lines truncated)
</file>

<file path="crates/openshell-prover/README.md">
<!-- SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -->
<!-- SPDX-License-Identifier: Apache-2.0 -->

# openshell-prover

Formal verifier for OpenShell sandbox policies. Encodes a policy + its
attached credential set + a binary capability registry as a Z3 SMT
model, then runs reachability queries to detect credentialed-reach and
capability changes a reviewer should be aware of.

The crate also exposes an independent containment API for checking whether a
fully composed candidate policy stays within an operator-supplied boundary. The
`openshell-prover-cli` package wraps that API for local files. Containment and
the legacy proposal-risk queries answer different questions; gateway callers
continue to use the proposal-risk API until the managed-policy migration.

Both prover entrypoints use the bounded `openshell-policy-schema` parser.
Containment rejects unknown fields and managed `metadata`/`review` annotations
as invalid input, then checks schema-valid controls against its supported model.
It uses shared filesystem defaults, port selection, and access-preset semantics.

The containment model accepts ASCII literals in network binary selectors,
endpoint host and path selectors, and REST allow and deny method and path
selectors. It returns `unsupported_policy_shape` when either policy uses a
non-ASCII literal in one of those fields. This boundary does not apply to
filesystem paths or unrelated policy text. Embedded NUL bytes in network
selector fields are also unsupported. ASCII wildcards are modeled over the
runtime match language and can therefore match non-ASCII runtime values. A
solver string that cannot be decoded and validated exactly produces
`invalid_witness` rather than counterexample evidence.
... (177 lines truncated)
</file>

<file path="crates/openshell-prover-cli/src/main.rs">
use std::fs::File;
⋮----
use std::fs::OpenOptions;
⋮----
use std::process::ExitCode;
use std::sync::Arc;
⋮----
use std::time::Duration;
⋮----
use serde::Serialize;
⋮----
struct Cli {
⋮----
enum Command {
⋮----
enum OutputFormat {
⋮----
struct Envelope<'a> {
⋮----
struct CoverageJson<'a> {
⋮----
struct InputsJson {
⋮----
enum CounterexampleJson<'a> {
⋮----
fn main() -> ExitCode {
⋮----
.and_then(|_| {
⋮----
let _ = writeln!(
... (220 lines truncated)
</file>

<file path="crates/openshell-prover-cli/Cargo.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

[package]
name = "openshell-prover-cli"
description = "Standalone OpenShell policy boundary checker"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true

[[bin]]
name = "openshell-prover"
path = "src/main.rs"

[features]
bundled-z3 = ["openshell-prover/bundled-z3"]
prebuilt-z3 = ["openshell-prover/prebuilt-z3"]

[dependencies]
clap.workspace = true
openshell-prover = { path = "../openshell-prover" }
serde.workspace = true
serde_json.workspace = true

[target.'cfg(unix)'.dependencies]
nix.workspace = true
signal-hook.workspace = true

... (3 lines truncated)
</file>

<file path="crates/openshell-prover-cli/README.md">
<!--
SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
SPDX-License-Identifier: Apache-2.0
-->

# OpenShell policy prover CLI

This package builds the standalone `openshell-prover` executable. It is a thin synchronous adapter around the reusable containment engine in `openshell-prover`; it owns local file loading, command parsing, result rendering, and process exit codes.

```shell
openshell-prover check candidate.yaml --boundary boundary.yaml
openshell-prover check candidate.yaml --boundary boundary.yaml --output json
```

The command checks whether a fully composed candidate policy stays within an operator-supplied boundary. It does not discover a gateway, fetch policy state, or apply policy changes.

Results use these exit codes:

| Exit code | Meaning |
| --- | --- |
| `0` | The candidate is within the boundary. |
| `1` | The candidate exceeds the boundary. |
| `2` | Usage, input, output, or internal error. |
| `3` | Unsupported policy semantics or an inconclusive solve. |
| `130` | Interrupted with Ctrl-C on Unix; graceful JSON output reports an inconclusive cancellation. |

Build and test the package with:

```shell
cargo build -p openshell-prover-cli --bin openshell-prover
... (11 lines truncated)
</file>

<file path="crates/openshell-providers/src/providers/google_cloud.rs">
use std::collections::HashMap;
⋮----
use openshell_core::google_cloud;
⋮----
pub struct GoogleCloudProvider;
⋮----
impl ProviderPlugin for GoogleCloudProvider {
fn id(&self) -> &'static str {
⋮----
fn inject_env(&self, provider: &Provider, env: &mut HashMap<String, String>) {
⋮----
.get(google_cloud::GCP_PROJECT_ID_CONFIG_KEY)
.filter(|v| !v.trim().is_empty())
⋮----
env.entry((*var).to_string())
.or_insert_with(|| project.trim().to_string());
⋮----
.get(google_cloud::GCP_REGION_CONFIG_KEY)
⋮----
.or_insert_with(|| region.trim().to_string());
⋮----
env.entry("GCE_METADATA_HOST".to_string())
.or_insert_with(|| google_cloud::METADATA_HOST.to_string());
⋮----
.get(google_cloud::GCP_SERVICE_ACCOUNT_EMAIL_CONFIG_KEY)
⋮----
.or_insert_with(|| email.trim().to_string());
⋮----
mod tests {
⋮----
... (38 lines truncated)
</file>

<file path="crates/openshell-providers/src/providers/mod.rs">
pub mod google_cloud;
pub mod vertex;
</file>

<file path="crates/openshell-providers/src/providers/vertex.rs">
use std::collections::HashMap;
⋮----
use openshell_core::google_cloud;
⋮----
pub struct VertexProvider;
⋮----
impl ProviderPlugin for VertexProvider {
fn id(&self) -> &'static str {
⋮----
fn inject_env(&self, provider: &Provider, env: &mut HashMap<String, String>) {
⋮----
.get(VERTEX_AI_PROJECT_ID_KEY)
.filter(|v| !v.trim().is_empty())
⋮----
let trimmed = project.trim().to_string();
⋮----
env.entry((*var).to_string())
.or_insert_with(|| trimmed.clone());
⋮----
env.entry(google_cloud::ANTHROPIC_VERTEX_PROJECT_ID_ENV_VAR.to_string())
⋮----
.get(VERTEX_AI_REGION_KEY)
⋮----
let trimmed = region.trim().to_string();
⋮----
env.entry(google_cloud::VERTEX_LOCATION_ENV_VAR.to_string())
⋮----
env.entry(google_cloud::GOOSE_PROVIDER_ENV_VAR.to_string())
.or_insert_with(|| "gcp_vertex_ai".to_string());
⋮----
... (38 lines truncated)
</file>

<file path="crates/openshell-providers/src/context.rs">
pub trait DiscoveryContext {
⋮----
pub struct RealDiscoveryContext;
⋮----
impl DiscoveryContext for RealDiscoveryContext {
fn env_var(&self, key: &str) -> Option<String> {
std::env::var(key).ok()
</file>

<file path="crates/openshell-providers/src/discovery.rs">
use std::collections::HashSet;
⋮----
pub fn discover_with_spec(
⋮----
if let Some(value) = context.env_var(key)
&& !value.trim().is_empty()
⋮----
.entry((*key).to_string())
.or_insert(value);
⋮----
if discovered.is_empty() {
Ok(None)
⋮----
Ok(Some(discovered))
⋮----
pub fn discover_from_profile(
⋮----
let credential_name = credential_name.trim();
⋮----
.iter()
.find(|credential| credential.name.trim() == credential_name)
⋮----
return Err(ProviderError::UnknownDiscoveryCredential {
profile_id: profile.id.clone(),
credential_name: credential_name.to_string(),
⋮----
let env_var = env_var.trim();
if env_var.is_empty() || !scanned_env_vars.insert(env_var.to_string()) {
⋮----
if let Some(value) = context.env_var(env_var)
... (57 lines truncated)
</file>

<file path="crates/openshell-providers/src/example_profiles.rs">
pub fn directory() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR")).join("../../providers")
⋮----
pub fn path(id: &str) -> PathBuf {
directory().join(format!("{id}.yaml"))
⋮----
pub fn load(id: &str) -> ProviderTypeProfile {
let file = path(id);
⋮----
.unwrap_or_else(|err| panic!("read example provider profile {}: {err}", file.display()));
parse_profile_yaml(&yaml)
.unwrap_or_else(|err| panic!("parse example provider profile {}: {err}", file.display()))
⋮----
pub fn load_all() -> Vec<ProviderTypeProfile> {
try_load_all().unwrap_or_else(|err| panic!("load example provider profiles: {err}"))
⋮----
pub fn try_load_all() -> Result<Vec<ProviderTypeProfile>, ProfileError> {
let dir = directory();
⋮----
.unwrap_or_else(|err| panic!("read directory {}: {err}", dir.display()))
.map(|entry| {
⋮----
.unwrap_or_else(|err| panic!("read directory entry in {}: {err}", dir.display()))
.path()
⋮----
.filter(|path| path.extension().is_some_and(|ext| ext == "yaml"))
⋮----
files.sort();
⋮----
.iter()
... (7 lines truncated)
</file>

<file path="crates/openshell-providers/src/lib.rs">
mod context;
mod discovery;
⋮----
pub mod example_profiles;
mod profiles;
mod providers;
⋮----
mod test_helpers;
⋮----
use std::collections::HashMap;
⋮----
pub use openshell_core::proto::Provider;
⋮----
pub enum ProviderError {
⋮----
pub struct DiscoveredProvider {
⋮----
impl DiscoveredProvider {
⋮----
pub fn is_empty(&self) -> bool {
self.credentials.is_empty() && self.config.is_empty()
⋮----
pub struct ProviderDiscoverySpec {
⋮----
trait ProviderPlugin: Send + Sync {
/// Canonical provider id.
    fn id(&self) -> &'static str;
⋮----
fn inject_env(&self, _provider: &Provider, _env: &mut HashMap<String, String>) {}
⋮----
... (24 lines truncated)
</file>

<file path="crates/openshell-providers/src/profiles.rs">
use openshell_core::secrets::uses_reserved_revision_namespace;
⋮----
use std::net::IpAddr;
⋮----
pub enum ProfileError {
⋮----
pub struct ProfileValidationDiagnostic {
⋮----
impl ProfileValidationDiagnostic {
fn error(
⋮----
source: source.into(),
profile_id: profile_id.into(),
field: field.into(),
message: message.into(),
severity: "error".to_string(),
⋮----
pub struct CredentialProfile {
⋮----
pub enum ProfileDurationWkt {
⋮----
impl ProfileDurationWkt {
fn from_proto(value: Option<prost_types::Duration>) -> Self {
value.map_or(Self::Absent, Self::Present)
⋮----
pub fn to_proto(self, legacy_seconds: i64) -> Option<prost_types::Duration> {
⋮----
Self::FromYaml => (legacy_seconds != 0).then_some(prost_types::Duration {
⋮----
Self::Present(value) => Some(value),
... (2382 lines truncated)
</file>

<file path="crates/openshell-providers/src/test_helpers.rs">
use crate::DiscoveryContext;
use std::collections::HashMap;
⋮----
pub struct MockDiscoveryContext {
⋮----
impl MockDiscoveryContext {
pub fn new() -> Self {
⋮----
pub fn with_env(mut self, key: &str, value: &str) -> Self {
self.env.insert(key.to_string(), value.to_string());
⋮----
impl DiscoveryContext for MockDiscoveryContext {
fn env_var(&self, key: &str) -> Option<String> {
self.env.get(key).cloned()
</file>

<file path="crates/openshell-providers/Cargo.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

[package]
name = "openshell-providers"
description = "Provider discovery and registry for OpenShell"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true

[features]
default = []
# Test-only access to the example profiles in `providers/`. Enable it from
# `[dev-dependencies]` only; it reads the source checkout at run time.
example-profiles = []

[dependencies]
prost-types = { workspace = true }
glob = { workspace = true }
openshell-core = { path = "../openshell-core", default-features = false }
openshell-policy = { path = "../openshell-policy" }
serde = { workspace = true }
serde_json = { workspace = true }
serde_yml = { workspace = true }
thiserror = { workspace = true }
url = { workspace = true }

[lints]
... (2 lines truncated)
</file>

<file path="crates/openshell-providers/README.md">
# openshell-providers

Provider discovery and normalization for credentials that sandboxes need at
runtime.

The gateway persists provider records. The sandbox supervisor fetches resolved
provider environment from the gateway and injects credentials into agent child
processes. This crate keeps provider-specific discovery and normalization logic
out of the CLI and gateway control flow.

## Responsibilities

- Discover local credentials from environment variables and known config files.
- Normalize discovered data into provider records.
- Keep provider-specific parsing rules in provider modules.
- Avoid logging credential values.

## Non-Responsibilities

- Persisting provider records.
- Authorizing provider CRUD operations.
- Injecting credentials into sandbox child processes.
- Routing inference requests.

Those are owned by the gateway, sandbox supervisor, and router.

## Security Notes

Provider data often contains API keys, bearer tokens, or local account
configuration. Discovery code should return structured values without printing
... (3 lines truncated)
</file>

<file path="crates/openshell-sandbox/src/sandbox/linux/landlock.rs">
use tracing::debug;
⋮----
pub enum LandlockAvailability {
⋮----
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
⋮----
Self::Available { abi } => write!(f, "available (ABI v{abi})"),
⋮----
write!(f, "not implemented (kernel lacks CONFIG_SECURITY_LANDLOCK)")
⋮----
Self::NotEnabled => write!(
⋮----
Self::Blocked => write!(
⋮----
Self::Unknown(errno) => write!(f, "unexpected probe error (errno {errno})"),
⋮----
/// Probe the kernel for Landlock support by issuing the `landlock_create_ruleset`
/// syscall with the version-check flag.
⋮----
/// syscall with the version-check flag.
///
⋮----
///
/// This is safe to call from the parent process and does not create any file
⋮----
/// This is safe to call from the parent process and does not create any file
/// descriptors or modify process state.
⋮----
/// descriptors or modify process state.
pub fn probe_availability() -> LandlockAvailability {
... (374 lines truncated)
</file>

<file path="crates/openshell-sandbox/src/sandbox/linux/mod.rs">
mod landlock;
mod seccomp;
⋮----
use miette::Result;
use openshell_core::policy::SandboxPolicy;
use std::path::PathBuf;
use std::sync::Once;
⋮----
pub struct PreparedSandbox {
⋮----
pub fn prepare(policy: &SandboxPolicy, workdir: Option<&str>) -> Result<PreparedSandbox> {
⋮----
Ok(PreparedSandbox {
landlock: landlock.into_iter().collect(),
policy: policy.clone(),
⋮----
pub fn prepare_current_user(
⋮----
pub fn prepare_capability_free(
⋮----
let mut landlock = vec![baseline];
landlock.extend(user);
⋮----
pub fn enforce(prepared: PreparedSandbox) -> Result<()> {
⋮----
Ok(())
⋮----
pub fn enforce_capability_free(
⋮----
.install()
... (19 lines truncated)
</file>

<file path="crates/openshell-sandbox/src/sandbox/linux/seccomp.rs">
use std::collections::BTreeMap;
use std::convert::TryInto;
use tracing::debug;
⋮----
use libc::SYS_kexec_file_load;
⋮----
pub fn apply_supervisor_prelude() -> Result<()> {
let filter = build_supervisor_prelude_filter()?;
set_no_new_privs()?;
apply_filter_all_threads(&filter).into_diagnostic()?;
Ok(())
⋮----
pub fn apply(policy: &SandboxPolicy) -> Result<()> {
let allow_inet = matches!(policy.network.mode, NetworkMode::Proxy | NetworkMode::Allow);
let main_filter = build_filter(allow_inet)?;
let compatibility_filter = build_compatibility_filter()?;
⋮----
apply_runtime_filters(&main_filter, &compatibility_filter)?;
⋮----
fn build_filter(allow_inet: bool) -> Result<seccompiler::BpfProgram> {
let rules = build_filter_rules(allow_inet)?;
compile_filter(rules, SeccompAction::Errno(libc::EPERM as u32))
⋮----
fn build_supervisor_prelude_filter() -> Result<seccompiler::BpfProgram> {
compile_filter(
build_supervisor_prelude_rules(),
⋮----
fn build_supervisor_prelude_rules() -> BTreeMap<i64, Vec<SeccompRule>> {
⋮----
rules.entry(syscall).or_default();
... (205 lines truncated)
</file>

<file path="crates/openshell-sandbox/src/sandbox/mod.rs">
use miette::Result;
⋮----
use openshell_core::policy::SandboxPolicy;
⋮----
pub mod linux;
⋮----
pub fn apply(policy: &SandboxPolicy, workdir: Option<&str>) -> Result<()> {
⋮----
Ok(())
⋮----
pub fn apply_supervisor_startup_hardening() -> Result<()> {
</file>

<file path="crates/openshell-sandbox/src/accept_interrupt.rs">
use std::collections::HashMap;
use std::io;
use std::marker::PhantomData;
use std::rc::Rc;
⋮----
use std::time::Duration;
⋮----
extern "C" fn interrupt_accept(_: libc::c_int) {}
⋮----
fn reserve_signal() -> io::Result<()> {
⋮----
return Err(io::Error::last_os_error());
⋮----
return Err(io::Error::other(
⋮----
Ok(())
⋮----
struct State {
⋮----
struct RegisteredThread(libc::pthread_t);
⋮----
unsafe impl Send for RegisteredThread {}
⋮----
pub struct AcceptMonitor {
⋮----
impl AcceptMonitor {
pub(crate) fn start(valid: impl Fn(u64) -> bool + Send + 'static) -> io::Result<Self> {
reserve_signal()?;
⋮----
let worker_state = state.clone();
... (127 lines truncated)
</file>

<file path="crates/openshell-sandbox/src/activity_aggregator.rs">
use std::collections::HashMap;
use std::future::Future;
use tokio::sync::mpsc;
⋮----
pub use openshell_core::activity::ActivityEvent;
⋮----
pub struct FlushableActivitySummary {
⋮----
pub struct ActivityAggregator {
⋮----
impl ActivityAggregator {
pub fn new(rx: mpsc::Receiver<ActivityEvent>, flush_interval_secs: u64) -> Self {
⋮----
pub async fn run<F, Fut, G>(mut self, flush_callback: F, ready_gate: G)
⋮----
while let Some(summary) = flush_rx.recv().await {
flush_callback(summary).await;
⋮----
flush_interval.tick().await;
⋮----
fn ingest(&mut self, event: ActivityEvent) {
self.network_activity_count = self.network_activity_count.saturating_add(1);
⋮----
self.denied_action_count = self.denied_action_count.saturating_add(1);
let group = sanitize_deny_group(event.deny_group).to_string();
let count = self.denials_by_group.entry(group).or_default();
*count = count.saturating_add(1);
⋮----
fn drain(&mut self) -> Option<FlushableActivitySummary> {
⋮----
... (47 lines truncated)
</file>

<file path="crates/openshell-sandbox/src/boundary_exec.rs">
use std::collections::HashMap;
⋮----
use std::net::Shutdown;
⋮----
use std::sync::Arc;
⋮----
use async_trait::async_trait;
⋮----
use nix::unistd::Pid;
use openshell_core::policy::SandboxPolicy;
use openshell_core::provider_credentials::ProviderCredentialState;
⋮----
pub struct LocalBoundaryExec {
⋮----
impl LocalBoundaryExec {
⋮----
pub fn new(
⋮----
fn runtime_helper(&self, spec: ExecSpec) -> Result<ExecSession, BackendError> {
self.runtime.ensure_active()?;
⋮----
!= Some(openshell_isolation_interface::contract::RuntimeHelper::Sftp)
⋮----
return Err(BackendError::Process(
"unsupported sandbox runtime helper request".to_string(),
⋮----
.as_deref()
.or(self.base_workdir.as_deref())
.map(std::path::PathBuf::from)
.ok_or_else(|| {
... (413 lines truncated)
</file>

<file path="crates/openshell-sandbox/src/boundary_io.rs">
use async_trait::async_trait;
⋮----
use std::collections::HashMap;
⋮----
pub struct BoundaryRuntimeState {
⋮----
impl BoundaryRuntimeState {
⋮----
pub fn new() -> Arc<Self> {
⋮----
pub fn new_exclusive_pid_namespace() -> Arc<Self> {
⋮----
pub const fn requires_dedicated_process_group(&self) -> bool {
⋮----
pub fn ensure_active(&self) -> Result<(), BackendError> {
match self.state.load(Ordering::Acquire) {
RUNTIME_ACTIVE => Ok(()),
RUNTIME_FROZEN => Err(BackendError::Unavailable(
"boundary is frozen while supervisor control recovers".to_string(),
⋮----
_ => Err(BackendError::Terminated("boundary has ended".to_string())),
⋮----
pub fn is_active(&self) -> bool {
self.state.load(Ordering::Acquire) == RUNTIME_ACTIVE
⋮----
pub fn enforcement_was_lost(&self) -> bool {
self.state.load(Ordering::Acquire) == RUNTIME_ENFORCEMENT_LOST
⋮----
pub fn register_process_group(
⋮----
... (207 lines truncated)
</file>

<file path="crates/openshell-sandbox/src/boundary_server.rs">
use std::path::Path;
⋮----
mod linux {
use std::fs::File;
⋮----
use std::mem::size_of;
⋮----
use std::pin::Pin;
⋮----
use std::time::Duration;
⋮----
use crate::boundary_io::BoundaryRuntimeState;
⋮----
use crate::network_broker::NetworkBroker;
use crate::process::ProcessStatus;
⋮----
use openshell_core::provider_credentials::ProviderCredentialState;
⋮----
use openshell_sandbox_backend::proto::isolation_boundary_client::IsolationBoundaryClient;
⋮----
use tokio_stream::wrappers::ReceiverStream;
⋮----
fn duration_micros(duration: Duration) -> u64 {
u64::try_from(duration.as_micros()).unwrap_or(u64::MAX)
⋮----
fn enrich_gpu_filesystem_paths(
⋮----
let has_gpu = Path::new("/dev/nvidiactl").exists() || Path::new("/dev/dxg").exists();
⋮----
.iter()
... (2265 lines truncated)
</file>

<file path="crates/openshell-sandbox/src/child_env.rs">
use std::path::Path;
⋮----
pub fn tls_env_vars(
⋮----
let ca_cert_path = ca_cert_path.display().to_string();
let combined_bundle_path = combined_bundle_path.display().to_string();
⋮----
("NODE_EXTRA_CA_CERTS", ca_cert_path.clone()),
⋮----
("SSL_CERT_FILE", combined_bundle_path.clone()),
("REQUESTS_CA_BUNDLE", combined_bundle_path.clone()),
("CURL_CA_BUNDLE", combined_bundle_path.clone()),
// Ubuntu Noble's git links against libcurl-gnutls, which ignores SSL_CERT_FILE.
⋮----
mod tests {
⋮----
use std::process::Command;
use std::process::Stdio;
⋮----
fn apply_tls_env_sets_node_and_bundle_paths() {
⋮----
cmd.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null());
⋮----
for (key, value) in tls_env_vars(ca_cert_path, combined_bundle_path) {
cmd.env(key, value);
⋮----
let output = cmd.output().expect("spawn env");
let stdout = String::from_utf8(output.stdout).expect("utf8");
... (8 lines truncated)
</file>

<file path="crates/openshell-sandbox/src/delegated.rs">
use std::sync::Arc;
⋮----
use std::time::Duration;
⋮----
use openshell_core::policy::SandboxPolicy;
use openshell_core::provider_credentials::ProviderCredentialState;
⋮----
fn ocsf_ctx() -> &'static openshell_ocsf::EventContext {
⋮----
/// Spawn the admitted workload without placing the gateway or policy authority
/// inside its boundary.
⋮----
/// inside its boundary.
#[allow(clippy::too_many_arguments, clippy::implicit_hasher)]
pub async fn spawn_workload(
⋮----
// Driver-selected workspaces are the sandbox identity's home. This keeps
⋮----
let workspace = ResolvedWorkspace::new(workdir.map(str::to_string), true);
⋮----
if let Some(workspace_root) = workspace.root()
⋮----
.wrap_err("image workspace validation failed")?;
⋮----
let mode = if std::env::var_os("OPENSHELL_REQUIRE_RUNTIME_PID_LIMIT").is_some() {
⋮----
crate::process::check_runtime_pid_limit(mode).wrap_err("check runtime PID limit")?;
⋮----
.unwrap_or_else(crate::boundary_io::BoundaryRuntimeState::new_exclusive_pid_namespace);
⋮----
... (91 lines truncated)
</file>

<file path="crates/openshell-sandbox/src/denial_aggregator.rs">
use std::collections::HashMap;
use std::future::Future;
use tokio::sync::mpsc;
⋮----
use openshell_core::denial::DenialEvent;
⋮----
struct AggregatedDenial {
⋮----
struct L7Sample {
⋮----
pub struct DenialAggregator {
⋮----
impl DenialAggregator {
⋮----
pub fn new(rx: mpsc::UnboundedReceiver<DenialEvent>, flush_interval_secs: u64) -> Self {
⋮----
pub async fn run<F, Fut, G>(mut self, flush_callback: F, ready_gate: G)
⋮----
flush_interval.tick().await;
⋮----
fn ingest(&mut self, event: DenialEvent) {
⋮----
let key = (event.host.clone(), event.port, event.binary.clone());
⋮----
.entry(key)
.or_insert_with(|| AggregatedDenial {
host: event.host.clone(),
⋮----
binary: event.binary.clone(),
ancestors: event.ancestors.clone(),
... (27 lines truncated)
</file>

<file path="crates/openshell-sandbox/src/lib.rs">
mod accept_interrupt;
pub mod boundary_exec;
pub mod boundary_io;
mod boundary_server;
pub mod child_env;
⋮----
pub(crate) mod delegated;
⋮----
pub mod main_session;
pub mod managed_children;
⋮----
mod network_broker;
⋮----
pub mod perf;
⋮----
pub mod process;
⋮----
mod provider_files;
mod pty;
pub mod sandbox;
⋮----
pub mod sftp;
⋮----
pub struct RuntimeQualification {
⋮----
pub struct RuntimeQualification;
⋮----
pub fn run(
⋮----
.map_err(|error| miette::miette!(error))
... (1 lines truncated)
</file>

<file path="crates/openshell-sandbox/src/main_session.rs">
use std::collections::VecDeque;
⋮----
use std::os::fd::AsRawFd;
⋮----
use bytes::Bytes;
⋮----
use nix::pty::Winsize;
use tokio::io::unix::AsyncFd;
⋮----
use tokio::sync::Notify;
use tokio::sync::watch;
⋮----
use crate::process::ProcessIo;
⋮----
pub enum MainOutput {
⋮----
impl MainOutput {
fn len(&self) -> usize {
⋮----
Self::Stdout(data) | Self::Stderr(data) => data.len(),
⋮----
struct SequencedOutput {
⋮----
struct OutputLogState {
⋮----
struct OutputLog {
⋮----
impl OutputLog {
fn new() -> Arc<Self> {
⋮----
... (634 lines truncated)
</file>

<file path="crates/openshell-sandbox/src/main.rs">
use std::mem::size_of;
use std::path::Path;
⋮----
use clap::Parser;
⋮----
use openshell_ocsf::OcsfShorthandLayer;
⋮----
use tracing_subscriber::EnvFilter;
⋮----
struct BoundaryArgs {
⋮----
fn run_capability_probe() -> Result<()> {
let (qualification, report) = qualify_runtime()?;
debug_assert!(qualification.seccomp.notification_round_trip);
println!("{}", serde_json::to_string(&report).into_diagnostic()?);
Ok(())
⋮----
struct QualificationReport {
⋮----
/// Whether the broker disables task-memory output writes (legacy mode).
    task_memory_writes_disabled: bool,
⋮----
fn qualify_runtime() -> Result<(openshell_sandbox::RuntimeQualification, QualificationReport)> {
⋮----
let uid = nix::unistd::geteuid().as_raw();
let gid = nix::unistd::getegid().as_raw();
⋮----
return Err(miette::miette!(
⋮----
.into_diagnostic()
... (931 lines truncated)
</file>

<file path="crates/openshell-sandbox/src/managed_children.rs">
use std::io;
use std::sync::atomic::AtomicI32;
⋮----
use std::time::Duration;
⋮----
extern "C" fn notify_reaper_on_sigchld(_: libc::c_int) {
let fd = REAPER_EVENT_FD.load(Ordering::Acquire);
⋮----
libc::write(fd, (&raw const wakeup).cast(), size_of::<u64>());
⋮----
pub struct ManagedChild {
⋮----
pub struct RegistryGuard(MutexGuard<'static, HashMap<i32, u64>>);
⋮----
impl RegistryGuard {
/// Add a newly spawned managed child.
    pub fn register(&mut self, pid: u32) -> Option<ManagedChild> {
⋮----
pub fn register(&mut self, pid: u32) -> Option<ManagedChild> {
⋮----
let generation = NEXT_GENERATION.fetch_add(1, Ordering::Relaxed);
self.0.insert(pid, generation);
Some(ManagedChild { pid, generation })
⋮----
/// Return whether the PID belongs to an explicit waiter.
    #[must_use]
pub fn contains(&self, pid: i32) -> bool {
self.0.contains_key(&pid)
⋮----
/// Lock the registry for an atomic spawn-and-register or inspect-and-reap
... (267 lines truncated)
</file>

<file path="crates/openshell-sandbox/src/mechanistic_mapper.rs">
use std::collections::HashMap;
use std::net::IpAddr;
⋮----
pub fn generate_proposals(summaries: &[DenialSummary]) -> Vec<PolicyChunk> {
⋮----
let binary_key = if summary.binary.is_empty() {
⋮----
summary.binary.clone()
⋮----
.entry((summary.host.clone(), summary.port, binary_key))
.or_default()
.push(summary);
⋮----
let rule_name = generate_rule_name(host, *port);
⋮----
if let Some(timestamp) = denial.first_seen_time.as_ref() {
⋮----
.min(openshell_core::time::timestamp_to_millis(timestamp).unwrap_or(i64::MAX));
⋮----
if let Some(timestamp) = denial.last_seen_time.as_ref() {
⋮----
.max(openshell_core::time::timestamp_to_millis(timestamp).unwrap_or_default());
⋮----
if denial.l7_inspection_active || !denial.l7_request_samples.is_empty() {
⋮----
.entry((sample.method.clone(), sample.path.clone()))
.or_insert(0) += sample.count;
⋮----
if is_always_blocked_destination(host) {
⋮----
... (111 lines truncated)
</file>

<file path="crates/openshell-sandbox/src/network_broker.rs">
use std::collections::HashMap;
use std::io;
use std::mem::size_of;
⋮----
use std::sync::atomic::AtomicUsize;
⋮----
use openshell_binary_identity::ProcfsIdentityResolver;
⋮----
use openshell_isolation_interface::linux::task_memory;
⋮----
fn retry_notification_receive(error: &io::Error) -> bool {
error.kind() == io::ErrorKind::Interrupted || error.raw_os_error() == Some(libc::ENOENT)
⋮----
struct PendingOpenSlot(Arc<AtomicUsize>);
⋮----
impl Drop for PendingOpenSlot {
fn drop(&mut self) {
self.0.fetch_sub(1, Ordering::AcqRel);
⋮----
struct PendingDnsSlot(Arc<AtomicUsize>);
⋮----
impl Drop for PendingDnsSlot {
⋮----
fn acquire_pending_dns_slot(active: &Arc<AtomicUsize>) -> io::Result<PendingDnsSlot> {
⋮----
.fetch_update(Ordering::AcqRel, Ordering::Acquire, |current| {
(current < DNS_WORKER_CAPACITY).then_some(current + 1)
⋮----
.map(|_| PendingDnsSlot(Arc::clone(active)))
.map_err(|_| io::Error::from_raw_os_error(libc::EAGAIN))
... (1138 lines truncated)
</file>

<file path="crates/openshell-sandbox/src/perf.rs">
use std::sync::mpsc;
use std::thread;
⋮----
use clap::ValueEnum;
use openshell_isolation_interface::linux::workload_launcher;
⋮----
use crate::network_broker::NetworkBroker;
⋮----
pub enum Layer {
⋮----
impl Layer {
pub fn selection(value: &str) -> anyhow::Result<Vec<Self>> {
⋮----
"all" => Ok(vec![Self::Native, Self::Filtered]),
"native" => Ok(vec![Self::Native]),
"filtered" => Ok(vec![Self::Filtered]),
_ => bail!("unknown layer {value}"),
⋮----
pub enum Protocol {
⋮----
impl Protocol {
⋮----
"all" => Ok(vec![Self::TcpConnect, Self::TcpStream]),
_ => Ok(vec![
⋮----
pub struct BenchmarkOptions {
⋮----
pub struct BenchmarkReport {
⋮----
pub fn run(options: BenchmarkOptions) -> anyhow::Result<Vec<BenchmarkReport>> {
... (209 lines truncated)
</file>

<file path="crates/openshell-sandbox/src/process.rs">
use crate::child_env;
⋮----
use crate::managed_children;
use crate::sandbox;
⋮----
use miette::WrapErr;
⋮----
use openshell_core::policy::SandboxPolicy;
use std::collections::HashMap;
⋮----
use std::os::fd::AsRawFd;
⋮----
use std::path::Path;
use std::path::PathBuf;
use std::process::Stdio;
use std::sync::Arc;
⋮----
use tracing::debug;
⋮----
fn set_controlling_tty(fd: libc::c_int) -> std::io::Result<()> {
if unsafe { libc::ioctl(fd, libc::TIOCSCTTY.into(), 0) } < 0 {
return Err(std::io::Error::last_os_error());
⋮----
Ok(())
⋮----
pub struct ResolvedWorkspace {
⋮----
impl ResolvedWorkspace {
⋮----
pub fn new(root: Option<String>, use_as_home: bool) -> Self {
... (570 lines truncated)
</file>

<file path="crates/openshell-sandbox/src/provider_files.rs">
use std::collections::HashMap;
use std::ffi::CString;
use std::fs::File;
⋮----
use openshell_isolation_interface::linux::task_memory;
⋮----
type Snapshot = HashMap<String, Arc<[u8]>>;
⋮----
pub struct ProviderFiles {
⋮----
impl ProviderFiles {
pub(crate) fn validate(desired: &HashMap<String, String>) -> io::Result<()> {
if desired.len() > 64 || desired.values().map(String::len).sum::<usize>() > MAX_TOTAL_BYTES
⋮----
return Err(io::Error::new(
⋮----
validate_path(path)?;
if content.len() > MAX_FILE_BYTES {
⋮----
Ok(())
⋮----
pub(crate) fn replace(&self, desired: HashMap<String, String>) -> io::Result<()> {
⋮----
.into_iter()
.map(|(path, content)| (path, Arc::<[u8]>::from(content.into_bytes())))
.collect();
⋮----
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner) = Arc::new(next);
⋮----
... (110 lines truncated)
</file>

<file path="crates/openshell-sandbox/src/pty.rs">
use std::os::fd::RawFd;
use std::process::Command;
⋮----
use nix::pty::Winsize;
use nix::unistd::setsid;
use openshell_core::policy::SandboxPolicy;
⋮----
pub fn set_winsize(fd: RawFd, winsize: Winsize) -> std::io::Result<()> {
⋮----
return Err(std::io::Error::last_os_error());
⋮----
Ok(())
⋮----
pub fn install_dedicated_process_group(command: &mut Command) {
⋮----
command.pre_exec(|| {
⋮----
fn set_controlling_tty(fd: RawFd) -> std::io::Result<()> {
⋮----
let rc = unsafe { libc::ioctl(fd, libc::TIOCSCTTY.into(), 0) };
⋮----
pub fn install_pre_exec(
⋮----
command.pre_exec(move || {
setsid().map_err(|error| std::io::Error::other(error.to_string()))?;
set_controlling_tty(slave_fd)?;
enter_sandbox(
⋮----
prepared.take(),
⋮----
... (6 lines truncated)
</file>

<file path="crates/openshell-sandbox/src/sftp.rs">
use std::collections::HashMap;
⋮----
use std::io;
⋮----
struct SftpHandler {
⋮----
impl Drop for SftpHandler {
fn drop(&mut self) {
if let Some(done) = self.done.take() {
let _ = done.send(());
⋮----
impl SftpHandler {
fn new(root: &Path, done: tokio::sync::oneshot::Sender<()>) -> io::Result<Self> {
⋮----
let root = openat(
⋮----
.map_err(io::Error::from)?;
Ok(Self {
⋮----
done: Some(done),
⋮----
fn path(&self, path: &str) -> Result<PathBuf, StatusCode> {
⋮----
let supplied = if supplied.is_absolute() && supplied.starts_with(&self.root_path) {
⋮----
.strip_prefix(&self.root_path)
.map_err(|_| StatusCode::PermissionDenied)?
⋮----
for component in supplied.components() {
⋮----
... (364 lines truncated)
</file>

<file path="crates/openshell-sandbox/Cargo.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

[package]
name = "openshell-sandbox"
description = "OpenShell process sandbox and monitor"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true

[[bin]]
name = "openshell-sandbox"
path = "src/main.rs"

[[bin]]
name = "openshell-seccomp-perf"
path = "src/bin/seccomp-perf.rs"
required-features = ["perf-harness"]

[features]
perf-harness = []

[dependencies]
openshell-core = { path = "../openshell-core", default-features = false }
openshell-binary-identity = { path = "../openshell-binary-identity" }
openshell-isolation-interface = { path = "../openshell-isolation-interface" }
openshell-sandbox-backend = { path = "../openshell-sandbox-backend" }
openshell-ocsf = { path = "../openshell-ocsf" }
... (57 lines truncated)
</file>

<file path="crates/openshell-sandbox-backend/src/boundary_protocol.rs">
use std::fmt;
use std::io;
⋮----
use std::path::PathBuf;
use std::str::FromStr;
⋮----
use openshell_core::SandboxSessionId;
⋮----
use openshell_isolation_interface::AgentSpec;
use openshell_isolation_interface::contract::Sha256Digest;
⋮----
use serde::de::DeserializeOwned;
⋮----
const _: () = assert!(BOUNDARY_CONNECTION_WINDOW_BYTES <= i32::MAX as u32);
⋮----
pub struct CapabilityEvidence {
⋮----
impl CapabilityEvidence {
⋮----
pub const fn is_empty(self) -> bool {
⋮----
pub struct SeccompEvidence {
⋮----
pub struct NativeLinuxSandboxAuditEvidence {
⋮----
impl NativeLinuxSandboxAuditEvidence {
⋮----
pub fn validate(&self) -> Result<(), BackendError> {
let complete = self.capabilities.is_empty()
⋮----
... (729 lines truncated)
</file>

<file path="crates/openshell-sandbox-backend/src/lib.rs">
pub mod boundary_protocol;
pub mod mediation;
mod runtime;
pub mod sandbox_auth;
⋮----
pub use runtime::OpenShellRuntimeBackend;
⋮----
pub mod proto {
</file>

<file path="crates/openshell-sandbox-backend/src/mediation.rs">
use std::io;
⋮----
use serde::de::DeserializeOwned;
⋮----
use openshell_isolation_interface::contract::DnsTransport;
⋮----
pub enum MediationFrameKind {
⋮----
type Error = io::Error;
⋮----
fn try_from(value: u8) -> Result<Self, Self::Error> {
⋮----
5 => Ok(Self::DnsQuery),
6 => Ok(Self::DnsResponse),
_ => Err(io::Error::new(
⋮----
format!("unknown mediation frame kind {value}"),
⋮----
pub struct MediationFrame {
⋮----
pub struct DnsQueryWire {
⋮----
pub fn encode_json<T: Serialize>(value: &T) -> io::Result<Vec<u8>> {
⋮----
.map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
if payload.len() > MAX_METADATA_BYTES {
return Err(io::Error::new(
⋮----
Ok(payload)
⋮----
... (49 lines truncated)
</file>

<file path="crates/openshell-sandbox-backend/src/runtime.rs">
use std::collections::HashMap;
⋮----
use std::mem::size_of;
⋮----
use std::path::PathBuf;
use std::sync::Arc;
⋮----
use async_trait::async_trait;
use hyper_util::rt::TokioIo;
use openshell_isolation_interface::AgentSpec;
⋮----
use tokio::net::UnixStream;
use tokio_stream::wrappers::ReceiverStream;
⋮----
const _: () = assert!(
⋮----
fn begin_recovery_window(
⋮----
*deadline.get_or_insert(failure_time + CONNECT_RETRY_TIMEOUT)
⋮----
pub struct OpenShellRuntimeBackend {
⋮----
impl OpenShellRuntimeBackend {
⋮----
pub async fn discover_policy(
⋮----
match client.call_idempotent(Request::DiscoverPolicy).await? {
Response::ImagePolicy { yaml, invalid } => Ok((yaml, invalid)),
_ => Err(BackendError::Descriptor(
"expected image policy discovery response".to_string(),
... (1388 lines truncated)
</file>

<file path="crates/openshell-sandbox-backend/src/sandbox_auth.rs">
use std::sync::Mutex;
⋮----
use openshell_core::sandbox_generation::SandboxGenerationId;
use tonic::metadata::MetadataMap;
use uuid::Uuid;
⋮----
pub struct SandboxConnectionId(Uuid);
⋮----
impl SandboxConnectionId {
⋮----
pub fn new() -> Self {
Self(Uuid::new_v4())
⋮----
impl Default for SandboxConnectionId {
fn default() -> Self {
⋮----
pub struct SandboxProtocolPrincipal {
⋮----
impl SandboxProtocolPrincipal {
⋮----
pub const fn connection_id(&self) -> SandboxConnectionId {
⋮----
pub const fn session(&self) -> &AuthenticatedSandboxSession {
⋮----
pub struct SandboxProtocolAuthenticator {
⋮----
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
⋮----
.debug_struct("SandboxProtocolAuthenticator")
.field("verifier", &self.verifier)
... (252 lines truncated)
</file>

<file path="crates/openshell-sandbox-backend/build.rs">
use std::env;
⋮----
fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("cargo:rerun-if-changed=proto/openshell_sandbox.proto");
⋮----
.build_server(true)
.build_client(true)
.compile_protos(&["proto/openshell_sandbox.proto"], &["proto"])?;
Ok(())
</file>

<file path="crates/openshell-sandbox-backend/Cargo.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

[package]
name = "openshell-sandbox-backend"
description = "OpenShell Sandbox Protocol and its supervisor-side IsolationBackend implementation"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true

[dependencies]
openshell-core = { path = "../openshell-core", default-features = false, features = ["jwt"] }
openshell-isolation-interface = { path = "../openshell-isolation-interface" }
async-trait = "0.1"
hyper-util = { workspace = true }
prost = { workspace = true }
rcgen = { workspace = true }
rustls = { workspace = true }
rustls-pemfile = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
sha2 = { workspace = true }
socket2 = { workspace = true }
thiserror = { workspace = true }
tokio = { workspace = true }
tokio-rustls = { workspace = true }
tokio-stream = { workspace = true }
tonic = { workspace = true }
... (18 lines truncated)
</file>

<file path="crates/openshell-sdk/src/auth.rs">
pub type BearerSlot = Arc<RwLock<Option<MetadataValue<Ascii>>>>;
⋮----
pub fn bearer_metadata(token: &str) -> Result<MetadataValue<Ascii>> {
format!("Bearer {token}")
.parse()
.map_err(|_| SdkError::auth("invalid OIDC token value"))
⋮----
pub struct EdgeAuthInterceptor {
⋮----
impl EdgeAuthInterceptor {
⋮----
pub fn new(oidc_token: Option<&str>, edge_token: Option<&str>) -> Result<Self> {
⋮----
let bearer = bearer_metadata(token)?;
return Ok(Self {
bearer: Some(Arc::new(RwLock::new(Some(bearer)))),
⋮----
.map_err(|_| SdkError::auth("invalid edge token value"))?;
let cv: MetadataValue<Ascii> = format!("CF_Authorization={t}")
⋮----
.map_err(|_| SdkError::auth("invalid edge token value for cookie"))?;
(Some(hv), Some(cv))
⋮----
Ok(Self {
⋮----
pub fn noop() -> Self {
⋮----
pub fn bearer_slot(&self) -> Option<BearerSlot> {
self.bearer.clone()
⋮----
... (13 lines truncated)
</file>

<file path="crates/openshell-sdk/src/client.rs">
use crate::raw::AuthedGrpcClient;
⋮----
use openshell_core::proto;
use std::collections::HashMap;
use std::future::Future;
use std::sync::Arc;
⋮----
use tonic::transport::Channel;
⋮----
pub struct OpenShellClient {
⋮----
impl OpenShellClient {
⋮----
pub async fn connect(config: ClientConfig) -> Result<Self> {
⋮----
let interceptor = interceptor_from_config(&config)?;
let bearer_slot = interceptor.bearer_slot();
let token_source = token_source_from_config(&config);
Ok(Self {
⋮----
pub fn from_parts(channel: Channel, interceptor: EdgeAuthInterceptor) -> Self {
⋮----
pub fn channel(&self) -> Channel {
self.channel.clone()
⋮----
pub fn raw_grpc(&self) -> AuthedGrpcClient {
⋮----
self.channel.clone(),
self.interceptor.clone(),
⋮----
... (437 lines truncated)
</file>

<file path="crates/openshell-sdk/src/config.rs">
use crate::refresh::Refresh;
use std::sync::Arc;
⋮----
pub enum AuthConfig {
⋮----
impl AuthConfig {
⋮----
pub fn oidc(token: impl Into<String>) -> Self {
⋮----
token: token.into(),
⋮----
pub struct ClientConfig {
⋮----
impl ClientConfig {
pub fn new(gateway: impl Into<String>) -> Self {
⋮----
gateway: gateway.into(),
</file>

<file path="crates/openshell-sdk/src/edge_tunnel.rs">
use openshell_core::net::set_tcp_nodelay_best_effort;
use std::net::SocketAddr;
use std::sync::Arc;
⋮----
use tokio_tungstenite::tungstenite::Message;
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
use tokio_tungstenite::tungstenite::http::HeaderValue;
⋮----
pub struct EdgeTunnelProxy {
⋮----
struct TunnelConfig {
⋮----
pub async fn start_tunnel_proxy(
⋮----
let local_addr = listener.local_addr()?;
⋮----
let ws_url = format!(
⋮----
edge_token: edge_token.to_string(),
⋮----
debug!(
⋮----
tokio::spawn(accept_loop(listener, config));
⋮----
Ok(EdgeTunnelProxy { local_addr })
⋮----
async fn accept_loop(listener: TcpListener, config: Arc<TunnelConfig>) {
⋮----
match listener.accept().await {
⋮----
... (73 lines truncated)
</file>

<file path="crates/openshell-sdk/src/error.rs">
use miette::Diagnostic;
pub use openshell_core::rpc_error::ErrorDetails;
use thiserror::Error;
⋮----
pub type Result<T> = std::result::Result<T, SdkError>;
⋮----
pub enum SdkError {
⋮----
impl SdkError {
⋮----
pub fn invalid_config(message: impl Into<String>) -> Self {
⋮----
message: message.into(),
⋮----
pub fn tls(message: impl Into<String>) -> Self {
⋮----
pub fn connect(message: impl Into<String>) -> Self {
⋮----
pub fn auth(message: impl Into<String>) -> Self {
⋮----
pub fn auth_retryable(message: impl Into<String>, retryable: bool) -> Self {
⋮----
pub fn from_status(status: tonic::Status) -> Self {
let message = status.message().to_owned();
let code = status.code();
⋮----
status: Some(status),
⋮----
pub fn grpc_status(&self) -> Option<&tonic::Status> {
⋮----
... (46 lines truncated)
</file>

<file path="crates/openshell-sdk/src/lib.rs">
pub mod auth;
pub mod client;
pub mod config;
pub mod edge_tunnel;
pub mod error;
pub mod oidc;
pub mod pagination;
pub mod provider_readiness;
pub mod raw;
pub mod refresh;
pub mod transport;
pub mod types;
⋮----
pub use auth::EdgeAuthInterceptor;
⋮----
pub use error::SdkError;
</file>

<file path="crates/openshell-sdk/src/oidc.rs">
use oauth2::basic::BasicClient;
⋮----
use serde::Deserialize;
⋮----
pub struct OidcDiscovery {
⋮----
pub struct RefreshTokenInput {
⋮----
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
// Omit `refresh_token` (a long-lived secret).
f.debug_struct("RefreshTokenInput")
.field("issuer", &self.issuer)
.field("client_id", &self.client_id)
.field("scopes", &self.scopes)
.field("insecure", &self.insecure)
.finish_non_exhaustive()
⋮----
impl RefreshTokenInput {
pub fn new(
⋮----
refresh_token: refresh_token.into(),
issuer: issuer.into(),
client_id: client_id.into(),
⋮----
/// Set the scopes to resend with the refresh-token grant.
    #[must_use]
pub fn with_scopes<I, S>(mut self, scopes: I) -> Self
⋮----
self.scopes = scopes.into_iter().map(Into::into).collect();
⋮----
... (126 lines truncated)
</file>

<file path="crates/openshell-sdk/src/pagination.rs">
use crate::error::Result;
use std::future::Future;
use std::pin::Pin;
⋮----
type PageFuture<T> = Pin<Box<dyn Future<Output = Result<Page<T>>> + Send>>;
type PageFetcher<T> = Box<dyn Fn(String) -> PageFuture<T> + Send + Sync>;
⋮----
pub struct Page<T> {
⋮----
pub struct Pager<T> {
⋮----
pub(crate) fn new<F, Fut>(page_token: String, fetch: F) -> Self
⋮----
fetch: Box::new(move |token| Box::pin(fetch(token))),
next_page_token: Some(page_token),
⋮----
pub async fn next_page(&mut self) -> Result<Option<Page<T>>> {
let Some(page_token) = self.next_page_token.clone() else {
return Ok(None);
⋮----
(!page.next_page_token.is_empty()).then(|| page.next_page_token.clone());
Ok(Some(page))
⋮----
pub async fn collect_all(mut self) -> Result<Vec<T>> {
⋮----
while let Some(page) = self.next_page().await? {
items.extend(page.items);
⋮----
Ok(items)
⋮----
... (46 lines truncated)
</file>

<file path="crates/openshell-sdk/src/provider_readiness.rs">
use crate::raw::GrpcClient;
⋮----
use std::future::Future;
use std::time::Duration;
use thiserror::Error;
use tokio::time::Instant;
use tonic::service::Interceptor;
use tonic::service::interceptor::InterceptedService;
use tonic::transport::Channel;
⋮----
pub enum ProviderWaitOutcome {
⋮----
pub struct ProviderWaitResult {
⋮----
pub enum ProviderReadinessError {
⋮----
pub async fn provider_status<I>(
⋮----
let expected = request.clone();
⋮----
.get_sandbox_provider_status(request)
⋮----
.map_err(|error| ProviderReadinessError::Rpc { code: error.code() })?
.into_inner()
⋮----
.ok_or(ProviderReadinessError::InvalidStatus)?;
validate_status_for_request(&status, &expected)?;
Ok(status)
⋮----
fn validate_status_for_request(
... (305 lines truncated)
</file>

<file path="crates/openshell-sdk/src/raw.rs">
pub use openshell_core::proto;
⋮----
pub type AuthedGrpcClient = GrpcClient<
</file>

<file path="crates/openshell-sdk/src/refresh.rs">
use std::fmt;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
⋮----
pub enum RefreshError {
⋮----
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
⋮----
Self::Transient(msg) => write!(f, "transient refresh error: {msg}"),
Self::Terminal(msg) => write!(f, "terminal refresh error: {msg}"),
⋮----
fn from(value: RefreshError) -> Self {
let retryable = matches!(value, RefreshError::Transient(_));
Self::auth_retryable(value.to_string(), retryable)
⋮----
/// A freshly minted access token + its absolute expiry.
///
⋮----
///
/// `expires_at` is seconds since the Unix epoch. `None` means the token's
⋮----
/// `expires_at` is seconds since the Unix epoch. `None` means the token's
⋮----
pub struct RefreshedToken {
⋮----
// `access_token` is a bearer secret; omit it so a stray `{:?}` or a
// containing struct's derived `Debug` cannot write it to logs.
f.debug_struct("RefreshedToken")
.field("expires_at", &self.expires_at)
... (323 lines truncated)
</file>

<file path="crates/openshell-sdk/src/transport.rs">
use crate::edge_tunnel;
⋮----
use openshell_core::net::set_tcp_nodelay_best_effort;
⋮----
use std::collections::HashMap;
use std::future::Future;
use std::net::SocketAddr;
use std::sync::OnceLock;
use std::time::Duration;
use tokio::sync::Mutex;
⋮----
use tracing::debug;
⋮----
fn standard_endpoint(uri: String) -> Result<Endpoint> {
⋮----
.map(|ep| {
ep.connect_timeout(Duration::from_secs(10))
.http2_adaptive_window(true)
.http2_keep_alive_interval(Duration::from_secs(10))
.keep_alive_while_idle(true)
⋮----
.map_err(|e| SdkError::invalid_config(format!("invalid gateway URL: {e}")))
⋮----
async fn edge_tunnel_addr(server: &str, token: &str) -> Result<SocketAddr> {
let key = (server.to_string(), token.to_string());
let registry = EDGE_TUNNEL_ADDRS.get_or_init(|| Mutex::new(HashMap::new()));
⋮----
let addrs = registry.lock().await;
if let Some(addr) = addrs.get(&key).copied() {
return Ok(addr);
... (101 lines truncated)
</file>

<file path="crates/openshell-sdk/src/types.rs">
use openshell_core::proto;
use std::collections::HashMap;
use std::time::Duration;
⋮----
pub struct DeleteOptions {
⋮----
pub enum DeletionOutcome {
⋮----
fn from(value: i32) -> Self {
⋮----
fn deletion_outcomes_preserve_unknown_values() {
assert_eq!(DeletionOutcome::from(0), DeletionOutcome::Unspecified);
assert_eq!(DeletionOutcome::from(1), DeletionOutcome::Completed);
assert_eq!(DeletionOutcome::from(2), DeletionOutcome::Accepted);
assert_eq!(DeletionOutcome::from(3), DeletionOutcome::AlreadyAbsent);
assert_eq!(DeletionOutcome::from(99), DeletionOutcome::Unknown(99));
⋮----
pub struct DeletionResult {
⋮----
pub struct Health {
⋮----
pub enum ServiceStatus {
⋮----
pub enum WatchEvent {
⋮----
pub struct WatchOptions {
⋮----
pub struct LogLine {
⋮----
pub struct PlatformEvent {
... (83 lines truncated)
</file>

<file path="crates/openshell-sdk/Cargo.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

[package]
name = "openshell-sdk"
description = "Shared async Rust client for OpenShell gateways"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true

[dependencies]
openshell-core = { path = "../openshell-core" }
async-trait = "0.1"
futures = { workspace = true }
hyper = { workspace = true }
hyper-util = { workspace = true }
miette = { workspace = true }
oauth2 = { version = "5", default-features = false, features = ["reqwest"] }
reqwest = { workspace = true }
rustls = { workspace = true }
serde = { workspace = true }
thiserror = { workspace = true }
tokio = { workspace = true }
tokio-rustls = { workspace = true }
tokio-tungstenite = { workspace = true }
tonic = { workspace = true, features = ["tls-native-roots"] }
tower = { workspace = true }
tracing = { workspace = true }
... (11 lines truncated)
</file>

<file path="crates/openshell-sdk/README.md">
# openshell-sdk

`openshell-sdk` is the shared async Rust client for OpenShell gateways. It owns
gRPC channel setup, TLS, OIDC refresh, and the Cloudflare Access tunnel so the
CLI, the TUI, and language bindings share one client implementation. Callers
pass an explicit bearer token; the SDK does no filesystem access and no
gateway-name resolution.

## Two layers

- `OpenShellClient` — the curated, sandbox-focused surface: health, sandbox
  CRUD, reusable sandbox template CRUD, readiness/deletion waits, and
  non-streaming exec.
- `raw` — direct access to the generated tonic clients for RPCs the curated
  surface doesn't yet cover (providers, policy, logs, settings, SSH,
  forwarding).

## Auth and refresh

The curated surface drives OIDC refresh automatically: proactively before a
request and reactively on `Unauthenticated`. Refreshes are single-flight, so
only one is in flight at a time.

The plain `raw_grpc` accessor does not refresh; it returns a client bound to
the current token. When a refresher is wired, use `raw_grpc_fresh` to refresh before the call, and
`force_refresh` to recover after a raw RPC returns `Unauthenticated`.

The SDK consumes a `Refresh` trait that the caller implements; it does not run
the OIDC browser flow itself. Its non-interactive refresh-token exchange also
accepts scopes that identity providers may require to select the API resource
... (168 lines truncated)
</file>

<file path="crates/openshell-server/src/auth/authenticator.rs">
use super::principal::Principal;
use async_trait::async_trait;
use std::sync::Arc;
use tonic::Status;
⋮----
pub trait Authenticator: Send + Sync + 'static {
/// Inspect an inbound request and return the authenticated principal.
    ///
⋮----
///
    /// - `Ok(Some(principal))` — this authenticator recognized the caller.
⋮----
/// - `Ok(Some(principal))` — this authenticator recognized the caller.
    ///   The chain stops and the principal is inserted into request
⋮----
///   The chain stops and the principal is inserted into request
    ///   extensions.
⋮----
///   extensions.
    /// - `Ok(None)` — this authenticator does not apply (e.g. no Bearer
⋮----
/// - `Ok(None)` — this authenticator does not apply (e.g. no Bearer
    ///   token for an OIDC authenticator). The chain falls through to
⋮----
///   token for an OIDC authenticator). The chain falls through to
    ///   the next authenticator.
⋮----
///   the next authenticator.
    /// - `Err(status)` — this authenticator applies but rejected the
⋮----
... (123 lines truncated)
</file>

<file path="crates/openshell-server/src/auth/authz.rs">
use super::identity::Identity;
⋮----
use tonic::Status;
use tracing::debug;
⋮----
pub struct AuthzPolicy {
⋮----
impl AuthzPolicy {
⋮----
pub fn validate(&self) -> Result<(), String> {
let admin_set = !self.admin_role.is_empty();
let user_set = !self.user_role.is_empty();
⋮----
return Err(format!(
⋮----
Ok(())
⋮----
pub fn check(&self, identity: &Identity, method: &str) -> Result<(), Status> {
⋮----
Some(entry) if entry.global_role.is_some() => Some(&self.admin_role),
Some(entry) if entry.workspace_role.is_some() => Some(&self.user_role),
⋮----
None => Some(&self.user_role),
⋮----
&& !required.is_empty()
⋮----
let has_role = identity.roles.iter().any(|r| r == required)
|| (!self.admin_role.is_empty()
⋮----
&& identity.roles.iter().any(|r| r == &self.admin_role));
... (150 lines truncated)
</file>

<file path="crates/openshell-server/src/auth/compute_driver.rs">
use super::authenticator::Authenticator;
⋮----
use crate::compute::ComputeRuntime;
use async_trait::async_trait;
use tonic::Status;
⋮----
pub struct ComputeDriverAuthenticator {
⋮----
impl ComputeDriverAuthenticator {
pub fn new(compute: ComputeRuntime) -> Self {
⋮----
impl Authenticator for ComputeDriverAuthenticator {
async fn authenticate(
⋮----
return Ok(None);
⋮----
.get(http::header::AUTHORIZATION)
.and_then(|value| value.to_str().ok())
.and_then(|value| value.strip_prefix("Bearer "))
⋮----
let authenticated = self.compute.authenticate_sandbox(credential).await?;
⋮----
if sandbox_id.is_empty() {
return Err(Status::permission_denied(
⋮----
if authenticated.runtime_identity.is_empty() {
⋮----
Ok(Some(Principal::Sandbox(SandboxPrincipal {
⋮----
driver_name: self.compute.configured_driver_name().to_string(),
... (65 lines truncated)
</file>

<file path="crates/openshell-server/src/auth/descriptor_authz.rs">
use std::collections::HashMap;
use std::sync::LazyLock;
⋮----
pub struct DescriptorAuthEntry {
⋮----
impl DescriptorAuthEntry {
⋮----
pub fn effective_role(&self) -> Option<Role> {
self.global_role.as_deref().map_or_else(
⋮----
self.workspace_role.as_deref().and_then(|wr| match wr {
"admin" => Some(Role::Admin),
"user" => Some(Role::User),
⋮----
"platform_admin" => Some(Role::Admin),
⋮----
pub fn is_workspace_scoped(&self) -> bool {
self.workspace_role.is_some()
⋮----
pub struct DescriptorAuthTable {
⋮----
impl DescriptorAuthTable {
fn from_descriptor_set(bytes: &[u8]) -> Result<Self, String> {
⋮----
DescriptorPool::decode(bytes).map_err(|e| format!("decode descriptor pool: {e}"))?;
⋮----
.get_extension_by_name(AUTHORIZATION_EXTENSION)
.ok_or_else(|| {
format!("extension {AUTHORIZATION_EXTENSION} not found in descriptor pool")
⋮----
... (179 lines truncated)
</file>

<file path="crates/openshell-server/src/auth/extension_mint_limit.rs">
use std::collections::HashMap;
use std::sync::Mutex;
⋮----
struct Window {
⋮----
pub struct ExtensionMintLimiter {
⋮----
impl Default for ExtensionMintLimiter {
fn default() -> Self {
⋮----
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
⋮----
.debug_struct("ExtensionMintLimiter")
.field("window", &self.window)
.field("max_per_window", &self.max_per_window)
.finish_non_exhaustive()
⋮----
impl ExtensionMintLimiter {
⋮----
pub fn new(window: Duration, max_per_window: u32) -> Self {
⋮----
pub fn try_acquire(&self, sandbox_id: &str) -> bool {
self.try_acquire_at(sandbox_id, Instant::now())
⋮----
fn try_acquire_at(&self, sandbox_id: &str, now: Instant) -> bool {
⋮----
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
⋮----
if windows.len() >= PRUNE_THRESHOLD {
... (29 lines truncated)
</file>

<file path="crates/openshell-server/src/auth/guard.rs">
use super::principal::Principal;
use super::principal::SandboxPrincipal;
use tonic::Status;
use tracing::info;
⋮----
pub fn ensure_sandbox_scope(principal: &Principal, claimed_sandbox_id: &str) -> Result<(), Status> {
⋮----
Principal::User(_) => Ok(()),
Principal::Peer(_) => Err(Status::permission_denied(
⋮----
Ok(())
⋮----
info!(
⋮----
Err(Status::permission_denied(
⋮----
Principal::Anonymous => Err(Status::unauthenticated(
⋮----
pub fn enforce_sandbox_scope<T>(
⋮----
.extensions()
⋮----
.cloned()
.ok_or_else(|| Status::unauthenticated("missing principal"))?;
ensure_sandbox_scope(&principal, claimed_sandbox_id)?;
Ok(principal)
⋮----
pub fn ensure_sandbox_principal_scope(
⋮----
ensure_sandbox_scope(principal, claimed_sandbox_id)?;
... (57 lines truncated)
</file>

<file path="crates/openshell-server/src/auth/http.rs">
use http::header;
use serde::Deserialize;
use std::sync::Arc;
⋮----
use crate::ServerState;
⋮----
fn is_valid_code(code: &str) -> bool {
let bytes = code.as_bytes();
bytes.len() == 8
⋮----
.iter()
.all(|b| b.is_ascii_uppercase() || b.is_ascii_digit())
⋮----
struct ConnectParams {
⋮----
/// One-time confirmation code generated by the CLI. Displayed on the
    /// connect page so the user can verify it matches their terminal before
⋮----
/// connect page so the user can verify it matches their terminal before
    /// clicking Connect. Sent back in the XHR POST to the CLI callback
⋮----
/// clicking Connect. Sent back in the XHR POST to the CLI callback
    /// server for cryptographic binding.
⋮----
/// server for cryptographic binding.
    code: String,
⋮----
/// Create the auth router.
pub fn router(state: Arc<ServerState>) -> Router {
⋮----
... (291 lines truncated)
</file>

<file path="crates/openshell-server/src/auth/identity.rs">
pub struct Identity {
⋮----
pub enum IdentityProvider {
</file>

<file path="crates/openshell-server/src/auth/method_authz.rs">
pub use super::descriptor_authz::DescriptorAuthEntry;
⋮----
pub enum AuthMode {
⋮----
pub enum Role {
⋮----
pub fn lookup(method: &str) -> Option<&'static DescriptorAuthEntry> {
⋮----
/// All registered RPC paths across every service.
#[cfg(test)]
pub fn all_paths() -> impl Iterator<Item = &'static str> {
⋮----
pub fn required_role(method: &str) -> Option<Role> {
lookup(method).and_then(DescriptorAuthEntry::effective_role)
⋮----
pub fn is_unauthenticated(method: &str) -> bool {
matches!(
⋮----
pub fn is_sandbox_callable(method: &str) -> bool {
⋮----
pub fn is_user_callable(method: &str) -> bool {
match lookup(method).map(|m| m.auth_mode) {
⋮----
pub fn is_peer_callable(method: &str) -> bool {
matches!(lookup(method).map(|m| m.auth_mode), Some(AuthMode::Peer))
⋮----
mod tests {
⋮----
fn every_proto_rpc_has_an_annotation() {
for path in all_paths() {
... (34 lines truncated)
</file>

<file path="crates/openshell-server/src/auth/mod.rs">
pub mod authenticator;
pub mod authz;
pub mod compute_driver;
pub mod descriptor_authz;
pub mod extension_mint_limit;
pub mod guard;
mod http;
pub mod identity;
pub mod method_authz;
pub mod oidc;
pub mod peer;
pub mod principal;
pub mod sandbox_jwt;
pub mod sandbox_methods;
pub mod sandbox_session;
pub mod workspace_authz;
⋮----
pub use http::router;
</file>

<file path="crates/openshell-server/src/auth/peer.rs">
use super::authenticator::Authenticator;
⋮----
use async_trait::async_trait;
⋮----
use k8s_openapi::apimachinery::pkg::apis::meta::v1::ObjectMeta;
⋮----
use std::collections::HashMap;
use std::path::PathBuf;
⋮----
use tonic::Status;
⋮----
pub struct ResolvedGatewayPeerIdentity {
⋮----
pub trait GatewayPeerIdentityResolver: Send + Sync + 'static {
⋮----
struct PeerTokenReviewIdentity {
⋮----
pub struct PeerServiceAccountAuthenticator {
⋮----
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("PeerServiceAccountAuthenticator")
.finish_non_exhaustive()
⋮----
impl PeerServiceAccountAuthenticator {
pub fn new(resolver: Arc<dyn GatewayPeerIdentityResolver>) -> Self {
⋮----
impl Authenticator for PeerServiceAccountAuthenticator {
async fn authenticate(
⋮----
return Ok(None);
... (379 lines truncated)
</file>

<file path="crates/openshell-server/src/auth/principal.rs">
use super::identity::Identity;
⋮----
pub enum Principal {
⋮----
pub struct UserPrincipal {
⋮----
pub struct SandboxPrincipal {
⋮----
pub struct PeerPrincipal {
⋮----
pub enum SandboxIdentitySource {
</file>

<file path="crates/openshell-server/src/auth/sandbox_jwt.rs">
use super::authenticator::Authenticator;
⋮----
use async_trait::async_trait;
⋮----
use serde::Serialize;
⋮----
use tonic::Status;
use tracing::warn;
⋮----
use openshell_core::SandboxSessionId;
⋮----
use openshell_core::sandbox_generation::SandboxGenerationId;
⋮----
pub struct GatewayJwks {
⋮----
pub struct GatewayJwk {
⋮----
pub struct ExtensionJwtIssuer {
⋮----
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ExtensionJwtIssuer")
.field("kid", &self.kid)
.field("issuer", &self.issuer)
.field("gateway_audience", &self.gateway_audience)
.field("ttl", &self.ttl)
.finish_non_exhaustive()
⋮----
/// Outcome of a successful mint.
#[derive(Debug, Clone)]
pub struct MintedToken {
... (277 lines truncated)
</file>

<file path="crates/openshell-server/src/auth/sandbox_methods.rs">
pub fn is_sandbox_callable(path: &str) -> bool {
⋮----
mod tests {
⋮----
fn supervisor_callbacks_are_allowed() {
assert!(is_sandbox_callable(
⋮----
assert!(is_sandbox_callable("/openshell.v1.OpenShell/RelayStream"));
assert!(!is_sandbox_callable("/openshell.v1.OpenShell/PeerRelay"));
⋮----
fn user_and_admin_methods_are_not_allowed() {
assert!(!is_sandbox_callable(
⋮----
assert!(!is_sandbox_callable("/openshell.v1.OpenShell/StopSandbox"));
assert!(!is_sandbox_callable("/openshell.v1.OpenShell/StartSandbox"));
</file>

<file path="crates/openshell-server/src/auth/sandbox_session.rs">
use std::collections::HashMap;
⋮----
use openshell_core::sandbox_generation::SandboxGenerationId;
⋮----
use tonic::Status;
use uuid::Uuid;
⋮----
use crate::persistence::Store;
⋮----
pub struct RefreshRequestHash(String);
⋮----
impl RefreshRequestHash {
⋮----
pub fn from_extension_services(names: &[String]) -> Self {
⋮----
digest.update(b"openshell-refresh-v1\0");
⋮----
let length = u64::try_from(name.len()).unwrap_or(u64::MAX);
digest.update(length.to_be_bytes());
digest.update(name.as_bytes());
⋮----
Self(hex::encode(digest.finalize()))
⋮----
fn parse(value: String) -> Result<Self, SessionJwtError> {
if value.len() != 64 || !value.bytes().all(|byte| byte.is_ascii_hexdigit()) {
return Err(SessionJwtError::InvalidRuntimeIdentity);
⋮----
Ok(Self(value))
⋮----
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
... (251 lines truncated)
</file>

<file path="crates/openshell-server/src/auth/workspace_authz.rs">
use super::principal::Principal;
⋮----
use tonic::Status;
⋮----
use crate::persistence::Store;
⋮----
fn shell_quote_for_hint(value: &str) -> String {
format!("'{}'", value.replace('\'', "'\"'\"'"))
⋮----
pub enum MinWorkspaceRole {
⋮----
impl MinWorkspaceRole {
fn as_str(self) -> &'static str {
⋮----
/// Result of a successful workspace authorization check.
#[derive(Debug)]
pub struct AuthorizedWorkspace {
/// Explicit workspace name selected by the caller.
    pub workspace: String,
/// How the caller was authorized.
    pub grant: AuthGrant,
⋮----
/// How a caller was granted workspace access.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AuthGrant {
/// Caller holds the platform admin OIDC role — bypasses membership.
    PlatformAdmin,
/// Caller is a workspace member with the given role.
    Member(ProtoWorkspaceRole),
/// Caller is a sandbox principal — scoped by JWT, no membership check.
... (261 lines truncated)
</file>

<file path="crates/openshell-server/src/compute/driver_config.rs">
use crate::config_file;
use crate::defaults::LocalTlsPaths;
⋮----
use serde::Deserialize;
use std::collections::BTreeMap;
use std::path::PathBuf;
⋮----
pub struct GuestTlsPaths {
⋮----
impl GuestTlsPaths {
pub(crate) fn as_path(&self) -> &std::path::Path {
⋮----
pub(crate) fn validate_configuration(
⋮----
if tls_disabled && gateway.is_some_and(|gateway| gateway.guest_tls_ca.is_some()) {
return Err(
"guest_tls_ca requires gateway TLS; remove it or omit --disable-tls".to_string(),
⋮----
Ok(())
⋮----
pub(crate) fn resolve(
⋮----
return Ok(None);
⋮----
if let Some(ca) = gateway.and_then(|gateway| gateway.guest_tls_ca.as_ref()) {
if !ca.is_file() {
return Err(format!(
⋮----
return Ok(Some(Self { ca: ca.clone() }));
⋮----
... (223 lines truncated)
</file>

<file path="crates/openshell-server/src/compute/lease.rs">
use openshell_core::time::now_ms;
⋮----
use std::sync::Arc;
use std::time::Duration;
use thiserror::Error;
⋮----
pub enum LeaseError {
⋮----
struct LeasePayload {
⋮----
pub struct LeaseRecord {
⋮----
pub struct LeaseGuard {
⋮----
impl LeaseGuard {
⋮----
pub fn resource_version(&self) -> u64 {
⋮----
pub struct ReconcilerLease {
⋮----
impl ReconcilerLease {
pub fn new(store: Arc<Store>, replica_id: String, ttl: Duration) -> Self {
⋮----
pub fn replica_id(&self) -> &str {
⋮----
pub async fn try_acquire(&self) -> Result<LeaseGuard, LeaseError> {
let acquired_at_ms = now_ms();
⋮----
holder: self.replica_id.clone(),
⋮----
... (241 lines truncated)
</file>

<file path="crates/openshell-server/src/compute/mod.rs">
pub mod driver_config;
pub mod lease;
pub mod provisioning_deadline;
pub mod rootfs_tar;
⋮----
use crate::grpc::policy::SANDBOX_SETTINGS_OBJECT_TYPE;
use crate::otel_tracing::TraceContextInterceptor;
⋮----
use crate::sandbox_index::SandboxIndex;
use crate::sandbox_watch::SandboxWatchBus;
⋮----
use crate::supervisor_session::SupervisorSessionRegistry;
use crate::tracing_bus::TracingLogBus;
⋮----
use hyper_util::rt::TokioIo;
⋮----
use openshell_core::proto::ServiceAuthorizationMode;
⋮----
use openshell_core::telemetry::TelemetryComputeDriver;
⋮----
use prost::Message;
use std::collections::HashMap;
use std::fmt;
use std::future::Future;
⋮----
use std::pin::Pin;
⋮----
use tokio::net::UnixStream;
⋮----
use tonic::transport::Channel;
... (4718 lines truncated)
</file>

<file path="crates/openshell-server/src/compute/provisioning_deadline.rs">
use openshell_core::proto::SandboxProvisioning;
⋮----
pub struct ConfigurationChange {
⋮----
pub(super) struct ProvisioningDeadline {
⋮----
enum DeadlineState {
⋮----
impl ProvisioningDeadline {
⋮----
pub fn from_record(record: &SandboxProvisioning) -> Result<Self, String> {
fn millis(value: Option<&prost_types::Timestamp>, field: &str) -> Result<i64, String> {
let value = value.ok_or_else(|| format!("missing provisioning {field}"))?;
timestamp_to_millis(value).map_err(|_| format!("invalid provisioning {field}"))
⋮----
if record.attempt_id.is_empty() || record.configuration_change_id.is_empty() {
return Err("missing provisioning identity".into());
⋮----
if record.deadline.is_some() && record.timeout_time.is_some() {
return Err("provisioning cannot be armed and expired".into());
⋮----
let state = if record.timeout_time.is_some() {
⋮----
expired_at_ms: millis(record.timeout_time.as_ref(), "timeout time")?,
⋮----
} else if record.deadline.is_some() {
⋮----
deadline_at_ms: millis(record.deadline.as_ref(), "deadline")?,
⋮----
Ok(Self {
... (363 lines truncated)
</file>

<file path="crates/openshell-server/src/compute/rootfs_tar.rs">
use std::collections::HashMap;
⋮----
use std::sync::Mutex;
⋮----
use openshell_core::time::now_ms;
use rand::RngCore;
use tonic::Status;
⋮----
fn unknown_token() -> Status {
⋮----
pub struct StagingSlot {
⋮----
struct StagingEntry {
⋮----
pub struct StagedRootfsTar {
⋮----
impl StagedRootfsTar {
pub fn path(&self) -> &Path {
⋮----
pub fn disarm(&mut self) {
⋮----
impl Drop for StagedRootfsTar {
fn drop(&mut self) {
let Some(dir) = self.dir.take() else {
⋮----
handle.spawn_blocking(move || remove_staging_dir(&dir));
⋮----
Err(_) => remove_staging_dir(&dir),
⋮----
fn remove_staging_dir(dir: &Path) {
... (279 lines truncated)
</file>

<file path="crates/openshell-server/src/grpc/mutation_replay/ordinary/tests.rs">
use crate::auth::principal::UserPrincipal;
use crate::grpc::mutation_replay::tests::reason;
⋮----
use openshell_core::proto::datamodel::v1::ObjectMeta;
⋮----
use tonic::Code;
⋮----
async fn protected_state() -> (tempfile::TempDir, Arc<ServerState>) {
let directory = tempfile::tempdir().unwrap();
let mut state = test_server_state().await;
configure_key(&mut state, &directory);
⋮----
fn configure_key(state: &mut Arc<ServerState>, directory: &tempfile::TempDir) {
let key = directory.path().join("private-key");
std::fs::write(&key, b"test-only stable private fingerprint material").unwrap();
Arc::get_mut(state).unwrap().config.gateway_jwt =
Some(openshell_core::config::GatewayJwtConfig {
⋮----
public_key_path: directory.path().join("public"),
kid_path: directory.path().join("kid"),
gateway_id: "test".into(),
⋮----
pub(in crate::grpc::mutation_replay) async fn exercise_protected_backend(url: &str) {
use crate::grpc::mutation_replay::tests::state_for;
⋮----
let mut first = state_for(Store::connect(url).await.unwrap()).await;
let mut second = state_for(Store::connect(url).await.unwrap()).await;
configure_key(&mut first, &directory);
configure_key(&mut second, &directory);
⋮----
... (453 lines truncated)
</file>

<file path="crates/openshell-server/src/grpc/mutation_replay/streaming/tests.rs">
use crate::grpc::test_support::authed_request;
⋮----
use openshell_core::proto::datamodel::v1::ObjectMeta;
⋮----
use prost::Message;
⋮----
use tokio_stream::StreamExt;
⋮----
type ExecClient =
⋮----
async fn wire_client(
⋮----
use crate::grpc::OpenShellService;
use openshell_core::proto::open_shell_server::OpenShellServer;
use tokio_stream::wrappers::TcpListenerStream;
⋮----
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let principal = authed_request(())
.extensions()
⋮----
.unwrap()
.clone();
⋮----
request.extensions_mut().insert(principal.clone());
⋮----
request.extensions_mut().insert(barrier.clone());
⋮----
request.extensions_mut().insert(original.clone());
⋮----
... (283 lines truncated)
</file>

<file path="crates/openshell-server/src/grpc/mutation_replay/ordinary.rs">
pub(super) mod tests;
⋮----
use std::collections::HashMap;
⋮----
use prost::Message;
⋮----
use crate::auth::principal::Principal;
⋮----
pub(in crate::grpc) struct Reference {
⋮----
impl Reference {
fn new(resource: &(impl ObjectId + GetResourceVersion)) -> Self {
⋮----
id: resource.object_id().into(),
version: resource.get_resource_version(),
⋮----
async fn restore<
⋮----
restore_resource(
⋮----
id: self.id.clone(),
⋮----
pub struct Facts(Arc<Mutex<WriteFacts>>);
⋮----
struct WriteFacts {
⋮----
impl Facts {
pub(crate) fn global(&self) -> Result<(), Status> {
self.0.lock().map_err(|_| uncertain())?.global = true;
Ok(())
... (150 lines truncated)
</file>

<file path="crates/openshell-server/src/grpc/mutation_replay/streaming.rs">
mod tests;
⋮----
use std::sync::Arc;
⋮----
use openshell_core::rpc_error;
⋮----
use prost_reflect::DynamicMessage;
use tokio::sync::Mutex;
use tokio_stream::wrappers::ReceiverStream;
⋮----
use crate::ServerState;
use crate::auth::principal::Principal;
use crate::grpc::sandbox;
use crate::persistence::Store;
⋮----
pub(in crate::grpc) type ExecStream = ReceiverStream<Result<ExecSandboxEvent, Status>>;
⋮----
pub(in crate::grpc) struct InteractiveInput(
⋮----
pub(in crate::grpc) fn start(input: &ExecSandboxInput) -> Result<&ExecSandboxRequest, Status> {
match input.payload.as_ref() {
Some(exec_sandbox_input::Payload::Start(request)) => Ok(request),
_ => Err(rpc_error::invalid_argument(
⋮----
async fn authorize(
⋮----
crate::auth::workspace_authz::selected_workspace_name(request.workspace_scope.as_ref())?,
⋮----
let mut scope = named_scope(state, sandbox.object_workspace()).await?;
scope.target_id = Some(sandbox.object_id().into());
... (37 lines truncated)
</file>

<file path="crates/openshell-server/src/grpc/mutation_replay/tests.rs">
use openshell_core::proto::datamodel::v1::ObjectMeta;
use openshell_core::proto::open_shell_server::OpenShell;
⋮----
use openshell_core::rpc_error::StatusExt;
use std::collections::HashMap;
⋮----
use std::time::Duration;
use tonic::Code;
⋮----
fn create(name: &str) -> CreateWorkspaceRequest {
⋮----
name: name.into(),
request_id: uuid::Uuid::new_v4().to_string(),
⋮----
pub(super) fn reason(status: &Status) -> String {
assert!(status.get_error_details().retry_info().is_none());
⋮----
.get_error_details()
.error_info()
.unwrap_or_else(|| panic!("missing structured reason: {status:?}"))
⋮----
.clone()
⋮----
pub(super) async fn state_for(store: Store) -> Arc<ServerState> {
⋮----
crate::ensure_default_workspace(&store).await.unwrap();
let compute = crate::compute::new_test_runtime(store.clone()).await;
⋮----
openshell_core::Config::new(None).with_credential_drivers(["test-static"]),
⋮----
... (379 lines truncated)
</file>

<file path="crates/openshell-server/src/grpc/policy/endpoint_status_tests.rs">
use openshell_core::endpoint_status::endpoint_id;
⋮----
use tonic::Code;
⋮----
fn timestamp(value: &str) -> prost_types::Timestamp {
value.parse().expect("valid test timestamp")
⋮----
fn test_initial_endpoint_status(endpoint_id: &str, host: &str, path: &str) -> EndpointStatus {
⋮----
endpoint_id: endpoint_id.to_string(),
host: host.to_string(),
ports: vec![443],
path: path.to_string(),
⋮----
fn ready_condition() -> SandboxCondition {
⋮----
r#type: "Ready".to_string(),
status: "True".to_string(),
reason: "SupervisorReady".to_string(),
⋮----
fn register_session(state: &ServerState, sandbox_id: &str, session_id: &str) {
⋮----
state.supervisor_sessions.register(
sandbox_id.to_string(),
session_id.to_string(),
⋮----
async fn stored_sandbox(state: &ServerState, sandbox_id: &str) -> Sandbox {
⋮----
.expect("load sandbox")
.expect("sandbox remains present")
... (532 lines truncated)
</file>

<file path="crates/openshell-server/src/grpc/policy/endpoint_status.rs">
use crate::ServerState;
⋮----
use crate::policy_store::PolicyStoreExt;
use crate::provider_profile_sources::EffectiveProviderProfileCatalog;
⋮----
use crate::supervisor_session::EndpointReportCursor;
use openshell_core::GetResourceVersion;
use openshell_core::endpoint_status::initial_endpoint_status;
use openshell_core::mcp::is_mcp_protocol;
⋮----
use prost::Message;
⋮----
use std::sync::Arc;
⋮----
use tracing::warn;
⋮----
struct ExpectedEndpoint {
⋮----
struct EndpointContext {
⋮----
pub(in crate::grpc) async fn handle_report_endpoint_status(
⋮----
let sandbox_id = request.get_ref().sandbox_id.clone();
⋮----
let req = request.into_inner();
⋮----
return Ok(Response::new(response));
⋮----
handle_report_endpoint_status_inner(state, req).await
⋮----
... (270 lines truncated)
</file>

<file path="crates/openshell-server/src/grpc/policy/provisioning_clock.rs">
use crate::compute::provisioning_deadline::ConfigurationChange;
⋮----
use crate::policy_store::PolicyStoreExt;
use crate::storage_proto::StoredProviderProfile;
⋮----
use openshell_core::time::timestamp_to_millis;
use prost::Message;
⋮----
use std::collections::BTreeSet;
⋮----
pub async fn configuration_change(
⋮----
let global = load_global_settings(store)
⋮----
.map_err(|e| e.to_string())?;
let local = load_sandbox_settings(store, sandbox.object_workspace(), sandbox.object_name())
⋮----
.as_ref()
.and_then(|meta| meta.created_time.as_ref())
.and_then(|time| timestamp_to_millis(time).ok())
.unwrap_or(0);
⋮----
.keys()
.chain(local.change_clocks.keys())
.collect();
⋮----
if key != POLICY_SETTING_KEY && openshell_core::settings::setting_for_key(key).is_none() {
⋮----
if let Some(clock) = global.change_clocks.get(key) {
sources.push((format!("global:{key}"), clock.id.clone()));
... (123 lines truncated)
</file>

<file path="crates/openshell-server/src/grpc/auth_rpc.rs">
use crate::ServerState;
use crate::auth::identity::IdentityProvider;
⋮----
use std::sync::Arc;
⋮----
pub async fn handle_get_current_user(
⋮----
return Err(Status::permission_denied(
⋮----
Ok(Response::new(GetCurrentUserResponse {
⋮----
display_name: identity.display_name.unwrap_or_default(),
⋮----
.to_string(),
⋮----
pub async fn handle_issue_sandbox_token(
⋮----
.extensions()
⋮----
.cloned()
.ok_or_else(|| Status::unauthenticated("missing principal"))?;
⋮----
debug!(
⋮----
.as_ref()
.ok_or_else(|| {
warn!(
⋮----
let sandbox_record = ensure_sandbox_exists(state, &sandbox.sandbox_id).await?;
⋮----
... (452 lines truncated)
</file>

<file path="crates/openshell-server/src/grpc/interactive_exec_tests.rs">
use std::time::Duration;
⋮----
struct ExecPeer {
⋮----
impl Drop for ExecPeer {
fn drop(&mut self) {
if let Some(task) = self.output_task.take() {
task.abort();
⋮----
impl Handler for ExecPeer {
type Error = russh::Error;
⋮----
async fn auth_none(&mut self, _user: &str) -> Result<Auth, Self::Error> {
Ok(Auth::Accept)
⋮----
async fn channel_open_session(
⋮----
reply.accept().await;
self.channel = Some(channel);
Ok(())
⋮----
async fn exec_request(
⋮----
session.channel_success(channel)?;
⋮----
let channel = self.channel.take().unwrap();
let release = self.release_output.clone();
⋮----
self.echo_tx = Some(echo_tx);
self.output_task = Some(tokio::spawn(async move {
... (184 lines truncated)
</file>

<file path="crates/openshell-server/src/grpc/mod.rs">
mod auth_rpc;
pub mod mutation_replay;
pub mod policy;
pub mod provider;
pub mod provider_readiness;
mod sandbox;
pub use sandbox::mint_persisted_authentication;
mod service;
mod validation;
pub mod workspace;
⋮----
use std::collections::BTreeMap;
use std::pin::Pin;
use std::sync::Arc;
use tokio_stream::wrappers::ReceiverStream;
⋮----
use crate::ServerState;
⋮----
pub fn persistence_error_to_status(
⋮----
use crate::persistence::PersistenceError;
⋮----
format!(
⋮----
other => Status::internal(format!("{operation} failed: {other}")),
⋮----
fn deletion_outcome(deleted: bool, allow_missing: bool, resource: &str) -> Result<i32, Status> {
use openshell_core::proto::DeletionOutcome;
⋮----
Ok(DeletionOutcome::Completed.into())
... (380 lines truncated)
</file>

<file path="crates/openshell-server/src/grpc/mutation_replay.rs">
use std::collections::BTreeMap;
⋮----
use prost::Message;
⋮----
use tokio::sync::Semaphore;
⋮----
use crate::ServerState;
use crate::auth::identity::IdentityProvider;
use crate::auth::principal::Principal;
⋮----
.expect("compiled protobuf descriptor set")
⋮----
struct Admission {
⋮----
struct Protection {
⋮----
pub struct OriginalMutation(pub(crate) Vec<u8>);
⋮----
pub(super) enum Success {
⋮----
pub(super) struct Scope {
⋮----
struct AuthorizationBarrier {
⋮----
pub(super) trait Mutation: Message + Default + Send + Sync + 'static {
⋮----
// Streaming producers, not returned stream handles, confirm completion.
⋮----
/// Name-addressed targets must keep their identity unless an interceptor
    /// actually changes the selector, not merely another request field.
... (312 lines truncated)
</file>

<file path="crates/openshell-server/src/grpc/mutation_tests.rs">
use openshell_core::proto::datamodel::v1::ObjectMeta;
⋮----
use tonic::Code;
⋮----
fn metadata(id: &str) -> ObjectMeta {
⋮----
id: id.into(),
name: id.into(),
workspace: "default".into(),
⋮----
async fn every_delete_requires_explicit_allow_missing() {
let state = test_server_state().await;
⋮----
.put_message(&Sandbox {
metadata: Some(metadata("parent-sandbox")),
⋮----
.unwrap();
⋮----
.put_message(&Provider {
metadata: Some(metadata("parent-provider")),
⋮----
macro_rules! check {
⋮----
check!(
⋮----
async fn allow_missing_does_not_hide_missing_parents_or_invalid_requests() {
⋮----
authed_request(DeleteServiceRequest {
sandbox: "missing-parent".into(),
⋮----
... (42 lines truncated)
</file>

<file path="crates/openshell-server/src/grpc/policy.rs">
mod endpoint_status;
mod provisioning_clock;
pub use provisioning_clock::configuration_change;
⋮----
use crate::ServerState;
use crate::auth::principal::Principal;
⋮----
use crate::pagination::Pagination;
⋮----
use crate::provider_profile_sources::EffectiveProviderProfileCatalog;
⋮----
use crate::provider_profile_sources::ProviderProfileSources;
⋮----
use crate::storage_proto::StoredProviderProfile;
⋮----
use openshell_core::proto::policy_merge_operation;
use openshell_core::proto::setting_value;
⋮----
use prost::Message;
⋮----
use std::net::IpAddr;
use std::sync::Arc;
⋮----
use crate::persistence::current_time_ms;
⋮----
struct LegacyStoredNetworkBinary {
⋮----
struct LegacyStoredNetworkPolicyRule {
⋮----
struct LegacyStoredSandboxPolicy {
... (5916 lines truncated)
</file>

<file path="crates/openshell-server/src/grpc/provider_readiness_tests.rs">
use crate::config_update_operation::CONFIG_UPDATE_OPERATION_OBJECT_TYPE;
⋮----
use crate::persistence::WriteCondition;
use crate::storage_proto::StoredConfigUpdateOperation;
use openshell_core::proto::SandboxSpec;
use openshell_core::proto::datamodel::v1::ObjectMeta;
use prost::Message;
use std::collections::HashMap;
⋮----
struct TestRegistry(crate::supervisor_session::SupervisorSessionRegistry);
⋮----
fn register_session(
⋮----
let session_id = Uuid::new_v4().to_string();
⋮----
registry.register(
hello.sandbox_id.clone(),
session_id.clone(),
⋮----
assert!(registry.initialize_endpoint_status_authority(&hello.sandbox_id, &session_id));
registry.initialize_provider_readiness(&hello.sandbox_id, &session_id, evidence)?;
Ok(session_id)
⋮----
impl TestRegistry {
fn register(&self, hello: &SupervisorHello) -> Result<String, Status> {
register_session(&self.0, hello)
⋮----
fn accept(
⋮----
assert_eq!(session_id, observation.session_id);
... (494 lines truncated)
</file>

<file path="crates/openshell-server/src/grpc/provider_readiness.rs">
use std::sync::Arc;
⋮----
use uuid::Uuid;
⋮----
use crate::ServerState;
⋮----
use crate::auth::workspace_authz::MinWorkspaceRole;
use crate::config_update_operation;
use crate::persistence::ObjectType;
⋮----
pub struct ProviderReadinessEvidence {
⋮----
impl ProviderReadinessEvidence {
⋮----
pub(crate) fn belongs_to_instance(&self, active_instance_id: &str) -> bool {
!active_instance_id.is_empty() && self.network_instance_id == active_instance_id
⋮----
pub(crate) fn from_hello(hello: &SupervisorHello) -> Result<Self, Status> {
⋮----
canonical_uuid(&hello.sandbox_id)?;
canonical_uuid(&hello.instance_id)?;
⋮----
Ok(Self {
network_instance_id: hello.instance_id.clone(),
⋮----
pub(crate) fn accept(
⋮----
return Err(Status::failed_precondition(
⋮----
return Err(Status::invalid_argument("report sequence is required"));
... (282 lines truncated)
</file>

<file path="crates/openshell-server/src/grpc/provider.rs">
use crate::credentials::RefreshMaterialScope;
use crate::pagination::Pagination;
⋮----
use openshell_core::metadata::ObjectWorkspace;
⋮----
use openshell_policy::ProviderPolicyLayer;
use prost::Message;
⋮----
use tonic::Status;
use tracing::warn;
⋮----
pub(super) fn redact_provider_credentials(mut provider: Provider) -> Provider {
for value in provider.credentials.values_mut() {
*value = "REDACTED".to_string();
⋮----
for key in provider.credential_handles.keys() {
⋮----
.entry(key.clone())
.or_insert_with(|| "REDACTED".to_string());
⋮----
provider.credential_handles.clear();
⋮----
pub(super) struct ProviderEnvironment {
⋮----
pub(super) struct ProviderEnvironmentRecord {
⋮----
impl ProviderEnvironment {
⋮----
fn is_empty(&self) -> bool {
self.environment.is_empty()
... (565 lines truncated)
</file>

<file path="crates/openshell-server/src/grpc/sandbox.rs">
use crate::ServerState;
⋮----
use crate::pagination::Pagination;
⋮----
use crate::tracing_bus::CursoredEvent;
use crate::watch_cursor::WatchCursor;
use futures::future;
use openshell_core::net::set_tcp_nodelay_best_effort;
use openshell_core::proto::datamodel::v1::ObjectMeta;
⋮----
use prost::Message;
⋮----
use std::net::IpAddr;
use std::pin::Pin;
use std::sync::Arc;
⋮----
use tokio_stream::wrappers::ReceiverStream;
⋮----
use russh::ChannelMsg;
use russh::client::AuthResult;
⋮----
use crate::persistence::current_time_ms;
⋮----
mod interactive_exec_tests;
⋮----
fn cursor_space_is(state: &ServerState, sandbox_id: &str, epoch: uuid::Uuid) -> bool {
⋮----
.cursor_space(sandbox_id)
.is_some_and(|space| space.epoch == epoch)
⋮----
... (2407 lines truncated)
</file>

<file path="crates/openshell-server/src/grpc/service.rs">
use std::collections::HashMap;
use std::sync::Arc;
⋮----
use openshell_core::proto::datamodel::v1::ObjectMeta;
⋮----
use uuid::Uuid;
⋮----
use crate::ServerState;
⋮----
use crate::pagination::Pagination;
⋮----
use crate::service_routing;
⋮----
struct DeleteServiceProbe {
⋮----
pub(super) async fn handle_expose_service(
⋮----
let req = request.into_inner();
⋮----
crate::auth::workspace_authz::selected_workspace_name(req.workspace_scope.as_ref())?,
⋮----
super::workspace::resolve_workspace(state.store.as_ref(), sandbox.object_workspace())
⋮----
.ensure_active()?;
⋮----
validate_service_exposure_request(&req.name, req.target_port, req.authorization_mode)?;
expose_service_endpoint(
⋮----
pub(super) fn validate_service_exposure_request(
⋮----
... (374 lines truncated)
</file>

<file path="crates/openshell-server/src/grpc/validation.rs">
use openshell_core::rpc_error::invalid_argument;
use prost::Message;
use tonic::Status;
⋮----
pub(super) fn validate_exec_request_fields(req: &ExecSandboxRequest) -> Result<(), Status> {
if req.sandbox.is_empty() {
return Err(Status::invalid_argument("sandbox is required"));
⋮----
if req.command.len() > MAX_EXEC_COMMAND_ARGS {
return Err(invalid_argument(
⋮----
format!("command array exceeds {MAX_EXEC_COMMAND_ARGS} argument limit"),
⋮----
for (i, arg) in req.command.iter().enumerate() {
if arg.len() > MAX_EXEC_ARG_LEN {
⋮----
&format!("command[{i}]"),
format!("command argument {i} exceeds {MAX_EXEC_ARG_LEN} byte limit"),
⋮----
reject_null_char(arg, &format!("command[{i}]"))?;
⋮----
if value.len() > MAX_EXEC_ARG_LEN {
⋮----
format!("environment value for '{key}' exceeds {MAX_EXEC_ARG_LEN} byte limit"),
⋮----
reject_control_chars(value, "environment")?;
⋮----
validate_exec_env_entries(&req.environment, "environment")?;
if !req.workdir.is_empty() {
if req.workdir.len() > MAX_EXEC_WORKDIR_LEN {
... (1001 lines truncated)
</file>

<file path="crates/openshell-server/src/grpc/workspace.rs">
use std::sync::Arc;
⋮----
use openshell_core::ObjectName;
⋮----
use prost::Message;
⋮----
use crate::ServerState;
use crate::auth::principal::Principal;
⋮----
use crate::pagination::Pagination;
⋮----
use std::collections::HashMap;
⋮----
impl ObjectType for Workspace {
fn object_type() -> &'static str {
⋮----
impl ObjectType for WorkspaceMember {
⋮----
fn membership_filter_subject<'a>(
⋮----
Ok(None)
⋮----
Ok(Some(&u.identity.subject))
⋮----
Principal::Sandbox(_) => Ok(None),
Principal::Peer(_) => Err(Status::permission_denied(
⋮----
Principal::Anonymous => Err(Status::unauthenticated("authentication required")),
⋮----
pub fn validate_workspace_name(name: &str) -> Result<(), Status> {
... (582 lines truncated)
</file>

<file path="crates/openshell-server/src/persistence/legacy_time_wire.rs">
use prost::Message;
⋮----
use std::sync::LazyLock;
⋮----
.expect("the embedded public protobuf descriptor set must be valid");
pool.decode_file_descriptor_set(crate::storage_proto::STORAGE_FILE_DESCRIPTOR_SET)
.expect("the embedded storage protobuf descriptor set must be valid");
⋮----
enum Conversion {
⋮----
pub(super) fn migrate(object_type: &str, payload: &[u8]) -> PersistenceResult<Vec<u8>> {
let Some(message_name) = root_message_name(object_type) else {
return Ok(payload.to_vec());
⋮----
.get_message_by_name(message_name)
.ok_or_else(|| {
PersistenceError::Decode(format!("missing descriptor for {message_name}"))
⋮----
rewrite_message(&descriptor, payload)
⋮----
fn root_message_name(object_type: &str) -> Option<&'static str> {
⋮----
"sandbox" => Some("openshell.v1.Sandbox"),
"provider" => Some("openshell.datamodel.v1.Provider"),
"workspace" => Some("openshell.datamodel.v1.Workspace"),
"workspace_member" => Some("openshell.v1.WorkspaceMember"),
"provider_profile" => Some("openshell.storage.v1.StoredProviderProfile"),
⋮----
Some("openshell.storage.v1.StoredProviderCredentialRefreshStateV2")
⋮----
... (291 lines truncated)
</file>

<file path="crates/openshell-server/src/persistence/mod.rs">
mod legacy_time_wire;
mod postgres;
mod sqlite;
⋮----
use prost::Message;
use rand::Rng;
use std::collections::HashMap;
use thiserror::Error;
⋮----
pub use postgres::PostgresStore;
pub use sqlite::SqliteStore;
⋮----
pub type PersistenceResult<T> = Result<T, PersistenceError>;
⋮----
pub enum PersistenceError {
⋮----
impl PersistenceError {
⋮----
pub fn is_expected(&self) -> bool {
matches!(self, Self::UniqueViolation { .. } | Self::Conflict { .. })
⋮----
pub fn unique_violation(constraint: Option<String>, detail: Option<String>) -> Self {
⋮----
.as_ref()
.map(|value| format!(" on {value}"))
.unwrap_or_default();
⋮----
pub fn is_unique_violation_on(&self, constraint: &str) -> bool {
matches!(
⋮----
... (399 lines truncated)
</file>

<file path="crates/openshell-server/src/persistence/postgres.rs">
use openshell_core::SetResourceVersion;
use openshell_core::proto::Sandbox;
use prost::Message;
use sqlx::pool::PoolConnection;
use sqlx::postgres::PgPoolOptions;
⋮----
pub(super) fn embedded_migration_sql(version: i64) -> Option<&'static str> {
⋮----
.iter()
.find(|migration| migration.version == version)
.map(|migration| migration.sql.as_ref())
⋮----
pub struct PostgresStore {
⋮----
// Stable cluster-wide key for serializing sandbox/provider cross-object
// mutations. The bytes spell "OPENSHLL" and stay within PostgreSQL's signed
⋮----
pub(super) struct PostgresAdvisoryLockGuard {
⋮----
impl PostgresStore {
pub async fn connect(url: &str) -> PersistenceResult<Self> {
⋮----
.max_connections(10)
.connect(url)
⋮----
.map_err(|e| map_db_error(&e))?;
⋮----
Ok(Self { pool })
⋮----
pub async fn migrate(&self) -> PersistenceResult<()> {
... (424 lines truncated)
</file>

<file path="crates/openshell-server/src/persistence/sqlite.rs">
use openshell_core::SetResourceVersion;
use openshell_core::paths::set_file_owner_only;
use openshell_core::proto::Sandbox;
use prost::Message;
⋮----
use std::str::FromStr;
use std::sync::Arc;
⋮----
use tokio::sync::Mutex;
⋮----
pub(super) fn embedded_migration_sql(version: i64) -> Option<&'static str> {
⋮----
.iter()
.find(|migration| migration.version == version)
.map(|migration| migration.sql.as_ref())
⋮----
pub struct SqliteStore {
⋮----
/// Pool for writes whose loss after a crash is harmless; see
    /// [`SqliteStore::create_relaxed`]. On-disk stores open it with
⋮----
/// [`SqliteStore::create_relaxed`]. On-disk stores open it with
    /// `synchronous=NORMAL`; in-memory stores share `pool`.
⋮----
/// `synchronous=NORMAL`; in-memory stores share `pool`.
    relaxed_pool: SqlitePool,
⋮----
fn push_label_selector(
⋮----
.into_iter()
... (567 lines truncated)
</file>

<file path="crates/openshell-server/src/persistence/tests.rs">
use prost::Message;
⋮----
async fn failed_store_calls_are_marked_on_the_span() {
use crate::otel_tracing::test_exporter;
⋮----
let store = test_store().await;
⋮----
store.close_for_test().await;
⋮----
.get("sandbox", "failed-store-call")
⋮----
.expect_err("a closed pool fails the query");
⋮----
let span = traced.span_with("store.get", "object.id", "failed-store-call");
⋮----
assert!(
⋮----
async fn expected_conflicts_leave_the_span_unmarked() {
⋮----
.put(
⋮----
.expect("seed conflicting record");
⋮----
.put_if(
⋮----
.expect_err("the name is already taken");
⋮----
let span = traced.span_with("store.put_if", "object.id", "expected-conflict-second");
⋮----
assert_eq!(
... (940 lines truncated)
</file>

<file path="crates/openshell-server/src/certgen.rs">
use clap::Args;
use k8s_openapi::ByteString;
⋮----
use kube::Client;
⋮----
use std::fmt;
⋮----
use tracing_subscriber::EnvFilter;
⋮----
pub struct CertgenArgs {
⋮----
pub async fn run(args: CertgenArgs) -> Result<()> {
⋮----
.with_env_filter(
EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")),
⋮----
.init();
⋮----
let bundle = generate_pki(&args.server_sans)?;
print_bundle(&bundle);
return Ok(());
⋮----
if let Some(dir) = args.output_dir.as_deref() {
run_local(dir, &args.server_sans)
⋮----
run_kubernetes(&args, &bundle).await?;
⋮----
create_backend_ca_configmap_if_needed(&args, cm_name).await?;
⋮----
Ok(())
... (483 lines truncated)
</file>

<file path="crates/openshell-server/src/cli.rs">
use clap::parser::ValueSource;
⋮----
use std::collections::BTreeMap;
use std::ffi::OsString;
⋮----
use std::path::PathBuf;
⋮----
use tracing_subscriber::EnvFilter;
⋮----
use crate::certgen;
use crate::compute::driver_config::GuestTlsPaths;
⋮----
struct Cli {
⋮----
enum Commands {
⋮----
struct ConfigArgs {
⋮----
enum ConfigCommand {
⋮----
struct ConfigPreflightArgs {
⋮----
struct RunArgs {
⋮----
/// Maximum gRPC requests allowed per rate-limit window. Set to 0 to disable.
    #[arg(long, env = "OPENSHELL_GRPC_RATE_LIMIT_REQUESTS")]
⋮----
pub fn command() -> Command {
⋮----
.name("openshell-gateway")
... (1015 lines truncated)
</file>

<file path="crates/openshell-server/src/config_file.rs">
use std::collections::BTreeMap;
use std::fs::OpenOptions;
⋮----
use std::net::SocketAddr;
⋮----
use openshell_core::proto::SupervisorMiddlewareService;
⋮----
pub struct ConfigFile {
⋮----
pub struct OpenShellRoot {
⋮----
pub struct GatewayFileSection {
⋮----
pub struct GatewayTlsFileConfig {
⋮----
pub enum OcsfLogRotation {
⋮----
pub enum OcsfSchemaVersion {
⋮----
impl OcsfSchemaVersion {
pub const fn as_str(self) -> &'static str {
⋮----
pub struct OcsfLogConfig {
⋮----
struct RawOcsfLogConfig {
⋮----
type Error = &'static str;
⋮----
fn try_from(raw: RawOcsfLogConfig) -> Result<Self, Self::Error> {
if raw.path.as_os_str().is_empty() {
... (515 lines truncated)
</file>

<file path="crates/openshell-server/src/config_update_operation.rs">
use std::collections::HashMap;
⋮----
use prost::Message;
⋮----
use crate::storage_proto::StoredConfigUpdateOperation;
⋮----
impl ObjectType for StoredConfigUpdateOperation {
fn object_type() -> &'static str {
⋮----
/// Provider-specific view of one common configuration operation.
#[derive(Clone, Debug)]
pub struct ProviderOperation {
/// Immutable desired authority captured for this operation.
    pub(crate) receipt: ProviderMutationReceipt,
/// A failed initial snapshot is never reconstructed into another target.
    pub(crate) snapshot_reason: ProviderReadinessReason,
/// Durable historical outcome; callers must separately evaluate live readiness.
    pub(crate) operation: ConfigUpdateOperation,
⋮----
fn storage_unavailable() -> Status {
// A provider mutation can already have committed when operation persistence
// fails. No retry hint is attached: repeating the mutation is not proven safe.
⋮----
fn invalid_record() -> Status {
⋮----
fn persisted_time(receipt: &ProviderMutationReceipt) -> Result<prost_types::Timestamp, Status> {
// Receipt identity includes the full canonical timestamp. Absence is not
// the Unix epoch, and reducing nanos to milliseconds would merge identities.
let timestamp = receipt.persisted_time.ok_or_else(invalid_record)?;
openshell_core::time::validate_timestamp(&timestamp).map_err(|_| invalid_record())?;
... (356 lines truncated)
</file>

<file path="crates/openshell-server/src/credentials.rs">
use std::future::Future;
⋮----
use std::process::Stdio;
use std::sync::Arc;
⋮----
use async_trait::async_trait;
⋮----
use hyper_util::rt::TokioIo;
⋮----
use openshell_driver_kubernetes_secrets::KubernetesSecretsCredentialDriver;
use openshell_driver_vault::VaultCredentialDriver;
⋮----
use tokio::net::UnixStream;
⋮----
use tokio::process::Command;
⋮----
use tower::service_fn;
use tracing::warn;
⋮----
use crate::storage_proto::StoredRefreshMaterialDeletion;
⋮----
pub trait CredentialDriver: std::fmt::Debug + Send + Sync {
⋮----
fn stored_credential_count(&self) -> Option<usize> {
⋮----
fn fail_next_store(&self) {}
⋮----
fn fail_next_delete(&self) {}
⋮----
fn gate_next_store(
... (1076 lines truncated)
</file>

<file path="crates/openshell-server/src/defaults.rs">
use miette::Result;
use openshell_core::GatewayJwtConfig;
⋮----
pub struct LocalTlsPaths {
⋮----
impl LocalTlsPaths {
fn resolve(dir: &Path) -> Self {
⋮----
ca: dir.join("ca.crt"),
server_cert: dir.join("server").join("tls.crt"),
server_key: dir.join("server").join("tls.key"),
client_cert: dir.join("client").join("tls.crt"),
client_key: dir.join("client").join("tls.key"),
⋮----
fn files(&self) -> [&Path; 5] {
⋮----
pub struct LocalJwtPaths {
⋮----
impl LocalJwtPaths {
⋮----
let jwt = dir.join("jwt");
⋮----
signing_key: jwt.join("signing.pem"),
public_key: jwt.join("public.pem"),
kid: jwt.join("kid"),
⋮----
fn files(&self) -> [&Path; 3] {
⋮----
pub fn default_gateway_config_path() -> Result<PathBuf> {
Ok(openshell_core::paths::openshell_config_dir()?.join("gateway.toml"))
... (93 lines truncated)
</file>

<file path="crates/openshell-server/src/gateway_listener.rs">
use std::net::SocketAddr;
use tokio::net::TcpListener;
use tracing::info;
⋮----
pub struct BoundGatewayListener {
⋮----
pub async fn bind_gateway_listener(address: SocketAddr) -> Result<BoundGatewayListener> {
⋮----
.map_err(|error| Error::transport(format!("failed to bind to {address}: {error}")))?;
let local_addr = listener.local_addr().unwrap_or(address);
info!(address = %local_addr, "Gateway listener bound");
Ok(BoundGatewayListener {
</file>

<file path="crates/openshell-server/src/gateway_ocsf.rs">
use std::sync::OnceLock;
⋮----
pub struct GatewayIdentity {
⋮----
pub fn set_identity(identity: GatewayIdentity) -> bool {
IDENTITY.set(identity).is_ok()
⋮----
pub fn identity() -> GatewayIdentity {
IDENTITY.get().cloned().unwrap_or_else(|| GatewayIdentity {
name: openshell_core::config::DEFAULT_GATEWAY_NAME.to_string(),
hostname: "openshell-gateway".to_string(),
⋮----
pub fn context(sandbox_id: &str, sandbox_name: &str) -> EventContext {
let identity = identity();
⋮----
sandbox_id: sandbox_id.to_string(),
sandbox_name: sandbox_name.to_string(),
⋮----
product_version: openshell_core::VERSION.to_string(),
⋮----
mod tests {
⋮----
fn context_marks_events_as_gateway_origin() {
let ctx = context("sb-1", "agent-01");
⋮----
assert!(matches!(ctx.origin, EventOrigin::Gateway { .. }));
assert_eq!(ctx.sandbox_id, "sb-1");
assert_eq!(ctx.sandbox_name, "agent-01");
⋮----
fn gateway_context_produces_gateway_product_and_no_container() {
... (10 lines truncated)
</file>

<file path="crates/openshell-server/src/http.rs">
use metrics_exporter_prometheus::PrometheusHandle;
use serde::Serialize;
use std::sync::Arc;
use tokio::sync::watch;
⋮----
use crate::persistence::Store;
⋮----
struct HealthRouterState {
⋮----
pub struct DependencyCheck {
⋮----
/// Wall-clock time of the latest background ping, when measurable.
    #[serde(skip_serializing_if = "Option::is_none")]
⋮----
/// Failure detail. Absent on success.
    #[serde(skip_serializing_if = "Option::is_none")]
⋮----
/// Aggregated dependency results.
#[derive(Debug, Serialize)]
pub struct HealthChecks {
⋮----
/// Readiness response payload.
#[derive(Debug, Serialize)]
pub struct HealthResponse {
/// Overall status: `"healthy"` if every dependency is healthy.
    pub status: &'static str,
⋮----
/// Per-dependency breakdown.
    pub checks: HealthChecks,
⋮----
... (262 lines truncated)
</file>

<file path="crates/openshell-server/src/lib.rs">
mod auth;
pub mod certgen;
pub mod cli;
mod compute;
pub mod config_file;
mod config_update_operation;
mod credentials;
mod defaults;
mod gateway_listener;
mod gateway_ocsf;
mod grpc;
mod http;
mod middleware;
mod multiplex;
mod ocsf_log;
mod otel_tracing;
mod pagination;
mod persistence;
pub(crate) mod policy_store;
mod provider_profile_sources;
mod provider_refresh;
mod readiness;
mod sandbox_index;
mod sandbox_watch;
mod service_routing;
mod ssh_sessions;
mod storage_proto;
mod supervisor_owner;
pub mod supervisor_session;
mod telemetry;
... (1112 lines truncated)
</file>

<file path="crates/openshell-server/src/middleware.rs">
use openshell_core::proto::SandboxPolicy;
use openshell_supervisor_middleware::MiddlewareRegistry;
use tonic::Status;
⋮----
pub async fn validate_policy(
⋮----
.validate_policy_configs(policy)
⋮----
.map_err(|error| {
Status::invalid_argument(format!("policy middleware validation failed: {error}"))
⋮----
mod tests {
⋮----
use openshell_core::proto::NetworkMiddlewareConfig;
⋮----
async fn unregistered_external_middleware_is_rejected_before_admission() {
⋮----
"guard".into(),
⋮----
middleware: "example/content-guard".into(),
⋮----
let error = validate_policy(&MiddlewareRegistry::default(), &policy)
⋮----
.expect_err("unregistered middleware must fail");
assert_eq!(error.code(), tonic::Code::InvalidArgument);
assert!(error.message().contains("not registered"));
⋮----
async fn invalid_builtin_config_is_rejected_by_implementation() {
⋮----
.expect("built-in registry");
... (18 lines truncated)
</file>

<file path="crates/openshell-server/src/multiplex.rs">
use http_body::Body;
⋮----
use hyper::body::Incoming;
⋮----
use openshell_core::proto::open_shell_server::OpenShellServer;
⋮----
use openshell_otel::HeaderMapExtractor;
use opentelemetry::propagation::TextMapPropagator;
⋮----
use opentelemetry_sdk::propagation::TraceContextPropagator;
use prost::Message;
use std::collections::BTreeMap;
use std::convert::Infallible;
use std::future::Future;
use std::pin::Pin;
⋮----
use tower::ServiceExt;
⋮----
struct UuidRequestId;
⋮----
impl MakeRequestId for UuidRequestId {
fn make_request_id<B>(&mut self, _req: &Request<B>) -> Option<RequestId> {
let id = uuid::Uuid::new_v4().to_string();
Some(RequestId::new(HeaderValue::from_str(&id).unwrap()))
⋮----
fn make_request_span<B>(req: &Request<B>) -> Span {
let path = req.uri().path();
⋮----
.headers()
.get("x-request-id")
... (1365 lines truncated)
</file>

<file path="crates/openshell-server/src/ocsf_log.rs">
use std::path::Path;
⋮----
use tracing_subscriber::Layer;
use tracing_subscriber::layer::Context;
⋮----
struct State {
⋮----
struct Shared {
⋮----
pub struct Collector(Arc<Shared>);
⋮----
impl Collector {
fn new(config: OcsfLogConfig) -> Self {
Self(Arc::new(Shared {
⋮----
pub(crate) fn collect(&self, event: &OcsfEvent) {
match serialize_event(event, self.0.config.schema_version) {
⋮----
self.enqueue(line);
⋮----
Err(_) => self.record_loss("serialization", 1),
⋮----
fn enqueue(&self, line: Vec<u8>) -> bool {
let mut state = self.0.state.lock().unwrap();
⋮----
Some("closed")
} else if line.len() > self.0.config.queue_max_bytes.get() {
Some("oversized")
} else if state.queue.len() >= self.0.config.queue_capacity.get() {
Some("queue_capacity")
... (408 lines truncated)
</file>

<file path="crates/openshell-server/src/otel_tracing.rs">
use opentelemetry_sdk::Resource;
use opentelemetry_sdk::trace::SdkTracerProvider;
use tracing::Subscriber;
use tracing_subscriber::registry::LookupSpan;
⋮----
use crate::config_file::OtlpConfig;
⋮----
pub struct GatewayResourceAttributes<'a> {
⋮----
pub fn new(name: Option<&'a str>, compute_driver: Option<&'a str>) -> Self {
⋮----
/// The configured gateway installation name, if any.
    pub fn name(&self) -> Option<&'a str> {
⋮----
pub fn name(&self) -> Option<&'a str> {
⋮----
pub fn compute_driver(&self) -> Option<&'a str> {
⋮----
fn trace_config<'cfg>(
⋮----
.as_deref()
.map(str::trim)
.filter(|s| !s.is_empty())
.map_or(
⋮----
service_version: Some(openshell_core::VERSION),
⋮----
gateway.name(),
gateway.compute_driver(),
⋮----
... (194 lines truncated)
</file>

<file path="crates/openshell-server/src/pagination.rs">
use prost::Message;
⋮----
use tonic::Status;
⋮----
use crate::persistence::ObjectCursor;
⋮----
pub struct Pagination {
⋮----
impl Pagination {
pub fn new(
⋮----
return Err(Status::invalid_argument("page_size must not be negative"));
⋮----
.expect("a positive i32 always fits in u32")
.min(MAX_PAGE_SIZE)
⋮----
let request_fingerprint = fingerprint(request_parameters);
let cursor = if page_token.is_empty() {
⋮----
.decode(page_token)
.map_err(|_| Status::invalid_argument("page_token is malformed"))?;
let token = PageToken::decode(bytes.as_slice())
⋮----
return Err(Status::invalid_argument(
⋮----
Ok(Self {
⋮----
pub fn page_size(&self) -> u32 {
⋮----
pub fn object_cursor(&self) -> Result<Option<ObjectCursor>, Status> {
... (140 lines truncated)
</file>

<file path="crates/openshell-server/src/policy_store.rs">
use prost::Message;
use std::collections::HashMap;
⋮----
struct RawPolicyRevisionPayload {
⋮----
pub struct AtomicPolicyRevisionWrite {
⋮----
pub fn policy_record_for_atomic_write(
⋮----
id: write.id.clone(),
sandbox_id: write.sandbox_id.clone(),
⋮----
policy_payload: write.policy_payload.clone(),
policy_hash: write.policy_hash.clone(),
status: "pending".to_string(),
⋮----
provenance: write.provenance.clone(),
⋮----
pub fn permits_initial_static_policy_repair(sandbox: &Sandbox) -> bool {
sandbox.status.as_ref().is_some_and(|status| {
status.configuration_activated == Some(false)
⋮----
.as_ref()
.is_some_and(|admission| {
matches!(
⋮----
pub fn project_policy_revision_onto_sandbox(
⋮----
return Err(PersistenceError::Conflict {
current_resource_version: Some(current_resource_version),
... (211 lines truncated)
</file>

<file path="crates/openshell-server/src/provider_profile_sources.rs">
use std::sync::Arc;
⋮----
use async_trait::async_trait;
use openshell_core::GatewayProviderProfileSourceConfig;
use openshell_core::mcp::normalize_provider_profile_mcp_fields;
use openshell_core::proto::ProviderProfile;
⋮----
use tonic::Status;
use tracing::debug;
⋮----
use crate::storage_proto::StoredProviderProfile;
⋮----
pub enum ProfileScope {
⋮----
pub struct ScopedSnapshotProfile {
⋮----
impl ObjectType for StoredProviderProfile {
fn object_type() -> &'static str {
⋮----
pub struct ProviderProfileSnapshot {
⋮----
pub trait ProviderProfileSource: Send + Sync + std::fmt::Debug {
⋮----
struct UserProviderProfileSource;
⋮----
impl ProviderProfileSource for UserProviderProfileSource {
fn source_id(&self) -> &str {
⋮----
fn user_managed(&self) -> bool {
⋮----
... (764 lines truncated)
</file>

<file path="crates/openshell-server/src/readiness.rs">
use std::sync::Arc;
⋮----
use tokio::sync::watch;
use tracing::warn;
⋮----
use crate::persistence::Store;
⋮----
const _: () = assert!(
⋮----
pub enum HealthState {
⋮----
impl HealthState {
⋮----
pub const fn is_healthy(&self) -> bool {
matches!(self, Self::Healthy { .. })
⋮----
pub enum HealthError {
⋮----
pub struct DatabaseHealthMonitor {
⋮----
impl DatabaseHealthMonitor {
⋮----
pub fn spawn(store: Arc<Store>) -> Self {
⋮----
pub fn spawn_with(store: Arc<Store>, interval: Duration, timeout: Duration) -> Self {
⋮----
tokio::spawn(monitor_loop(store, tx, interval, timeout));
⋮----
pub fn subscribe(&self) -> watch::Receiver<HealthState> {
self.receiver.clone()
... (84 lines truncated)
</file>

<file path="crates/openshell-server/src/sandbox_index.rs">
use std::collections::HashMap;
⋮----
use openshell_core::proto::Sandbox;
⋮----
pub struct SandboxIndex {
⋮----
struct Inner {
⋮----
impl SandboxIndex {
⋮----
pub fn new() -> Self {
⋮----
pub fn update_from_sandbox(&self, sandbox: &Sandbox) {
let mut inner = self.inner.write().expect("sandbox index lock poisoned");
⋮----
if !metadata.name.is_empty() {
inner.sandbox_name_to_id.insert(
(metadata.workspace.clone(), metadata.name.clone()),
metadata.id.clone(),
⋮----
if let Some(status) = sandbox.status.as_ref()
&& !status.agent_pod.is_empty()
⋮----
.insert(status.agent_pod.clone(), metadata.id.clone());
⋮----
pub fn remove_sandbox(&self, sandbox_id: &str) {
⋮----
inner.sandbox_name_to_id.retain(|_, v| v != sandbox_id);
inner.agent_pod_to_id.retain(|_, v| v != sandbox_id);
⋮----
... (10 lines truncated)
</file>

<file path="crates/openshell-server/src/sandbox_watch.rs">
use std::time::Duration;
⋮----
use openshell_core::proto::SandboxStreamWarning;
⋮----
use crate::persistence::Store;
use openshell_core::proto::Sandbox;
⋮----
pub struct SandboxWatchBus {
⋮----
impl SandboxWatchBus {
⋮----
pub fn new() -> Self {
⋮----
fn sender_for(&self, sandbox_id: &str) -> broadcast::Sender<()> {
let mut inner = self.inner.lock().expect("sandbox watch bus lock poisoned");
⋮----
.entry(sandbox_id.to_string())
.or_insert_with(|| {
⋮----
.clone()
⋮----
pub fn notify(&self, sandbox_id: &str) {
let tx = self.sender_for(sandbox_id);
let _ = tx.send(());
⋮----
pub fn subscribe(&self, sandbox_id: &str) -> broadcast::Receiver<()> {
self.sender_for(sandbox_id).subscribe()
⋮----
pub fn remove(&self, sandbox_id: &str) {
⋮----
... (95 lines truncated)
</file>

<file path="crates/openshell-server/src/service_routing.rs">
use hyper_util::rt::TokioIo;
use openshell_core::ObjectId;
use openshell_core::config::ServiceRoutingConfig;
⋮----
use std::collections::HashMap;
⋮----
use tokio::io::AsyncWriteExt;
use tracing::warn;
⋮----
use crate::ServerState;
⋮----
type UpstreamSender = hyper::client::conn::http1::SendRequest<Body>;
⋮----
struct PooledUpstream {
⋮----
struct UpstreamPoolInner {
⋮----
impl UpstreamPoolInner {
⋮----
fn sweep_if_due(&mut self, now: Instant) {
⋮----
&& now.duration_since(last) < UPSTREAM_SWEEP_INTERVAL
⋮----
self.last_sweep = Some(now);
self.idle.retain(|_, entries| {
entries.retain(|entry| is_reusable(entry, now));
!entries.is_empty()
⋮----
pub struct ServiceUpstreamPool {
⋮----
... (847 lines truncated)
</file>

<file path="crates/openshell-server/src/ssh_sessions.rs">
use openshell_core::ObjectId;
use openshell_core::proto::SshSession;
use openshell_core::time::now_ms;
use prost::Message;
use std::future::Future;
use std::sync::Arc;
use std::time::Duration;
⋮----
impl ObjectType for SshSession {
fn object_type() -> &'static str {
⋮----
pub fn spawn_session_reaper(store: Arc<Store>, interval: Duration) {
⋮----
if let Err(e) = reap_expired_sessions(&store).await {
warn!(error = %e, "SSH session reaper sweep failed");
⋮----
async fn reap_expired_sessions(store: &Store) -> Result<(), String> {
reap_expired_sessions_after_page(store, |_| std::future::ready(())).await
⋮----
async fn reap_expired_sessions_after_page<F, Fut>(
⋮----
let now_ms = now_ms();
⋮----
.list_by_type_after(
⋮----
cursor.as_ref(),
⋮----
.map_err(|e| e.to_string())?;
let page_len = records.len();
⋮----
... (93 lines truncated)
</file>

<file path="crates/openshell-server/src/storage_proto.rs">
include!(concat!(env!("OUT_DIR"), "/openshell.storage.v1.rs"));
⋮----
include_bytes!(concat!(env!("OUT_DIR"), "/storage_descriptor.bin"));
⋮----
use std::collections::HashMap;
⋮----
impl ObjectId for StoredProviderProfile {
fn object_id(&self) -> &str {
self.metadata.as_ref().map_or("", |m| m.id.as_str())
⋮----
impl ObjectName for StoredProviderProfile {
fn object_name(&self) -> &str {
self.metadata.as_ref().map_or("", |m| m.name.as_str())
⋮----
impl ObjectLabels for StoredProviderProfile {
fn object_labels(&self) -> Option<HashMap<String, String>> {
self.metadata.as_ref().map(|m| m.labels.clone())
⋮----
impl SetResourceVersion for StoredProviderProfile {
fn set_resource_version(&mut self, version: u64) {
if let Some(meta) = self.metadata.as_mut() {
⋮----
impl GetResourceVersion for StoredProviderProfile {
fn get_resource_version(&self) -> u64 {
self.metadata.as_ref().map_or(0, |m| m.resource_version)
⋮----
impl ObjectWorkspace for StoredProviderProfile {
fn object_workspace(&self) -> &str {
self.metadata.as_ref().map_or("", |m| m.workspace.as_str())
⋮----
... (370 lines truncated)
</file>

<file path="crates/openshell-server/src/supervisor_owner.rs">
use openshell_core::time::now_ms;
⋮----
use std::sync::Arc;
⋮----
use thiserror::Error;
⋮----
fn owner_object_id(sandbox_id: &str) -> String {
format!("supervisor-owner:{sandbox_id}")
⋮----
pub enum OwnerError {
⋮----
impl OwnerError {
⋮----
pub fn is_ownership_lost(&self) -> bool {
matches!(self, Self::AlreadyOwned | Self::Conflict)
⋮----
struct OwnerPayload {
⋮----
pub struct OwnerRecord {
⋮----
impl OwnerRecord {
⋮----
pub fn is_fresh(&self, ttl: Duration) -> bool {
let ttl_ms = i64::try_from(ttl.as_millis()).unwrap_or(i64::MAX);
now_ms().saturating_sub(self.updated_at_ms).max(0) < ttl_ms
⋮----
pub struct OwnerGuard {
⋮----
impl OwnerGuard {
⋮----
... (164 lines truncated)
</file>

<file path="crates/openshell-server/src/supervisor_session.rs">
use std::collections::HashMap;
use std::pin::Pin;
⋮----
use tokio_stream::wrappers::ReceiverStream;
⋮----
use uuid::Uuid;
⋮----
use openshell_core::transport_errors::is_expected_transport_close_status;
⋮----
use crate::ServerState;
use crate::auth::principal::Principal;
use crate::grpc::provider_readiness::ProviderReadinessEvidence;
use crate::persistence::ObjectId;
⋮----
struct PeerTlsClientConfig {
⋮----
impl PeerTlsClientConfig {
fn from_env() -> Self {
⋮----
ca_file: nonempty_env(PEER_TLS_CA_FILE_ENV).map(Into::into),
cert_file: nonempty_env(PEER_TLS_CERT_FILE_ENV).map(Into::into),
key_file: nonempty_env(PEER_TLS_KEY_FILE_ENV).map(Into::into),
server_name: nonempty_env(PEER_TLS_SERVER_NAME_ENV),
⋮----
fn load(&self) -> Result<ClientTlsConfig, Status> {
let mut tls = if let Some(path) = self.ca_file.as_deref() {
let pem = std::fs::read(path).map_err(|err| {
Status::failed_precondition(format!(
⋮----
ClientTlsConfig::new().ca_certificate(Certificate::from_pem(pem))
... (1435 lines truncated)
</file>

<file path="crates/openshell-server/src/telemetry.rs">
use openshell_core::proto::NetworkActivitySummary;
use openshell_core::telemetry::DenyGroup;
⋮----
use std::collections::HashMap;
⋮----
pub struct TelemetryState {
⋮----
impl TelemetryState {
pub fn new() -> Self {
⋮----
pub fn sandbox_session_connected(&self, _sandbox_id: &str) {}
⋮----
pub fn sandbox_session_disconnected(&self, _sandbox_id: &str) {}
⋮----
pub fn end_sandbox_session(&self, sandbox_id: &str) {
⋮----
.lock()
.expect("telemetry session lock poisoned")
.push(sandbox_id.to_string());
⋮----
pub(crate) fn ended_sandbox_sessions(&self) -> Vec<String> {
⋮----
.clone()
⋮----
pub fn record_network_activity(&self, sandbox_id: &str, summary: &NetworkActivitySummary) {
if sandbox_id.is_empty() || !openshell_core::telemetry::enabled() {
⋮----
emit_network_activity_summary(summary);
⋮----
fn calculate_denial_rate_pct(network_activity_count: u64, denied_action_count: u64) -> f64 {
... (35 lines truncated)
</file>

<file path="crates/openshell-server/src/test_support.rs">
use crate::ServerState;
⋮----
use crate::persistence::Store;
use crate::sandbox_index::SandboxIndex;
use crate::sandbox_watch::SandboxWatchBus;
use crate::supervisor_session::SupervisorSessionRegistry;
use crate::tracing_bus::TracingLogBus;
⋮----
use openshell_core::Config;
⋮----
use openshell_core::proto::compute::v1::compute_driver_server::ComputeDriverServer;
⋮----
use std::collections::HashMap;
⋮----
use std::io;
⋮----
use std::pin::Pin;
⋮----
use tokio::task::JoinHandle;
⋮----
type WatchStream = Pin<Box<dyn Stream<Item = Result<WatchSandboxesEvent, Status>> + Send>>;
⋮----
pub async fn gateway_service_with_driver(driver_name: &str) -> crate::OpenShellService {
⋮----
.expect("in-memory gateway store should open"),
⋮----
.expect("default workspace should be created");
⋮----
new_test_runtime(store.clone()).await
⋮----
... (203 lines truncated)
</file>

<file path="crates/openshell-server/src/tls_test_utils.rs">
use std::fs::File;
use std::io::Write;
use std::path::Path;
⋮----
pub fn write_test_file(dir: &Path, name: &str, data: &[u8]) {
let path = dir.join(name);
⋮----
.and_then(|mut file| file.write_all(data))
.expect("failed to write test file");
⋮----
pub fn generate_test_certs_with_ca(dir: &Path) -> (rcgen::Certificate, KeyPair) {
⋮----
CertificateParams::new(Vec::<String>::new()).expect("failed to create CA params");
⋮----
.push(rcgen::DnType::CommonName, "test-ca");
let ca_key = KeyPair::generate().expect("failed to generate CA key");
⋮----
.self_signed(&ca_key)
.expect("failed to sign CA cert");
⋮----
let server_params = CertificateParams::new(vec!["localhost".to_string()])
.expect("failed to create server params");
let server_key = KeyPair::generate().expect("failed to generate server key");
⋮----
.signed_by(&server_key, &ca_cert, &ca_key)
.expect("failed to sign server cert");
⋮----
write_test_file(dir, "ca.pem", ca_cert.pem().as_bytes());
write_test_file(dir, "server-cert.pem", server_cert.pem().as_bytes());
write_test_file(dir, "server-key.pem", server_key.serialize_pem().as_bytes());
... (1 lines truncated)
</file>

<file path="crates/openshell-server/src/tls.rs">
use std::fs::File;
use std::io::BufReader;
⋮----
use std::sync::Arc;
⋮----
use std::time::Duration;
⋮----
use arc_swap::ArcSwap;
use notify::event::EventKind;
⋮----
use rustls::ServerConfig;
use rustls::crypto::aws_lc_rs::sign;
⋮----
use rustls::sign::CertifiedKey;
⋮----
pub struct TlsAcceptor {
⋮----
impl TlsAcceptor {
⋮----
pub fn from_files(
⋮----
let config = build_server_config(
⋮----
Ok(Self {
⋮----
cert_path: cert_path.to_path_buf(),
key_path: key_path.to_path_buf(),
client_ca_path: client_ca_path.map(Path::to_path_buf),
⋮----
external_cert_path: external_cert_path.map(Path::to_path_buf),
... (602 lines truncated)
</file>

<file path="crates/openshell-server/src/tracing_bus.rs">
use openshell_ocsf::OCSF_TARGET;
use tokio::sync::broadcast;
⋮----
use tracing_subscriber::Layer;
use tracing_subscriber::layer::Context;
use uuid::Uuid;
⋮----
use crate::watch_cursor::WatchCursor;
⋮----
pub struct TracingLogBus {
⋮----
struct Inner {
⋮----
pub(crate) struct CursoredEvent {
⋮----
struct PerSandbox {
⋮----
impl PerSandbox {
fn new() -> Self {
⋮----
pub struct ResumeGap {
⋮----
struct CursorSpace {
⋮----
pub(crate) struct CursorSpaceInfo {
⋮----
struct SeqAllocator {
⋮----
impl SeqAllocator {
⋮----
... (431 lines truncated)
</file>

<file path="crates/openshell-server/src/tracing_setup.rs">
use openshell_ocsf::OcsfJsonlLayer;
use opentelemetry_sdk::trace::SdkTracerProvider;
use tracing_subscriber::EnvFilter;
⋮----
use crate::config_file::OtlpConfig;
⋮----
use crate::tracing_bus::TracingLogBus;
⋮----
pub struct TracingHandle {
⋮----
impl TracingHandle {
pub fn shutdown(&self) {
⋮----
&& let Err(err) = provider.shutdown()
⋮----
fn filter_from(directives: &str) -> EnvFilter {
EnvFilter::try_new(directives).unwrap_or_else(|_| EnvFilter::new("info"))
⋮----
struct GatewayEventFormat;
⋮----
fn format_event(
⋮----
if event.metadata().target() == openshell_ocsf::OCSF_TARGET
⋮----
return writeln!(
⋮----
tracing_subscriber::fmt::format().format_event(context, writer, event)
⋮----
pub fn install(
⋮----
... (147 lines truncated)
</file>

<file path="crates/openshell-server/src/watch_cursor.rs">
use std::fmt;
⋮----
use uuid::Uuid;
⋮----
const ENCODED_LEN: usize = VERSION.len() + 1 + 36 + 1 + SEQ_WIDTH;
⋮----
pub struct WatchCursor {
⋮----
pub struct CursorParseError;
⋮----
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("resume_after_cursor is not a valid watch cursor")
⋮----
impl WatchCursor {
pub(crate) const fn new(epoch: Uuid, seq: u64) -> Self {
⋮----
/// Encode as the opaque wire token.
    pub(crate) fn encode(&self) -> String {
⋮----
pub(crate) fn encode(&self) -> String {
format!(
⋮----
/// Parse a client-supplied token.
    ///
⋮----
///
    /// Strict by design. Anything this server would not have produced is
⋮----
/// Strict by design. Anything this server would not have produced is
    /// rejected, so a client cannot hand back a hand-built or truncated cursor
... (73 lines truncated)
</file>

<file path="crates/openshell-server/src/ws_tunnel.rs">
use std::sync::Arc;
⋮----
use crate::ServerState;
⋮----
pub fn router(state: Arc<ServerState>) -> Router {
⋮----
.route("/_ws_tunnel", get(ws_tunnel_handler))
.with_state(state)
⋮----
async fn ws_tunnel_handler(
⋮----
ws.on_upgrade(move |socket| async move {
if let Err(e) = handle_ws_tunnel(socket, state).await {
warn!(error = %e, "WebSocket tunnel connection failed");
⋮----
async fn handle_ws_tunnel(
⋮----
debug!("WS tunnel: spawned in-memory multiplex connection");
⋮----
let (ws_sink, ws_source) = ws.split();
⋮----
if let Err(e) = service.serve(service_stream).await {
debug!(error = %e, "WS tunnel: multiplex service error");
⋮----
let mut tunnel_to_ws = tokio::spawn(copy_reader_to_ws(tunnel_read, ws_sink));
let mut ws_to_tunnel = tokio::spawn(copy_ws_to_writer(ws_source, tunnel_write));
⋮----
service_task.abort();
⋮----
Ok(())
... (27 lines truncated)
</file>

<file path="crates/openshell-server/build.rs">
use std::env;
use std::path::PathBuf;
⋮----
fn main() -> Result<(), Box<dyn std::error::Error>> {
⋮----
let storage_proto_dir = manifest_dir.join("proto");
let public_proto_dir = manifest_dir.join("../../proto");
let storage_proto = storage_proto_dir.join("storage.proto");
⋮----
println!("cargo:rerun-if-changed={}", storage_proto.display());
⋮----
println!(
⋮----
let descriptor_path = PathBuf::from(env::var("OUT_DIR")?).join("storage_descriptor.bin");
⋮----
.build_server(false)
.build_client(false)
.extern_path(".openshell.v1", "::openshell_core::proto")
.extern_path(
⋮----
.file_descriptor_set_path(&descriptor_path)
.compile_protos(&[storage_proto], &[storage_proto_dir, public_proto_dir])?;
⋮----
Ok(())
</file>

<file path="crates/openshell-server/Cargo.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

[package]
name = "openshell-server"
description = "OpenShell gRPC/HTTP server with protocol multiplexing"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true

[dependencies]
openshell-bootstrap = { path = "../openshell-bootstrap" }
openshell-core = { path = "../openshell-core", default-features = false, features = ["jwt", "oauth"] }
openshell-driver-db-credstore = { path = "../openshell-driver-db-credstore" }
openshell-driver-kubernetes-secrets = { path = "../openshell-driver-kubernetes-secrets" }
openshell-driver-vault = { path = "../openshell-driver-vault" }
openshell-extension-core = { path = "../openshell-extension-core" }
openshell-gateway-interceptors = { path = "../openshell-gateway-interceptors" }
openshell-ocsf = { path = "../openshell-ocsf" }
openshell-otel = { path = "../openshell-otel" }
openshell-policy = { path = "../openshell-policy" }
openshell-prover = { path = "../openshell-prover" }
openshell-providers = { path = "../openshell-providers" }
openshell-supervisor-middleware = { path = "../openshell-supervisor-middleware" }
openshell-supervisor-middleware-builtins = { path = "../openshell-supervisor-middleware-builtins" }

# Kubernetes client used by ServiceAccount bootstrap authentication and the
# `generate-certs` subcommand.
... (117 lines truncated)
</file>

<file path="crates/openshell-server-macros/src/lib.rs">
use proc_macro::TokenStream;
use quote::quote;
⋮----
struct AuthzArgs {
⋮----
impl Parse for AuthzArgs {
fn parse(input: ParseStream<'_>) -> Result<Self> {
let key: Ident = input.parse()?;
⋮----
return Err(Error::new(
key.span(),
⋮----
let _eq: Token![=] = input.parse()?;
let service: LitStr = input.parse()?;
Ok(Self { service })
⋮----
struct RpcAuth {
⋮----
enum AuthMode {
⋮----
enum RoleLit {
⋮----
impl RpcAuth {
fn parse(meta: &Meta) -> Result<Self> {
let span = meta.span();
⋮----
list.parse_nested_meta(|m| {
⋮----
.get_ident()
.ok_or_else(|| m.error("expected `auth`, `scope`, or `role`"))?;
... (122 lines truncated)
</file>

<file path="crates/openshell-server-macros/Cargo.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

[package]
name = "openshell-server-macros"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true

[lib]
proc-macro = true

[dependencies]
proc-macro2 = "1"
quote = "1"
syn = { version = "2", features = ["full", "extra-traits"] }
</file>

<file path="crates/openshell-supervisor/src/activity_aggregator.rs">
use std::collections::HashMap;
use std::future::Future;
use tokio::sync::mpsc;
⋮----
pub use openshell_core::activity::ActivityEvent;
⋮----
pub struct FlushableActivitySummary {
⋮----
pub struct ActivityAggregator {
⋮----
impl ActivityAggregator {
pub fn new(rx: mpsc::Receiver<ActivityEvent>, flush_interval_secs: u64) -> Self {
⋮----
pub async fn run<F, Fut, G>(mut self, flush_callback: F, ready_gate: G)
⋮----
while let Some(summary) = flush_rx.recv().await {
flush_callback(summary).await;
⋮----
flush_interval.tick().await;
⋮----
fn ingest(&mut self, event: ActivityEvent) {
self.network_activity_count = self.network_activity_count.saturating_add(1);
⋮----
self.denied_action_count = self.denied_action_count.saturating_add(1);
let group = sanitize_deny_group(event.deny_group).to_string();
let count = self.denials_by_group.entry(group).or_default();
*count = count.saturating_add(1);
⋮----
fn drain(&mut self) -> Option<FlushableActivitySummary> {
⋮----
... (47 lines truncated)
</file>

<file path="crates/openshell-supervisor/src/denial_aggregator.rs">
use std::collections::HashMap;
use std::future::Future;
use tokio::sync::mpsc;
⋮----
use openshell_core::denial::DenialEvent;
⋮----
struct AggregatedDenial {
⋮----
struct L7Sample {
⋮----
pub struct DenialAggregator {
⋮----
impl DenialAggregator {
⋮----
pub fn new(rx: mpsc::UnboundedReceiver<DenialEvent>, flush_interval_secs: u64) -> Self {
⋮----
pub async fn run<F, Fut, G>(mut self, flush_callback: F, ready_gate: G)
⋮----
flush_interval.tick().await;
⋮----
fn ingest(&mut self, event: DenialEvent) {
⋮----
let key = (event.host.clone(), event.port, event.binary.clone());
⋮----
.entry(key)
.or_insert_with(|| AggregatedDenial {
host: event.host.clone(),
⋮----
binary: event.binary.clone(),
ancestors: event.ancestors.clone(),
... (27 lines truncated)
</file>

<file path="crates/openshell-supervisor/src/endpoint_status.rs">
use std::time::Duration;
⋮----
use openshell_core::mcp::is_mcp_protocol;
use openshell_core::proto::SandboxPolicy;
use tokio::time::timeout;
use tracing::warn;
⋮----
pub async fn run_reporter<C: PolicyGatewayClient>(
⋮----
let mut tracker = commands.tracker();
⋮----
let mut active_session = supervisor_session_id.borrow_and_update().clone();
⋮----
tracker.clear_observations();
⋮----
// Endpoint state can accumulate while disconnected, but it cannot leave
// the sandbox until an authenticated supervisor session is active.
while !dirty || active_session.is_none() {
⋮----
if let Some(flush_at) = coalesce_until.take() {
⋮----
while let Ok(command) = commands.try_recv() {
dirty |= apply_command(&mut tracker, &mut observed_endpoint_ids, command);
⋮----
let Some(session_id) = active_session.clone() else {
⋮----
let Some(mut snapshot) = tracker.snapshot() else {
⋮----
snapshot.observed_endpoint_ids = observed_endpoint_ids.iter().cloned().collect();
⋮----
... (349 lines truncated)
</file>

<file path="crates/openshell-supervisor/src/lib.rs">
compile_error!(
⋮----
mod activity_aggregator;
mod denial_aggregator;
mod endpoint_status;
mod mechanistic_mapper;
mod provider_readiness;
⋮----
use std::future::Future;
⋮----
use std::pin::Pin;
use std::sync::Arc;
⋮----
use std::time::Duration;
⋮----
use openshell_core::PolicyValidationFailureMode;
⋮----
async fn retain_remote_access_plane(
⋮----
async fn completion_phase_or_shutdown<F, S>(phase: F, mut shutdown: Pin<&mut S>) -> bool
⋮----
enum ReadinessEndpoint {
⋮----
enum ReadinessListener {
⋮----
impl ReadinessEndpoint {
fn bind(&self) -> Result<ReadinessListener> {
⋮----
prepare_control_readiness_path(path)?;
⋮----
... (2456 lines truncated)
</file>

<file path="crates/openshell-supervisor/src/main.rs">
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
⋮----
use openshell_isolation_interface::contract::BackendDescriptor;
⋮----
use tracing_subscriber::EnvFilter;
use tracing_subscriber::filter::LevelFilter;
⋮----
enum SupervisorRole {
⋮----
struct HealthArgs {
⋮----
struct Args {
⋮----
fn arm_parent_liveness(raw_fd: Option<i32>) -> Result<()> {
⋮----
return Ok(());
⋮----
return Err(miette::miette!("parent liveness descriptor is invalid"));
⋮----
.map_err(|error| miette::miette!("parent liveness descriptor is not open: {error}"))?;
⋮----
.name("supervisor-parent-liveness".to_string())
.spawn(move || {
⋮----
match stream.read(&mut byte) {
⋮----
.map(|_| ())
.into_diagnostic()
⋮----
... (165 lines truncated)
</file>

<file path="crates/openshell-supervisor/src/mechanistic_mapper.rs">
use std::collections::HashMap;
use std::net::IpAddr;
⋮----
pub fn generate_proposals(summaries: &[DenialSummary]) -> Vec<PolicyChunk> {
⋮----
let binary_key = if summary.binary.is_empty() {
⋮----
summary.binary.clone()
⋮----
.entry((summary.host.clone(), summary.port, binary_key))
.or_default()
.push(summary);
⋮----
let rule_name = generate_rule_name(host, *port);
⋮----
if let Some(timestamp) = denial.first_seen_time.as_ref() {
⋮----
.min(openshell_core::time::timestamp_to_millis(timestamp).unwrap_or(i64::MAX));
⋮----
if let Some(timestamp) = denial.last_seen_time.as_ref() {
⋮----
.max(openshell_core::time::timestamp_to_millis(timestamp).unwrap_or_default());
⋮----
if denial.l7_inspection_active || !denial.l7_request_samples.is_empty() {
⋮----
.entry((sample.method.clone(), sample.path.clone()))
.or_insert(0) += sample.count;
⋮----
if is_always_blocked_destination(host) {
⋮----
... (113 lines truncated)
</file>

<file path="crates/openshell-supervisor/src/provider_readiness.rs">
use std::sync::Arc;
use std::time::Duration;
⋮----
use openshell_core::provider_credentials::ProviderCredentialState;
⋮----
use openshell_supervisor_network::opa::PolicyGenerationGuard;
use tokio::sync::watch;
⋮----
pub struct EnvironmentIdentity {
⋮----
impl EnvironmentIdentity {
⋮----
pub(crate) fn from_environment(
⋮----
attachment_epoch: result.provider_attachment_epoch.clone(),
⋮----
policy_hash: result.policy_hash.clone(),
⋮----
pub(crate) fn from_settings(result: &openshell_core::grpc_client::SettingsPollResult) -> Self {
⋮----
struct InstalledPolicy {
⋮----
struct FailedPolicy {
⋮----
struct State {
⋮----
pub struct Tracker {
⋮----
impl Tracker {
⋮----
... (293 lines truncated)
</file>

<file path="crates/openshell-supervisor/Cargo.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

[package]
name = "openshell-supervisor"
description = "OpenShell policy and workload supervisor"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true

[[bin]]
name = "openshell-supervisor"
path = "src/main.rs"

[dependencies]
openshell-core = { path = "../openshell-core", default-features = false, features = ["jwt"] }
openshell-extension-core = { path = "../openshell-extension-core" }
openshell-isolation-interface = { path = "../openshell-isolation-interface" }
openshell-sandbox-backend = { path = "../openshell-sandbox-backend" }
openshell-ocsf = { path = "../openshell-ocsf" }
openshell-policy = { path = "../openshell-policy" }
openshell-supervisor-middleware = { path = "../openshell-supervisor-middleware" }
openshell-supervisor-middleware-builtins = { path = "../openshell-supervisor-middleware-builtins" }
openshell-supervisor-network = { path = "../openshell-supervisor-network", default-features = false }
openshell-supervisor-process = { path = "../openshell-supervisor-process" }

clap = { workspace = true }
miette = { workspace = true }
... (32 lines truncated)
</file>

<file path="crates/openshell-supervisor-middleware/src/response/preflight.rs">
impl ChainRunner {
⋮----
pub fn http_response_input_unrepresentable(
⋮----
response_preflight_input_failure(entries, Vec::new(), "response_input_unrepresentable")
⋮----
pub async fn preflight_http_response(
⋮----
let described = self.describe_http_response_chain(entries).await?;
self.preflight_described_http_response(described, input)
⋮----
pub async fn preflight_described_http_response(
⋮----
if described.is_empty() {
return Ok(empty_preflight_outcome(input.headers));
⋮----
if validate_preflight_input(&input).is_err() {
return Ok(response_preflight_input_failure(
⋮----
let session_admission = match self.try_reserve_middleware_session() {
⋮----
return Ok(response_session_capacity_exhausted(
⋮----
let _work = self.reserve_middleware_work_admission().await?;
let original_restriction = body_restriction(&input);
let mut headers = input.headers.clone();
⋮----
let Some(service) = entry.service.as_ref() else {
⋮----
collect_preflight_failure(&entry, "binding_not_described", &mut invocations)
... (81 lines truncated)
</file>

<file path="crates/openshell-supervisor-middleware/src/response/validation.rs">
pub(super) enum BodyAction {
⋮----
pub(super) enum CurrentBodyAction {
⋮----
pub(super) struct BodyDecision {
⋮----
pub(super) struct TrailersDecision {
⋮----
pub(super) fn validate_trailers_result(
⋮----
return Err("unexpected_response_result".into());
⋮----
validate_diagnostics(
⋮----
.map_err(str::to_string)?;
if result.trailer_mutations.len() > headers::MAX_HEADER_MUTATIONS {
return Err("header_mutation_count_over_capacity".into());
⋮----
.iter()
.fold(0usize, |total, mutation| {
total.saturating_add(mutation.encoded_len())
⋮----
return Err("header_mutation_bytes_over_capacity".into());
⋮----
.map_err(|error| {
entry.service.as_ref().map_or_else(
|| error.to_string(),
⋮----
.header_mutation_error_reason(&error)
⋮----
... (138 lines truncated)
</file>

<file path="crates/openshell-supervisor-middleware/src/headers.rs">
pub enum HeaderAuthority {
⋮----
pub enum HeaderMutationError {
⋮----
impl HeaderMutationError {
⋮----
pub(crate) fn code(&self) -> &'static str {
⋮----
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
⋮----
Self::TooMany { count } => write!(
⋮----
write!(
⋮----
Self::CredentialPlaceholder { name } => write!(
⋮----
Self::TooLarge => write!(
⋮----
write!(formatter, "middleware returned invalid on_existing action")
⋮----
Self::MissingExistingAction { name } => write!(
⋮----
Self::AbsentTrailerName { name } => write!(
⋮----
Self::Empty => write!(formatter, "middleware returned an empty header mutation"),
⋮----
pub fn apply(
⋮----
if mutations.len() > MAX_HEADER_MUTATIONS {
return Err(HeaderMutationError::TooMany {
... (291 lines truncated)
</file>

<file path="crates/openshell-supervisor-middleware/src/lib.rs">
pub mod headers;
mod remote;
mod response;
mod websocket;
⋮----
use std::future::Future;
use std::sync::Arc;
use std::time::Duration;
⋮----
use prost::Message;
⋮----
use openshell_core::proto::middleware::v1::supervisor_middleware_server::SupervisorMiddleware;
⋮----
pub type MiddlewareService =
⋮----
struct GeneratedMiddlewareEndpoint {
⋮----
impl SupervisorMiddlewareEndpoint for GeneratedMiddlewareEndpoint {
async fn describe(
⋮----
self.service.describe(request).await
⋮----
async fn validate_config(
⋮----
self.service.validate_config(request).await
⋮----
async fn evaluate_http_request(
⋮----
self.service.evaluate_http_request(request).await
⋮----
... (2297 lines truncated)
</file>

<file path="crates/openshell-supervisor-middleware/src/remote.rs">
use openshell_core::proto::middleware::v1::http_response_pre_return_client::HttpResponsePreReturnClient;
use openshell_core::proto::middleware::v1::supervisor_middleware_client::SupervisorMiddlewareClient;
⋮----
use std::sync::Arc;
use tonic::service::interceptor::InterceptedService;
use tonic::transport::Channel;
⋮----
use crate::MIDDLEWARE_GRPC_MESSAGE_BYTES;
⋮----
type ExtensionChannel = InterceptedService<Channel, BearerTokenInterceptor>;
⋮----
pub struct GrpcMiddlewareService {
⋮----
impl GrpcMiddlewareService {
⋮----
pub async fn connect(
⋮----
Ok(Self {
⋮----
pub fn from_service(service: Arc<dyn SupervisorMiddlewareEndpoint>) -> Self {
⋮----
pub async fn describe(&self) -> std::result::Result<Response<MiddlewareManifest>, Status> {
⋮----
.describe(Request::new(MiddlewareDescribeRequest {
gateway: Some(openshell_core::extension_protocol::gateway_metadata(
⋮----
pub async fn validate_config(
⋮----
.validate_config(Request::new(ValidateConfigRequest {
config: Some(config.clone()),
... (74 lines truncated)
</file>

<file path="crates/openshell-supervisor-middleware/src/response.rs">
mod preflight;
mod validation;
⋮----
use validation::permitted_body_modes;
⋮----
use std::collections::BTreeMap;
use std::time::Duration;
⋮----
use tokio::sync::mpsc;
use tokio::time::Instant;
⋮----
pub fn is_stale_http_response_integrity_header(name: &str) -> bool {
matches!(
⋮----
pub struct HttpResponsePreflightInput {
⋮----
pub enum HttpResponseInvocationOutcome {
⋮----
pub struct HttpResponseInvocation {
⋮----
pub struct HttpResponsePreflightOutcome {
⋮----
pub struct HttpResponseMiddlewareFailure {
⋮----
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str(&self.reason)
⋮----
impl HttpResponseMiddlewareFailure {
fn with_diagnostics(mut self, diagnostics: HttpResponseDiagnostics) -> Self {
⋮----
... (995 lines truncated)
</file>

<file path="crates/openshell-supervisor-middleware/src/websocket.rs">
use std::collections::BTreeMap;
use std::time::Duration;
⋮----
use tokio::sync::mpsc;
use tokio::time::Instant;
⋮----
pub struct WebSocketPreflightInput {
⋮----
pub enum WebSocketInvocationOutcome {
⋮----
pub struct WebSocketInvocation {
⋮----
pub enum WebSocketCoverageState {
⋮----
pub enum WebSocketMessageType {
⋮----
pub struct WebSocketCoverage {
⋮----
pub struct WebSocketPreflightResult {
⋮----
pub struct WebSocketSessionStartOutcome {
⋮----
pub struct WebSocketMessageOutcome {
⋮----
struct WebSocketStageTransport {
⋮----
impl WebSocketStageTransport {
async fn end(self, reason: MiddlewareSessionEndReason) {
let _ = tokio::time::timeout(SESSION_END_TIMEOUT, self.end_inner(reason)).await;
⋮----
... (529 lines truncated)
</file>

<file path="crates/openshell-supervisor-middleware/Cargo.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

[package]
name = "openshell-supervisor-middleware"
description = "Supervisor middleware registry and chain execution for OpenShell"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
rust-version.workspace = true

[dependencies]
openshell-core = { path = "../openshell-core", default-features = false }
openshell-extension-core = { path = "../openshell-extension-core" }

miette = { workspace = true }
futures = { workspace = true }
prost = { workspace = true }
prost-types = { workspace = true }
tokio = { workspace = true }
tokio-stream = { workspace = true }
tonic = { workspace = true, features = ["channel", "server", "tls-native-roots"] }

[dev-dependencies]
openshell-supervisor-middleware-builtins = { path = "../openshell-supervisor-middleware-builtins" }
tokio-stream = { workspace = true, features = ["net"] }

[lints]
workspace = true
... (1 lines truncated)
</file>

<file path="crates/openshell-supervisor-middleware-builtins/src/lib.rs">
mod regex;
⋮----
use std::sync::Arc;
⋮----
use tonic::Status;
⋮----
pub fn services() -> Vec<Arc<dyn InProcessMiddleware>> {
vec![Arc::new(BuiltinMiddlewareService)]
⋮----
pub fn validate_config(implementation: &str, config: &prost_types::Struct) -> Result<()> {
⋮----
other => Err(miette!(
⋮----
fn evaluate_http_request(request: HttpRequestView<'_>) -> Result<HttpRequestResult> {
match request.middleware_name() {
BUILTIN_REGEX => regex::evaluate_http_request(request.config(), request.body()),
⋮----
/// Aggregate service exposing first-party middleware through the borrowed in-process contract.
#[derive(Debug, Default)]
pub struct BuiltinMiddlewareService;
⋮----
impl BuiltinMiddlewareService {
fn websocket_stream<S>(mut requests: S) -> WebSocketResponseStream
⋮----
let mut sequence_lower_bound = Some(1u64);
⋮----
while let Some(request) = requests.next().await {
⋮----
let _ = responses_tx.send(Err(error)).await;
⋮----
... (181 lines truncated)
</file>

<file path="crates/openshell-supervisor-middleware-builtins/src/regex.rs">
use std::borrow::Cow;
use std::collections::HashMap;
use std::sync::LazyLock;
⋮----
use regex::Regex;
use serde::Deserialize;
⋮----
pub struct RegexConfig {
⋮----
pub enum RegexMode {
⋮----
impl RegexConfig {
⋮----
pub fn from_struct(config: &prost_types::Struct) -> Result<Self> {
serde_json::from_value(openshell_core::proto_struct::struct_to_json_value(config)).map_err(
⋮----
miette!("invalid {NAME} config: {error}; this example supports only mode: redact")
⋮----
pub fn describe() -> Vec<MiddlewareBinding> {
vec![
⋮----
struct ReplacementPattern {
⋮----
impl ReplacementPattern {
fn new(kind: &'static str, pattern: &str) -> Self {
⋮----
regex: Regex::new(pattern).expect("valid built-in replacement pattern"),
⋮----
/// Validate one regex middleware configuration.
pub fn validate_config(config: &prost_types::Struct) -> Result<()> {
... (61 lines truncated)
</file>

<file path="crates/openshell-supervisor-middleware-builtins/Cargo.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

[package]
name = "openshell-supervisor-middleware-builtins"
description = "First-party in-process supervisor middleware implementations for OpenShell"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
rust-version.workspace = true

[dependencies]
openshell-core = { path = "../openshell-core", default-features = false }

async-trait = "0.1"
miette = { workspace = true }
prost-types = { workspace = true }
regex = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
tokio = { workspace = true }
tokio-stream = { workspace = true }
tonic = { workspace = true, features = ["server"] }

[lints]
workspace = true
</file>

<file path="crates/openshell-supervisor-network/src/l7/rest/http_response.rs">
pub struct HttpResponseMiddlewareRelay<'a> {
⋮----
pub(super) struct RelayResponseOptions<'a> {
⋮----
impl Default for RelayResponseOptions<'_> {
fn default() -> Self {
⋮----
pub(super) async fn relay_response<U, C>(
⋮----
.windows(4)
.position(|w| w == b"\r\n\r\n")
.map(|end| end + 4);
⋮----
if header_end.is_some_and(|end| end > remaining_header_bytes)
|| (header_end.is_none() && buf.len() >= remaining_header_bytes)
⋮----
if let Some(observer) = options.observer.as_ref() {
observer.observe(EndpointResult::TransportFailed);
⋮----
return Err(miette!("HTTP response headers exceed limit"));
⋮----
if matches!(
⋮----
.write_all(&buf[..header_end])
⋮----
.into_diagnostic()?;
client.flush().await.into_diagnostic()?;
buf.drain(..header_end);
⋮----
let n = upstream.read(&mut tmp).await.into_diagnostic()?;
... (769 lines truncated)
</file>

<file path="crates/openshell-supervisor-network/src/l7/graphql.rs">
use apollo_parser::Parser;
use apollo_parser::cst;
⋮----
use serde::Serialize;
use serde_json::Value;
⋮----
pub struct GraphqlRequestInfo {
⋮----
pub struct GraphqlOperationInfo {
⋮----
pub struct GraphqlHttpRequest {
⋮----
pub(crate) fn log_summary(info: &GraphqlRequestInfo) -> String {
⋮----
return format!("graphql_error={error:?}");
⋮----
let operations = info.operations.iter().map(|operation| {
let name = operation.operation_name.as_deref().unwrap_or("-");
let fields = if operation.fields.is_empty() {
"-".to_string()
⋮----
operation.fields.join(",")
⋮----
.as_deref()
.or(operation.persisted_query_id.as_deref())
.unwrap_or("-");
format!(
⋮----
format!("graphql_ops={}", operations.collect::<Vec<_>>().join(";"))
⋮----
... (346 lines truncated)
</file>

<file path="crates/openshell-supervisor-network/src/l7/http.rs">
pub async fn read_body_for_inspection<C: AsyncRead + Unpin>(
⋮----
.windows(4)
.position(|w| w == b"\r\n\r\n")
.map_or(request.raw_header.len(), |p| p + 4);
let overflow = request.raw_header[header_end..].to_vec();
⋮----
BodyLength::None => Ok(Vec::new()),
⋮----
.map_err(|_| miette!("HTTP request body length exceeds platform limit"))?;
⋮----
return Err(miette!(
⋮----
if overflow.len() > len {
⋮----
let remaining = len - overflow.len();
⋮----
let start = body.len();
body.resize(len, 0);
⋮----
.read_exact(&mut body[start..])
⋮----
.into_diagnostic()?;
⋮----
request.raw_header.truncate(header_end);
request.raw_header.extend_from_slice(&body);
Ok(body)
⋮----
let body = read_chunked_body_for_inspection(
⋮----
... (161 lines truncated)
</file>

<file path="crates/openshell-supervisor-network/src/l7/jsonrpc.rs">
use miette::Result;
⋮----
pub enum JsonRpcInspectionMode {
⋮----
impl JsonRpcInspectionMode {
pub(crate) fn for_protocol(protocol: crate::l7::L7Protocol) -> Self {
⋮----
pub struct JsonRpcInspectionOptions {
⋮----
impl JsonRpcInspectionOptions {
pub(crate) fn for_config(config: &crate::l7::L7EndpointConfig) -> Self {
⋮----
pub const fn mcp_bootstrap(strict_tool_names: bool) -> Self {
⋮----
pub const fn mcp_selected(revision: McpProtocolVersion, strict_tool_names: bool) -> Self {
⋮----
mcp_revision: Some(revision),
⋮----
pub const fn with_mcp_revision(mut self, revision: McpProtocolVersion) -> Self {
self.mcp_revision = Some(revision);
⋮----
fn from(mode: JsonRpcInspectionMode) -> Self {
⋮----
pub struct JsonRpcHttpRequest {
⋮----
pub(crate) async fn parse_jsonrpc_http_request<C: AsyncRead + AsyncWrite + Unpin + Send>(
⋮----
let Some(mut request) = provider.parse_request(client).await? else {
return Ok(None);
⋮----
... (752 lines truncated)
</file>

<file path="crates/openshell-supervisor-network/src/l7/mcp.rs">
use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use openshell_core::mcp::McpProtocolVersion;
⋮----
use crate::l7::jsonrpc::JsonRpcRequestInfo;
use crate::l7::provider::L7Request;
⋮----
pub(super) enum McpRequestProtocolVersion {
⋮----
pub(super) enum McpProtocolVersionError {
⋮----
impl McpProtocolVersionError {
⋮----
pub(super) fn rejection_detail(self, request: &L7Request) -> String {
⋮----
format!("{self}; {}", selected_revision_context(request, version))
⋮----
_ => self.to_string(),
⋮----
pub(super) const fn http_status(self) -> &'static str {
⋮----
/// Return a stable machine-readable response code.
    #[must_use]
pub(super) const fn response_code(self) -> &'static str {
⋮----
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
⋮----
Self::InvalidHeader => formatter.write_str(
⋮----
formatter.write_str("MCP-Protocol-Version names a revision unsupported by this OpenShell build; use a supported client/server revision permitted by mcp.versions")
... (259 lines truncated)
</file>

<file path="crates/openshell-supervisor-network/src/l7/middleware.rs">
use crate::l7::relay::L7EvalContext;
use crate::opa::PolicyGenerationGuard;
⋮----
use std::path::PathBuf;
⋮----
pub enum MiddlewareApplyResult {
⋮----
pub struct HttpMiddlewareExchange {
⋮----
impl HttpMiddlewareExchange {
pub fn new(
⋮----
pub async fn apply_request<C>(
⋮----
apply_middleware_chain_for_scheme_with_request_id(
⋮----
self.chain.clone(),
⋮----
pub fn response_relay<'a>(
⋮----
request_id: self.request_id.clone(),
sandbox_id: sandbox.sandbox_id.clone(),
sandbox: sandbox.sandbox_name.clone(),
workspace: ctx.workspace.clone(),
⋮----
scheme: scheme.to_string(),
host: ctx.host.clone(),
⋮----
method: request.action.clone(),
path: request.target.clone(),
... (476 lines truncated)
</file>

<file path="crates/openshell-supervisor-network/src/l7/mod.rs">
pub mod graphql;
pub(crate) mod http;
pub mod jsonrpc;
pub(crate) mod mcp;
pub(crate) mod middleware;
pub mod path;
pub mod provider;
pub mod relay;
pub mod rest;
pub mod tls;
pub(crate) mod token_grant_injection;
pub(crate) mod websocket;
⋮----
use openshell_core::mcp::McpProtocolVersion;
pub use openshell_policy::L7Protocol;
⋮----
use crate::opa::PolicyGenerationGuard;
⋮----
pub(crate) fn build_credential_endpoint_mismatch_finding(
⋮----
let mut evidence = vec![("policy", policy_name), ("host", host)];
⋮----
evidence.push(("protocol", protocol));
⋮----
evidence.push(("disposition", "denied"));
⋮----
.activity(ActivityId::Open)
.action(ActionId::Denied)
.disposition(DispositionId::Blocked)
.severity(SeverityId::High)
... (1212 lines truncated)
</file>

<file path="crates/openshell-supervisor-network/src/l7/path.rs">
use thiserror::Error;
⋮----
pub enum CanonicalizeError {
⋮----
pub struct CanonicalizeOptions {
⋮----
impl Default for CanonicalizeOptions {
fn default() -> Self {
⋮----
pub struct CanonicalPath {
⋮----
pub fn canonicalize_request_target(
⋮----
for &b in target.as_bytes() {
⋮----
return Err(CanonicalizeError::NullOrControlByte);
⋮----
return Err(CanonicalizeError::NonAscii);
⋮----
if target.contains('#') {
return Err(CanonicalizeError::FragmentInRequestTarget);
⋮----
let (path_part, query_part) = match target.split_once('?') {
Some((p, q)) => (p, Some(q.to_string())),
⋮----
.ok()
.filter(|uri| uri.scheme().is_some());
⋮----
.as_ref()
.map(http::Uri::path)
... (303 lines truncated)
</file>

<file path="crates/openshell-supervisor-network/src/l7/provider.rs">
use miette::Result;
use std::collections::HashMap;
use std::future::Future;
⋮----
pub enum RelayOutcome {
⋮----
pub enum BodyLength {
⋮----
pub struct L7Request {
⋮----
pub trait L7Provider: Send + Sync {
</file>

<file path="crates/openshell-supervisor-network/src/l7/relay.rs">
use crate::l7::rest::WebSocketExtensionMode;
⋮----
use std::collections::BTreeMap;
use std::sync::Arc;
⋮----
pub struct L7EvalContext {
⋮----
fn request_default_port(ctx: &L7EvalContext) -> Option<u16> {
⋮----
fn scoped_context_for_request(
⋮----
let mut scoped = ctx.clone();
if matches!(
⋮----
return Some(scoped);
⋮----
let credentials = ctx.provider_credentials.as_ref()?;
⋮----
credentials.resolver_and_body_classifier_for_endpoint(&ctx.host, ctx.port, &request.target);
⋮----
scoped.provider_credential_revision = Some(revision);
Some(scoped)
⋮----
fn credential_generation_guard(
⋮----
Some(crate::l7::rest::CredentialGenerationGuard::new(
ctx.provider_credentials.as_ref()?,
⋮----
fn request_authority_matches_endpoint(
⋮----
... (2026 lines truncated)
</file>

<file path="crates/openshell-supervisor-network/src/l7/rest.rs">
mod http_response;
⋮----
use crate::l7::EndpointObserver;
⋮----
use crate::opa::PolicyGenerationGuard;
use aws_sigv4::http_request::SignableBody;
⋮----
use openshell_core::endpoint_status::EndpointResult;
⋮----
use tracing::debug;
⋮----
async fn max_middleware_body_bytes() -> usize {
⋮----
.into_iter()
.next()
.expect("built-in middleware service"),
⋮----
.describe_chain(&[openshell_supervisor_middleware::ChainEntry {
name: "test".into(),
implementation: openshell_supervisor_middleware_builtins::BUILTIN_REGEX.into(),
⋮----
.expect("describe built-in middleware");
chain[0].max_payload_bytes()
⋮----
pub struct RestProvider {
⋮----
impl RestProvider {
⋮----
pub fn with_options(canonicalize_options: crate::l7::path::CanonicalizeOptions) -> Self {
⋮----
... (3982 lines truncated)
</file>

<file path="crates/openshell-supervisor-network/src/l7/tls.rs">
use std::collections::HashMap;
⋮----
pub struct SandboxCa {
⋮----
impl SandboxCa {
⋮----
pub fn generate() -> Result<Self> {
let ca_key = KeyPair::generate().into_diagnostic()?;
⋮----
.push(DnType::CommonName, "OpenShell Sandbox CA");
⋮----
.push(DnType::OrganizationName, "OpenShell");
params.key_usages = vec![KeyUsagePurpose::KeyCertSign, KeyUsagePurpose::CrlSign];
⋮----
let ca_cert = params.self_signed(&ca_key).into_diagnostic()?;
let ca_cert_pem = ca_cert.pem();
⋮----
Ok(Self {
⋮----
pub fn cert_pem(&self) -> &str {
⋮----
pub fn private_key_pem(&self) -> String {
self.ca_key.serialize_pem()
⋮----
pub fn load_from_paths(certificate_path: &Path, private_key_path: &Path) -> Result<Self> {
if !certificate_path.is_absolute() || !private_key_path.is_absolute() {
return Err(miette!(
⋮----
.into_diagnostic()
.wrap_err_with(|| {
... (355 lines truncated)
</file>

<file path="crates/openshell-supervisor-network/src/l7/token_grant_injection.rs">
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
⋮----
use tracing::warn;
⋮----
use crate::l7::provider::L7Request;
use crate::l7::relay::L7EvalContext;
⋮----
pub struct TokenGrantRequest<'a> {
⋮----
pub trait TokenGrantResolver: Send + Sync {
⋮----
pub struct SpiffeTokenGrantResolver;
⋮----
impl TokenGrantResolver for SpiffeTokenGrantResolver {
fn obtain<'a>(
⋮----
pub fn default_resolver() -> Arc<dyn TokenGrantResolver> {
⋮----
pub async fn inject_if_needed(req: L7Request, ctx: &L7EvalContext) -> Result<L7Request> {
let request_path = req.target.split('?').next().unwrap_or(req.target.as_str());
let token_grant_credential = ctx.dynamic_credentials.as_ref().and_then(|dyn_creds| {
dyn_creds.read().map_or(None, |creds_guard| {
⋮----
.iter()
.filter_map(|(key, cred)| {
⋮----
dynamic_credential_key_match_score(key, &ctx.host, ctx.port, request_path)?;
⋮----
... (346 lines truncated)
</file>

<file path="crates/openshell-supervisor-network/src/l7/websocket.rs">
use openshell_core::provider_credentials::ProviderCredentialState;
⋮----
use std::collections::HashMap;
use std::future::Future;
use std::sync::Arc;
⋮----
pub struct WebSocketAssemblyBudget {
⋮----
impl Default for WebSocketAssemblyBudget {
fn default() -> Self {
⋮----
impl WebSocketAssemblyBudget {
pub fn new(active: usize, waiters: usize) -> Self {
⋮----
pub async fn reserve(&self) -> Result<WebSocketAssemblyAdmissionOutcome> {
if let Ok(active) = Arc::clone(&self.active).try_acquire_owned() {
return Ok(WebSocketAssemblyAdmissionOutcome::Admitted(
⋮----
let Ok(waiter) = Arc::clone(&self.waiters).try_acquire_owned() else {
return Ok(WebSocketAssemblyAdmissionOutcome::QueueExhausted);
⋮----
.acquire_owned()
⋮----
.map_err(|_| miette!("websocket assembly admission semaphore closed"))?;
drop(waiter);
Ok(WebSocketAssemblyAdmissionOutcome::Admitted(
⋮----
pub struct WebSocketAssemblyAdmission {
⋮----
pub enum WebSocketAssemblyAdmissionOutcome {
... (1978 lines truncated)
</file>

<file path="crates/openshell-supervisor-network/src/opa/raw_schema.rs">
use miette::Result;
⋮----
pub(super) fn validate_network_settings(data: &Value) -> Result<()> {
let Some(policies) = data.get("network_policies").and_then(Value::as_object) else {
return Ok(());
⋮----
for policy in policies.values() {
let mut fields = object_copy(policy)?;
fields.remove("endpoints");
fields.remove("binaries");
⋮----
for binary in array_entries(policy, "binaries") {
⋮----
object_copy(binary)?,
⋮----
for endpoint in array_entries(policy, "endpoints") {
validate_endpoint(endpoint)?;
⋮----
Ok(())
⋮----
fn validate_endpoint(endpoint: &Value) -> Result<()> {
⋮----
let mut fields = object_copy(endpoint)?;
⋮----
fields.remove("rules");
fields.remove("deny_rules");
⋮----
fields.remove("mcp");
fields.remove("json_rpc");
⋮----
... (175 lines truncated)
</file>

<file path="crates/openshell-supervisor-network/src/policy_dns/mod.rs">
mod name;
mod resolver;
mod runtime;
mod store;
mod wire;
⋮----
pub(crate) use name::NormalizedName;
⋮----
use crate::opa::OpaEngine;
⋮----
use crate::proxy::is_host_gateway_alias;
use openshell_core::host_pattern::HostSelector;
⋮----
use std::sync::Arc;
⋮----
pub(crate) struct SyntheticAnswer {
⋮----
pub(crate) enum PolicyDnsError {
⋮----
pub(crate) struct PolicyDnsService<R> {
⋮----
pub(crate) fn new(
⋮----
pub(crate) async fn answer_query(
⋮----
NormalizedName::parse(raw_name).map_err(|_| PolicyDnsError::InvalidName)?;
if normalized_name.as_str() == crate::policy_local::POLICY_LOCAL_HOST {
⋮----
Ok(SyntheticAnswer {
address: POLICY_LOCAL_ADDRESS.into(),
... (552 lines truncated)
</file>

<file path="crates/openshell-supervisor-network/src/policy_dns/name.rs">
use hickory_proto::rr::Name;
use std::fmt;
⋮----
pub(crate) struct NormalizedName(String);
⋮----
impl NormalizedName {
pub(crate) fn parse(raw: &str) -> Result<Self, NameError> {
let trimmed = raw.trim();
if trimmed.is_empty() || trimmed.parse::<std::net::IpAddr>().is_ok() {
return Err(NameError);
⋮----
let absolute = if trimmed.ends_with('.') {
trimmed.to_string()
⋮----
format!("{trimmed}.")
⋮----
let parsed = Name::from_ascii(&absolute).map_err(|_| NameError)?;
if parsed.is_root() {
⋮----
let normalized = parsed.to_ascii().trim_end_matches('.').to_ascii_lowercase();
if normalized.is_empty() {
⋮----
Ok(Self(normalized))
⋮----
pub(crate) fn as_str(&self) -> &str {
⋮----
pub(crate) fn as_absolute_name(&self) -> Name {
Name::from_ascii(format!("{}.", self.0)).expect("normalized DNS name must remain valid")
⋮----
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
... (15 lines truncated)
</file>

<file path="crates/openshell-supervisor-network/src/policy_dns/resolver.rs">
use super::name::NormalizedName;
⋮----
use openshell_core::net::connect_tcp_nodelay_best_effort;
⋮----
use std::time::Duration;
⋮----
use tokio::net::UdpSocket;
use tokio::time::timeout;
⋮----
pub(crate) enum AddressFamily {
⋮----
impl AddressFamily {
pub(crate) const fn as_str(self) -> &'static str {
⋮----
pub(crate) fn record_type(self) -> RecordType {
⋮----
pub(crate) fn accepts(self, address: IpAddr) -> bool {
matches!(
⋮----
pub(crate) struct TrustedAnswer {
⋮----
pub(crate) enum ResolveError {
⋮----
pub(crate) trait TrustedResolver: Send + Sync {
⋮----
/// A DNS client pinned to one operator-supplied upstream socket address.
pub(crate) struct SocketTrustedResolver {
⋮----
pub(crate) struct SocketTrustedResolver {
⋮----
... (228 lines truncated)
</file>

<file path="crates/openshell-supervisor-network/src/policy_dns/runtime.rs">
use crate::opa::OpaEngine;
use crate::policy_dns::resolver::MAX_DNS_MESSAGE_BYTES;
⋮----
use openshell_core::net::set_tcp_nodelay_best_effort;
⋮----
use std::sync::Arc;
⋮----
use tokio::task::JoinHandle;
⋮----
async fn accept_mediated_dns(source: Arc<dyn NetworkMediationSource>) -> PendingDnsQuery {
⋮----
match source.accept_dns().await {
⋮----
delay = delay.saturating_mul(2).min(MEDIATION_MAX_RETRY_DELAY);
⋮----
pub(crate) struct PolicyDnsRuntimeConfig {
⋮----
impl PolicyDnsRuntimeConfig {
pub(crate) fn for_epoch(epoch: u64) -> Result<Self> {
let ipv4_parent: ipnet::Ipv4Net = "198.18.0.0/15".parse().unwrap();
⋮----
let ipv4_start = u32::from(ipv4_parent.network())
+ u32::try_from(ipv4_window * (1 << (32 - IPV4_POOL_PREFIX))).unwrap();
⋮----
.map_err(|error| miette::miette!(error.to_string()))?;
⋮----
let ipv6_parent: ipnet::Ipv6Net = "fd23:6f70:656e::/48".parse().unwrap();
⋮----
u128::from(ipv6_parent.network()) + (ipv6_window << (128 - IPV6_POOL_PREFIX));
⋮----
... (160 lines truncated)
</file>

<file path="crates/openshell-supervisor-network/src/policy_dns/store.rs">
use super::name::NormalizedName;
use super::resolver::AddressFamily;
⋮----
use std::ops::RangeInclusive;
use std::sync::RwLock;
⋮----
use uuid::Uuid;
⋮----
pub(crate) struct PolicyEndpointId {
⋮----
pub(crate) struct ResolvedPortContract {
⋮----
pub(crate) struct PublishRequest {
⋮----
pub(crate) struct ResolvedEndpointRecord {
⋮----
impl ResolvedEndpointRecord {
⋮----
pub(crate) fn is_observation(&self) -> bool {
self.contracts.is_empty()
⋮----
pub(crate) fn allowed_ports(&self) -> BTreeSet<u16> {
⋮----
.iter()
.map(|contract| contract.port)
.collect()
⋮----
pub(crate) struct MappingLookup {
⋮----
impl MappingLookup {
... (389 lines truncated)
</file>

<file path="crates/openshell-supervisor-network/src/policy_dns/wire.rs">
use std::net::IpAddr;
use std::time::Instant;
⋮----
pub(crate) enum WireError {
⋮----
pub(crate) async fn handle_udp_query<R: TrustedResolver>(
⋮----
handle_udp_query_with_ipv6(service, wire, true).await
⋮----
pub(crate) async fn handle_udp_query_with_ipv6<R: TrustedResolver>(
⋮----
.get(..2)
.map(|bytes| u16::from_be_bytes([bytes[0], bytes[1]]))
.unwrap_or_default();
if wire.len() > MAX_DNS_MESSAGE_BYTES {
return encode_message(Message::error_msg(
⋮----
let Some((query, family)) = validate_request(&request) else {
⋮----
|| request.queries.len() != 1
⋮----
return encode_message(response_with_code(&request, code));
⋮----
let raw_name = query.name.to_ascii();
⋮----
return encode_message(response_with_code(&request, ResponseCode::NoError));
⋮----
.answer_query(&raw_name, family, Instant::now())
⋮----
IpAddr::V4(address) if family == AddressFamily::Ipv4 => RData::A(A(address)),
... (149 lines truncated)
</file>

<file path="crates/openshell-supervisor-network/src/proxy/destination.rs">
use ipnet::IpNet;
⋮----
use tokio::net::TcpStream;
⋮----
pub(crate) enum AddressAuthorization {
⋮----
pub(crate) struct DestinationValidationPlan {
⋮----
pub(crate) struct DestinationRequest<'a> {
⋮----
/// Destination-validation branch that rejected an egress request.
///
⋮----
///
/// Adapters use this classification to preserve their existing HTTP response
⋮----
/// Adapters use this classification to preserve their existing HTTP response
/// and OCSF message shapes while sharing the underlying validation logic.
⋮----
/// and OCSF message shapes while sharing the underlying validation logic.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum DestinationDenialKind {
⋮----
pub(crate) struct DestinationDenial {
⋮----
impl DestinationDenial {
fn new(kind: DestinationDenialKind, reason: String) -> Self {
⋮----
fn from_check(error: DestinationCheckError, denied_kind: DestinationDenialKind) -> Self {
⋮----
... (244 lines truncated)
</file>

<file path="crates/openshell-supervisor-network/src/proxy/egress.rs">
use super::destination::DestinationValidationPlan;
use crate::opa::NetworkAction;
use std::path::PathBuf;
⋮----
pub(super) struct L7ConfigSnapshot {
⋮----
pub(super) struct L7RouteSnapshot {
⋮----
pub(super) struct EndpointDecision {
⋮----
impl Default for EndpointDecision {
fn default() -> Self {
⋮----
impl EndpointDecision {
pub(super) fn from_authorization(authorization: &crate::opa::EgressAuthorization) -> Self {
⋮----
policy_configs: authorization.endpoint_configs.clone(),
matched_endpoints: authorization.matched_endpoints.clone(),
⋮----
pub(super) enum EgressTransport {
⋮----
pub(super) struct RequestedDestination {
⋮----
pub(super) struct EgressIntent {
⋮----
impl EgressIntent {
pub(super) fn connect(host: String, port: u16) -> Self {
⋮----
pub(super) fn forward_http(host: String, port: u16) -> Self {
⋮----
... (27 lines truncated)
</file>

<file path="crates/openshell-supervisor-network/src/proxy/relay.rs">
use crate::l7::relay::L7EvalContext;
⋮----
use openshell_core::activity::ActivitySender;
use openshell_core::endpoint_status::EndpointObservationSender;
use openshell_core::proto::ProviderProfileCredential;
use openshell_core::secrets::SecretResolver;
use std::collections::HashMap;
use std::sync::Arc;
⋮----
type DynamicCredentials = Arc<std::sync::RwLock<HashMap<String, ProviderProfileCredential>>>;
⋮----
enum PreparedHttpPolicy {
⋮----
pub(super) struct RelayContext<'a> {
⋮----
/// Non-blocking observation channels attached to an authorized HTTP relay.
pub(super) struct RelaySignals {
⋮----
pub(super) struct RelaySignals {
/// Receives general sandbox network activity.
    pub(super) activity: Option<ActivitySender>,
/// Receives terminal tool server results for endpoint status reporting.
    pub(super) endpoint_observation: Option<EndpointObservationSender>,
⋮----
/// Build the request-processing context shared by CONNECT and forward HTTP.
pub(super) fn http_context(
⋮----
pub(super) fn http_context(
⋮----
// Provider-backed credentials must be acquired from the live state for
... (230 lines truncated)
</file>

<file path="crates/openshell-supervisor-network/src/host.rs">
use std::net::SocketAddr;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::AtomicU32;
⋮----
use miette::Result;
use openshell_core::activity::ActivitySender;
use openshell_core::denial::DenialEvent;
use openshell_core::policy::ProxyPolicy;
use openshell_core::proposals::AgentProposals;
⋮----
use openshell_core::provider_credentials::ProviderCredentialState;
⋮----
use tokio::sync::mpsc::UnboundedSender;
⋮----
use crate::identity::BinaryIdentityCache;
⋮----
use crate::opa::OpaEngine;
use crate::policy_local::PolicyLocalContext;
use crate::proxy::ProxyHandle;
⋮----
pub struct HostProxyConfig {
⋮----
pub struct HostProxyHandle {
⋮----
impl HostProxyHandle {
⋮----
pub const fn http_addr(&self) -> Option<SocketAddr> {
self.proxy.http_addr()
⋮----
... (109 lines truncated)
</file>

<file path="crates/openshell-supervisor-network/src/identity_source.rs">
use std::sync::Arc;
use std::sync::atomic::AtomicU32;
⋮----
pub struct ProcfsIdentityResolver {
⋮----
impl ProcfsIdentityResolver {
⋮----
pub fn resolve_connection(
⋮----
self.resolve_via_procfs(workload_addr, proxy_addr)
⋮----
Err(ResolveError::Failed(
"no procfs on this platform; identity resolution unavailable".to_string(),
⋮----
fn resolve_via_procfs(
⋮----
use std::sync::atomic::Ordering;
⋮----
let entrypoint_pid = self.entrypoint_pid.load(Ordering::Acquire);
⋮----
return Err(ResolveError::NotFound);
⋮----
.map_err(|_| ResolveError::NotFound)?;
⋮----
let mut identities = Vec::with_capacity(owners.owners.len());
⋮----
identities.push(resolver.resolve(owner.pid)?);
⋮----
let Some(identity) = identities.first().cloned() else {
⋮----
... (18 lines truncated)
</file>

<file path="crates/openshell-supervisor-network/src/identity.rs">
use crate::procfs;
use miette::Result;
use openshell_isolation_interface::contract::BinaryIdentity;
use std::collections::HashMap;
use std::fs::Metadata;
⋮----
use std::os::unix::fs::MetadataExt;
⋮----
use std::sync::Mutex;
use tracing::debug;
⋮----
struct FileFingerprint {
⋮----
impl FileFingerprint {
fn from_metadata(metadata: &Metadata) -> Self {
⋮----
Some((metadata.mtime(), metadata.mtime_nsec())),
Some((metadata.ctime(), metadata.ctime_nsec())),
⋮----
metadata.modified().ok().and_then(system_time_parts),
metadata.created().ok().and_then(system_time_parts),
⋮----
len: metadata.len(),
⋮----
dev: metadata.dev(),
⋮----
ino: metadata.ino(),
⋮----
fn system_time_parts(time: std::time::SystemTime) -> Option<(i64, i64)> {
let duration = time.duration_since(std::time::UNIX_EPOCH).ok()?;
... (329 lines truncated)
</file>

<file path="crates/openshell-supervisor-network/src/lib.rs">
pub mod host;
pub mod identity;
pub mod identity_source;
pub mod l7;
pub mod opa;
pub(crate) mod policy_dns;
pub mod policy_local;
pub mod procfs;
pub mod proxy;
pub mod run;
pub mod sigv4;
mod spiffe_endpoint;
mod token_grant;
pub mod upstream_proxy;
⋮----
pub(crate) mod test_alloc {
⋮----
struct CountingAllocator;
⋮----
unsafe impl GlobalAlloc for CountingAllocator {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
let pointer = unsafe { System.alloc(layout) };
if !pointer.is_null() {
ALLOCATIONS.fetch_add(1, Ordering::Relaxed);
ALLOCATED_BYTES.fetch_add(layout.size() as u64, Ordering::Relaxed);
⋮----
unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
let pointer = unsafe { System.alloc_zeroed(layout) };
⋮----
unsafe fn dealloc(&self, pointer: *mut u8, layout: Layout) {
... (16 lines truncated)
</file>

<file path="crates/openshell-supervisor-network/src/opa.rs">
use miette::Result;
use openshell_core::host_pattern::HostSelector;
use openshell_core::mcp::is_mcp_protocol;
⋮----
use openshell_core::policy_identity::deterministic_policy_hash;
⋮----
use tokio::sync::watch;
use tracing::info;
⋮----
mod raw_schema;
⋮----
const BAKED_POLICY_RULES: &str = include_str!("../data/sandbox-policy.rego");
⋮----
pub type MiddlewareConfigValidator =
⋮----
pub struct PolicyDecision {
⋮----
pub enum NetworkAction {
⋮----
pub struct MatchedEndpoint {
⋮----
pub struct PolicyDnsEligibilitySnapshot {
⋮----
pub struct EgressAuthorization {
⋮----
pub struct NetworkInput {
⋮----
fn inject_runtime_policy_data(data: &mut serde_json::Value, require_binary_identity: bool) {
let Some(obj) = data.as_object_mut() else {
⋮----
... (3165 lines truncated)
</file>

<file path="crates/openshell-supervisor-network/src/policy_local.rs">
use openshell_core::proposals::AgentProposals;
⋮----
use serde::Deserialize;
use std::collections::HashMap;
⋮----
use std::sync::Arc;
⋮----
use tokio::sync::RwLock;
⋮----
pub struct PolicyLocalContext {
⋮----
impl PolicyLocalContext {
pub fn new(
⋮----
fn with_log_dir(
⋮----
current_policy: Arc::new(RwLock::new(current_policy.map(Arc::new))),
⋮----
pub async fn set_current_policy(&self, policy: ProtoSandboxPolicy) {
⋮----
*self.current_policy.write().await = Some(Arc::new(policy));
⋮----
pub fn workspace(&self) -> String {
self.workspace_rx.borrow().clone()
⋮----
pub fn agent_proposals(&self) -> AgentProposals {
self.agent_proposals.clone()
⋮----
pub fn agent_proposals_enabled(&self) -> bool {
self.agent_proposals.enabled()
... (919 lines truncated)
</file>

<file path="crates/openshell-supervisor-network/src/procfs.rs">
use miette::Result;
⋮----
use std::collections::HashSet;
use std::net::SocketAddr;
⋮----
use std::path::Path;
⋮----
use std::path::PathBuf;
use tracing::debug;
⋮----
pub enum SocketOwnerSource {
⋮----
pub struct SocketOwner {
⋮----
pub struct TcpPeerSocketOwners {
⋮----
pub struct WorkloadProxyTcpConnection {
⋮----
impl WorkloadProxyTcpConnection {
pub fn new(workload: SocketAddr, proxy: SocketAddr) -> Self {
⋮----
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{} -> {}", self.workload, self.proxy)
⋮----
enum ProcTcpAddressFamily {
⋮----
impl ProcTcpAddressFamily {
fn table_name(self) -> &'static str {
⋮----
struct DescendantPid {
... (465 lines truncated)
</file>

<file path="crates/openshell-supervisor-network/src/proxy.rs">
pub(crate) mod destination;
mod egress;
mod relay;
⋮----
use crate::l7::tls::ProxyTlsState;
⋮----
use crate::policy_dns::PolicyEndpointId;
⋮----
use http::StatusCode;
⋮----
use openshell_core::denial::DenialEvent;
⋮----
use openshell_core::policy::ProxyPolicy;
⋮----
use std::mem::size_of;
⋮----
use std::path::PathBuf;
use std::sync::Arc;
⋮----
use tokio::net::TcpListener;
⋮----
use tokio::net::TcpStream;
use tokio::sync::mpsc;
use tokio::task::JoinHandle;
⋮----
type ProxyClient = tokio::io::BufReader<BoundaryDuplexStream>;
type AcceptedProxyConnection = (
⋮----
struct TransparentOpen {
⋮----
... (3885 lines truncated)
</file>

<file path="crates/openshell-supervisor-network/src/run.rs">
use std::sync::Arc;
⋮----
use std::time::Duration;
⋮----
use miette::Result;
⋮----
use openshell_core::provider_credentials::ProviderCredentialState;
⋮----
use openshell_core::activity::ActivitySender;
use openshell_core::denial::DenialEvent;
use openshell_core::proposals::AgentProposals;
use tokio::sync::mpsc::UnboundedSender;
⋮----
use crate::identity::BinaryIdentityCache;
⋮----
use crate::opa::OpaEngine;
use crate::policy_local::PolicyLocalContext;
use crate::proxy::ProxyHandle;
use openshell_core::endpoint_status::EndpointObservationSender;
use openshell_isolation_interface::contract::NetworkMediationSource;
⋮----
pub struct TransparentRuntimeSetup {
⋮----
impl TransparentRuntimeSetup {
⋮----
pub fn new(
⋮----
let epoch = advance_allocation_epoch(
⋮----
Ok(Self {
... (172 lines truncated)
</file>

<file path="crates/openshell-supervisor-network/src/sigv4.rs">
use aws_credential_types::Credentials;
⋮----
use aws_sigv4::sign::v4;
use aws_smithy_runtime_api::client::identity::Identity;
⋮----
use std::time::SystemTime;
⋮----
fn looks_like_region(s: &str) -> bool {
let bytes = s.as_bytes();
for i in 0..bytes.len().saturating_sub(1) {
if bytes[i] == b'-' && bytes[i + 1].is_ascii_digit() {
⋮----
/// Extract the AWS region from an AWS hostname.
///
⋮----
///
/// Supports standard, dualstack, FIPS, virtual-hosted, and China partition
⋮----
/// Supports standard, dualstack, FIPS, virtual-hosted, and China partition
/// hostnames. The region is the label immediately before `amazonaws.com`
⋮----
/// hostnames. The region is the label immediately before `amazonaws.com`
/// (or `amazonaws.com.cn`).
⋮----
/// (or `amazonaws.com.cn`).
pub fn extract_aws_region(host: &str) -> Option<String> {
⋮----
pub fn extract_aws_region(host: &str) -> Option<String> {
// The global S3 endpoint and its virtual-hosted bucket form always sign
// in us-east-1. This keeps policy metadata consistent across overlapping
... (281 lines truncated)
</file>

<file path="crates/openshell-supervisor-network/src/spiffe_endpoint.rs">
use std::path::Path;
⋮----
pub fn workload_api_endpoint(path: &Path) -> String {
let path = path.to_string_lossy();
if path.starts_with("unix:") || path.starts_with("tcp:") {
path.into_owned()
⋮----
format!("unix:{path}")
</file>

<file path="crates/openshell-supervisor-network/src/token_grant.rs">
use std::collections::HashMap;
use std::future::Future;
⋮----
use openshell_core::proto::ProviderCredentialTokenGrantType;
use openshell_core::sandbox_env;
use spiffe::WorkloadApiClient;
⋮----
let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();
⋮----
.timeout(Duration::from_secs(30))
.connect_timeout(Duration::from_secs(30))
.no_proxy()
.redirect(reqwest::redirect::Policy::none())
.build()
.expect("token grant HTTP client configuration should be valid")
⋮----
struct CachedToken {
⋮----
struct TokenCache {
⋮----
impl TokenCache {
fn new() -> Self {
⋮----
fn get(&self, provider_name: &str) -> Option<String> {
let now_ms = current_time_ms();
let tokens = self.tokens.read().ok()?;
let cached = tokens.get(provider_name)?;
⋮----
Some(cached.access_token.clone())
⋮----
... (456 lines truncated)
</file>

<file path="crates/openshell-supervisor-network/src/upstream_proxy.rs">
use std::pin::Pin;
use std::sync::Arc;
⋮----
use std::time::Duration;
⋮----
use openshell_core::net::set_tcp_nodelay_best_effort;
use rustls::ClientConfig;
use rustls::pki_types::ServerName;
⋮----
use tokio::net::TcpStream;
use tokio_rustls::TlsConnector;
use tracing::debug;
⋮----
pub struct ProxyEndpoint {
⋮----
impl ProxyEndpoint {
⋮----
pub fn display_addr(&self) -> String {
format!("{}:{}", self.host, self.port)
⋮----
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ProxyEndpoint")
.field("host", &self.host)
.field("port", &self.port)
.field("dial_ip", &self.dial_ip)
.field("proxy_authorization", &self.proxy_authorization.is_some())
.field("tls", &self.tls.is_some())
.finish()
⋮----
/// The pattern half of one parsed `NO_PROXY` entry.
... (1280 lines truncated)
</file>

<file path="crates/openshell-supervisor-network/testdata/sandbox-policy.yaml">
version: 1
filesystem_policy:
  include_workdir: true
  read_only:
    - /usr
    - /lib
    - /proc
    - /dev/urandom
    - /app
    - /etc
    - /var/log
  read_write:
    - /sandbox
    - /tmp
    - /dev/null
landlock:
  compatibility: best_effort
process:
  run_as_user: sandbox
  run_as_group: sandbox
network_policies:
  claude_code:
    name: claude_code
    endpoints:
      - { host: api.anthropic.com, port: 443 }
      - { host: statsig.anthropic.com, port: 443 }
    binaries:
      - { path: /usr/local/bin/claude }
      - { path: /usr/bin/node }
  github_ssh_over_https:
... (41 lines truncated)
</file>

<file path="crates/openshell-supervisor-network/Cargo.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

[package]
name = "openshell-supervisor-network"
description = "Network component of the OpenShell supervisor: proxy, L7 enforcement, OPA, and denial aggregation"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
rust-version.workspace = true

[dependencies]
openshell-binary-identity = { path = "../openshell-binary-identity" }
openshell-core = { path = "../openshell-core", features = ["oauth"] }
openshell-isolation-interface = { path = "../openshell-isolation-interface" }
openshell-ocsf = { path = "../openshell-ocsf" }
openshell-policy = { path = "../openshell-policy" }
openshell-policy-schema = { path = "../openshell-policy-schema" }
openshell-supervisor-middleware = { path = "../openshell-supervisor-middleware" }

async-trait = "0.1"

apollo-parser = { workspace = true }
aws-sigv4 = { version = "1", features = ["sign-http", "http1"] }
aws-credential-types = { version = "1", features = ["hardcoded-credentials"] }
aws-smithy-runtime-api = { version = "1", features = ["client"] }
http = { workspace = true }
base64 = { workspace = true }
bytes = { workspace = true }
... (51 lines truncated)
</file>

<file path="crates/openshell-supervisor-process/src/skills/policy-advisor/SKILL.md">
---
name: openshell-policy-advisor
description: Use when an OpenShell sandbox returns policy_denied, mentions policy.local, or needs a narrow network policy proposal.
---

# OpenShell Policy Advisor

When a request fails with `policy_denied`, do not treat the denial as final if the user task still needs the request. Read `/etc/openshell/skills/policy_advisor.md`, inspect `http://policy.local/v1/policy/current`, submit the narrowest proposal to `http://policy.local/v1/proposals`, wait on `/v1/proposals/{chunk_id}/wait?timeout=300`, and retry only after approval with `policy_reloaded: true`.
</file>

<file path="crates/openshell-supervisor-process/src/skills/policy_advisor.md">
# OpenShell Policy Advisor

Use this when OpenShell blocks a network request and the response or logs say
`policy_denied`.

## Goal

Draft the smallest policy proposal that allows the user's current task without
giving the sandbox broad new network access. The developer approves or rejects
the proposal; do not try to bypass policy.

## Local API

The sandbox-local policy API is reachable at `http://policy.local`:

- `GET /v1/policy/current` — current effective policy as YAML.
- `GET /v1/denials?last=10` — most recent network/L7 denials seen by this
  sandbox (newest first), returned as raw shorthand log lines. Each line
  carries the timestamp, class, severity, action, host/port, binary, policy
  name, and (for denied events) a short reason. Read the lines directly; you
  do not need to parse them into structured fields.
- `POST /v1/proposals` — submit a proposal. The 202 response carries
  `accepted_chunk_ids` (one ID per operation the gateway accepted) and
  `rejection_reasons` (one entry per operation the gateway refused at
  submit-time). The two arrays together account for every operation you
  sent.
- `GET /v1/proposals/{chunk_id}` — immediate state of one proposal.
  Returns `status` (`pending` / `approved` / `rejected`),
  `rejection_reason` (the reviewer's free-form note, only set on reject),
  and `validation_result` (the gateway prover's verdict on this chunk;
... (200 lines truncated)
</file>

<file path="crates/openshell-supervisor-process/src/ssh/peer_stream.rs">
use std::future::Future;
use std::io;
use std::pin::Pin;
⋮----
use std::time::Duration;
⋮----
pub(super) struct PeerStream<S> {
⋮----
pub(super) fn new(stream: S, timeout: Duration) -> Self {
⋮----
fn poll_deadline(&mut self, cx: &mut Context<'_>) -> io::Result<()> {
if self.deadline.as_mut().poll(cx).is_ready() {
return Err(io::Error::new(
⋮----
Ok(())
⋮----
impl<S: AsyncRead + Unpin> AsyncRead for PeerStream<S> {
fn poll_read(
⋮----
self.poll_deadline(cx)?;
let before = buf.filled().len();
match Pin::new(&mut self.stream).poll_read(cx, buf) {
⋮----
if buf.filled().len() > before {
⋮----
self.deadline.as_mut().reset(next);
⋮----
Poll::Ready(Ok(()))
⋮----
impl<S: AsyncWrite + Unpin> AsyncWrite for PeerStream<S> {
... (32 lines truncated)
</file>

<file path="crates/openshell-supervisor-process/src/ssh/reconnect_tests.rs">
enum RelayMode {
⋮----
struct RetainedProcess(AtomicUsize);
⋮----
impl BoundaryProcess for RetainedProcess {
async fn wait(&self) -> Result<BoundaryExitStatus, BackendError> {
⋮----
async fn signal(&self, _: BoundarySignal) -> Result<(), BackendError> {
self.0.fetch_add(1, Ordering::SeqCst);
Ok(())
⋮----
async fn terminate(&self) -> Result<(), BackendError> {
⋮----
struct CanonicalProcess {
⋮----
impl CanonicalProcess {
fn new() -> Self {
⋮----
process.clone(),
⋮----
output: Some(output),
⋮----
async fn assert_input(&mut self, channel: &russh::Channel<russh::client::Msg>) {
channel.data(&b"typing restored\n"[..]).await.unwrap();
self.expect_input().await;
⋮----
async fn expect_input(&mut self) {
⋮----
tokio::time::timeout(WAIT, self.input.read_exact(&mut received))
⋮----
... (226 lines truncated)
</file>

<file path="crates/openshell-supervisor-process/src/debug_rpc.rs">
pub async fn run(args: &[String]) -> Result<i32> {
⋮----
.first()
.map(String::as_str)
.ok_or_else(|| miette::miette!("{}", USAGE))?;
⋮----
"get-sandbox-config" => run_get_sandbox_config(&args[1..]).await,
"refresh" => run_refresh().await,
"show-token" => run_show_token(),
"show-principal" => run_show_principal(),
⋮----
println!("{USAGE}");
Ok(0)
⋮----
other => Err(miette::miette!(
⋮----
async fn open_client() -> Result<OpenShellClient<AuthedChannel>> {
⋮----
.into_diagnostic()
.wrap_err("OPENSHELL_ENDPOINT must be set")?;
let channel = connect_channel_pub(&endpoint).await?;
Ok(OpenShellClient::new(channel))
⋮----
async fn run_get_sandbox_config(args: &[String]) -> Result<i32> {
let sandbox_name = parse_flag(args, "--sandbox")
.ok_or_else(|| miette::miette!("get-sandbox-config: --sandbox <NAME> is required"))?;
let mut client = open_client().await?;
⋮----
.get_sandbox_config(GetSandboxConfigRequest {
name: sandbox_name.to_string(),
... (109 lines truncated)
</file>

<file path="crates/openshell-supervisor-process/src/delegated.rs">
use std::sync::Arc;
⋮----
use std::time::Duration;
⋮----
use miette::Result;
⋮----
fn ocsf_ctx() -> &'static openshell_ocsf::EventContext {
⋮----
/// Supervisor-owned SSH and gateway-session tasks for a running sandbox.
pub struct BoundaryAccess {
⋮----
pub struct BoundaryAccess {
⋮----
impl BoundaryAccess {
/// Stable supervisor instance ID used for lifecycle reporting.
    #[must_use]
pub fn instance_id(&self) -> &str {
⋮----
/// Observe whether the gateway has accepted the current supervisor
    /// session. The value returns to false while the session reconnects.
⋮----
/// session. The value returns to false while the session reconnects.
    #[must_use]
pub fn session_readiness(&self) -> Option<tokio::sync::watch::Receiver<bool>> {
self.session_readiness.clone()
⋮----
/// Publish the canonical process's terminal status to attached clients.
    pub async fn publish_main_exit(&self, exit_code: i32, attachment_expected: bool) {
⋮----
pub async fn publish_main_exit(&self, exit_code: i32, attachment_expected: bool) {
... (76 lines truncated)
</file>

<file path="crates/openshell-supervisor-process/src/lib.rs">
pub mod debug_rpc;
pub mod delegated;
pub mod log_push;
pub mod main_session;
pub mod skills;
pub mod ssh;
pub mod supervisor_session;
⋮----
mod unix_socket;
</file>

<file path="crates/openshell-supervisor-process/src/log_push.rs">
use openshell_core::grpc_client::CachedOpenShellClient;
⋮----
use tokio::sync::mpsc;
⋮----
use tracing_subscriber::Layer;
use tracing_subscriber::layer::Context;
⋮----
pub struct LogPushLayer {
⋮----
impl LogPushLayer {
pub fn new(sandbox_id: String, tx: mpsc::Sender<SandboxLogLine>) -> Self {
let max_level = parse_max_level(std::env::var("OPENSHELL_LOG_PUSH_LEVEL").ok().as_deref());
⋮----
fn parse_max_level(raw: Option<&str>) -> tracing::Level {
raw.and_then(|s| s.parse().ok())
.unwrap_or(tracing::Level::INFO)
⋮----
fn on_event(&self, event: &Event<'_>, _ctx: Context<'_, S>) {
let meta = event.metadata();
⋮----
if *meta.level() > self.max_level {
⋮----
let (msg, fields) = if meta.target() == openshell_ocsf::OCSF_TARGET {
⋮----
ocsf_event.format_shorthand(),
⋮----
event.record(&mut visitor);
visitor.into_parts(meta.name())
⋮----
let is_ocsf = meta.target() == openshell_ocsf::OCSF_TARGET;
... (201 lines truncated)
</file>

<file path="crates/openshell-supervisor-process/src/main_session.rs">
use std::collections::VecDeque;
⋮----
use std::os::fd::AsRawFd;
⋮----
use bytes::Bytes;
⋮----
use nix::pty::Winsize;
use tokio::io::unix::AsyncFd;
⋮----
use tokio::sync::Notify;
use tokio::sync::watch;
⋮----
pub enum ProcessIo {
⋮----
pub enum MainOutput {
⋮----
impl MainOutput {
fn len(&self) -> usize {
⋮----
Self::Stdout(data) | Self::Stderr(data) => data.len(),
⋮----
struct SequencedOutput {
⋮----
struct OutputLogState {
⋮----
struct OutputLog {
⋮----
impl OutputLog {
fn new() -> Arc<Self> {
⋮----
... (384 lines truncated)
</file>

<file path="crates/openshell-supervisor-process/src/skills.rs">
const POLICY_ADVISOR_CONTENT: &str = include_str!("skills/policy_advisor.md");
const POLICY_ADVISOR_SKILL_CONTENT: &str = include_str!("skills/policy-advisor/SKILL.md");
⋮----
pub struct InstalledSkills {
⋮----
pub fn install_static_skills() -> Result<InstalledSkills> {
install_static_skills_at(Path::new("/"))
⋮----
fn install_static_skills_at(root: &Path) -> Result<InstalledSkills> {
let skills_dir = root.join(SKILLS_RELATIVE_DIR);
std::fs::create_dir_all(&skills_dir).into_diagnostic()?;
⋮----
let policy_advisor = skills_dir.join(POLICY_ADVISOR_FILE);
write_readonly(&policy_advisor, POLICY_ADVISOR_CONTENT)?;
⋮----
let policy_advisor_skill_dir = skills_dir.join(POLICY_ADVISOR_SKILL_DIR);
std::fs::create_dir_all(&policy_advisor_skill_dir).into_diagnostic()?;
let policy_advisor_skill = policy_advisor_skill_dir.join(POLICY_ADVISOR_SKILL_FILE);
write_readonly(&policy_advisor_skill, POLICY_ADVISOR_SKILL_CONTENT)?;
⋮----
let agents = install_optional_agents_pointer(root);
⋮----
Ok(InstalledSkills {
⋮----
fn write_readonly(path: &Path, contents: &str) -> Result<()> {
std::fs::write(path, contents).into_diagnostic()?;
⋮----
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o444)).into_diagnostic()?;
⋮----
Ok(())
... (62 lines truncated)
</file>

<file path="crates/openshell-supervisor-process/src/ssh.rs">
use libc;
⋮----
use openshell_core::VERSION;
⋮----
use std::borrow::Cow;
use std::collections::HashMap;
⋮----
use std::time::Duration;
use tokio::net::UnixListener;
use tracing::warn;
⋮----
mod peer_stream;
⋮----
mod reconnect_tests;
⋮----
fn filter_main_detach_sequence(prefix_pending: &mut bool, data: &[u8]) -> (Vec<u8>, bool) {
let mut forward = Vec::with_capacity(data.len() + usize::from(*prefix_pending));
⋮----
forward.push(MAIN_DETACH_PREFIX);
⋮----
forward.push(byte);
⋮----
type SshServerInit = (
⋮----
fn ssh_server_init(
⋮----
let host_key = PrivateKey::random(&mut rng, Algorithm::Ed25519).into_diagnostic()?;
⋮----
server_id: russh::SshId::Standard(Cow::Owned(format!("SSH-2.0-OpenShell_{VERSION}"))),
⋮----
... (797 lines truncated)
</file>

<file path="crates/openshell-supervisor-process/src/supervisor_session.rs">
use std::net::IpAddr;
use std::sync::Arc;
⋮----
use std::time::Duration;
⋮----
use openshell_core::proto::open_shell_client::OpenShellClient;
⋮----
use tokio_stream::StreamExt;
⋮----
use openshell_core::grpc_client;
use openshell_core::transport_errors::is_expected_transport_close_status;
⋮----
pub struct SessionRuntimeContext {
⋮----
fn ocsf_gateway_endpoint(endpoint: &str) -> Endpoint {
⋮----
.split_once("://")
.map_or(endpoint, |(_, rest)| rest);
let host_and_port = without_scheme.split('/').next().unwrap_or(without_scheme);
if let Some((host, port)) = host_and_port.rsplit_once(':')
⋮----
fn session_established_event(
⋮----
.activity(ActivityId::Open)
.severity(SeverityId::Informational)
.status(StatusId::Success)
.dst_endpoint(ocsf_gateway_endpoint(endpoint))
.message(format!(
⋮----
.build()
... (591 lines truncated)
</file>

<file path="crates/openshell-supervisor-process/src/unix_socket.rs">
use std::borrow::Cow;
use std::path::Path;
⋮----
use std::path::PathBuf;
⋮----
pub fn is_abstract(path: &Path) -> bool {
⋮----
use std::os::unix::ffi::OsStrExt;
path.as_os_str().as_bytes().starts_with(b"@")
⋮----
pub fn runtime_path(path: &Path) -> Cow<'_, Path> {
⋮----
use std::ffi::OsString;
⋮----
let bytes = path.as_os_str().as_bytes();
if let Some(name) = bytes.strip_prefix(b"@") {
let mut abstract_name = Vec::with_capacity(name.len() + 1);
abstract_name.push(0);
abstract_name.extend_from_slice(name);
⋮----
mod tests {
⋮----
fn at_name_maps_to_abstract_socket_path() {
⋮----
let runtime = runtime_path(configured);
assert!(is_abstract(configured));
assert_eq!(runtime.as_os_str().as_bytes(), b"\0openshell-test");
</file>

<file path="crates/openshell-supervisor-process/Cargo.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

[package]
name = "openshell-supervisor-process"
description = "Process access and gateway session runtime for the OpenShell supervisor"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
rust-version.workspace = true

[dependencies]
openshell-core = { path = "../openshell-core" }
openshell-isolation-interface = { path = "../openshell-isolation-interface" }
openshell-ocsf = { path = "../openshell-ocsf" }

anyhow = { workspace = true }
async-trait = "0.1"
base64 = { workspace = true }
bytes = { workspace = true }
hex = "0.4"
miette = { workspace = true }
nix = { workspace = true }
rand = "0.10"
russh = "0.62"
serde_json = { workspace = true }
sha2 = { workspace = true }
tokio = { workspace = true }
tokio-stream = { workspace = true }
... (16 lines truncated)
</file>

<file path="crates/openshell-tui/src/ui/create_provider.rs">
use ratatui::Frame;
⋮----
use indexmap::IndexMap;
use std::ops::Range;
⋮----
use super::centered_rect;
⋮----
pub fn draw(frame: &mut Frame<'_>, app: &App, area: Rect) {
⋮----
CreateProviderPhase::SelectType => draw_select_type(frame, form, area, t),
CreateProviderPhase::ChooseMethod => draw_choose_method(frame, form, area, t),
CreateProviderPhase::EnterKey => draw_enter_key(frame, form, area, t),
CreateProviderPhase::Creating => draw_creating(frame, form, area, t),
⋮----
// ---------------------------------------------------------------------------
// Phase 1: Select provider type
⋮----
fn draw_select_type(
⋮----
let modal_width = 50u16.min(area.width.saturating_sub(4));
⋮----
let type_rows = form.types.len().clamp(1, 10) as u16;
⋮----
let modal_height = (content_height + 4).min(area.height.saturating_sub(2));
let popup_area = centered_rect(modal_width, modal_height, area);
⋮----
frame.render_widget(Clear, popup_area);
⋮----
.title(Span::styled(" Create Provider ", t.heading))
.borders(Borders::ALL)
... (338 lines truncated)
</file>

<file path="crates/openshell-tui/src/ui/create_sandbox.rs">
use ratatui::Frame;
⋮----
use super::centered_rect;
⋮----
pub fn draw(frame: &mut Frame<'_>, app: &App, area: Rect) {
⋮----
CreatePhase::Form => draw_form(frame, app, area),
CreatePhase::Creating => draw_creating(frame, app, area),
⋮----
// ---------------------------------------------------------------------------
// Form view
⋮----
fn draw_form(frame: &mut Frame<'_>, app: &App, area: Rect) {
⋮----
let modal_width = 72u16.min(area.width.saturating_sub(4));
⋮----
let provider_rows = form.providers.len().clamp(1, 8) as u16;
⋮----
let modal_height = (content_height + 4).min(area.height.saturating_sub(2));
let popup_area = centered_rect(modal_width, modal_height, area);
⋮----
frame.render_widget(Clear, popup_area);
⋮----
.title(Span::styled(" Create Sandbox ", t.heading))
.borders(Borders::ALL)
.border_style(t.accent)
.padding(Padding::new(2, 2, 1, 1));
⋮----
let inner = block.inner(popup_area);
frame.render_widget(block, popup_area);
... (105 lines truncated)
</file>

<file path="crates/openshell-tui/src/ui/dashboard.rs">
use ratatui::Frame;
⋮----
use super::draw_empty_message;
⋮----
pub fn draw(frame: &mut Frame<'_>, app: &App, area: Rect) {
⋮----
.direction(Direction::Vertical)
.constraints([
⋮----
.split(area);
⋮----
draw_gateway_list(frame, app, chunks[0]);
⋮----
fn draw_gateway_list(frame: &mut Frame<'_>, app: &App, area: Rect) {
⋮----
let header = Row::new(vec![
⋮----
.bottom_margin(1);
⋮----
.iter()
.enumerate()
.map(|(i, entry)| {
⋮----
let name_cell = Cell::from(Line::from(vec![
⋮----
let status_style = if app.status_text.contains("Healthy") {
⋮----
} else if app.status_text.contains("Degraded") {
⋮----
} else if app.status_text.contains("Unhealthy") {
... (19 lines truncated)
</file>

<file path="crates/openshell-tui/src/ui/global_settings.rs">
use ratatui::Frame;
⋮----
use super::draw_empty_message;
⋮----
pub fn draw(frame: &mut Frame<'_>, app: &App, area: Rect, focused: bool) {
⋮----
let header = Row::new(vec![
⋮----
.bottom_margin(1);
⋮----
.iter()
.enumerate()
.map(|(i, entry)| {
⋮----
Cell::from(Line::from(vec![
⋮----
let type_label = entry.kind.as_str();
let value_display = entry.display_value();
let value_style = if entry.value.is_some() {
⋮----
Row::new(vec![
⋮----
.collect();
⋮----
let title = draw_tab_title(app, focused);
⋮----
.title(title)
.borders(Borders::ALL)
.border_style(border_style)
.padding(Padding::horizontal(1));
... (34 lines truncated)
</file>

<file path="crates/openshell-tui/src/ui/mod.rs">
pub mod create_provider;
pub mod create_sandbox;
mod dashboard;
pub mod global_settings;
pub mod providers;
pub mod sandbox_detail;
mod sandbox_draft;
pub mod sandbox_logs;
mod sandbox_policy;
pub mod sandbox_settings;
pub mod sandboxes;
mod splash;
⋮----
use ratatui::Frame;
⋮----
use ratatui::style::Style;
⋮----
use crate::theme::Theme;
⋮----
pub fn draw(frame: &mut Frame<'_>, app: &mut App) {
// Splash screen is a full-screen takeover — no chrome.
⋮----
splash::draw(frame, frame.size(), &app.theme);
⋮----
.direction(Direction::Vertical)
.constraints([
Constraint::Length(1), // title bar
Constraint::Min(0),    // main content
Constraint::Length(1), // nav bar
Constraint::Length(1), // command bar
... (334 lines truncated)
</file>

<file path="crates/openshell-tui/src/ui/providers.rs">
use ratatui::Frame;
⋮----
use crate::app::App;
⋮----
pub fn draw(frame: &mut Frame<'_>, app: &App, area: Rect, focused: bool) {
draw_v2(frame, app, area, focused);
⋮----
fn draw_legacy(frame: &mut Frame<'_>, app: &App, area: Rect, focused: bool) {
⋮----
header_cells.push(Cell::from(Span::styled("WORKSPACE", t.muted)));
⋮----
header_cells.extend([
⋮----
let header = Row::new(header_cells).bottom_margin(1);
⋮----
.map(|i| {
let workspace = app.provider_workspaces.get(i).map_or("", String::as_str);
let name = app.provider_names.get(i).map_or("", String::as_str);
let ptype = app.provider_types.get(i).map_or("", String::as_str);
let cred_key = app.provider_cred_keys.get(i).map_or("", String::as_str);
⋮----
Cell::from(Line::from(vec![
⋮----
cells.push(Cell::from(Span::styled(workspace, t.muted)));
⋮----
cells.extend([
⋮----
.collect();
⋮----
vec![
... (27 lines truncated)
</file>

<file path="crates/openshell-tui/src/ui/sandbox_detail.rs">
use ratatui::Frame;
use ratatui::layout::Rect;
⋮----
use crate::app::App;
⋮----
fn pending_draft_count(app: &App) -> usize {
⋮----
.get(app.sandbox_selected)
.copied()
.unwrap_or(0);
⋮----
.iter()
.filter(|chunk| chunk.status == "pending")
.count()
⋮----
fn note_lines(app: &App, width: u16) -> Vec<String> {
⋮----
.filter(|s| !s.is_empty())
.map_or("none", String::as_str);
⋮----
&format!("  Notes: {notes}"),
usize::from(width.saturating_sub(4).max(1)),
⋮----
pub(super) fn required_height(app: &App, width: u16) -> u16 {
⋮----
u16::from(pending_draft_count(app) > 0)
⋮----
+ u16::try_from(note_lines(app, width).len().saturating_sub(1)).unwrap_or(u16::MAX - 16)
⋮----
pub fn draw(frame: &mut Frame<'_>, app: &App, area: Rect) {
... (78 lines truncated)
</file>

<file path="crates/openshell-tui/src/ui/sandbox_draft.rs">
use crate::app::App;
⋮----
use ratatui::Frame;
⋮----
use super::centered_rect;
⋮----
pub fn draw(frame: &mut Frame<'_>, app: &mut App, area: Rect) {
⋮----
.iter()
.filter(|c| c.status == "pending")
.count();
⋮----
Line::from(vec![
⋮----
.title(title)
.borders(Borders::ALL)
.border_style(t.border_focused)
.padding(Padding::horizontal(1));
⋮----
block = block.title_bottom(
⋮----
.left_aligned(),
⋮----
if app.draft_chunks.is_empty() {
⋮----
.block(block)
.style(t.muted);
frame.render_widget(msg, area);
⋮----
// Calculate visible area inside the block (borders + padding).
... (628 lines truncated)
</file>

<file path="crates/openshell-tui/src/ui/sandbox_logs.rs">
use ratatui::Frame;
use ratatui::layout::Rect;
⋮----
use super::centered_rect;
⋮----
pub fn draw(frame: &mut Frame<'_>, app: &mut App, area: Rect) {
⋮----
.get(app.sandbox_selected)
.map_or("-", String::as_str);
⋮----
let filter_label = app.log_source_filter.label();
⋮----
.title(Span::styled(format!(" Logs: {name} "), t.heading))
.borders(Borders::ALL)
.border_style(t.border_focused)
.padding(Padding::horizontal(1));
⋮----
// Calculate visible area inside the block (borders + padding).
let inner_height = area.height.saturating_sub(2) as usize;
// Inner width = total width - 2 (borders) - 2 (horizontal padding).
let inner_width = area.width.saturating_sub(4) as usize;
// Store viewport height so autoscroll calculations can use it.
⋮----
// Clamp cursor to visible range before borrowing filtered log lines.
⋮----
let filtered_len = app.filtered_log_lines().len();
⋮----
.saturating_sub(app.sandbox_log_scroll)
.min(inner_height);
⋮----
... (267 lines truncated)
</file>

<file path="crates/openshell-tui/src/ui/sandbox_policy.rs">
use ratatui::Frame;
use ratatui::layout::Rect;
⋮----
use crate::app::App;
⋮----
pub fn draw(frame: &mut Frame<'_>, app: &mut App, area: Rect) {
let inner_height = area.height.saturating_sub(2) as usize;
⋮----
let version = app.sandbox_policy.as_ref().map_or(0, |p| p.version);
⋮----
let version_hint = format!(" (v{version}) ");
⋮----
if app.policy_lines.is_empty() {
let lines = vec![Line::from(Span::styled("Loading...", t.muted))];
⋮----
.title(tab_title)
.borders(Borders::ALL)
.border_style(t.border_focused)
.padding(Padding::horizontal(1));
frame.render_widget(Paragraph::new(lines).block(block), area);
⋮----
let total = app.policy_lines.len();
let scroll = app.policy_scroll.min(total.saturating_sub(1));
⋮----
.iter()
.skip(scroll)
.take(inner_height)
.cloned()
.collect();
⋮----
... (9 lines truncated)
</file>

<file path="crates/openshell-tui/src/ui/sandbox_settings.rs">
use ratatui::Frame;
⋮----
use super::draw_empty_message;
⋮----
pub fn draw(frame: &mut Frame<'_>, app: &App, area: Rect) {
⋮----
let header = Row::new(vec![
⋮----
.bottom_margin(1);
⋮----
.iter()
.enumerate()
.map(|(i, entry)| {
⋮----
Cell::from(Line::from(vec![
⋮----
let type_label = entry.kind.as_str();
let value_display = entry.display_value();
let value_style = if entry.value.is_some() {
if entry.is_globally_managed() {
⋮----
Row::new(vec![
⋮----
.collect();
⋮----
let title = draw_policy_tab_title(app);
⋮----
.title(title)
.borders(Borders::ALL)
.border_style(t.border_focused)
... (36 lines truncated)
</file>

<file path="crates/openshell-tui/src/ui/sandboxes.rs">
use ratatui::Frame;
⋮----
use crate::app::App;
⋮----
pub fn draw(frame: &mut Frame<'_>, app: &App, area: Rect, focused: bool) {
⋮----
header_cells.push(Cell::from(Span::styled("WORKSPACE", t.muted)));
⋮----
header_cells.extend([
⋮----
let header = Row::new(header_cells).bottom_margin(1);
⋮----
.map(|i| {
let workspace = app.sandbox_workspaces.get(i).map_or("", String::as_str);
let name = app.sandbox_names.get(i).map_or("", String::as_str);
let phase = app.sandbox_phases.get(i).map_or("", String::as_str);
let created = app.sandbox_created.get(i).map_or("", String::as_str);
let age = app.sandbox_ages.get(i).map_or("", String::as_str);
let image = app.sandbox_images.get(i).map_or("", String::as_str);
let labels = app.sandbox_labels.get(i).map_or("", String::as_str);
let notes = app.sandbox_notes.get(i).map_or("", String::as_str);
let draft_count = app.sandbox_draft_counts.get(i).copied().unwrap_or(0);
⋮----
vec![Span::styled("▌ ", t.accent), Span::styled(name, t.text)]
⋮----
vec![Span::raw("  "), Span::styled(name, t.text)]
⋮----
name_spans.push(Span::raw(" "));
name_spans.push(Span::styled(
format!(
... (20 lines truncated)
</file>

<file path="crates/openshell-tui/src/ui/splash.rs">
use ratatui::Frame;
⋮----
use super::centered_rect;
⋮----
pub fn draw(frame: &mut Frame<'_>, area: Rect, theme: &crate::theme::Theme) {
⋮----
let modal_w = MODAL_WIDTH.min(area.width.saturating_sub(2));
let modal_h = MODAL_HEIGHT.min(area.height.saturating_sub(2));
⋮----
// Center the modal.
let popup = centered_rect(modal_w, modal_h, area);
⋮----
// Clear the area behind the modal.
frame.render_widget(Clear, popup);
⋮----
// Outer double-line border.
⋮----
.borders(Borders::ALL)
.border_type(BorderType::Double)
.border_style(t.border)
.padding(Padding::new(3, 3, 1, 1));
⋮----
let inner = block.inner(popup);
frame.render_widget(block, popup);
⋮----
// Split inner area: art content + spacer + footer (2 lines).
⋮----
.direction(Direction::Vertical)
.constraints([
Constraint::Length(CONTENT_LINES), // OPEN + SHELL + blank + tagline
... (23 lines truncated)
</file>

<file path="crates/openshell-tui/src/app.rs">
use std::collections::HashMap;
⋮----
use indexmap::IndexMap;
use openshell_bootstrap::GatewayMetadataSource;
use openshell_core::auth::EdgeAuthInterceptor;
use openshell_core::proto::open_shell_client::OpenShellClient;
use openshell_core::proto::setting_value;
⋮----
use tonic::service::interceptor::InterceptedService;
use tonic::transport::Channel;
⋮----
pub enum Screen {
⋮----
pub enum InputMode {
⋮----
pub enum Focus {
⋮----
pub struct LogLine {
⋮----
pub enum LogSourceFilter {
⋮----
impl LogSourceFilter {
pub fn next(self) -> Self {
⋮----
pub fn label(self) -> &'static str {
⋮----
// ---------------------------------------------------------------------------
// Middle pane tab (Providers vs Global Settings)
⋮----
/// Which tab is active in the middle pane of the dashboard.
... (1686 lines truncated)
</file>

<file path="crates/openshell-tui/src/clipboard.rs">
use base64::Engine;
use std::io::Write;
⋮----
pub fn copy_to_clipboard(text: &str) {
let encoded = base64::engine::general_purpose::STANDARD.encode(text);
⋮----
let seq = format!("\x1b]52;c;{encoded}\x07");
if let Ok(mut tty) = std::fs::OpenOptions::new().write(true).open("/dev/tty") {
let _ = tty.write_all(seq.as_bytes());
let _ = tty.flush();
</file>

<file path="crates/openshell-tui/src/event.rs">
use std::sync::Arc;
⋮----
use std::time::Duration;
use tokio::sync::mpsc;
⋮----
use crate::app::LogLine;
⋮----
pub enum Event {
⋮----
pub struct EventHandler {
⋮----
impl EventHandler {
pub fn new(tick_rate: Duration) -> Self {
⋮----
let keepalive = tx.clone();
⋮----
let paused_flag = paused.clone();
⋮----
if paused_flag.load(Ordering::Relaxed) {
⋮----
if event::poll(poll_interval).unwrap_or(false) {
⋮----
Ok(TermEvent::Key(key)) if tx.send(Event::Key(key)).is_err() => {
⋮----
Ok(TermEvent::Mouse(mouse)) if tx.send(Event::Mouse(mouse)).is_err() => {
⋮----
Ok(TermEvent::Resize(w, h)) if tx.send(Event::Resize(w, h)).is_err() => {
⋮----
} else if since_tick.elapsed() >= tick_rate {
⋮----
... (17 lines truncated)
</file>

<file path="crates/openshell-tui/src/lib.rs">
mod app;
mod clipboard;
mod event;
pub mod theme;
mod ui;
⋮----
use std::collections::HashMap;
use std::future::Future;
use std::io;
use std::path::PathBuf;
use std::time::Duration;
⋮----
use crossterm::execute;
⋮----
use openshell_bootstrap::list_gateways_with_source;
use openshell_core::auth::EdgeAuthInterceptor;
⋮----
use openshell_core::proto::open_shell_client::OpenShellClient;
⋮----
use ratatui::Terminal;
use ratatui::backend::CrosstermBackend;
use tokio::sync::mpsc;
use tonic::Code;
use tonic::service::interceptor::InterceptedService;
⋮----
type ProviderProfileCache = HashMap<(String, String), openshell_core::proto::ProviderProfile>;
type TuiClient = OpenShellClient<InterceptedService<Channel, EdgeAuthInterceptor>>;
⋮----
pub(crate) struct ListRefreshResult {
⋮----
... (1331 lines truncated)
</file>

<file path="crates/openshell-tui/src/theme.rs">
pub enum ThemeMode {
⋮----
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
⋮----
Self::Auto => write!(f, "auto"),
Self::Dark => write!(f, "dark"),
Self::Light => write!(f, "light"),
⋮----
type Err = String;
⋮----
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_lowercase().as_str() {
"auto" => Ok(Self::Auto),
"dark" => Ok(Self::Dark),
"light" => Ok(Self::Light),
other => Err(format!(
⋮----
/// Complete color theme for the TUI.
///
⋮----
///
/// Obtain a theme via [`Theme::dark`], [`Theme::light`], or [`detect`].
⋮----
/// Obtain a theme via [`Theme::dark`], [`Theme::light`], or [`detect`].
/// All fields are public [`Style`] values matching the semantic roles used
⋮----
/// All fields are public [`Style`] values matching the semantic roles used
/// throughout the UI.
⋮----
/// throughout the UI.
... (193 lines truncated)
</file>

<file path="crates/openshell-tui/Cargo.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

[package]
name = "openshell-tui"
description = "OpenShell interactive TUI"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true

[dependencies]
openshell-core = { path = "../openshell-core", default-features = false }
openshell-bootstrap = { path = "../openshell-bootstrap" }
openshell-policy = { path = "../openshell-policy" }
openshell-providers = { path = "../openshell-providers" }

base64 = { workspace = true }
futures = { workspace = true }
ratatui = { workspace = true }
crossterm = { workspace = true }
terminal-colorsaurus = { workspace = true }
tokio = { workspace = true }
tonic = { workspace = true, features = ["tls-native-roots"] }
miette = { workspace = true }
owo-colors = { workspace = true }
serde = { workspace = true }
url = { workspace = true }
indexmap = { workspace = true }
... (4 lines truncated)
</file>

<file path="crates/openshell-vfio/src/bind.rs">
use crate::VfioError;
⋮----
use std::collections::HashMap;
⋮----
use std::time::Duration;
⋮----
pub(crate) fn current_driver_name(sysfs: &SysfsRoot, bdf: &str) -> Option<String> {
sysfs.pci_device_ref(bdf).driver_name()
⋮----
pub(crate) fn vfio_id_string(sysfs: &SysfsRoot, bdf: &str) -> Option<String> {
sysfs.pci_device_ref(bdf).vfio_id_string()
⋮----
pub(crate) fn register_vfio_new_id(sysfs: &SysfsRoot, bdf: &str) {
let Some(id_str) = vfio_id_string(sysfs, bdf) else {
⋮----
let registration = VFIO_ID_REGISTRY.lock().unwrap().register(&id_str);
⋮----
let new_id_path = sysfs.vfio_pci_new_id();
match write_sysfs(&new_id_path, &id_str) {
⋮----
pub(crate) fn deregister_vfio_new_id(sysfs: &SysfsRoot, bdf: &str) {
⋮----
deregister_vfio_id(sysfs, &id_str, Some(bdf));
⋮----
fn deregister_vfio_id(sysfs: &SysfsRoot, id_str: &str, bdf: Option<&str>) {
let deregistration = VFIO_ID_REGISTRY.lock().unwrap().deregister(id_str);
⋮----
let remove_id_path = sysfs.vfio_pci_remove_id();
match write_sysfs(&remove_id_path, id_str) {
⋮----
... (172 lines truncated)
</file>

<file path="crates/openshell-vfio/src/error.rs">
pub enum VfioError {
</file>

<file path="crates/openshell-vfio/src/gpu.rs">
use crate::VfioError;
⋮----
use std::fs;
⋮----
fn is_gpu_class(class_str: &str) -> bool {
⋮----
if let Some(hex) = class_str.strip_prefix("0x")
⋮----
pub fn probe_host_nvidia_vfio_readiness(sysfs: &SysfsRoot) -> Vec<PciInfo> {
let devices_dir = sysfs.pci_devices_dir();
⋮----
for entry in entries.filter_map(Result::ok) {
let bdf = entry.file_name().to_string_lossy().into_owned();
let device = sysfs.pci_device_ref(&bdf);
⋮----
let Ok(vendor) = device.vendor() else {
⋮----
let Ok(class) = device.class() else {
⋮----
if !is_gpu_class(&class) {
⋮----
let device_id = device.device_id().unwrap_or_default();
⋮----
.read_trimmed("label")
.unwrap_or_else(|_| format!("NVIDIA {device_id}"));
⋮----
let Ok(iommu_group) = sysfs.iommu_group(&bdf) else {
⋮----
gpus.push(PciInfo {
⋮----
... (94 lines truncated)
</file>

<file path="crates/openshell-vfio/src/lib.rs">
pub mod bind;
pub mod error;
pub mod gpu;
pub mod pci;
pub mod reconcile;
pub mod sysfs;
⋮----
mod test_support;
⋮----
pub use error::VfioError;
⋮----
pub use reconcile::reconcile_stale_bindings;
</file>

<file path="crates/openshell-vfio/src/pci.rs">
use crate::VfioError;
⋮----
use std::collections::BTreeSet;
use std::fs;
use std::path::Path;
⋮----
pub struct PciInfo {
⋮----
pub struct PciBindGuard {
⋮----
impl PciBindGuard {
pub fn bdf(&self) -> &str {
⋮----
pub fn companion_bdfs(&self) -> &[String] {
⋮----
pub fn disarm(mut self) {
⋮----
pub fn adopt(sysfs: &SysfsRoot, bdf: &str) -> Result<Self, VfioError> {
validate_pci_for_passthrough(sysfs, bdf)?;
ensure_bound_to_vfio(sysfs, bdf)?;
⋮----
Ok(Self::new_armed(
bdf.to_string(),
⋮----
sysfs.clone(),
⋮----
pub fn adopt_group(sysfs: &SysfsRoot, bdfs: &[&str]) -> Result<Self, VfioError> {
validate_pci_group_for_passthrough(sysfs, bdfs)?;
⋮----
.split_first()
... (375 lines truncated)
</file>

<file path="crates/openshell-vfio/src/reconcile.rs">
use crate::pci::PciBindState;
⋮----
use std::fs;
use std::path::Path;
⋮----
pub fn reconcile_stale_bindings(sysfs: &SysfsRoot, state_path: &Path) -> Vec<String> {
⋮----
failed_bindings.push(binding.clone());
⋮----
restored.push(binding.bdf.clone());
⋮----
let device = sysfs.pci_device_ref(&binding.bdf);
if let Ok(val) = device.driver_override()
⋮----
if let Err(err) = device.clear_driver_override() {
⋮----
let probe = sysfs.drivers_probe();
if let Err(err) = write_sysfs(&probe, &binding.bdf) {
⋮----
if failed_bindings.is_empty() {
⋮----
mod tests {
⋮----
use crate::bind::test_refcounts;
⋮----
fn test_reconcile_clears_stale_driver_override_when_not_on_vfio() {
⋮----
let (tmp, sysfs) = setup_mock_sysfs();
create_pci_device(
⋮----
... (21 lines truncated)
</file>

<file path="crates/openshell-vfio/src/sysfs.rs">
use crate::VfioError;
use std::fs;
⋮----
pub struct SysfsRoot {
⋮----
pub(crate) struct SysfsPciDevice<'a> {
⋮----
impl SysfsRoot {
/// Production root pointing at the real `/sys` filesystem.
    pub fn system() -> Self {
⋮----
pub fn system() -> Self {
⋮----
/// Custom root for testing.
    pub fn new(base: impl Into<PathBuf>) -> Self {
⋮----
pub fn new(base: impl Into<PathBuf>) -> Self {
Self { base: base.into() }
⋮----
pub(crate) fn base(&self) -> &Path {
⋮----
pub fn pci_devices_dir(&self) -> PathBuf {
self.base.join("bus/pci/devices")
⋮----
pub fn pci_device(&self, bdf: &str) -> PathBuf {
self.pci_devices_dir().join(bdf)
⋮----
pub(crate) fn pci_device_ref<'a>(&'a self, bdf: &'a str) -> SysfsPciDevice<'a> {
⋮----
pub fn drivers_probe(&self) -> PathBuf {
... (191 lines truncated)
</file>

<file path="crates/openshell-vfio/src/test_support.rs">
use crate::SysfsRoot;
use std::fs;
use std::os::unix::fs::symlink;
use std::path::Path;
use tempfile::TempDir;
⋮----
pub fn setup_mock_sysfs() -> (TempDir, SysfsRoot) {
let tmp = TempDir::new().unwrap();
let sysfs = SysfsRoot::new(tmp.path());
⋮----
pub fn create_pci_device(
⋮----
let dev = sysfs.pci_device(bdf);
fs::create_dir_all(&dev).unwrap();
⋮----
fs::write(dev.join("vendor"), format!("{vendor}\n")).unwrap();
fs::write(dev.join("device"), format!("{device}\n")).unwrap();
fs::write(dev.join("class"), format!("{class}\n")).unwrap();
⋮----
let group_dir = tmp.join(format!("kernel/iommu_groups/{iommu_group}"));
fs::create_dir_all(&group_dir).unwrap();
symlink(&group_dir, dev.join("iommu_group")).unwrap();
⋮----
let group_devices_dir = group_dir.join("devices");
fs::create_dir_all(&group_devices_dir).unwrap();
symlink(&dev, group_devices_dir.join(bdf)).unwrap();
⋮----
pub fn set_mock_driver(sysfs: &SysfsRoot, bdf: &str, driver_name: &str) {
let driver_dir = sysfs.base().join(format!("bus/pci/drivers/{driver_name}"));
fs::create_dir_all(&driver_dir).unwrap();
... (19 lines truncated)
</file>

<file path="crates/openshell-vfio/Cargo.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

[package]
name = "openshell-vfio"
description = "VFIO PCIe passthrough lifecycle for OpenShell VM sandboxes"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true

[dependencies]
serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
tracing = { workspace = true }

[dev-dependencies]
tempfile = "3"

[lints]
workspace = true
</file>

<file path="docs/_components/BadgeLinks.tsx">
export type BadgeItem = {
  href: string;
  src: string;
  alt: string;
};
⋮----
export function BadgeLinks(
</file>

<file path="docs/_components/CommandTerminal.tsx">
<span style=
</file>

<file path="docs/_components/jsx.d.ts">

</file>

<file path="docs/about/architecture.mdx">
---
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
title: "Architecture"
sidebar-title: "Architecture"
description: "Understand the OpenShell control plane, sandbox boundary, runtime isolation, and policy-enforced network path."
keywords: "Generative AI, Cybersecurity, AI Agents, Architecture, Gateway, Sandbox, Supervisor, Isolation"
position: 2
---

![OpenShell system architecture showing a trusted supervisor separated from a network-isolated sandbox workload. The workload can connect only to the supervisor.](../images/openshell-system-architecture.svg)

OpenShell governs what agents can do in two ways: it instruments the kernel to enforce policy on every file access, system call, and network connection at runtime, and it uses formal verification to check what a policy change would allow before it is applied.

- **Kernel-level enforcement.** Each agent runs in an isolated sandbox. Kernel controls confine which files it can access and which system calls it can make, and every network connection passes through a policy check before it leaves the sandbox. Agents never see real credentials; OpenShell adds them only to requests bound for approved endpoints.
- **Formally verified policy changes.** Before a policy change is approved, OpenShell uses formal verification to flag risky new access it would grant, such as reaching a new host with credentials or calling a new API method, so those changes wait for human review.

The **gateway** is the control plane: it manages the lifecycle of sandboxes and
provides connectivity and management of sandboxes to end users and operators.
When you create a sandbox, its **compute driver** provisions a **workload** and
a separate **supervisor**, establishes their protected channel, and builds the
isolation boundary; the **supervisor** confirms that boundary before starting the
**agent** and then connects back to the gateway for policy, credentials, logs,
and interactive sessions.

## What Each Piece Does

| Component | What it does |
|---|---|
| [**Sandbox**](#inside-the-sandbox-boundary) | Lives inside the boundary with the agent. It owns the agent's processes, knows which program made each request, applies process controls, and forwards TCP and DNS traffic to the **supervisor**. |
... (163 lines truncated)
</file>

<file path="docs/about/installation.mdx">
---
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
title: "Installation"
sidebar-title: "Installation"
description: "Install OpenShell on a local workstation or Kubernetes."
keywords: "Generative AI, Cybersecurity, AI Agents, Sandboxing, Installation, Setup, Gateway, Docker, Podman, MicroVM, Kubernetes"
position: 3
---

Install OpenShell on a local workstation or Kubernetes.

## Install OpenShell

Install the CLI, policy prover, and a local gateway with one command:

```shell
curl -LsSf https://raw.githubusercontent.com/NVIDIA/OpenShell/main/install.sh | sh
```

The script picks a package for your platform and starts the gateway. Confirm the CLI can reach it:

```shell
openshell status
```

To install a specific release, set `OPENSHELL_VERSION` to a release tag. Release artifacts are also on the [GitHub Releases](https://github.com/NVIDIA/OpenShell/releases) page.

## Prerelease and Development Builds

... (163 lines truncated)
</file>

<file path="docs/about/overview.mdx">
---
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
title: "Overview of NVIDIA OpenShell"
sidebar-title: "Overview"
description: "OpenShell is the safe, private runtime for fleets of autonomous AI agents. Run agents in sandboxed environments that protect your data, credentials, and infrastructure."
keywords: "Generative AI, Cybersecurity, AI Agents, Sandboxing, Security, Privacy, Provider Credentials"
position: 1
---

NVIDIA OpenShell is an open-source runtime for executing fleets of autonomous AI agents in sandboxed environments with kernel-level isolation. It combines sandbox runtime controls and a declarative YAML policy so teams can run agents without giving them unrestricted access to local files, credentials, and external networks.

<Note>
New in OpenShell 0.1.x: a [stable release cadence](/about/support-matrix#releases), new [isolation primitives](/about/architecture), and an expanded [extension surface](/extensibility/overview), along with much more.

See our [upgrade guide](/upgrade/0-1-0) for everything that's changed.
</Note>

## Why OpenShell Exists

AI agents are most useful when they can read files, install packages, call APIs, and use credentials. That same access can create material risk. OpenShell is designed for this tradeoff: preserve agent capability while enforcing explicit controls over what the agent can access.

## Common Risks and Controls

The table below summarizes common failure modes and how OpenShell mitigates them.

| Threat | Without controls | With OpenShell |
|---|---|---|
| Data exfiltration | Agent uploads source code or internal files to unauthorized endpoints. | Network policies allow only approved destinations; other outbound traffic is denied. |
| Credential theft | Agent reads local secrets such as SSH keys or cloud credentials. | Filesystem restrictions (Landlock) confine access to declared paths only. |
... (35 lines truncated)
</file>

<file path="docs/about/run-your-first-agent.mdx">
---
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
title: "Run Your First Agent"
sidebar-title: "Run Your First Agent"
description: "Configure a provider, image, and policy to run an AI agent in an OpenShell sandbox."
keywords: "Generative AI, Cybersecurity, AI Agents, Sandboxing, Provider Profiles, Policies, Custom Images"
position: 4
---

OpenShell can run any agent that is available in a sandbox image. Configure the
agent's external services, choose its image and policy, then create the sandbox
with the agent as its main process.

**1. Configure what the agent has access to.**

A [provider profile](/how-it-works/providers/profiles) defines the credentials, service
endpoints, and executable paths an agent may use.

This example runs OpenCode
against OpenRouter. Review the
[example profile](https://github.com/NVIDIA/OpenShell/blob/main/providers/openrouter.yaml),
which allows `/usr/local/bin/opencode` to reach `openrouter.ai`, then import
it and [create a provider](/how-it-works/providers/overview#create-a-provider)
that stores its credentials.

```shell
openshell profile import \
  --url https://raw.githubusercontent.com/NVIDIA/OpenShell/main/providers/openrouter.yaml

... (86 lines truncated)
</file>

<file path="docs/about/support-matrix.mdx">
---
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
title: "Support Matrix"
description: ""
position: 5
---

This page lists the host platform, compute driver, software, runtime, and kernel requirements for running OpenShell.

## Releases

OpenShell publishes dev, pre-release, and stable builds for different stages of
the release cycle. Use a stable release for production deployments.

| Release | Publication | Intended use |
|---|---|---|
| Dev | Built from every commit to `main` that passes normal CI. The floating `dev` alias points to the newest build. | Testing upcoming functionality. Dev builds enable development features and have not passed release qualification. |
| Pre-release | Built nightly when `main` has changed and normal CI passes. Versions use the form `X.Y.Z-pre.N`. | Validating the immutable artifact set proposed for the next stable release. Pre-releases use the stable feature set but may not have passed qualification. |
| Stable | Promoted from a pre-release that passes conformance, upgrade, API compatibility, artifact, and security checks. Versions use the form `X.Y.Z`. | Production use within this support matrix. |

Tagged stable releases generally go out every week. OpenShell targets Tuesday
publication when there are changes and every blocking qualification check
passes. A security release may ship sooner.

Stable APIs and other Stable interfaces remain backward-compatible across
patch releases. Patch releases can contain fixes and additive functionality. A
breaking change to a Stable interface requires a minor release with notice and
migration guidance. Interfaces marked Experimental may change or be removed in
a patch release.
... (182 lines truncated)
</file>

<file path="docs/extensibility/supervisor-middleware/configure.mdx">
---
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
title: "Supervisor Middleware Configuration"
sidebar-title: "Configuration"
slug: "extensibility/supervisor-middleware/configure"
description: "Attach supervisor middleware to sandbox traffic, register your own middleware services, and observe middleware decisions."
keywords: "Supervisor Middleware, Configuration, Network Policy, Operations, OCSF, Logging"
---

Register your middleware service in gateway configuration, then attach it to destination hosts in sandbox policy. This page also covers ordering, failure behavior, service lifecycle, and observability. Built-in middleware needs only a policy entry.

## Use Your Own Middleware Service

A middleware service is a gRPC server that implements the supervisor middleware protocol. The [content guard example](https://github.com/NVIDIA/OpenShell/tree/main/examples/supervisor-middleware-content-guard) implements request, response, and WebSocket checks in one service, and includes a policy and a local launcher.

To use your own service:

1. Start the service where both the gateway and sandbox supervisors can reach it.
2. Register it in gateway configuration.
3. Restart the gateway.
4. Attach it in sandbox policy by setting `middleware` to the registration `name`.

Register the service in gateway TOML:

```toml
[[openshell.supervisor.middleware]]
name = "content-guard"
grpc_endpoint = "https://content-guard.example:50051"
tls_ca_cert_path = "/path/to/content-guard-ca.pem"
... (170 lines truncated)
</file>

<file path="docs/extensibility/supervisor-middleware/index.mdx">
---
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
title: "Supervisor Middleware"
slug: "extensibility/supervisor-middleware"
description: "Inspect, block, or change sandbox requests and responses with supervisor middleware."
keywords: "Generative AI, Cybersecurity, AI Agents, Supervisor Middleware, Extensibility, Request Filtering"
---

Supervisor middleware lets you inspect, block, or change the content that an agent sends and receives over the network. The sandbox supervisor, which enforces the sandbox's network policy, runs middleware as traffic passes between the agent and an external service.

## When to Use Middleware

A network policy decides whether an agent can call an API. Use middleware when you also need to check what the agent sends to that API or what the API returns, without changing the agent's code. For example, you can:

- Redact API tokens from outgoing request bodies.
- Reject requests that contain content your organization prohibits.
- Remove sensitive content from HTTP responses before the agent receives them.
- Check outgoing WebSocket text messages during a session.

The [content guard example](https://github.com/NVIDIA/OpenShell/tree/main/examples/supervisor-middleware-content-guard) shows a complete middleware service that performs checks like these.

## How Middleware Processes Traffic

The sandbox supervisor calls middleware after it checks network policy and before it forwards traffic to the external service:

```mermaid
sequenceDiagram
  participant Sandbox
  participant Supervisor
... (82 lines truncated)
</file>

<file path="docs/extensibility/supervisor-middleware/operations.mdx">
---
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
title: "Supported Operations"
sidebar-title: "Supported Operations"
slug: "extensibility/supervisor-middleware/operations"
description: "Build a middleware service that inspects and changes sandbox HTTP requests, HTTP responses, and WebSocket messages."
keywords: "Supervisor Middleware, Operations, Bindings, HTTP, WebSocket, Request Body, Response Body, Header Mutation, Payload Limits"
---

A middleware service handles one or more operations, such as HTTP requests or WebSocket messages. This page describes when OpenShell calls your service for each operation, what your service receives, and what it can return. The RPCs that every middleware service implements are described in [Build Your Middleware Service](/extensibility/supervisor-middleware#build-your-middleware-service).

## Operations and Phases

| Operation | Phase | When OpenShell calls your service | RPC |
| --- | --- | --- | --- |
| `HTTP_REQUEST` | `PRE_CREDENTIALS` | After network policy allows a request, before OpenShell injects provider credentials. | `EvaluateHttpRequest` |
| `HTTP_RESPONSE` | `PRE_RETURN` | After the external service responds, before the sandbox receives the response. | `HttpResponsePreReturn.Evaluate` |
| `WEBSOCKET_MESSAGE` | `PRE_CREDENTIALS` | When the sandbox opens a WebSocket connection, and for each text message it sends. | `EvaluateWebSocketSession` |

Your service declares each operation it supports as a binding, an operation and its phase, in its `Describe` manifest. OpenShell calls your service only for the operations it declares.

When several middleware match the same traffic, OpenShell calls them in ascending `order`, and each middleware sees the changes that earlier middleware made.

## Common Inputs and Results

Every operation includes a request context. The context always includes `sandbox_id`. Use it for authorization, persistence, and correlation. The context also includes `sandbox` and `workspace` names when available. Names can be reused, so use them only for display and logging.

Operations that include headers deliver them in wire order, and repeated headers stay separate. OpenShell removes credential, routing, and hop-by-hop headers before sending them to your service. It also removes framing headers from request input. Response preflight retains upstream `Content-Length`, `Content-Encoding`, and `Content-Range` as read-only metadata, unless `Connection` names them as hop-by-hop headers. Your service cannot change or remove these fields; OpenShell handles downstream framing.

... (222 lines truncated)
</file>

<file path="docs/extensibility/drivers.mdx">
---
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
title: "Drivers"
description: "Understand the compute and credential driver extension points in OpenShell."
keywords: "OpenShell Extensions, Compute Drivers, Credential Drivers, Extensibility"
---

OpenShell uses drivers to connect the gateway to workload runtimes and
credential stores. Drivers implement a stable capability boundary while the
gateway owns the public API, authorization, workspace scoping, and resource
lifecycle.

## Compute Drivers

Compute drivers create, inspect, and delete sandbox workloads. OpenShell ships
drivers for Kubernetes, Docker, Podman, virtual machines, and Windows MXC. An
external compute driver communicates with the gateway over a Unix domain
socket and negotiates its protocol version and capabilities before serving
requests.

For built-in driver configuration and behavior, refer to
[Runtimes](/how-it-works/sandboxes/runtimes). For implementation details, refer
to each driver crate:

| Driver | Crate |
|---|---|
| Docker | [`openshell-driver-docker`](https://github.com/NVIDIA/OpenShell/blob/main/crates/openshell-driver-docker/README.md) |
| Podman | [`openshell-driver-podman`](https://github.com/NVIDIA/OpenShell/blob/main/crates/openshell-driver-podman/README.md) |
| MicroVM | [`openshell-driver-vm`](https://github.com/NVIDIA/OpenShell/blob/main/crates/openshell-driver-vm/README.md) |
... (31 lines truncated)
</file>

<file path="docs/extensibility/gateway-interceptors.mdx">
---
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
title: "Gateway Interceptors"
sidebar-title: "Gateway Interceptors"
slug: "extensibility/gateway-interceptors"
description: "Extend OpenShell gateway operations with deployment-specific governance and business logic."
keywords: "Generative AI, Cybersecurity, AI Agents, Gateway Interceptors, Extensibility, Governance"
---
Gateway interceptors let operators add deployment-specific governance to OpenShell control-plane operations without modifying the gateway. An external gRPC service can modify or validate selected API writes before the gateway handles them, then observe successful responses after commit.

See the [governance interceptor example](https://github.com/NVIDIA/OpenShell/tree/main/examples/governance-interceptor) for a complete service that vends provider profiles, applies a signed policy to new sandboxes, and rejects attempts to weaken that policy.

## When to Use Gateway Interceptors

Use a gateway interceptor when an external service needs to govern gateway API operations. For example, an interceptor can:

- Apply an approved policy to every new sandbox.
- Reject provider or policy changes that violate organizational rules.
- Enforce tenant quotas or naming conventions.
- Observe committed operations for an audit or inventory service.
- Vend an authoritative or composed provider profile catalog.

Gateway interceptors do not replace gateway persistence, authentication, authorization, policy safety checks, or driver validation. The gateway remains the system of record and validates an operation after interceptor modification.

## How Interception Works

The gateway runs interceptors after authentication and before dispatching a request to its handler:

`authenticate → decode and omit secrets → modify_operation → validate → gateway handler → post_commit`
... (145 lines truncated)
</file>

<file path="docs/extensibility/isolation-backends.mdx">
---
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
title: "Isolation Backends"
description: "Understand the runtime boundary used to launch and supervise sandboxed workloads."
keywords: "OpenShell Extensions, Isolation Backends, Sandbox Runtime, Extensibility"
---

The supervisor uses one Rust interface, `IsolationBackend`, to launch and
control the agent workload. `OpenShellRuntimeBackend` implements that interface
by calling `openshell-sandbox` over the OpenShell Sandbox Protocol. Because the
supervisor depends only on the interface, another backend can provide the same
operations with different isolation mechanisms without changing the gateway API
or policy model.

![The supervisor calls the IsolationBackend interface. OpenShellRuntimeBackend implements it as a supervisor-side client and talks to openshell-sandbox, the workload-side server, over the Sandbox Protocol.](../images/openshell-isolation-backend.svg)

## The Interface

Each step returns a new type, so the supervisor can't start an agent on a
boundary that hasn't been confirmed. The traits are defined in
[`contract.rs`](https://github.com/NVIDIA/OpenShell/blob/main/crates/openshell-isolation-interface/src/contract.rs)
in the
[`openshell-isolation-interface`](https://github.com/NVIDIA/OpenShell/tree/main/crates/openshell-isolation-interface)
crate. `OpenShellRuntimeBackend` is implemented in
[`openshell-sandbox-backend`](https://github.com/NVIDIA/OpenShell/tree/main/crates/openshell-sandbox-backend).

| Rust surface | What it does | Returns |
|---|---|---|
| `IsolationBackend::attach()` | Binds a verified runtime descriptor to one admitted sandbox. | `BoundBoundary` |
... (19 lines truncated)
</file>

<file path="docs/extensibility/overview.mdx">
---
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
title: "Extensibility"
sidebar-title: "Overview"
slug: "extensibility/overview"
description: "Understand how OpenShell adapts to deployment-specific infrastructure, governance, and workload requirements."
keywords: "OpenShell Extensions, Middleware, Interceptors, Drivers, Isolation Backends, Protocol Negotiation"
---

![OpenShell extension points. Data plane: the sandboxed agent reaches the supervisor through the isolation backend, and supervisor middleware processes requests before they reach models and APIs. Control plane: you reach the gateway through interceptors, and gateway drivers connect it to runtimes and secret stores.](../images/openshell-extension-points.svg)

Extensibility sits at the core of OpenShell. OpenShell is designed to run
everywhere and adapt to the infrastructure, governance, and workload
requirements of each deployment. Its extension points add deployment-specific
behavior while preserving the same API, policy model, and security boundaries.

You can extend each layer of OpenShell:

- **Control plane:** Gateway interceptors govern API operations.
- **Data plane:** Middleware processes agent traffic, and isolation backends
  control the sandboxed workload.
- **Infrastructure:** Drivers connect OpenShell to compute runtimes and secret
  stores.

## Extension Points

### [Middleware](/extensibility/supervisor-middleware)

Supervisor middleware inspects, transforms, or denies allowed HTTP and
... (118 lines truncated)
</file>

<file path="docs/how-it-works/gateways/authentication.mdx">
---
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
title: "Gateway Authentication"
sidebar-title: "Authentication"
description: "Gateway resolution, authentication modes, connection flow, OIDC support, and credential file layout."
keywords: "Generative AI, Cybersecurity, Gateway, Authentication, mTLS, OIDC, OpenID Connect, Edge Authentication, Reference"
position: 1
---

This page describes how the CLI resolves a gateway, authenticates with it, and where credentials are stored. For how to deploy or register gateways, refer to [Gateways](/how-it-works/gateways/overview).

## Gateway Resolution

When any CLI command needs to talk to the gateway, it resolves the target through a priority chain:

1. `--gateway-endpoint <URL>` flag (direct URL).
2. `-g <NAME>` flag.
3. `OPENSHELL_GATEWAY` environment variable.
4. Active gateway from `~/.config/openshell/active_gateway`, falling back to `/etc/openshell/active_gateway` when no user selection exists.

The CLI loads gateway metadata from `~/.config/openshell/gateways/<name>/metadata.json` first and falls back to `/etc/openshell/gateways/<name>/metadata.json` when no user entry exists.

## Authentication Status

`openshell status` reports gateway reachability and authentication separately. The public health RPC determines whether the gateway is connected and supplies its version. The CLI then calls the existing protected gateway-info capability query to verify the configured credentials. An authorization denial still confirms that the gateway authenticated the caller.

For example, an expired bearer token can produce `Status: Connected` and `Authentication: Failed`. This means the gateway is healthy but protected commands cannot use the current credentials. Run `openshell gateway login <name>` to re-authenticate. When a gateway predates the gateway-info capability query, the CLI reports `Authentication: Unverified` rather than treating a successful public health check as proof of authentication.

## Authentication Modes
... (288 lines truncated)
</file>

<file path="docs/how-it-works/gateways/configuration.mdx">
---
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
title: "Gateway Configuration File"
sidebar-title: "Configuration"
description: "Reference for the OpenShell gateway TOML configuration file (RFC 0003)."
keywords: "Generative AI, Cybersecurity, AI Agents, Sandboxing, Gateway, Configuration, TOML, Reference"
position: 5
---

The OpenShell gateway reads its configuration from a TOML file when `--config` or `OPENSHELL_GATEWAY_CONFIG` is set. When neither is set, the gateway reads `$XDG_CONFIG_HOME/openshell/gateway.toml` if that file exists. If no config file exists, the gateway starts from built-in defaults. Gateway process flags and gateway `OPENSHELL_*` environment variables override the file. Compute driver settings live in the driver TOML tables. See [RFC 0003](https://github.com/NVIDIA/OpenShell/blob/main/rfc/0003-gateway-configuration/README.md) for the full schema.

## Source Precedence

```text
Gateway CLI flag  >  gateway OPENSHELL_* env var  >  TOML file  >  built-in default
```

`database_url` is env-only. The loader rejects it when it appears in the file. When `OPENSHELL_DB_URL` is unset, the gateway stores its SQLite database under `$XDG_STATE_HOME/openshell/gateway/openshell.db`.

On-disk SQLite databases run in WAL mode with `synchronous=FULL`: the gateway keeps `openshell.db-wal` and `openshell.db-shm` next to the database file, the file must live on a local filesystem, and a backup must use `sqlite3 openshell.db ".backup <copy>"` rather than copying `openshell.db` on its own. Every acknowledged write, including SSH session revocations, survives a power loss. The one exception is SSH session issuance, which skips the per-commit sync; a power loss can drop a just-issued session token, and the client must request a new one.

`name` assigns an operator-facing identity to the gateway installation. Set it with `[openshell.gateway].name`, `--name`, or `OPENSHELL_GATEWAY_NAME`. It defaults to `openshell`; the Helm chart defaults it to the chart fullname so all replicas in one installation share a name. Chart fullnames are only unique within their Kubernetes namespace, so set `server.name` explicitly when one collector receives telemetry from multiple namespaces or clusters. This identity is independent of client-side gateway aliases, TLS names, and `gateway_jwt.gateway_id`.

## Package-Managed Locations

Package-managed gateways use either built-in defaults or a package-seeded TOML file. Set `OPENSHELL_GATEWAY_CONFIG` in the launch environment to use a different file.

| Package | Gateway TOML location |
|---|---|
... (1254 lines truncated)
</file>

<file path="docs/how-it-works/gateways/container-deployment.mdx">
---
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
title: "Running the Gateway as a Container"
sidebar-title: "Container Deployment"
description: "Run the OpenShell gateway using docker run or docker-compose without the installer."
keywords: "Generative AI, Cybersecurity, AI Agents, Sandboxing, Docker, Podman, docker-compose, container, immutable OS, bootc, rpm-ostree"
position: 8
---

Use this approach when you want to run the OpenShell gateway as a container instead of installing it with the system package manager. This is useful on immutable OS distributions (Fedora CoreOS, bootc-based images, Silverblue) where the standard installer is not appropriate, or anywhere you prefer a container-first workflow.

The gateway image is published at `ghcr.io/nvidia/openshell/gateway`.

## Prerequisites for the Docker Driver

When the gateway runs as a container and creates Docker-backed sandboxes, the gateway container
communicates with the host Docker daemon via the mounted socket. This requires three things beyond
a basic `docker run`:

1. **Docker socket access.** The gateway process must be able to read and write the Docker socket.
   Add the `docker` group (or the GID of `/var/run/docker.sock`) so the socket is accessible
   without running as root.

2. **gRPC endpoint.** Sandbox containers call back to the gateway over the `OPENSHELL_GRPC_ENDPOINT`
   address. The Docker driver substitutes `host.openshell.internal` as the host and the gateway's
   own bind port as the port — only the **scheme** (`http` or `https`) is preserved. Use
   `http://host.openshell.internal:8080` when TLS is disabled and `https://host.openshell.internal:8080`
   when mTLS is enabled. The docker driver automatically binds the gateway to the bridge network
   interface so sandbox containers can reach it — you do not need to expose the port on `0.0.0.0`.
... (173 lines truncated)
</file>

<file path="docs/how-it-works/gateways/overview.mdx">
---
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
title: "Manage Gateways"
sidebar-title: "Overview"
description: "Register OpenShell gateways, switch between environments, inspect gateway status, and troubleshoot gateway access."
keywords: "Generative AI, Cybersecurity, Gateway, Docker, Podman, Kubernetes, MicroVM, CLI"
position: 2
---

The gateway is the control plane for OpenShell. All control-plane traffic between the CLI and running sandboxes flows through the gateway.

The gateway is responsible for:

- Provisioning and managing sandboxes, including creation, deletion, and status monitoring.
- Storing provider credentials and delivering them to sandboxes at startup.
- Delivering network and filesystem policies to sandboxes. Policy enforcement itself happens inside each sandbox through the proxy, OPA, Landlock, and seccomp.
- Resolving endpoint-bound provider environments for the providers attached to each sandbox.
- Providing the SSH tunnel endpoint so you can connect to sandboxes without exposing them directly.

OpenShell separates gateway access from the compute driver that runs sandboxes. Use [Installation](/about/installation) to install OpenShell, choose a compute driver, and start a gateway. This page covers working with gateway entries after a gateway exists.

## Gateway Runtimes

A gateway provisions sandboxes through the compute driver configured for that gateway.

| Runtime | Where sandboxes run | Best for |
|---|---|---|
| Docker | Containers on the gateway host. | Solo development, quick iteration, and single-machine gateways. |
| Podman | Rootless containers on the gateway host. | Workstations that avoid a rootful Docker daemon. |
... (170 lines truncated)
</file>

<file path="docs/how-it-works/policies/advisor.mdx">
---
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
title: "Policy Advisor"
sidebar-title: "Policy Advisor"
description: "Let an agent in a sandbox propose the network rule it needs when OpenShell blocks a request, and control which proposals take effect."
keywords: "Generative AI, Cybersecurity, Policy Advisor, Policy, Sandbox, policy.local, Agent Policy"
position: 5
---

The policy advisor lets an agent in a sandbox propose a new network rule when
OpenShell blocks one of its network requests, and you decide which proposals
take effect. It handles network access only. A proposal can add a network rule,
but it cannot remove rules or change filesystem, Landlock, or process settings.

Without the policy advisor, an agent whose request is blocked usually cannot
finish its task until someone changes the policy by hand. With it, the agent can
request the access it needs. Because network rules can change while a sandbox
runs, an approved rule takes effect without a restart.

The policy advisor is off by default. When you enable it, OpenShell gives the
agent instructions and a local HTTP API for submitting proposals. A proposal
never changes the policy on its own. By default, every proposal waits for your
review. You can opt in to automatic approval, which approves a proposal when
OpenShell's risk checks find nothing to flag.

## How the Policy Advisor Works

A proposal goes through these steps:

... (288 lines truncated)
</file>

<file path="docs/how-it-works/policies/default-policy.mdx">
---
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
title: "Default Policy and Baseline Paths"
sidebar-title: "Default Policy"
description: "The restrictive fallback policy used when a sandbox has no explicit or embedded policy, and the baseline paths OpenShell adds to sandbox policies."
keywords: "Generative AI, Cybersecurity, AI Agents, Sandboxing, Security, Policy, Landlock, Filesystem"
position: 6
---

This reference describes the restrictive policy OpenShell uses when a sandbox
has no other policy, and the filesystem paths that OpenShell adds to sandbox
policies at runtime.

## When the Default Applies

OpenShell uses the restrictive default only when no global policy is active, the
sandbox has no saved policy, and its image contains no policy. Creating a
sandbox without `--policy` does not by itself mean the default is active,
because the image or `OPENSHELL_SANDBOX_POLICY` can supply one. An invalid image
policy keeps the workload from starting until you repair it. It does not select
the default. Refer to [Where the Active Policy Comes
From](/how-it-works/policies/overview#where-the-active-policy-comes-from) for
the complete selection order.

## Default Filesystem Access

The default policy includes the sandbox working directory as read-write and
grants read-only access to these paths:

... (93 lines truncated)
</file>

<file path="docs/how-it-works/policies/manage-policies.mdx">
---
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
title: "Manage Sandbox Policies"
sidebar-title: "Manage Policies"
description: "Use the OpenShell CLI to set, inspect, change, verify, and roll back sandbox policies, apply a global policy, and troubleshoot policy problems."
keywords: "Generative AI, Cybersecurity, Policy, Sandbox, CLI, Hot Reload, Revision"
position: 3
---

This page shows how to use the OpenShell CLI to manage a sandbox's policy, from
setting a policy when you create a sandbox to changing it while the sandbox
runs, confirming that the change took effect, and rolling it back. Run
`openshell policy --help` for every command and option.

## Create a Sandbox with a Policy

Pass a policy file when you create a sandbox. Filesystem, Landlock, and process
settings take effect only when the sandbox starts, so set them here:

```shell
openshell sandbox create --name my-sandbox --policy ./policy.yaml
```

The rest of this page refers to this sandbox as `my-sandbox`. If you omit the
sandbox name from an `openshell policy` command, the CLI uses the sandbox you
most recently created, connected to, or ran a command in, and prints its name.

To use the same file for every sandbox you create, set
`OPENSHELL_SANDBOX_POLICY` instead of passing `--policy`:
... (362 lines truncated)
</file>

<file path="docs/how-it-works/policies/network-rules.mdx">
---
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
title: "Network Rules"
sidebar-title: "Network Rules"
description: "Understand how OpenShell evaluates network rules, and adapt examples for REST APIs, package registries, internal services, WebSocket, GraphQL, MCP, and native TCP."
keywords: "Generative AI, Cybersecurity, Policy, Network, REST, TCP, WebSocket, GraphQL, MCP, PyPI, npm"
position: 2
---

Network rules control which destinations each binary in a sandbox can reach, and
which requests it can send. They make up most of a typical policy. This page
explains how OpenShell evaluates network rules, then gives example rules for
common services and protocols that you can adapt.

## How Network Rules Work

OpenShell checks every outbound connection from a sandbox against the
`network_policies` section of its policy, and denies any connection that no rule
allows.

### Rule Structure

Each entry in `network_policies` is a rule. The entry's key is the rule's name,
and the rule contains two lists. `endpoints` lists the destinations the rule
allows, and `binaries` lists the executables that can connect to them. A rule
allows every listed binary to reach every listed endpoint.

For example, this rule is named `example_api` and lists two binaries and two
endpoints:
... (637 lines truncated)
</file>

<file path="docs/how-it-works/policies/overview.mdx">
---
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
title: "Sandbox Policies"
sidebar-title: "Overview"
description: "Understand what sandbox policies control and where a sandbox's policy comes from."
keywords: "Generative AI, Cybersecurity, Policy, Network Policy, Sandbox, Security, Hot Reload"
position: 1
---

A sandbox policy is a YAML configuration that controls what a sandbox can
access. It defines which files processes in the sandbox can read and write,
which user they run as, which network destinations each binary can reach, and
which requests it can send. OpenShell denies anything the policy does not allow.

This page explains how policies work. To try one in a running sandbox, follow
[Write Your First Sandbox Network Policy](/tutorials/first-network-policy). To
create and change policies, refer to [Manage Sandbox
Policies](/how-it-works/policies/manage-policies).

## What a Policy Controls

A policy file sets `version: 1` and has up to five other top-level sections.
Each section controls a different part of the sandbox and takes effect at a
specific time:

| Section | Controls | Enforced by | Takes effect |
|---|---|---|---|
| `filesystem_policy` | Paths that sandbox processes can read, or read and write. | Landlock LSM in the kernel. | At sandbox startup. |
| `landlock` | Whether the sandbox still starts, without your filesystem rules, if OpenShell cannot apply them. | Sandbox runtime. | At sandbox startup. |
... (75 lines truncated)
</file>

<file path="docs/how-it-works/policies/prover.mdx">
---
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
title: "Policy Prover"
sidebar-title: "Policy Prover"
description: "Understand how OpenShell uses the policy prover, and check that a policy grants no more access than a boundary policy you define."
keywords: "Generative AI, Cybersecurity, Policy, Prover, Boundary, Subagent"
position: 4
---

The policy prover is OpenShell's policy verification engine. It uses an SMT
solver to check whether policies satisfy specified properties, such as staying
within an allowed access boundary. Its guarantees apply to the policy features
and behavior represented by its model. OpenShell is actively extending the model
to cover more policy features.

OpenShell uses the prover for two types of checks:

- A boundary check verifies that a policy allows no access beyond a boundary
  policy, which defines the most access allowed in an environment.
- A proposal risk check verifies that a proposed network rule adds no risky
  access compared with the sandbox's current policy, such as access to cloud
  metadata addresses or new destinations for provider credentials.

You run a boundary check with the `openshell-prover` CLI, which is primarily
intended for agents. For example, a parent agent can check that a policy it
writes for a subagent stays within the parent's own maximum allowed policy. A
proposal risk check runs automatically each time an agent proposes a network
rule through the [policy advisor](/how-it-works/policies/advisor).

... (202 lines truncated)
</file>

<file path="docs/how-it-works/policies/schema.mdx">
---
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
title: "Policy Schema Reference"
sidebar-title: "Schema Reference"
description: "Fields, defaults, and constraints for the sandbox policy schema."
keywords: "Generative AI, Cybersecurity, Policy, Schema, YAML, Reference, Security"
position: 7
---

This reference defines the sandbox policy schema. A policy is a YAML file of at
most 4 MiB. OpenShell rejects a policy that contains unknown fields or duplicate
keys.

## Top-Level Fields

```yaml showLineNumbers={false}
version: 1
filesystem_policy: { ... }
landlock: { ... }
process: { ... }
network_policies: { ... }
network_middlewares: { ... }
```

| Field | Type | Required | Takes effect | Description |
|---|---|---|---|---|
| `version` | integer | Yes | -- | Schema version. Must be `1`. |
| `filesystem_policy` | object | No | Startup | Paths the workload can read and write. |
| `landlock` | object | No | Startup | Landlock enforcement behavior. |
... (600 lines truncated)
</file>

<file path="docs/how-it-works/providers/aws.mdx">
---
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
title: "AWS SigV4 Credential Signing"
sidebar-title: "AWS"
description: "Configure proxy-side AWS SigV4 request signing so sandbox agents can reach AWS services through CONNECT tunnels without holding real credentials."
keywords: "Generative AI, Cybersecurity, AI Agents, AWS, SigV4, Bedrock, S3, Credential Signing, Sandbox"
---

AWS SigV4 credential signing lets sandbox agents call AWS services (Bedrock, S3, STS, and others) through the proxy's CONNECT tunnel. The proxy intercepts outbound requests, strips the sandbox client's placeholder `Authorization` header, and re-signs the request with real AWS credentials from the provider. The sandbox never sees the real credentials.

## Prerequisites

- A provider with `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY` credentials configured. Optionally include `AWS_SESSION_TOKEN` for STS temporary credentials.
- An endpointless `aws` provider profile when the sandbox policy defines the service endpoints, or an endpoint-bearing service profile such as `aws-s3`.
- A sandbox policy with `credential_signing` enabled on the target endpoint. For the endpointless `aws` profile, the endpoint must also set `credential_binding.provider` to the attached provider name.

## Provider Setup

Import the `aws` profile first; a gateway serves only the profiles you
imported:

```shell
openshell profile import --url https://raw.githubusercontent.com/NVIDIA/OpenShell/main/providers/aws.yaml --global
```

Create a provider with AWS credentials:

```shell
openshell provider create \
... (151 lines truncated)
</file>

<file path="docs/how-it-works/providers/google.mdx">
---
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
title: "Google"
sidebar-title: "Google"
description: "Authenticate with Google Cloud APIs and Vertex AI inside OpenShell sandboxes."
keywords: "Generative AI, Google Cloud, Vertex AI, GCP, OAuth2, Credentials, Sandbox"
---

The `google-cloud` provider gives sandboxes native GCP credentials so
any Google Cloud SDK works out of the box — Cloud Storage, BigQuery, Drive,
Maps, Discovery Engine, or any other GCP API. A GCE metadata server emulator
on loopback provides credential placeholders that the
sandbox proxy resolves to real tokens at request time. The sandbox process
never holds a real GCP credential.

## Quick Start

Import the `google-cloud` profile first; a gateway serves only the profiles you
imported:

```shell
openshell profile import --url https://raw.githubusercontent.com/NVIDIA/OpenShell/main/providers/google-cloud.yaml --global
```

If you already have `gcloud` configured with Application Default Credentials,
create a provider with automatic credential refresh in one command:

```shell
openshell provider create \
... (349 lines truncated)
</file>

<file path="docs/how-it-works/providers/overview.mdx">
---
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
title: "Providers"
sidebar-title: "Overview"
description: "Create and manage credential providers that inject API keys and tokens into OpenShell sandboxes."
keywords: "Generative AI, Cybersecurity, Providers, Credentials, API Keys, Sandbox, Security"
position: 4
---

AI agents typically need credentials to access external services: an API key for the AI model provider, a token for GitHub or GitLab, and so on. OpenShell manages these credentials as first-class entities called *providers*.

Create and manage providers that supply credentials to sandboxes.

<Info>
Provider profiles define provider credentials, policy, and refresh behavior. See
[Profiles](/how-it-works/providers/profiles) for the profile format and custom
profile workflow.
</Info>

Provider profiles include metadata for known endpoints and binaries. View
the available profiles before creating a provider:

```shell
openshell profile list
openshell profile describe github
```

## Create a Provider

... (460 lines truncated)
</file>

<file path="docs/how-it-works/providers/profiles.mdx">
---
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
title: "Profiles"
sidebar-title: "Profiles"
description: "Use provider profiles to attach credentials, network policy, and refresh metadata to OpenShell sandboxes."
keywords: "Generative AI, Cybersecurity, Providers, Provider Profiles, Credentials, Policy, Sandbox"
position: 1
---

Provider profiles turn providers from credential records into profile-backed access bundles. A provider profile describes the credentials, endpoints, binaries, policy rules, and refresh behavior for a provider type. A provider instance stores the concrete credential and config values for one gateway.

Use provider profiles when you want provider-owned policy rules to travel with provider credentials. For example, a GitHub provider can describe both `GITHUB_TOKEN` and the GitHub API endpoints that a sandbox needs, so users do not have to copy the same network policy into every sandbox.

## Why Provider Profiles Exist

Provider credentials and network policy were previously configured through separate workflows. A user could create a GitHub provider that stored `GITHUB_TOKEN`, but the sandbox still needed a separate policy that allowed `api.github.com`, selected the right binaries, and configured REST enforcement.

Provider profiles keep those pieces together:

| Need | Profile-backed behavior |
|---|---|
| Repeatable provider setup | Imported provider profiles define reusable provider types. |
| Provider-aware policy | Attached providers contribute `_provider_*` network policy entries to the effective sandbox policy. |
| Custom provider definitions | You can export, edit, lint, import, list, and delete custom profiles. |
| Runtime provider lifecycle | You can list, attach, and detach providers on existing sandboxes. |
| Credential rotation | Provider refresh metadata lets the gateway refresh short-lived access tokens and update provider records. |
| Credential transport | Credential delivery uses environment placeholders and proxy rewrite. Static placeholders resolve only at profile endpoints or explicitly bound sandbox policy endpoints for endpointless profiles. |

## Available Features
... (1060 lines truncated)
</file>

<file path="docs/how-it-works/sandboxes/overview.mdx">
---
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
title: "Manage Sandboxes"
sidebar-title: "Overview"
description: "Create sandboxes, understand sandbox isolation, and manage the full sandbox lifecycle."
keywords: "Generative AI, Cybersecurity, Gateway, Sandboxing, AI Agents, Sandbox Management, CLI"
position: 1
---

A sandbox is the OpenShell data plane: a safe, private execution environment where an AI agent runs. Each sandbox combines runtime isolation with OpenShell policy controls that prevent unauthorized data access, credential exposure, and network exfiltration.

<Info>You need an active gateway before creating a sandbox.</Info>

## Create a Sandbox

Create a sandbox with a single command. For example, to create a sandbox with Claude, run:

```shell
openshell sandbox create --from registry.example.com/your-org/claude-agent:latest -- claude
```

The trailing command is the sandbox's canonical main process. OpenShell streams
its output and returns its exit status. By default, exit code 0 leaves a
retained sandbox in `Completed`; a nonzero exit leaves it in `Error` with a
`MainProcessFailed` condition. With no trailing command, OpenShell starts a
login shell in a retained pseudo-terminal: `/bin/bash -l` when the image
provides bash, otherwise a shell detected in the image such as `/bin/sh` on
minimal bases like Alpine. Add `--detach` to create the sandbox without
attaching:
... (954 lines truncated)
</file>

<file path="docs/how-it-works/sandboxes/runtimes.mdx">
---
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
title: "Sandbox Runtimes"
sidebar-title: "Runtimes"
description: "Configure the Docker, Podman, MicroVM, or Kubernetes runtime that runs OpenShell sandboxes."
keywords: "Generative AI, Cybersecurity, AI Agents, Sandboxing, Docker, Podman, MicroVM, Kubernetes, MXC, Reference"
position: 4
---

Each gateway runs agent workloads on one compute runtime, selected by its compute driver. Pick the runtime that matches the isolation boundary and infrastructure you need. The CLI workflow stays the same across runtimes: you create, connect to, stop, start, and delete sandboxes through the gateway.

The gateway owns main-process restart policy. Docker, Podman, Kubernetes, and
MicroVM native restart mechanisms remain disabled. When policy selects a
replacement, the gateway stops and starts the compute resource while retaining
the sandbox record and driver-supported persistent storage.

| Runtime | Driver | Use when |
|---|---|---|
| [Docker](#docker-driver) | `docker` | Local development and single-machine gateways. |
| [Podman](#podman-driver) | `podman` | Rootless Linux workstations without a Docker daemon. |
| [MicroVM](#microvm-driver) | `vm` | Workloads need a VM boundary instead of a container boundary. |
| [Kubernetes](#kubernetes-driver) | `kubernetes` | Shared clusters, remote compute, and GPU scheduling. |
| Windows MXC | `mxc` | Coming soon. |

## Select a Compute Driver

Set `compute_driver` in the gateway TOML file. A gateway uses one driver at a time.

```toml
... (273 lines truncated)
</file>

<file path="docs/how-it-works/sandboxes/templates.mdx">
---
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
title: "Sandbox Templates"
sidebar-title: "Templates"
slug: "how-it-works/sandboxes/templates"
description: "Define reusable sandbox workload settings and create sandboxes from templates."
keywords: "OpenShell, Sandboxes, Workload Templates, Images, Resources, Compute Drivers"
---

Sandbox workload templates let workspace admins define reusable runtime shapes for a workspace. A template stores the image, environment, resource requests, and driver-specific configuration that sandboxes should inherit. When you create a sandbox from a template, the create request can still attach providers, labels, and policy, but the workload comes from the named template.

## Create a Template

```shell
openshell sandbox template create gpu-kata \
  --image registry.example.com/agent:latest \
  --cpu 2 \
  --memory 4Gi \
  --gpu 1 \
  --label team=runtime \
  --env FEATURE_FLAG=on
```

Use `--gpu` without a count when the template should request the active
driver's default GPU assignment. Use `--gpu COUNT` when the template needs a
specific number of GPUs.

For a separate template with driver-specific settings, create it with
`--driver-config-json`:
... (36 lines truncated)
</file>

<file path="docs/how-it-works/inference.mdx">
---
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
title: "Inference"
sidebar-title: "Inference"
description: "Grant a sandbox access to model providers through provider profiles, attachments, and native endpoints."
keywords: "Generative AI, Cybersecurity, Inference, Provider Profiles, Credentials, LLM"
position: 8
---

OpenShell grants model-provider access through provider profiles and sandbox
attachments. The workload calls the provider's native API. OpenShell evaluates
the request against the profile-derived network policy and substitutes the real
credential only at an endpoint authorized by that profile.

This keeps the complete access contract in one place:

| Concern | Owner |
|---|---|
| Credential and refresh lifecycle | Provider instance |
| Authorized hosts, ports, paths, and binaries | Provider profile |
| Which workload receives access | Sandbox provider attachment |
| Base URL, model, request shape, and timeout | Native client or workload configuration |

## Define and Attach a Hosted Provider

Start from the [NVIDIA example profile](https://github.com/NVIDIA/OpenShell/blob/main/providers/nvidia.yaml),
review its access, and import an edited copy under a new ID. A new gateway has
no profiles to export. Download the example so you can add the Python paths
used by this workload:
... (294 lines truncated)
</file>

<file path="docs/how-it-works/workspaces.mdx">
---
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
title: "Workspaces"
sidebar-title: "Workspaces"
description: "Create OpenShell workspaces, assign members, and understand platform and workspace roles."
keywords: "Generative AI, Cybersecurity, Workspaces, Access Control, RBAC, OIDC, Membership, CLI"
position: 3
---

An OpenShell workspace is an access and resource isolation boundary. Sandboxes,
sandbox workload templates, providers, provider profiles, services, policies,
and settings belong to a workspace and are not visible to members of other
workspaces.

The CLI targets the `default` workspace unless you set `--workspace` or
`OPENSHELL_WORKSPACE`. The logical OpenShell workspace described here is
separate from the `/sandbox` filesystem directory inside a sandbox.

## Understand the Role Model

OpenShell combines an identity-provider role with a membership record for each
workspace.

| Role | Assignment | Access |
|---|---|---|
| Platform Admin | The OIDC role configured as `admin_role`. | Manages platform-scoped configuration and every workspace. Platform Admins bypass workspace membership checks. |
| Workspace Admin | An `admin` membership stored by the gateway for one workspace. | Manages providers, provider profiles, policies, settings, and members in that workspace. |
| Workspace User | A `user` membership stored by the gateway for one workspace. | Creates and uses sandboxes and services, reads providers, and uses provider attachments in that workspace. |

... (211 lines truncated)
</file>

<file path="docs/kubernetes/access-control.mdx">
---
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
title: "Access Control"
sidebar-title: "Access Control"
description: "Configure OIDC user authentication or reverse-proxy auth termination for a Kubernetes-deployed OpenShell gateway."
keywords: "Generative AI, Cybersecurity, Kubernetes, Authentication, mTLS, OIDC, Keycloak, Entra ID, Okta, Gateway Auth"
position: 6
---

The OpenShell gateway supports these access-control models for human callers on Kubernetes:

| Model | When to use |
|---|---|
| mTLS | Gateways with a configured client CA and no OIDC issuer. The gateway maps a verified client certificate to a user identity. |
| OIDC (recommended) | Production deployments. Integrates with an existing identity provider, supports role-based access control, and gives each user their own identity without distributing certificates. |
| Reverse-proxy auth termination | An access proxy (Cloudflare Access, ngrok, corporate SSO) authenticates callers in front of the gateway. The gateway trusts the proxy and skips its own client-cert check. |

The Helm chart generates a gateway TLS certificate and a user client certificate at install time. Supervisor Pods project only `ca.crt` from the client Secret so they can authenticate the gateway; the client certificate and private key are not exposed to sandboxes. Supervisors authenticate their RPCs with gateway-minted sandbox JWTs.

For how the CLI resolves gateways and stores credentials, refer to [Gateway Authentication](/how-it-works/gateways/authentication).

## Sandbox Supervisor Identity

Kubernetes sandbox supervisors authenticate back to the gateway as sandbox workloads. By default, the Kubernetes compute driver validates each projected ServiceAccount token and returns the authenticated sandbox ID plus a stable runtime identity to the gateway. The gateway requires that identity to match the namespace, immutable Sandbox resource UID, and supervisor Pod UID recorded during provisioning before it mints its own sandbox JWT.

Dynamic provider token grants can use SPIFFE without changing supervisor-to-gateway authentication. Set `server.providerTokenGrants.spiffe.enabled=true` to mount the SPIFFE CSI Workload API socket into gateway and sandbox pods while keeping the projected ServiceAccount token bootstrap and gateway-minted sandbox JWT path.

Provider token grants require a SPIFFE implementation such as SPIRE and identities for the gateway and sandbox pods. The repository's local SPIRE overlay assigns sandbox IDs from the pod's `openshell.ai/sandbox-id` annotation, but the gateway validation path only requires the supervisor SVID to be valid and in the same SPIFFE trust domain as the gateway SVID. Provider profiles with `token_grant` metadata cause the sandbox supervisor to request JWT-SVIDs and exchange them for upstream OAuth2 access tokens. Token-exchange profiles also require a gateway SPIFFE identity because the gateway brokers the intermediate token exchange with its own JWT-SVID.

... (104 lines truncated)
</file>

<file path="docs/kubernetes/ingress.mdx">
---
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
title: "Ingress"
sidebar-title: "Ingress"
description: "Expose the OpenShell gateway externally using the Kubernetes Gateway API and a GRPCRoute."
keywords: "Generative AI, Cybersecurity, Kubernetes, Gateway API, Envoy Gateway, GRPCRoute, Ingress, External Access"
position: 5
---

By default, the OpenShell gateway is only reachable inside the cluster. To let CLI clients connect without a `kubectl port-forward`, expose the gateway through an ingress.

OpenShell uses the [Kubernetes Gateway API](https://gateway-api.sigs.k8s.io) for ingress. The chart creates a `GRPCRoute` that routes inbound gRPC traffic to the gateway pod. You need a Gateway API implementation installed on your cluster to fulfill the `GRPCRoute`. This page uses [Envoy Gateway](https://gateway.envoyproxy.io), which the chart is tested with.

## Install Envoy Gateway

Envoy Gateway installs the Gateway API CRDs and controller:

```shell
helm install eg \
  oci://docker.io/envoyproxy/gateway-helm \
  --version v1.8.1 \
  --namespace envoy-gateway-system \
  --create-namespace \
  --wait
```

## Create the GatewayClass

Create the `eg` GatewayClass that the OpenShell chart references:
... (186 lines truncated)
</file>

<file path="docs/kubernetes/managing-certificates.mdx">
---
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
title: "Managing Certificates"
sidebar-title: "Managing Certificates"
description: "Configure the OpenShell Helm chart to use cert-manager for mTLS certificate issuance and automatic renewal."
keywords: "Generative AI, Cybersecurity, Kubernetes, cert-manager, PKI, TLS, mTLS, Certificates"
position: 4
---

The OpenShell gateway uses TLS for transport to sandbox supervisors. Supervisor Pods receive the gateway CA, not a client certificate or private key, and authenticate RPCs with sandbox JWTs. The generated client certificate can authenticate user clients when gateway mTLS user authentication is enabled; shared deployments can instead configure OIDC or a trusted access proxy. The Helm chart supports two ways to provision and manage the certificate bundle:

| Mode | When to use |
|---|---|
| Built-in `pkiInitJob` (default) | The default path. A pre-install Kubernetes Job generates a self-signed CA and certificates during installation. No additional dependencies. |
| cert-manager | Production deployments that need automatic certificate rotation managed by a running controller. |

The rest of this page covers switching to cert-manager. The built-in mode requires no configuration.

<Note>
When `certManager.enabled=true`, cert-manager owns TLS certificate generation.
The chart still runs a JWT-only initialization hook because cert-manager does
not create the sandbox JWT signing Secret required by the gateway. This
cert-manager precedence applies even if `pkiInitJob.enabled` remains true.
</Note>

## Install cert-manager

Install cert-manager from the OCI registry with CRD support enabled:

... (93 lines truncated)
</file>

<file path="docs/kubernetes/openshift.mdx">
---
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
title: "OpenShift"
sidebar-title: "OpenShift"
description: "Install the OpenShell Helm chart on OpenShift with capability-free sandbox workloads."
keywords: "Generative AI, Cybersecurity, Kubernetes, OpenShift, SCC, Security Context Constraints, Helm, Gateway, Installation"
position: 7
---

The Kubernetes driver resolves the UID range assigned to each OpenShift
namespace and renders the sandbox and supervisor with a numeric non-root
identity from that range. OpenShell does not require the `privileged` SCC or any
added Linux capability.

<Warning>
Verify that the selected OpenShift runtime profile permits an unprivileged
process to install a nested seccomp user-notification filter and use Landlock.
OpenShell fails sandbox startup when either capability-free runtime probe fails.
</Warning>

## Node kernel and legacy read-only mode

OpenShift nodes run RHCOS, which currently ships a RHEL 9.x kernel (5.14). That
kernel predates `SECCOMP_FILTER_FLAG_WAIT_KILLABLE_RECV` (Linux 5.19), so the
sandbox starts in a reduced **legacy read-only** cancellation mode. Isolation is
unchanged, but the broker fails closed with `EOPNOTSUPP` on the mediated
operations that write results back into workload memory — `getpeername`,
`accept`/`accept4` with a non-null peer-address argument, and `sendmmsg`
per-message length write-backs. Outbound-oriented workloads run unchanged;
... (220 lines truncated)
</file>

<file path="docs/kubernetes/setup.mdx">
---
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
title: "Set Up OpenShell on Kubernetes"
sidebar-title: "Setup"
description: "Deploy the OpenShell gateway to a Kubernetes cluster using the official Helm chart from GHCR."
keywords: "Generative AI, Cybersecurity, Kubernetes, Helm, Gateway, Deployment, OCI, GHCR, Installation"
position: 1
---

<Warning>
Your cluster MUST use a CNI that enforces Kubernetes `NetworkPolicy` for both
ingress and egress in every sandbox namespace. OpenShell creates the policies,
but Kubernetes accepts them even when no CNI enforces them. Without enforcement,
sandbox workloads may reach the network directly and bypass supervisor policy.
Verify CNI support before installing OpenShell.
</Warning>

![OpenShell on Kubernetes: the gateway provisions a Sandbox resource, separate supervisor and workload Pods, a boundary Service, NetworkPolicy, and a workspace PVC.](../images/openshell-kubernetes-runtime.svg)

The gateway's Kubernetes compute driver creates a `Sandbox` resource and a
separate supervisor Pod. The Agent Sandbox controller creates the workload Pod
from that resource. A Service gives the supervisor a stable address for the
workload's authenticated TLS boundary, and a PVC preserves `/sandbox` across
Pod restarts. The gateway can run in the same namespace as these resources or
in a separate namespace.

The supervisor opens the boundary connection and maintains an outbound session
to the gateway. A `NetworkPolicy` allows only supervisor ingress to the
workload's boundary port and denies new workload-initiated connections. Agent
... (467 lines truncated)
</file>

<file path="docs/observability/accessing-logs.mdx">
---
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
title: "Accessing Logs"
description: "How to view sandbox logs through the CLI, TUI, and directly on the sandbox filesystem."
keywords: "Generative AI, Cybersecurity, Logging, CLI, TUI, Observability"
---

OpenShell provides three ways to access sandbox logs: the CLI, the TUI, and direct filesystem access inside the sandbox.

## CLI

Use `openshell logs` to stream logs from a running sandbox:

```shell
openshell logs smoke-l4 --source sandbox
```

The CLI receives logs from the gateway over gRPC. Each line includes a timestamp, source, level, and message:

```text
[1775014132.118] [sandbox] [OCSF ] [ocsf] NET:OPEN [INFO] ALLOWED /usr/bin/curl(58) -> api.github.com:443 [policy:github_api engine:opa]
[1775014132.190] [sandbox] [OCSF ] [ocsf] HTTP:GET [INFO] ALLOWED GET http://api.github.com/zen [policy:github_api]
[1775014132.690] [sandbox] [OCSF ] [ocsf] NET:OPEN [MED] DENIED /usr/bin/curl(64) -> httpbin.org:443 [policy:- engine:opa]
[1775014113.058] [sandbox] [INFO ] [openshell_sandbox] Starting sandbox
```

OCSF structured events show `OCSF` as the level. Standard tracing events show `INFO`, `WARN`, or `ERROR`.

Gateway-originated policy mutations also appear in this stream. When the gateway merges `openshell policy update` operations or approves or removes draft policy chunks, it emits `gateway` `OCSF` `CONFIG:*` lines for the affected sandbox so you can see the exact logical change that produced a new policy revision.
... (82 lines truncated)
</file>

<file path="docs/observability/logging.mdx">
---
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
title: "Sandbox Logging"
sidebar-title: "Logging"
description: "How OpenShell logs sandbox activity using standard tracing and OCSF structured events."
keywords: "Generative AI, Cybersecurity, Logging, OCSF, Observability"
---

Every OpenShell sandbox produces a log that records network connections, process lifecycle events, filesystem policy decisions, and configuration changes. The log uses two formats depending on the type of event.

## Log Formats

### Standard tracing

Internal operational events use Rust's `tracing` framework with a conventional format:

```text
2026-04-01T03:28:39.160Z INFO openshell_sandbox: Fetching sandbox policy via gRPC
2026-04-01T03:28:39.175Z INFO openshell_sandbox: Creating OPA engine from proto policy data
```

These events cover startup plumbing, gRPC communication, and internal state transitions that are useful for debugging but do not represent security-relevant decisions.

### OCSF structured events

Network, process, filesystem, configuration, and API activity events use the [Open Cybersecurity Schema Framework (OCSF)](https://ocsf.io) format. OCSF is an open standard for normalizing security telemetry across tools and platforms. OpenShell maps sandbox events to OCSF v1.8.0 event classes.

In the log file, OCSF events appear in a shorthand format with an `OCSF` level label, designed for quick human and agent scanning:

... (241 lines truncated)
</file>

<file path="docs/observability/ocsf-json-export.mdx">
---
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
title: "OCSF JSON Export"
sidebar-title: "OCSF JSON Export"
description: "How to enable full OCSF JSON logging for SIEM integration, compliance, and structured analysis. Includes schema version downgrade for AWS Security Lake, Splunk, and CrowdStrike compatibility."
keywords: "Generative AI, Cybersecurity, OCSF, JSON, SIEM, Compliance, Observability"
---

The [shorthand log format](/observability/logging) is optimized for humans and agents reading logs in real time. For machine consumption or SIEM integration, enable OCSF JSON output: one native JSON object per line. Collection is best-effort, not a guarantee of complete audit history.

## Gateway Output

Configure `[openshell.gateway.ocsf_log]` in `gateway.toml` to collect gateway-origin OCSF events into one JSONL file. This includes gateway-wide events such as TLS certificate reloads, even when no sandbox log stream applies. Collection preserves native OCSF fields and event IDs and does not depend on `RUST_LOG`.

The gateway writes OCSF events to a local JSONL file. Give each replica its own path and configure the shipper to follow renamed rotation segments. See [OCSF JSONL configuration](/how-it-works/gateways/configuration#ocsf-jsonl-output) for queue bounds, retention, loss metrics, and best-effort delivery limits.

This output is separate from the sandbox-local file described below. Enabling one does not enable the other.

Gateway records use the configured gateway name for both `device.uid` and `device.name`. Replicas of one installation share that identity; `device.hostname` identifies the emitting replica. Assign distinct gateway names to installations whose events are collected together. Reusing a name, including the default name, groups those installations under the same identity. Renaming a gateway changes its audit identity.

Without JSONL enabled, gateway OCSF events still appear as shorthand in console output, subject to the diagnostic log filter. Events associated with a sandbox also appear in its gateway log stream; gateway-wide events have no sandbox association.

## Enable Sandbox JSON Export

Use the `ocsf_json_enabled` setting to toggle JSON export. The setting can be applied globally, for all sandboxes, or per-sandbox.

Global:

```shell
... (263 lines truncated)
</file>

<file path="docs/observability/telemetry.mdx">
---
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
title: "Telemetry"
sidebar-title: "Telemetry"
description: "What anonymous telemetry OpenShell collects and how to disable it at runtime or compile it out."
keywords: "Generative AI, Cybersecurity, Telemetry, Privacy, Opt Out, Cargo Features, Observability"
---

OpenShell collects anonymous telemetry to help improve the project. The data shows aggregate usage of sandbox, provider, and policy workflows. It is not used to track individual users. Aggregate usage trends are published every two weeks in the [community telemetry reports](https://github.com/NVIDIA/OpenShell/tree/main/telemetry).

## What Is Collected

Telemetry events are limited to anonymous operational categories and counts, such as sandbox lifecycle outcomes, provider profile buckets, policy decision counts, and aggregate network activity denial categories.

OpenShell telemetry does not collect sandbox names or IDs, hostnames, file paths, binary paths, prompts, credentials, provider names, model names, or user content.

Opting out applies only to telemetry emitted by OpenShell. Third-party services, model providers, inference endpoints, agents, or tools that you configure and use with OpenShell may have their own terms and privacy practices.

## Disable Telemetry at Runtime

Set `OPENSHELL_TELEMETRY_ENABLED=false` on the gateway deployment. For Helm installs, set `server.telemetryEnabled=false`. OpenShell propagates this setting into sandbox supervisor environments, so sandbox-side telemetry collection is disabled as well.

## Compile Telemetry Out

Telemetry support is a default-on `telemetry` Cargo feature. Each crate that carries it also defines a `defaults-without-telemetry` alias covering every other default feature. Build telemetry-free artifacts with `--no-default-features --features defaults-without-telemetry`:

```shell
cargo build --release -p openshell-gateway --no-default-features --features defaults-without-telemetry
cargo build --release -p openshell-sandbox --no-default-features --features defaults-without-telemetry
... (24 lines truncated)
</file>

<file path="docs/resources/license.mdx">
---
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
title: "License"
description: "NVIDIA OpenShell is licensed under the Apache License, Version 2.0."
keywords: "Legal, License, Apache 2.0"
position: 1
---

NVIDIA OpenShell is licensed under the [Apache License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0).

Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
... (172 lines truncated)
</file>

<file path="docs/sdk/api-errors.mdx">
---
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
title: "API Errors"
sidebar-title: "API Errors"
description: "Inspect structured gateway failures and choose an appropriate recovery action."
keywords: "OpenShell, SDK, gRPC, API errors, retries"
---

Gateway errors include a gRPC status code and a message. Shared request validation
and concurrency checks also return standard protobuf details in
`grpc-status-details-bin`. Use the status code and structured fields for decisions.
Treat messages as explanations whose text can change.

## Structured details

The SDKs decode these standard detail types while retaining the original failure.
Older gateways and checks that have not adopted structured details can return only
a code and message. Missing details do not change the meaning of the status code.

| Detail | Meaning |
|---|---|
| `google.rpc.BadRequest` | `field_violations` identifies rejected fields and explains each violation. Shared sandbox, exec, provider size, and workspace selector checks supply these details. |
| `google.rpc.ErrorInfo` | `reason`, `domain`, and `metadata` identify a failure without parsing its message. Gateway reasons use the `openshell.nvidia.com` domain. |
| `google.rpc.RetryInfo` | `retry_delay` gives a minimum delay before an otherwise safe retry. Its presence does not guarantee that a mutation has not already committed. |

Recognized gateway reasons include the following.

| Reason | Code | Recovery |
|---|---|---|
... (280 lines truncated)
</file>

<file path="docs/sdk/go.mdx">
---
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
title: "Go SDK"
sidebar-title: "Go"
description: "Install the OpenShell Go SDK, connect to a gateway, and manage a sandbox."
keywords: "OpenShell, SDK, Go, Golang, gRPC, Sandbox"
position: 1
---

Use the Go SDK to manage OpenShell resources from Go applications, operators,
and controllers. Its typed subclients follow familiar Kubernetes client
patterns. Use the SDK and gateway from the same OpenShell release when possible.

## Install the SDK

The SDK requires Go 1.25.13 or later. Add it to your Go module:

```shell
go get github.com/NVIDIA/OpenShell/sdk/go@latest
```

## Connect to a Gateway

Pass a `host:port` address to `NewClient`. For a local gateway that allows
unauthenticated plaintext connections:

```go
package main

... (97 lines truncated)
</file>

<file path="docs/sdk/protobuf-time-types.mdx">
---
title: Protobuf time types
sidebar-title: "Protobuf Time Types"
description: Timestamp and duration representation in the OpenShell API
---

OpenShell represents absolute times with `google.protobuf.Timestamp` and
elapsed times with `google.protobuf.Duration` in its protobuf APIs.

Provider profile YAML and JSON accept canonical duration strings such as
`cache_ttl: "0.500s"`. The legacy `cache_ttl_seconds`, `refresh_before_seconds`,
and `max_lifetime_seconds` inputs remain supported for existing profiles.

In protobuf JSON, timestamps are RFC 3339 strings and durations are strings
ending in `s`:

```json
{
  "createdTime": "2026-08-31T14:05:06.123456789Z",
  "executionTimeout": "1.500s"
}
```

An absent message means that no timestamp or duration was supplied. It is
different from the Unix epoch (`1970-01-01T00:00:00Z`) and from a zero duration
(`0s`). OpenShell validates protobuf timestamp and duration bounds at API
boundaries.

## Upgrade from scalar time fields

... (34 lines truncated)
</file>

<file path="docs/sdk/python.mdx">
---
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
title: "Python SDK"
sidebar-title: "Python"
description: "Install the OpenShell Python SDK, reuse a registered gateway, and manage a sandbox."
keywords: "OpenShell, SDK, Python, PyPI, gRPC, Sandbox"
position: 3
---

Use the Python SDK to manage sandboxes from applications, notebooks, and
automation. It can reuse gateway registration and authentication state created
by the OpenShell CLI. Use the SDK and gateway from the same OpenShell release
when possible.

## Install the SDK

The package requires Python 3.11 or later. Add it to your project with `uv`:

```shell
uv add openshell
```

The `openshell` package contains the SDK. It does not install the OpenShell CLI.

## Connect to a Registered Gateway

Register and select a gateway with the CLI first. Then construct the client from
the active gateway:

... (85 lines truncated)
</file>

<file path="docs/sdk/rust.mdx">
---
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
title: "Rust SDK"
sidebar-title: "Rust"
description: "Install the OpenShell Rust SDK, connect to a gateway, and manage a sandbox asynchronously."
keywords: "OpenShell, SDK, Rust, Cargo, Tonic, gRPC, Sandbox"
position: 2
---

The Rust SDK is the asynchronous gateway client used by the OpenShell CLI and
TUI. Its curated API covers common sandbox operations, while `raw` exposes the
generated Tonic clients for the complete RPC surface. Use the SDK and gateway
from the same OpenShell release when possible.

## Install the SDK

The Rust SDK is currently consumed from source. Pin the dependency to the same
release tag as your gateway:

```shell
cargo add openshell-sdk \
  --git https://github.com/NVIDIA/OpenShell \
  --tag <release-tag>
cargo add tokio --features macros,rt-multi-thread
```

## Connect to a Gateway

`ClientConfig` accepts a full gateway URL. This local example uses plaintext
... (100 lines truncated)
</file>

<file path="docs/sdk/typescript.mdx">
---
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
title: "TypeScript SDK"
sidebar-title: "TypeScript"
description: "Install the OpenShell TypeScript SDK, connect to a gateway, and manage a sandbox."
keywords: "OpenShell, SDK, TypeScript, Node.js, Connect, gRPC, Sandbox"
position: 4
---

Use the TypeScript SDK in Node.js applications and automation. It provides a
curated sandbox API and a raw generated client for the full gateway RPC surface.
Use the SDK and gateway from the same OpenShell release when possible.

## Install the SDK

The package requires Node.js 20.3 or later and is currently distributed through
GitHub Packages. Configure the `@nvidia` scope in your project `.npmrc`:

```text
@nvidia:registry=https://npm.pkg.github.com
```

Authenticate npm with a GitHub token that has `read:packages`, then install the
package:

```shell
npm install @nvidia/openshell-sdk
```

... (81 lines truncated)
</file>

<file path="docs/security/best-practices.mdx">
---
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
title: "OpenShell Security Best Practices for Controls, Risks, and Configuration Guidance"
sidebar-title: "Security Best Practices"
slug: "security/best-practices"
description: "A guide to every configurable security control in OpenShell: defaults, what you can change, and the risks of each choice."
keywords: "Generative AI, Cybersecurity, Security, Policy, Sandbox, Landlock, Seccomp"
position: 1
---

OpenShell enforces sandbox security across four layers: network, filesystem, process, and provider credentials.
This page documents every configurable control, its default, what it protects, and the risk of relaxing it.

For the full policy YAML schema, refer to the [Policy Schema](/how-it-works/policies/schema).
For the architecture of each enforcement layer, refer to [Architecture](/about/architecture).

<Note>
If you use [NemoClaw](https://github.com/NVIDIA/NemoClaw), its [Security Best Practices](https://docs.nvidia.com/nemoclaw/latest/security/best-practices.html) guide covers additional entrypoint-level controls, policy presets, provider trust tiers, and posture profiles specific to the NemoClaw blueprint.

</Note>

## Enforcement Layers

OpenShell applies security controls at two enforcement points.
OpenShell locks static controls at sandbox creation and requires destroying and recreating the sandbox to change them.
You can update dynamic controls on a running sandbox with `openshell policy update` or `openshell policy set`.

| Layer | What it protects | Enforcement point | Changeable at runtime |
| --- | --- | --- | --- |
... (276 lines truncated)
</file>

<file path="docs/security/verify-image-contents.mdx">
---
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
title: "Verify the Contents of Published OpenShell Images"
sidebar-title: "Verify Image Contents"
slug: "security/verify-image-contents"
description: "Read the SBOM attestation attached to published gateway and supervisor images to audit what each image contains."
keywords: "Generative AI, Cybersecurity, Supply Chain, SBOM, Container Images"
position: 2
---

Published gateway and supervisor images carry one SPDX SBOM per platform as OCI attestations.

## Inspect an Image

Read a platform's document without pulling the image:

```shell
docker buildx imagetools inspect ghcr.io/nvidia/openshell/gateway:latest --format '{{ json (index .SBOM "linux/amd64").SPDX }}'
```

List the packages instead of the full document:

```shell
docker buildx imagetools inspect ghcr.io/nvidia/openshell/gateway:latest --format '{{ range (index .SBOM "linux/amd64").SPDX.packages }}{{ .name }}@{{ .versionInfo }}{{ println }}{{ end }}'
```

The same commands work for `ghcr.io/nvidia/openshell/supervisor`.

## Coverage
... (7 lines truncated)
</file>

<file path="docs/tutorials/first-network-policy.mdx">
---
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
title: "Write Your First Sandbox Network Policy"
sidebar-title: "First Network Policy"
description: "Learn how OpenShell network policies work by creating a sandbox, observing default-deny in action, and applying a fine-grained L7 read-only rule."
keywords: "Generative AI, Cybersecurity, Tutorial, Policy, Network Policy, Sandbox, Security"
---

This tutorial shows how OpenShell's network policy system works in under five minutes. You create a sandbox, watch a request get blocked by the default-deny policy, apply a fine-grained L7 rule, and verify that reads are allowed while writes are blocked, all without restarting anything.

After completing this tutorial, you understand:

- How default-deny networking blocks all outbound traffic from a sandbox.
- How to apply a network policy that grants read-only access to a specific API.
- How L7 enforcement distinguishes between HTTP methods such as GET and POST on the same endpoint.
- How to inspect deny logs for a complete audit trail.

## Prerequisites

- A working OpenShell installation with an active gateway. Refer to [Installation](/about/installation) before proceeding.
- Docker Desktop running on your machine.
- A user-owned workload image with `curl` installed.

<Tip>
To run every step of this tutorial, you can also use the automated demo script at the [examples/sandbox-policy-quickstart](https://github.com/NVIDIA/OpenShell/blob/main/examples/sandbox-policy-quickstart) directory in the NVIDIA OpenShell repository. It runs the full walkthrough in under a minute but without any user interaction.

```shell
bash examples/sandbox-policy-quickstart/demo.sh
```
... (180 lines truncated)
</file>

<file path="docs/tutorials/github-push-access.mdx">
---
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
title: "Grant GitHub Push Access to a Sandboxed Agent"
sidebar-title: "GitHub Push Access"
slug: "tutorials/github-push-access"
description: "Launch an agent with a GitHub provider, diagnose a denied push, and grant repository-scoped write access."
keywords: "Generative AI, Cybersecurity, Tutorial, GitHub, Sandbox, Policy, Claude Code"
---

This tutorial shows how provider access and sandbox policy work together. You
attach a GitHub provider that contributes read-only GitHub access, observe a
denied push, and add a user policy that permits writes to one repository.

The built-in [default policy](/how-it-works/policies/default-policy) does not grant network
access. Imported provider profiles contribute the endpoints and executable
paths needed by their providers.

## Prerequisites

You need:

- A working OpenShell installation and active gateway.
- An OCI image you built with Claude Code, `git`, and the GitHub CLI installed.
- An Anthropic API key.
- A GitHub fine-grained personal access token with read and write access to the
  target repository's contents.
- A scratch GitHub repository that you can push to.

Use two host terminals. Terminal 1 runs the agent. Terminal 2 inspects denials
... (198 lines truncated)
</file>

<file path="docs/tutorials/index.mdx">
---
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
title: "Tutorials"
description: "Step-by-step walkthroughs for OpenShell, from first sandbox to production-ready policies."
keywords: "Generative AI, Cybersecurity, Tutorial, Sandbox, Policy"
position: 1
---

Hands-on walkthroughs that teach OpenShell concepts by building real configurations. Each tutorial builds on the previous one, starting with core sandbox mechanics and progressing to production workflows.

<Cards>

<Card title="Run Pi with OpenRouter" href="/tutorials/run-pi-with-openrouter">

Build a Pi coding-agent image, configure OpenRouter access, and run it inside an OpenShell sandbox.
</Card>

<Card title="First Network Policy" href="/tutorials/first-network-policy">

Create a sandbox, observe default-deny networking, apply a read-only L7 policy, and inspect audit logs. No AI agent required.
</Card>

<Card title="GitHub Push Access" href="/tutorials/github-push-access">

Launch Claude Code in a sandbox, diagnose a policy denial, and iterate on a custom GitHub policy from outside the sandbox.
</Card>

<Card title="Microsoft Graph Provider Refresh" href="/tutorials/microsoft-graph-provider-refresh">

... (5 lines truncated)
</file>

<file path="docs/tutorials/microsoft-graph-provider-refresh.mdx">
---
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
title: "Refresh Microsoft Graph Credentials with a Provider Profile"
sidebar-title: "Microsoft Graph Provider Refresh"
description: "Configure a Microsoft Graph provider profile with gateway-managed OAuth2 refresh-token rotation."
keywords: "Generative AI, Cybersecurity, Tutorial, Providers, Microsoft Graph, OAuth2, Credential Refresh, Sandbox"
---

Use a provider profile to keep Microsoft Graph access tokens short lived while sandboxes receive a stable `MS_GRAPH_ACCESS_TOKEN` placeholder. OpenShell stores the non-injectable refresh material at the gateway, refreshes the Microsoft Graph access token before it expires, updates the provider record, and injects the current credential into newly launched sandbox processes.

After completing this tutorial, you have:

- A custom Microsoft Graph mail provider profile.
- A provider instance configured with `oauth2-refresh-token`.
- A sandbox that can use `curl` to read Microsoft Graph mail through provider-owned policy.

<Note>
This tutorial starts after your OAuth client has already completed the initial Microsoft sign-in flow. It does not publish a token bootstrap script. Use the Microsoft identity platform documentation for the [device authorization grant flow](https://learn.microsoft.com/en-ie/entra/identity-platform/v2-oauth2-device-code) or [authorization code flow](https://learn.microsoft.com/en-us/entra/identity-platform/v2-oauth2-auth-code-flow), and use any standards-compliant client that returns an access token, refresh token, and expiry.
</Note>

## Prerequisites

- A working OpenShell installation with an active gateway. Refer to [Installation](/about/installation) before proceeding.
- A Microsoft Entra app registration that can acquire delegated Microsoft Graph mail access.
- Delegated Microsoft Graph mail permission for the signed-in user. `Mail.Read` allows reading the signed-in user's mailbox; see the [Microsoft Graph permissions reference](https://learn.microsoft.com/en-us/graph/permissions-reference).
OAuth material from your initial Microsoft sign-in flow:

| Variable | Value |
|---|---|
... (151 lines truncated)
</file>

<file path="docs/tutorials/run-pi-with-openrouter.mdx">
---
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
title: "Run Pi with OpenRouter"
description: "Build a Pi coding-agent image, configure OpenRouter access, and run Pi inside an OpenShell sandbox."
keywords: "Generative AI, Cybersecurity, Tutorial, Pi Coding Agent, OpenRouter, Sandbox, Provider Profile"
---

In this tutorial, we'll run [Pi](https://pi.dev), a terminal coding agent,
inside an OpenShell sandbox. Pi works with many model providers out of the box,
including [OpenRouter](https://openrouter.ai), which we use here.

We'll build a Pi image, give the sandbox access to OpenRouter, and start Pi.
The sandbox lets Pi reach OpenRouter but nothing else on the network, and Pi
never sees your real API key.

## Prerequisites

You'll need:

- A working OpenShell installation with an active gateway. Refer to
  [Installation](/about/installation).
- Docker or Podman to build the image.
- An OpenRouter API key.

<Steps toc={true}>

## Build the Pi Image

Pi doesn't publish a container image, so we'll build one from its npm package,
... (204 lines truncated)
</file>

<file path="docs/upgrade/0-1-0.mdx">
---
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
title: "Upgrade to NVIDIA OpenShell 0.1.0"
sidebar-title: "0.1.0"
description: "Prepare OpenShell operators and users for the breaking changes in version 0.1.0."
keywords: "Generative AI, Cybersecurity, AI Agents, Sandboxing, Upgrade, Migration"
---

<Warning>
Local OpenShell 0.0.x installations cannot be upgraded in place. Clean up the
old runtime and [uninstall the existing package](/about/installation#uninstall-openshell)
before installing OpenShell 0.1.0.
</Warning>

OpenShell 0.1.0 introduces breaking changes for deployments, sandboxes, policies, APIs, and SDKs. Review the changes that apply to your role before upgrading:

- [Operators](#operators): Plan the rollout, migrate configuration and credentials, and update custom extensions.
- [End users](#end-users): Update sandbox workflows, policies, API clients, and SDK integrations.

## Operators

If you run OpenShell for a team, start here.

- **Coordinate the upgrade.** Stop all gateway replicas, back up the database, and upgrade gateways, compute and credential drivers, supervisors, middleware, CLI clients, and SDK clients from the same release. The protocol, field-name, and time-type changes do not support mixed 0.0.x and 0.1.0 peers ([PR #3113](https://github.com/NVIDIA/OpenShell/pull/3113), [PR #3272](https://github.com/NVIDIA/OpenShell/pull/3272), [PR #3352](https://github.com/NVIDIA/OpenShell/pull/3352)).

- **Recreate every sandbox.** Remove 0.0.x sandboxes before the upgrade and recreate them afterward. The persisted sandbox boundary and runtime descriptors are not compatible with 0.1.0 ([PR #2942](https://github.com/NVIDIA/OpenShell/pull/2942), [PR #3366](https://github.com/NVIDIA/OpenShell/pull/3366)).

- **Export provider profiles before upgrading.** The gateway no longer includes built-in profiles. Import the saved profiles after the upgrade at the same global or workspace scope. Replace profile aliases such as `claude` and `gh` with the canonical IDs `claude-code` and `github` ([PR #2962](https://github.com/NVIDIA/OpenShell/pull/2962), [PR #3383](https://github.com/NVIDIA/OpenShell/pull/3383)).

... (100 lines truncated)
</file>

<file path="docs/.markdownlint-cli2.jsonc">
{
  "config": {
    // MDX pages get their title from Fern frontmatter, not a top-level H1.
    "MD041": false,
    // MDX uses JSX components (<Callout>, <CodeBlock>, ...) that look like HTML.
    "MD033": false,
    // Published docs should label fenced code blocks for rendering and copy UX.
    "MD040": true
  }
}
</file>

<file path="docs/CONTRIBUTING.mdx">
---
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
title: "Contributing to NVIDIA OpenShell Documentation"
description: ""
---
This guide covers how to write, edit, and review documentation for NVIDIA OpenShell. If you change code that affects user-facing behavior, update the relevant docs in the same PR.

The published docs live in `docs/`, navigation is defined in `docs/index.yml`, and `fern/` contains the site config, components, and theme assets.

## Use the Agent Skills

If you use an AI coding agent (Cursor, Claude Code, Codex, etc.), the repo includes skills that automate doc work. Use them before writing from scratch.

| Skill | What it does | When to use |
|---|---|---|
| `update-docs-from-commits` | Scans recent commits for user-facing changes and drafts doc updates. | After landing features, before a release, or to find doc gaps. |
| `build-from-issue` | Plans and implements work from a GitHub issue, including doc updates. | When working from an issue that has doc impact. |

These contributor workflows live in `.agents/skills/` and follow the style guide below automatically. They are separate from the public skills in `skills/`, which help users operate OpenShell and can be installed without cloning the repository. To use a contributor skill, ask your repository-aware agent to run it (e.g., "catch up the docs for everything merged since v0.2.0").

## When to Update Docs

Update documentation when your change:

- Adds, removes, or renames a CLI command or flag.
- Changes default behavior or configuration.
- Adds, removes, renames, or changes defaults for gateway TOML fields or driver-specific config options. Update `docs/how-it-works/gateways/configuration.mdx` for these changes.
- Adds a new feature that users interact with.
- Fixes a bug that the docs describe incorrectly.
... (156 lines truncated)
</file>

<file path="docs/index.mdx">
---
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
title: "NVIDIA OpenShell Developer Guide"
description: "OpenShell is the safe, private runtime for fleets of autonomous AI agents. Run agents in sandboxed environments that protect your data, credentials, and infrastructure."
keywords: "Generative AI, Cybersecurity, AI Agents, Sandboxing, Security, Privacy, Provider Credentials"
position: 1
---

import { BadgeLinks } from "./_components/BadgeLinks";
import { CommandTerminal } from "./_components/CommandTerminal";

<BadgeLinks
  badges={[
    {
      href: "https://github.com/NVIDIA/OpenShell",
      src: "https://img.shields.io/badge/github-repo-green?logo=github",
      alt: "GitHub",
    },
    {
      href: "https://github.com/NVIDIA/OpenShell/blob/main/LICENSE",
      src: "https://img.shields.io/badge/License-Apache_2.0-blue",
      alt: "License",
    },
    {
      href: "https://pypi.org/project/openshell/",
      src: "https://img.shields.io/badge/PyPI-openshell-orange?logo=pypi",
      alt: "PyPI",
    },
  ]}
... (117 lines truncated)
</file>

<file path="docs/index.yml">
landing-page:
  page: "Home"
  path: index.mdx
navigation:
- section: "About NVIDIA OpenShell"
  slug: about
  contents:
  - page: "Overview"
    path: about/overview.mdx
  - page: "Architecture"
    path: about/architecture.mdx
  - page: "Installation"
    path: about/installation.mdx
  - page: "Run Your First Agent"
    path: about/run-your-first-agent.mdx
  - page: "Support Matrix"
    path: about/support-matrix.mdx
- section: "How It Works"
  slug: how-it-works
  contents:
  - section: "Gateways"
    slug: gateways
    contents:
    - page: "Overview"
      path: how-it-works/gateways/overview.mdx
    - page: "Authentication"
      path: how-it-works/gateways/authentication.mdx
    - page: "Configuration"
      path: how-it-works/gateways/configuration.mdx
    - page: "Container Deployment"
... (107 lines truncated)
</file>

<file path="examples/agent-driven-policy-management/agent-task.md">
<!-- SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -->
<!-- SPDX-License-Identifier: Apache-2.0 -->

# Agent Task

You are running inside an OpenShell sandbox. Your job has two steps. Each
step starts with a `curl` call that the L7 proxy will deny; for each
denial, read `/etc/openshell/skills/policy_advisor.md`, draft a narrow
proposal, submit it to `http://policy.local/v1/proposals`, wait on
`GET /v1/proposals/{chunk_id}/wait?timeout=300`, then retry.

## Target

- Repository: `{{OWNER}}/{{REPO}}`
- Branch: `{{BRANCH}}`
- File path: `{{FILE_PATH}}`
- Run id: `{{RUN_ID}}`

## What to do

### Step 1 — Fetch a public schema (un-credentialed action)

1. Fetch the well-known GitHub OpenAPI description from
   `https://raw.githubusercontent.com/github/rest-api-description/main/descriptions/api.github.com/api.github.com.json`
   with `curl`. Do not send any authentication header — this resource is
   public. Save the response to `/tmp/github-openapi.json`.

   The first attempt will fail with HTTP 403 and a JSON body containing
   `"error": "policy_denied"`. Read the body — it tells you which layer
   denied you, which method/path was missing, and where to learn more.
... (78 lines truncated)
</file>

<file path="examples/agent-driven-policy-management/demo.sh">
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "${SCRIPT_DIR}/../.." && pwd)"
POLICY_TEMPLATE="${SCRIPT_DIR}/policy.template.yaml"
TASK_TEMPLATE="${SCRIPT_DIR}/agent-task.md"
SANDBOX_AGENT="${SCRIPT_DIR}/sandbox-agent.sh"
OPENSHELL_BIN="${OPENSHELL_BIN:-}"
if [[ -z "$OPENSHELL_BIN" ]]; then
    if [[ -x "${REPO_ROOT}/target/debug/openshell" ]]; then
        OPENSHELL_BIN="${REPO_ROOT}/target/debug/openshell"
    else
        OPENSHELL_BIN="openshell"
    fi
fi
DEMO_GITHUB_OWNER="${DEMO_GITHUB_OWNER:-}"
DEMO_GITHUB_REPO="${DEMO_GITHUB_REPO:-openshell-policy-demo}"
DEMO_BRANCH="${DEMO_BRANCH:-main}"
DEMO_RUN_ID="${DEMO_RUN_ID:-$(date +%Y%m%d-%H%M%S)}"
DEMO_FILE_DIR="${DEMO_FILE_DIR:-openshell-policy-advisor-demo}"
DEMO_FILE_PATH="${DEMO_FILE_DIR}/${DEMO_RUN_ID}.md"
DEMO_SANDBOX_NAME="${DEMO_SANDBOX_NAME:-pd-${DEMO_RUN_ID}}"
DEMO_CODEX_PROVIDER_NAME="${DEMO_CODEX_PROVIDER_NAME:-codex-policy-demo-${DEMO_RUN_ID}}"
DEMO_GITHUB_PROVIDER_NAME="${DEMO_GITHUB_PROVIDER_NAME:-github-policy-demo-${DEMO_RUN_ID}}"
DEMO_CODEX_MODEL="${DEMO_CODEX_MODEL:-gpt-5.4-mini}"
DEMO_CODEX_LOCAL_BIN="${DEMO_CODEX_LOCAL_BIN:-}"
DEMO_MANUAL_APPROVE="${DEMO_MANUAL_APPROVE:-0}"
if [[ "$DEMO_MANUAL_APPROVE" == "1" ]]; then
    DEMO_APPROVAL_TIMEOUT_SECS="${DEMO_APPROVAL_TIMEOUT_SECS:-1800}"
else
    DEMO_APPROVAL_TIMEOUT_SECS="${DEMO_APPROVAL_TIMEOUT_SECS:-240}"
... (485 lines truncated)
</file>

<file path="examples/agent-driven-policy-management/policy.template.yaml">
version: 1
filesystem_policy:
  include_workdir: true
  read_only: [/usr, /lib, /proc, /dev/urandom, /app, /etc, /var/log]
  read_write: [/sandbox, /tmp, /dev/null]
landlock:
  compatibility: best_effort
network_policies:
  codex:
    name: codex
    endpoints:
      - { host: api.openai.com, port: 443, protocol: rest, enforcement: enforce, access: full }
      - { host: auth.openai.com, port: 443, protocol: rest, enforcement: enforce, access: full }
      - { host: chatgpt.com, port: 443, protocol: rest, enforcement: enforce, access: full }
      - { host: ab.chatgpt.com, port: 443, protocol: rest, enforcement: enforce, access: full }
    binaries:
      - { path: /usr/bin/codex }
      - { path: /sandbox/payload/codex }
      - { path: /usr/bin/node }
      - { path: "/usr/lib/node_modules/@openai/**" }
  github_api_readonly:
    name: github-api-readonly
    endpoints:
      - host: api.github.com
        port: 443
        protocol: rest
        enforcement: enforce
        access: read-only
    binaries:
      - { path: /usr/bin/curl }
... (14 lines truncated)
</file>

<file path="examples/agent-driven-policy-management/README.md">
<!-- SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -->
<!-- SPDX-License-Identifier: Apache-2.0 -->

# Agent-Driven Policy Management Demo

Run the full agent-driven policy loop end-to-end:

1. A Codex agent inside an OpenShell sandbox tries to write a markdown file to
   GitHub via the Contents API.
2. OpenShell denies the request with a structured `policy_denied` 403 because
   the initial policy only allows read-only access to `api.github.com`.
3. The agent reads `/etc/openshell/skills/policy_advisor.md`, drafts the
   narrowest rule needed, and submits it to `http://policy.local/v1/proposals`.
   It saves the returned `chunk_id`.
4. The gateway merges the proposed rule with the current sandbox policy, runs
   the policy prover, and stores a concise `validation_result` on the pending
   chunk. This is deterministic control-plane evidence, not agent prose.
5. The agent calls `GET /v1/proposals/{chunk_id}/wait?timeout=300` — a single
   HTTP request that the supervisor holds open until the developer decides.
   This is the load-bearing UX point: the agent burns zero LLM tokens while
   it waits; it's literally sleeping on a socket.
6. You approve the proposal from the host with one keystroke after seeing the
   exact rule and the prover verdict in `openshell rule get`.
7. The agent's `/wait` returns within ~1 second of the approval. The sandbox
   has hot-reloaded the merged policy; the agent retries the original PUT
   once and exits.

The whole loop usually finishes in under two minutes; most of that time is
sandbox cold-start (SSH bring-up + Codex install inside the sandbox), not
the policy round-trip itself.
... (118 lines truncated)
</file>

<file path="examples/agent-driven-policy-management/sandbox-agent.sh">
set -euo pipefail
require_env() {
    local name="$1"
    [[ -n "${!name:-}" ]] || { echo "missing required env: $name" >&2; exit 1; }
}
require_env CODEX_AUTH_ACCESS_TOKEN
require_env CODEX_AUTH_REFRESH_TOKEN
require_env CODEX_AUTH_ACCOUNT_ID
require_env DEMO_GITHUB_TOKEN
export GITHUB_TOKEN="$DEMO_GITHUB_TOKEN"
mkdir -p "$HOME/.codex"
node - <<'NODE'
const fs = require("fs");
const path = `${process.env.HOME}/.codex/auth.json`;
const b64u = (obj) => Buffer.from(JSON.stringify(obj)).toString("base64url");
const now = Math.floor(Date.now() / 1000);
// Placeholder id_token is required by Codex but never validated against an
// upstream JWKS in this flow.
const idToken = [
  b64u({ alg: "none", typ: "JWT" }),
  b64u({
    iss: "https://auth.openai.com",
    aud: "codex",
    sub: "openshell-policy-demo",
    email: "demo@openshell.local",
    iat: now,
    exp: now + 3600,
  }),
  "placeholder",
].join(".");
... (38 lines truncated)
</file>

<file path="examples/bring-your-own-container/app.py">
PORT = 8080
⋮----
class Handler(BaseHTTPRequestHandler)
⋮----
def do_GET(self)
⋮----
name = self.path[len("/hello/") :]
⋮----
def _json(self, code, body)
⋮----
payload = json.dumps(body).encode()
⋮----
def log_message(self, format, *args)
⋮----
server = HTTPServer(("0.0.0.0", PORT), Handler)
</file>

<file path="examples/bring-your-own-container/Dockerfile">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

# Example: a minimal Python REST API that runs inside a OpenShell sandbox.
# The image exposes port 8080 with a /hello endpoint.  Use port forwarding
# (--forward 8080 on the CLI) to reach it from your local machine.

FROM python:3.13-slim

# System tools useful for sandbox networking and debugging.
# iproute2: required for network namespace management (ip netns, veth pairs)
# nftables: optional, enables bypass detection (log + reject for direct connections)
RUN apt-get update && apt-get install -y --no-install-recommends \
        curl iproute2 nftables \
    && rm -rf /var/lib/apt/lists/*

RUN groupadd --gid 1500 app \
    && useradd --uid 1500 --gid app --create-home app

RUN install -d -o app -g app /sandbox
WORKDIR /sandbox
COPY --chown=app:app app.py .

EXPOSE 8080

# Docker and Podman use this non-root identity when policy omits either process
# identity field. OpenShell starts the supervisor as root and drops only agent
# children to this account.
USER app

... (4 lines truncated)
</file>

<file path="examples/bring-your-own-container/README.md">
# Bring Your Own Container

Run a sandbox with a custom container image. This example includes a
ready-to-use Python REST API that you can build, deploy, and reach from
your local machine through port forwarding.

## Prerequisites

- A running OpenShell gateway (`mise run gateway:docker` for local development)
- Docker or Podman running, matching the gateway driver

## What's in this example

| File         | Description                                             |
| ------------ | ------------------------------------------------------- |
| `Dockerfile` | Builds a Python 3.12 image that starts a REST API      |
| `app.py`     | Minimal HTTP server with `/hello` and `/health` routes  |

## Quick start

### 1. Build the image and create a sandbox with port forwarding

```bash
# Docker gateway
docker build -t openshell-byoc:latest examples/bring-your-own-container
openshell sandbox create \
    --from openshell-byoc:latest \
    --forward 8080 \
    -- python /sandbox/app.py

... (72 lines truncated)
</file>

<file path="examples/codex-app-server/codex.yaml">
id: codex
display_name: Codex
description: OpenAI Codex CLI with gateway-managed token refresh
category: agent
inference_capable: true
credentials:
  - name: access_token
    description: Codex OAuth access token refreshed by the gateway
    env_vars: [CODEX_AUTH_ACCESS_TOKEN]
    required: true
    auth_style: bearer
    header_name: authorization
    refresh:
      strategy: oauth2_refresh_token
      token_url: https://auth.openai.com/oauth/token
      refresh_before_seconds: 300
      max_lifetime_seconds: 3600
      material:
        - name: client_id
          description: Codex OAuth client ID
          required: true
        - name: refresh_token
          description: Codex OAuth refresh token
          required: true
          secret: true
  - name: refresh_token
    description: Codex OAuth refresh token for clients that manage their own refresh
    env_vars: [CODEX_AUTH_REFRESH_TOKEN]
  - name: account_id
    description: Codex account identifier
... (34 lines truncated)
</file>

<file path="examples/codex-app-server/Dockerfile">
# syntax=docker/dockerfile:1.7

# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

FROM ubuntu:24.04

ENV DEBIAN_FRONTEND=noninteractive

RUN apt-get update \
    && apt-get install --yes --no-install-recommends \
        ca-certificates \
        nodejs \
        npm \
    && rm -rf /var/lib/apt/lists/*

RUN useradd \
    --create-home \
    --home-dir /sandbox \
    --shell /bin/bash \
    sandbox

RUN npm install --global --force "@openai/codex@latest" \
    && npm cache clean --force \
    && codex --version

COPY --chmod=0755 start-codex-app-server /usr/local/bin/start-codex-app-server

ENV CODEX_APP_SERVER_PORT=4500
ENV HOME=/sandbox
... (4 lines truncated)
</file>

<file path="examples/codex-app-server/README.md">
# Codex app server in an OpenShell sandbox

This example builds a sandbox image with Codex, runs its app server inside an
OpenShell sandbox, exposes the WebSocket service through the local gateway, and
connects a Codex client running on the host.

Use this example only with a local, loopback-bound OpenShell gateway. The app
server does not use its own bearer-token authentication, and the exposed URL is
reachable by other local processes.

## Prerequisites

- A running local OpenShell gateway backed by Docker
- `docker`, `openshell`, the latest Codex client, and `jq` on the host
- A host Codex login in `$HOME/.codex/auth.json`

Run the following commands from the example directory:

```shell
cd examples/codex-app-server
```

## 1. Build the image

This installs the latest published Codex version in the image. Keep the host
client current as well to avoid app-server protocol incompatibilities.

```shell
docker build --pull --no-cache --tag openshell/codex-app-server:local --file Dockerfile .
```
... (83 lines truncated)
</file>

<file path="examples/codex-app-server/start-codex-app-server">
#!/usr/bin/env node

// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

const fs = require("fs");
const path = require("path");
const { spawn } = require("child_process");

const required = [
  "CODEX_AUTH_ACCESS_TOKEN",
  "CODEX_AUTH_ACCOUNT_ID",
];
for (const name of required) {
  if (!process.env[name]) {
    throw new Error(`missing required provider credential: ${name}`);
  }
}

const b64u = (value) => Buffer.from(JSON.stringify(value)).toString("base64url");
const now = Math.floor(Date.now() / 1000);
const idToken = [
  b64u({ alg: "none", typ: "JWT" }),
  b64u({
    iss: "https://auth.openai.com",
    aud: "codex",
    sub: "openshell-app-server",
    email: "app-server@openshell.local",
    iat: now,
    exp: now + 3600,
... (40 lines truncated)
</file>

<file path="examples/governance-interceptor/profiles/github.yaml">
display_name: GitHub
description: GitHub API and Git operations
category: source_control
credentials:
  - name: api_token
    description: GitHub token
    env_vars: [GITHUB_TOKEN, GH_TOKEN]
    required: true
    auth_style: bearer
    header_name: authorization
discovery:
  credentials: [api_token]
endpoints:
  - host: api-1.github.com
    port: 443
    protocol: rest
    access: read-only
    enforcement: enforce
  - host: api.github.com
    port: 443
    path: /graphql
    protocol: graphql
    access: read-only
    enforcement: enforce
  - host: github.com
    port: 443
    protocol: rest
    access: read-only
    enforcement: enforce
binaries: [/usr/bin/gh, /usr/local/bin/gh, /usr/bin/git, /usr/local/bin/git]
... (1 lines truncated)
</file>

<file path="examples/governance-interceptor/profiles/slack.yaml">
display_name: Slack
description: Read-only Slack Web API access for governed sandbox agents
category: messaging
credentials:
  - name: api_token
    description: Slack bot or user token
    env_vars: [SLACK_BOT_TOKEN, SLACK_TOKEN]
    required: true
    auth_style: bearer
    header_name: authorization
discovery:
  credentials: [api_token]
endpoints:
  - host: slack.com
    port: 443
    protocol: rest
    enforcement: enforce
    rules:
      - allow:
          method: GET
          path: /api/team.info
      - allow:
          method: GET
          path: /api/users.info
      - allow:
          method: GET
          path: /api/conversations.info
      - allow:
          method: GET
          path: /api/conversations.history
... (4 lines truncated)
</file>

<file path="examples/governance-interceptor/src/main.rs">
mod policy_hash;
mod proto_json;
⋮----
use std::collections::HashMap;
use std::net::SocketAddr;
⋮----
use openshell_policy::parse_sandbox_policy;
⋮----
use prost_types::ListValue;
⋮----
use tonic::Code;
⋮----
struct PolicySigner {
⋮----
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("PolicySigner")
.field("kid", &self.kid)
.finish_non_exhaustive()
⋮----
struct PolicySignatureClaims {
⋮----
struct ProfileSignatureClaims {
⋮----
impl PolicySigner {
fn generate() -> Result<Self, String> {
⋮----
.map_err(|err| format!("failed to generate policy signing key: {err}"))?;
let signing_key_pem = keypair.serialize_pem();
let public_key_pem = keypair.public_key_pem();
let encoding_key = EncodingKey::from_ed_pem(signing_key_pem.as_bytes())
... (740 lines truncated)
</file>

<file path="examples/governance-interceptor/src/policy_hash.rs">
use prost::Message;
use serde_json::Value;
⋮----
use crate::proto_json::decode_message_to_json;
⋮----
pub(crate) fn canonical_policy_hash(policy: &SandboxPolicy) -> Result<String, String> {
canonical_message_hash(SANDBOX_POLICY_TYPE, policy, POLICY_DOMAIN)
⋮----
pub(crate) fn canonical_profile_hash(profile: &ProviderProfile) -> Result<String, String> {
canonical_message_hash(PROVIDER_PROFILE_TYPE, profile, PROFILE_DOMAIN)
⋮----
pub(crate) fn canonical_profile_snapshot_revision(
⋮----
.iter()
.map(|profile| {
Ok((
profile.id.as_bytes(),
canonical_message_bytes(PROVIDER_PROFILE_TYPE, profile)?,
⋮----
canonical_profiles.sort_by(|left, right| left.0.cmp(right.0));
⋮----
hasher.update(HASH_ALGORITHM.as_bytes());
hash_framed(&mut hasher, PROFILE_SNAPSHOT_DOMAIN.as_bytes())?;
hash_framed(&mut hasher, PROVIDER_PROFILE_TYPE.as_bytes())?;
hash_framed(
⋮----
&u64::try_from(canonical_profiles.len())
.map_err(|_| "provider profile count exceeds hash framing limit")?
.to_be_bytes(),
⋮----
... (146 lines truncated)
</file>

<file path="examples/governance-interceptor/src/proto_json.rs">
use serde_json::Value;
⋮----
struct ProtoJsonCodec {
⋮----
impl ProtoJsonCodec {
fn openshell() -> Result<Self, String> {
⋮----
.map_err(|err| format!("decode OpenShell protobuf descriptor set: {err}"))?;
Ok(Self {
⋮----
fn decode_message_to_json<M>(&self, type_name: &str, message: &M) -> Result<Value, String>
⋮----
let descriptor = self.message_descriptor(type_name)?;
let message = DynamicMessage::decode(descriptor, message.encode_to_vec().as_slice())
.map_err(|err| format!("decode {type_name} protobuf message: {err}"))?;
⋮----
.map_err(|err| format!("serialize {type_name} as ProtoJSON: {err}"))
⋮----
fn encode_json_to_message(&self, type_name: &str, value: &Value) -> Result<Vec<u8>, String> {
⋮----
.map_err(|err| format!("serialize {type_name} JSON before protobuf encoding: {err}"))?;
⋮----
.map_err(|err| format!("encode {type_name} from ProtoJSON: {err}"))?;
⋮----
.end()
⋮----
Ok(message.encode_to_vec())
⋮----
fn message_descriptor(&self, type_name: &str) -> Result<MessageDescriptor, String> {
let normalized = type_name.strip_prefix('.').unwrap_or(type_name);
... (20 lines truncated)
</file>

<file path="examples/governance-interceptor/src/smoke_client.rs">
use serde::Serialize;
use tonic::Code;
use tonic::metadata::AsciiMetadataValue;
use tonic::service::interceptor::InterceptedService;
use tonic::transport::Channel;
⋮----
struct SandboxJwtClaims {
⋮----
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut args = std::env::args().skip(1);
⋮----
let endpoint = args.next().ok_or(usage)?;
let sandbox_name = args.next().ok_or(usage)?;
let sandbox_id = args.next().ok_or(usage)?;
let signing_key_path = args.next().ok_or(usage)?;
let gateway_kid = args.next().ok_or(usage)?;
let gateway_id = args.next().ok_or(usage)?;
if args.next().is_some() {
return Err(usage.into());
⋮----
let token = mint_sandbox_token(
⋮----
let channel = Channel::from_shared(endpoint)?.connect().await?;
let bearer = AsciiMetadataValue::try_from(format!("Bearer {token}"))?;
⋮----
.metadata_mut()
.insert("authorization", bearer.clone());
Ok(request)
⋮----
.get_sandbox_config(GetSandboxConfigRequest {
... (70 lines truncated)
</file>

<file path="examples/governance-interceptor/src/tests.rs">
use serde_json::json;
⋮----
fn service() -> GovernanceInterceptorService {
let profiles = load_provider_profiles(&default_profiles_path()).unwrap();
GovernanceInterceptorService::from_profiles(profiles).unwrap()
⋮----
async fn describe_rejects_incompatible_gateway_metadata() {
let service = service();
⋮----
gateway.protocol_version.as_mut().unwrap().major = 2;
⋮----
gateway: Some(gateway),
⋮----
.unwrap_err();
⋮----
assert_eq!(error.code(), Code::FailedPrecondition);
assert!(error.message().contains("unsupported protocol"));
⋮----
fn evaluation(
⋮----
let proposed_operation = Some(json_to_struct(&operation).unwrap());
⋮----
GatewayInterceptorPhase::Unspecified => panic!("test evaluation phase must be specified"),
⋮----
interceptor_name: "test".to_string(),
binding_id: "binding".to_string(),
service: SERVICE.to_string(),
method: method.to_string(),
⋮----
phase: Some(phase),
... (354 lines truncated)
</file>

<file path="examples/governance-interceptor/Cargo.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

[workspace]

[package]
name = "openshell-governance-interceptor-example"
version = "0.0.0"
edition = "2024"
rust-version = "1.94"
license = "Apache-2.0"

[dependencies]
jsonwebtoken = { version = "10", features = ["aws_lc_rs"] }
openshell-core = { path = "../../crates/openshell-core", default-features = false }
openshell-policy = { path = "../../crates/openshell-policy" }
openshell-providers = { path = "../../crates/openshell-providers" }
prost = "0.14"
prost-reflect = { version = "0.16.5", features = ["serde"] }
prost-types = "0.14"
rcgen = { version = "0.13", default-features = false, features = ["crypto", "pem", "aws_lc_rs"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
serde_yml = { package = "noyalib", version = "0.0.28", default-features = false, features = ["std", "compat-serde-yaml"] }
sha2 = "0.10"
tokio = { version = "1.43", features = ["macros", "rt-multi-thread", "fs", "signal"] }
tonic = { version = "0.14", features = ["transport"] }

[[bin]]
name = "governance-interceptor"
... (6 lines truncated)
</file>

<file path="examples/governance-interceptor/policy.yaml">
version: 1
filesystem_policy:
  include_workdir: true
  read_only: [/usr, /lib, /proc, /dev/urandom, /app, /etc, /var/log]
  read_write: [/sandbox, /tmp, /dev/null]
landlock:
  compatibility: best_effort
network_policies:
  my_api:
    name: my-api
    endpoints:
      - host: api-1.example.com
        port: 443
        protocol: rest
        enforcement: enforce
        access: full
    binaries:
      - path: /usr/bin/curl
</file>

<file path="examples/governance-interceptor/README.md">
# Governance Interceptor Example

This standalone example implements the
`openshell.gateway_interceptor.v1.GatewayInterceptor` service. It demonstrates
how an interceptor can vend provider profiles and make them the gateway's
authoritative profile source.

- provider profile YAML lives in `profiles/*.yaml`
- `profile list` shows only the profiles vended by this interceptor
- providers can only be created with a `type` that matches one of those vended
  profile IDs
- every vended provider profile gets governance annotations for its hash,
  signature, and signing key ID
- every new sandbox receives `policy.yaml` during `CreateSandbox`
- requested sandbox providers must match one of the vended profile IDs
- every new sandbox gets an `openshell.nvidia.com/policy-signature` metadata
  annotation that is used to verify the policy
- sandbox creation evaluations add a `correlation_id` log annotation for gateway
  audit logs, plus non-secret policy hash/signing key metadata
- sandbox policy synchronization must carry the current signed governance
  policy; unsigned, stale, or modified policies are denied for every caller
- sandbox policy analysis may report telemetry, but sandbox-authored policy
  proposals are denied before they reach the gateway handler
- `proposal_approval_mode=auto` is blocked at both sandbox and global scope
- users cannot import or update provider profiles outside the vended set
- provider profile deletion is blocked by the interceptor

Run the interceptor:

```shell
... (127 lines truncated)
</file>

<file path="examples/governance-interceptor/smoke.sh">
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
EXAMPLE_DIR="$ROOT/examples/governance-interceptor"
RUN_TEST_SUITE=0
usage() {
  cat <<EOF
usage: $0 [--test-suite|--test]
Without flags, starts a local gateway with the governance interceptor attached
and keeps it running for interactive use.
Options:
  --test-suite, --test  Run the governance smoke test suite, then stop.
  -h, --help            Show this help.
EOF
}
while [[ "$#" -gt 0 ]]; do
  case "$1" in
    --test-suite | --test)
      RUN_TEST_SUITE=1
      shift
      ;;
    -h | --help)
      usage
      exit 0
      ;;
    *)
      echo "unknown argument: $1" >&2
      usage >&2
      exit 2
      ;;
  esac
... (536 lines truncated)
</file>

<file path="examples/local-inference/inference.py">
PROMPT = (
MESSAGES = [{"role": "user", "content": PROMPT}]
⋮----
def run_non_streaming(client: OpenAI, label: str, model: str) -> None
⋮----
t0 = time.monotonic()
response = client.chat.completions.create(
elapsed = time.monotonic() - t0
⋮----
content = (response.choices[0].message.content or "").strip()
words = content.split()
⋮----
def run_streaming(client: OpenAI, label: str, model: str) -> None
⋮----
ttfb = None
chunks = []
⋮----
stream = client.chat.completions.create(
⋮----
ttfb = time.monotonic() - t0
⋮----
delta = chunk.choices[0].delta if chunk.choices else None
⋮----
content = "".join(chunks).strip()
⋮----
DIRECT_URL = "https://integrate.api.nvidia.com/v1"
DIRECT_MODEL = "meta/llama-3.1-8b-instruct"
⋮----
def main() -> None
⋮----
... (4 lines truncated)
</file>

<file path="examples/local-inference/nvidia-inference.yaml">
id: nvidia-inference
display_name: NVIDIA Inference
description: NVIDIA API Catalog access for native Python clients
category: inference
inference_capable: true
credentials:
  - name: api_key
    description: NVIDIA API key
    env_vars: [NVIDIA_API_KEY]
    required: true
    auth_style: bearer
    header_name: authorization
discovery:
  credentials: [api_key]
endpoints:
  - host: integrate.api.nvidia.com
    port: 443
    protocol: rest
    access: read-write
    enforcement: enforce
binaries:
  - /usr/bin/python3
  - /usr/bin/python3.13
  - /usr/local/bin/python
  - /sandbox/.venv/**
</file>

<file path="examples/local-inference/README.md">
# Inference Example

This example calls the NVIDIA API Catalog through its native OpenAI-compatible
endpoint. OpenShell supplies endpoint-bound credentials and network policy from
an explicitly imported provider profile; the Python client owns the endpoint,
model, request shape, timeout, and streaming behavior.

## Files

| File | Description |
|---|---|
| `nvidia-inference.yaml` | Example profile for the endpoint, credential, and allowed Python binaries |
| `inference.py` | Native endpoint streaming and non-streaming client |
| `sandbox-policy.yaml` | Minimal policy that lets Python install the OpenAI client from PyPI |

## Run the Example

Export the built-in profile as a starting point and compare it with the example
before import. A custom profile must use a new ID; built-in IDs are reserved.

```shell
openshell provider profile export nvidia -o yaml > /tmp/nvidia-profile.yaml
diff -u /tmp/nvidia-profile.yaml examples/local-inference/nvidia-inference.yaml
openshell provider profile lint -f examples/local-inference/nvidia-inference.yaml
openshell provider profile import -f examples/local-inference/nvidia-inference.yaml
```

Create the provider from the local `NVIDIA_API_KEY`, then attach it to the new
sandbox:

... (40 lines truncated)
</file>

<file path="examples/local-inference/sandbox-policy.yaml">
version: 1
filesystem_policy:
  include_workdir: true
  read_only:
  - /usr
  - /lib
  - /etc
  - /app
  - /var/log
  - /proc/self
  - /dev/urandom
  read_write:
  - /sandbox
  - /tmp
  - /dev/null
landlock:
  compatibility: best_effort
network_policies:
  pypi:
    name: PyPI
    endpoints:
      - { host: pypi.org, port: 443 }
      - { host: files.pythonhosted.org, port: 443 }
    binaries:
      - path: /usr/bin/python3.13
</file>

<file path="examples/multi-agent-notepad/prompts/synthesis.md">
<!-- SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -->
<!-- SPDX-License-Identifier: Apache-2.0 -->
<!-- markdownlint-disable MD041 -->

You are the synthesis agent in an OpenShell multi-agent demo.

Topic: {{TOPIC}}

You will receive markdown notes from multiple isolated worker agents. Create a concise final brief that combines their findings.

Return markdown only. Use this structure:

# Multi-Agent Summary

## Executive Summary

Two to four sentences.

## Strongest Findings

- Four to six bullets.

## Disagreements Or Tensions

- Note any conflicts, missing context, or tradeoffs.

## Recommended Next Steps

- Three practical next steps.

... (2 lines truncated)
</file>

<file path="examples/multi-agent-notepad/prompts/worker.md">
<!-- SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -->
<!-- SPDX-License-Identifier: Apache-2.0 -->
<!-- markdownlint-disable MD041 -->

You are agent {{AGENT_INDEX}} of {{AGENT_COUNT}} in an OpenShell multi-agent demo.

Topic: {{TOPIC}}

Your job is to write one focused research note from your assigned angle:

{{SLICE}}

Return markdown only. Use this structure:

# Agent {{AGENT_INDEX}} Note

## Angle

One sentence describing your angle.

## Findings

- Three to five concise findings.

## Evidence To Gather Next

- Two concrete follow-up checks or sources.

## Open Questions

... (4 lines truncated)
</file>

<file path="examples/multi-agent-notepad/demo.sh">
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
POLICY_TEMPLATE="${SCRIPT_DIR}/policy.template.yaml"
PROMPTS_DIR="${SCRIPT_DIR}/prompts"
OPENSHELL_BIN="${OPENSHELL_BIN:-openshell}"
DEMO_TOPIC="${DEMO_TOPIC:-How should teams evaluate sandboxed coding agents?}"
DEMO_AGENT_COUNT="${DEMO_AGENT_COUNT:-5}"
DEMO_AGENT_IMAGE="${DEMO_AGENT_IMAGE:-}"
DEMO_BRANCH="${DEMO_BRANCH:-main}"
DEMO_RUN_ID="${DEMO_RUN_ID:-$(date +%Y%m%d-%H%M%S)}"
SANDBOX_TAG="${DEMO_RUN_ID:2:12}"
DEMO_KEEP_SANDBOXES="${DEMO_KEEP_SANDBOXES:-0}"
DEMO_CODEX_PROVIDER_NAME="${DEMO_CODEX_PROVIDER_NAME:-codex-oauth-${DEMO_RUN_ID}}"
DEMO_GITHUB_PROVIDER_NAME="${DEMO_GITHUB_PROVIDER_NAME:-github-memory-${DEMO_RUN_ID}}"
TMP_DIR="$(mktemp -d "${TMPDIR:-/tmp}/openshell-codex-github.XXXXXX")"
POLICY_FILE="${TMP_DIR}/policy.yaml"
PAYLOAD_DIR="${TMP_DIR}/payload"
RUNNER_FILE="${PAYLOAD_DIR}/demo-runner.sh"
PROMPTS_UPLOAD_DIR="${PAYLOAD_DIR}/prompts"
LOG_DIR="${TMP_DIR}/logs"
mkdir -p "$LOG_DIR" "$PROMPTS_UPLOAD_DIR"
BOLD='\033[1m'
DIM='\033[2m'
CYAN='\033[36m'
GREEN='\033[32m'
RED='\033[31m'
YELLOW='\033[33m'
RESET='\033[0m'
WORKER_SLICES=(
  "Adoption criteria: what makes a sandboxed coding-agent workflow trustworthy enough to try?"
... (176 lines truncated)
</file>

<file path="examples/multi-agent-notepad/policy.template.yaml">
version: 1
filesystem_policy:
  include_workdir: true
  read_only: [/usr, /lib, /proc, /dev/urandom, /app, /etc, /var/log]
  read_write: [/sandbox, /tmp, /dev/null]
landlock:
  compatibility: best_effort
network_policies:
  codex:
    name: codex
    endpoints:
      - { host: api.openai.com, port: 443, protocol: rest, enforcement: enforce, access: full }
      - { host: auth.openai.com, port: 443, protocol: rest, enforcement: enforce, access: full }
      - { host: chatgpt.com, port: 443, protocol: rest, enforcement: enforce, access: full }
      - { host: ab.chatgpt.com, port: 443, protocol: rest, enforcement: enforce, access: full }
    binaries:
      - { path: /usr/bin/codex }
      - { path: /usr/bin/node }
      - { path: "/usr/lib/node_modules/@openai/**" }
  codex_plugins:
    name: codex-plugins
    endpoints:
      - host: github.com
        port: 443
        protocol: rest
        enforcement: enforce
        rules:
          - allow:
              method: GET
              path: "/openai/plugins.git/info/refs*"
... (30 lines truncated)
</file>

<file path="examples/multi-agent-notepad/README.md">
<!-- SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -->
<!-- SPDX-License-Identifier: Apache-2.0 -->

# Multi-Agent Shared Notepad Demo

Run multiple Codex coding agents in parallel OpenShell sandboxes, with a
GitHub repository as the durable shared notepad they coordinate through.

## Why GitHub as a shared notepad?

Long-running agents that produce artifacts — research notes, memory entries,
reports, decision logs — need somewhere durable to write them. The store has
to survive individual sandbox death, accept many concurrent writers safely,
and stay inspectable after the fact. GitHub provides all three for free:

- **Durable across sandbox restarts.** A sandbox can crash mid-run; the
  committed artifact persists.
- **Concurrency control built in.** Every PUT must include the current file
  SHA, and the branch ref serializes commits. Racing writers see HTTP 409
  and retry instead of silently overwriting each other.
- **Auditable.** Every write is a commit with author, message, diff, and
  timestamp. Free observability.
- **Reviewable.** Humans review agent output with the same PR/diff tooling
  they already use for code.
- **No new infra.** Most teams already have a GitHub org.

The pattern works best when artifacts are markdown or other text (so diffs
are useful) and when write rates are moderate (commits per minute, not per
second). For higher rates or structured queries, graduate to a real
datastore — see [Beyond map/reduce](#beyond-mapreduce-memory-architecture-variants)
... (176 lines truncated)
</file>

<file path="examples/multi-agent-notepad/runner.sh">
set -euo pipefail
MODE="$1"
OWNER="$2"
REPO="$3"
BRANCH="$4"
RUN_ID="$5"
AGENT_INDEX="${6:-0}"
AGENT_COUNT="${7:-0}"
TOPIC="${8:-}"
api_url() {
    printf 'https://api.github.com%s' "$1"
}
github_request() {
    local method="$1"
    local path="$2"
    local output="$3"
    shift 3
    curl -sS \
        -X "$method" \
        -H "Accept: application/vnd.github+json" \
        -H "Authorization: Bearer ${DEMO_GITHUB_TOKEN}" \
        -H "X-GitHub-Api-Version: 2022-11-28" \
        "$@" \
        -o "$output" \
        -w "%{http_code}" \
        "$(api_url "$path")"
}
render_template() {
    local template="$1"
    local slice="${2:-}"
... (166 lines truncated)
</file>

<file path="examples/policy-advisor/ctf.py">
GREEN = "\033[92m"
RED = "\033[91m"
YELLOW = "\033[93m"
BLUE = "\033[94m"
CYAN = "\033[96m"
MAGENTA = "\033[95m"
BOLD = "\033[1m"
DIM = "\033[2m"
RESET = "\033[0m"
⋮----
RETRY_INTERVAL = 10
MAX_RETRIES = 180
⋮----
def log(level: str, msg: str, **kv: object) -> None
⋮----
ts = datetime.now().strftime("%H:%M:%S.%f")[:-3]
colours = {
c = colours.get(level, "")
extra = "  ".join(f"{DIM}{k}={v}{RESET}" for k, v in kv.items())
⋮----
# -- Gate definitions ----------------------------------------------------------
⋮----
GATES: list[dict] = [
⋮----
# -- Gate 1: HTTPS on 443 (CONNECT tunnel) --------------------------------
⋮----
# -- Gate 2: plain HTTP on 80 (forward proxy, python) ----------------------
⋮----
# -- Gates 4-6: concurrent HTTPS requests (batch approval) ----------------
⋮----
... (67 lines truncated)
</file>

<file path="examples/policy-advisor/README.md">
<!-- SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -->
<!-- SPDX-License-Identifier: Apache-2.0 -->

# Policy Advisor CTF -- Mechanistic Mode

A capture-the-flag challenge that walks you through OpenShell's policy
recommendation pipeline.  You start with a sandbox that only allows traffic to
`api.anthropic.com`.  A Python script tries to reach 7 endpoints -- and fails.
The sandbox proxy detects each denial, the sandbox-side mechanistic mapper
turns it into a concrete `NetworkPolicyRule` proposal, and submits it to the
gateway for your approval.  You approve those recommendations in the TUI, and
the script progresses through each gate.

## How It Works

1. **Script makes a request** -- the sandbox proxy blocks it and emits a
   `DenialEvent`.
2. **DenialAggregator batches events** -- every ~10 seconds it drains
   aggregated denial summaries.
3. **Mechanistic mapper generates proposals (sandbox-side)** -- each unique
   `(host, port, binary)` triple becomes a `PolicyChunk` with a proposed
   `NetworkPolicyRule`, confidence score, and rationale.  If the host resolves
   to a private IP, the mapper includes `allowed_ips` for the SSRF override.
4. **Proposals submitted to gateway** -- via `SubmitPolicyAnalysis`.  The
   gateway validates and persists the proposals.
5. **TUI shows recommendations** -- navigate to the sandbox's rules panel to
   see pending proposals.
6. **You approve** -- the approved rule merges into the active sandbox policy
   and the proxy begins allowing the connection.
7. **Script retries and succeeds** -- on to the next gate.
... (129 lines truncated)
</file>

<file path="examples/policy-advisor/sandbox-policy.yaml">
version: 1
network_policies:
  anthropic:
    name: Anthropic API
    endpoints:
      - { host: api.anthropic.com, port: 443 }
</file>

<file path="examples/private-ip-routing/Dockerfile">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

FROM python:3.13-slim
COPY server.py /app/server.py
EXPOSE 8080
CMD ["python", "/app/server.py"]
</file>

<file path="examples/private-ip-routing/README.md">
# Private IP Routing via `allowed_ips`

Demonstrates the `allowed_ips` sandbox policy feature, which lets sandboxes
reach services on private IP space (e.g. cluster-internal pods) that would
normally be blocked by the proxy's SSRF protection.

## How it works

The sandbox proxy blocks all connections to RFC 1918 addresses by default.
When an endpoint in the sandbox policy includes an `allowed_ips` field, the
proxy validates the resolved IP against that CIDR allowlist instead of
blanket-blocking. Loopback and link-local remain always-blocked regardless.

Save an explicit policy as `private-policy.yaml` that allows the client binary
to reach port 8080 on the configured pod network:

```yaml
cluster_pods:
  name: cluster_pods
  endpoints:
    - port: 8080
      allowed_ips:
        - "10.42.0.0/16"
  binaries:
    - { path: "/**" }
```

## Launch the demo server

Build the image and push it to a registry that your Kubernetes cluster can pull from:
... (63 lines truncated)
</file>

<file path="examples/private-ip-routing/server.py">
class Handler(BaseHTTPRequestHandler)
⋮----
def do_GET(self)
⋮----
body = json.dumps(
⋮----
def log_message(self, fmt, *args)
⋮----
server = HTTPServer(("0.0.0.0", 8080), Handler)
</file>

<file path="examples/provider-managed-files/acme-config.yaml">
id: acme-config
display_name: Acme client configuration
description: Non-secret settings installed as a managed sandbox file
category: other
files:
  - path: client.toml
    env_var: ACME_CONFIG_FILE
    content: |
      endpoint = "{{config.endpoint}}"
      project = "{{config.project}}"
</file>

<file path="examples/sandbox-policy-quickstart/demo.sh">
set -euo pipefail
SANDBOX_NAME="policy-demo"
SSH_CONFIG=$(mktemp)
cleanup() {
    rm -f "$SSH_CONFIG"
    printf '\n'
    step "Cleaning up"
    openshell sandbox delete "$SANDBOX_NAME" 2>/dev/null || true
}
trap cleanup EXIT
BOLD='\033[1m'
DIM='\033[2m'
CYAN='\033[36m'
GREEN='\033[32m'
RED='\033[31m'
YELLOW='\033[33m'
MAGENTA='\033[35m'
RESET='\033[0m'
STEP_PAUSE="${DEMO_PAUSE:-1}"
step() {
    sleep "$STEP_PAUSE"
    printf "\n${BOLD}${CYAN}▸ %s${RESET}\n\n" "$1"
}
run() {
    printf "  ${BOLD}\$ %s${RESET}\n" "$*"
    "$@" 2>&1 | sed 's/^/  /'
    return "${PIPESTATUS[0]}"
}
policy_events() {
    grep -E '(NET|HTTP):[A-Z]+ .*(ALLOWED|DENIED)'
... (83 lines truncated)
</file>

<file path="examples/sandbox-policy-quickstart/policy.yaml">
version: 1
filesystem_policy:
  include_workdir: true
  read_only: [/bin, /usr, /lib, /proc, /dev/urandom, /app, /etc, /var/log]
  read_write: [/sandbox, /tmp, /dev/null]
landlock:
  compatibility: best_effort
network_policies:
  github_api:
    name: github-api-readonly
    endpoints:
      - host: api.github.com
        port: 443
        protocol: rest
        enforcement: enforce
        access: read-only
    binaries:
      - { path: /usr/bin/curl }
</file>

<file path="examples/sandbox-policy-quickstart/README.md">
# Sandbox Policy Quickstart

See how OpenShell's network policy system works in under five minutes.
You'll create a sandbox, watch a request get blocked by the default-deny
policy, apply a fine-grained L7 rule, and verify that reads are allowed
while writes are blocked — all without restarting anything.

## Prerequisites

- A running OpenShell gateway (`mise run gateway:docker` for local development)
- Docker daemon running

## What's in this example

| File          | Description                                                          |
| ------------- | -------------------------------------------------------------------- |
| `policy.yaml` | Complete policy with the same rule, for `sandbox create --policy`    |
| `demo.sh`     | Automated script that runs the full walkthrough non-interactively    |

## Walkthrough

### 1. Create a sandbox

```bash
openshell sandbox create --name demo --no-auto-providers
```

`--no-auto-providers` skips the provider setup prompt since this
demo doesn't use an AI agent.

... (202 lines truncated)
</file>

<file path="examples/spiffe-token-exchange-demo/k8s/kustomization.yaml">
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
generatorOptions:
  disableNameSuffixHash: true
configMapGenerator:
  - name: openshell-spiffe-token-exchange-demo-scripts
    files:
      - token-issuer.js
      - protected-service.js
  - name: openshell-spiffe-token-exchange-demo-helper
    files:
      - spiffe-helper.conf
resources:
  - workloads.yaml
</file>

<file path="examples/spiffe-token-exchange-demo/k8s/protected-service.js">
function b64urlDecode(value)
⋮----
function b64urlEncode(value)
⋮----
function parseJwt(jwt)
⋮----
function verifyAccessToken(jwt)
⋮----
function text(res, status, body)
</file>

<file path="examples/spiffe-token-exchange-demo/k8s/spiffe-helper.conf">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

agent_address = "/run/spire/sockets/spire-agent.sock"
cert_dir = "/target"
svid_file_name = "svid.pem"
svid_key_file_name = "key.pem"
svid_bundle_file_name = "bundle.pem"
</file>

<file path="examples/spiffe-token-exchange-demo/k8s/token-issuer.js">
function b64urlDecode(value)
⋮----
function b64urlEncode(value)
⋮----
function parseJwt(jwt)
⋮----
async function jwks()
⋮----
function fetchJson(url)
⋮----
function hasAudience(payload, expected)
⋮----
async function verifyJwtSvid(jwt, subjectPrefix)
⋮----
function signAccessToken(payload)
⋮----
function verifyAccessToken(jwt, tokenUse)
⋮----
function issueDemoSubjectToken()
⋮----
function json(res, status, body)
⋮----
async function bodyText(req)
⋮----
async function handleTokenExchange(req, res)
</file>

<file path="examples/spiffe-token-exchange-demo/k8s/workloads.yaml">
apiVersion: apps/v1
kind: Deployment
metadata:
  name: token-exchange-issuer
  namespace: default
  labels:
    app: token-exchange-issuer
spec:
  replicas: 1
  selector:
    matchLabels:
      app: token-exchange-issuer
  template:
    metadata:
      labels:
        app: token-exchange-issuer
    spec:
      containers:
        - name: token-exchange-issuer
          image: node:22-alpine
          imagePullPolicy: IfNotPresent
          command: ["node", "/demo/token-issuer.js"]
          ports:
            - name: http
              containerPort: 8080
          env:
            - name: ACCESS_TOKEN_SECRET
              valueFrom:
                secretKeyRef:
                  name: openshell-spiffe-token-exchange-demo
... (198 lines truncated)
</file>

<file path="examples/spiffe-token-exchange-demo/podman/spire/agent.conf">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

agent {
    data_dir = "/run/spire/agent/data"
    log_level = "INFO"
    server_address = "spire-server"
    server_port = "8081"
    socket_path = "/run/spire/agent/sockets/agent.sock"
    trust_domain = "openshell.local"
    insecure_bootstrap = true
}

plugins {
    NodeAttestor "join_token" {
        plugin_data {}
    }

    KeyManager "disk" {
        plugin_data {
            directory = "/run/spire/agent/data"
        }
    }

    WorkloadAttestor "unix" {
        plugin_data {}
    }

    # Podman exposes a Docker-compatible API. The demo mounts the Podman socket
    # here so SPIRE can use Docker-style selectors for the sandbox container
... (8 lines truncated)
</file>

<file path="examples/spiffe-token-exchange-demo/podman/spire/common.sh">
set -euo pipefail
SPIRE_SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PODMAN_NETWORK="${PODMAN_NETWORK:-openshell}"
TRUST_DOMAIN="${TRUST_DOMAIN:-openshell.local}"
SPIRE_AGENT_PARENT_ID="${SPIRE_AGENT_PARENT_ID:-spiffe://${TRUST_DOMAIN}/openshell/spire-agent/demo}"
SPIRE_SERVER_IMAGE="${SPIRE_SERVER_IMAGE:-ghcr.io/spiffe/spire-server:1.12.4}"
SPIRE_AGENT_IMAGE="${SPIRE_AGENT_IMAGE:-ghcr.io/spiffe/spire-agent:1.12.4}"
SPIRE_OIDC_IMAGE="${SPIRE_OIDC_IMAGE:-ghcr.io/spiffe/oidc-discovery-provider:1.12.4}"
SPIRE_SERVER_CONTAINER="${SPIRE_SERVER_CONTAINER:-openshell-spiffe-demo-spire-server}"
SPIRE_AGENT_CONTAINER="${SPIRE_AGENT_CONTAINER:-openshell-spiffe-demo-spire-agent}"
SPIRE_OIDC_CONTAINER="${SPIRE_OIDC_CONTAINER:-openshell-spiffe-demo-spire-oidc}"
SPIRE_SERVER_BIN="${SPIRE_SERVER_BIN:-/opt/spire/bin/spire-server}"
OIDC_PORT="${OIDC_PORT:-18081}"
SPIRE_STATE_DIR="${SPIRE_STATE_DIR:-}"
SPIRE_ENV_FILE="${SPIRE_ENV_FILE:-}"
CLEANUP_EXISTING="${CLEANUP_EXISTING:-1}"
PODMAN_SOCKET_DEMO_OWNED="${PODMAN_SOCKET_DEMO_OWNED:-0}"
run() {
    printf "\n$ %s\n" "$*" >&2
    "$@"
}
require_cmd() {
    local cmd="$1"
    if ! command -v "$cmd" >/dev/null 2>&1; then
        printf "missing required command: %s\n" "$cmd" >&2
        exit 1
    fi
}
cleanup_container() {
    podman rm -f "$1" >/dev/null 2>&1 || true
... (108 lines truncated)
</file>

<file path="examples/spiffe-token-exchange-demo/podman/spire/oidc-discovery-provider.conf">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

log_level = "INFO"
domains = ["spire-oidc", "127.0.0.1", "localhost"]
allow_insecure_scheme = true
insecure_addr = "0.0.0.0:8080"
jwt_issuer = "http://spire-oidc:8080"
jwks_uri = "http://spire-oidc:8080/keys"

server_api {
    address = "unix:///run/spire/server/private/api.sock"
}

health_checks {
    bind_port = "8008"
    ready_path = "/ready"
    live_path = "/live"
}
</file>

<file path="examples/spiffe-token-exchange-demo/podman/spire/register-gateway.sh">
set -euo pipefail
TRUST_DOMAIN="${TRUST_DOMAIN:-openshell.local}"
GATEWAY_SPIFFE_ID="${GATEWAY_SPIFFE_ID:-spiffe://${TRUST_DOMAIN}/openshell/gateway/demo}"
SPIRE_AGENT_PARENT_ID="${SPIRE_AGENT_PARENT_ID:-spiffe://${TRUST_DOMAIN}/openshell/spire-agent/demo}"
SPIRE_SERVER_SOCKET="${SPIRE_SERVER_SOCKET:-/run/spire/server/private/api.sock}"
SPIRE_SERVER_CONTAINER="${SPIRE_SERVER_CONTAINER:-openshell-spiffe-demo-spire-server}"
SPIRE_SERVER_BIN="${SPIRE_SERVER_BIN:-/opt/spire/bin/spire-server}"
if [[ -n "${GATEWAY_SELECTORS:-}" ]]; then
    read -r -a selectors <<<"$GATEWAY_SELECTORS"
else
    gateway_path="${GATEWAY_WORKLOAD_PATH:-$(command -v openshell-server || true)}"
    if [[ -n "$gateway_path" ]]; then
        selectors=("unix:uid:$(id -u)" "unix:path:${gateway_path}")
    else
        printf "GATEWAY_WORKLOAD_PATH is unset and openshell-server is not on PATH; falling back to unix:uid only\n" >&2
        selectors=("unix:uid:$(id -u)")
    fi
fi
args=(
    entry create
    -socketPath "$SPIRE_SERVER_SOCKET"
    -parentID "$SPIRE_AGENT_PARENT_ID"
    -spiffeID "$GATEWAY_SPIFFE_ID"
    -jwtSVIDTTL 300
)
for selector in "${selectors[@]}"; do
    args+=(-selector "$selector")
done
printf "Registering gateway SPIFFE entry: %s\n" "$GATEWAY_SPIFFE_ID" >&2
podman exec "$SPIRE_SERVER_CONTAINER" "$SPIRE_SERVER_BIN" "${args[@]}"
... (1 lines truncated)
</file>

<file path="examples/spiffe-token-exchange-demo/podman/spire/register-sandbox.sh">
set -euo pipefail
if [[ $
    printf "usage: %s <sandbox-id>\n" "$0" >&2
    exit 2
fi
SANDBOX_ID="$1"
TRUST_DOMAIN="${TRUST_DOMAIN:-openshell.local}"
SANDBOX_SPIFFE_ID="${SANDBOX_SPIFFE_ID:-spiffe://${TRUST_DOMAIN}/openshell/sandbox/${SANDBOX_ID}}"
SPIRE_AGENT_PARENT_ID="${SPIRE_AGENT_PARENT_ID:-spiffe://${TRUST_DOMAIN}/openshell/spire-agent/demo}"
SPIRE_SERVER_SOCKET="${SPIRE_SERVER_SOCKET:-/run/spire/server/private/api.sock}"
SPIRE_SERVER_CONTAINER="${SPIRE_SERVER_CONTAINER:-openshell-spiffe-demo-spire-server}"
SPIRE_SERVER_BIN="${SPIRE_SERVER_BIN:-/opt/spire/bin/spire-server}"
if [[ -n "${SANDBOX_SELECTORS:-}" ]]; then
    read -r -a selectors <<<"$SANDBOX_SELECTORS"
else
    selectors=(
        "docker:label:openshell.managed:true"
        "docker:label:openshell.ai/sandbox-id:${SANDBOX_ID}"
    )
fi
args=(
    entry create
    -socketPath "$SPIRE_SERVER_SOCKET"
    -parentID "$SPIRE_AGENT_PARENT_ID"
    -spiffeID "$SANDBOX_SPIFFE_ID"
    -jwtSVIDTTL 300
)
for selector in "${selectors[@]}"; do
    args+=(-selector "$selector")
done
... (3 lines truncated)
</file>

<file path="examples/spiffe-token-exchange-demo/podman/spire/server.conf">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

server {
    bind_address = "0.0.0.0"
    bind_port = "8081"
    socket_path = "/run/spire/server/private/api.sock"
    trust_domain = "openshell.local"
    data_dir = "/run/spire/server/data"
    log_level = "INFO"
    jwt_issuer = "http://spire-oidc:8080"
    default_x509_svid_ttl = "1h"
    default_jwt_svid_ttl = "5m"

    ca_subject {
        country = ["US"]
        organization = ["OpenShell Demo"]
        common_name = "OpenShell Demo SPIRE"
    }
}

plugins {
    DataStore "sql" {
        plugin_data {
            database_type = "sqlite3"
            connection_string = "/run/spire/server/data/datastore.sqlite3"
        }
    }

    NodeAttestor "join_token" {
... (10 lines truncated)
</file>

<file path="examples/spiffe-token-exchange-demo/podman/spire/start-agent.sh">
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${SCRIPT_DIR}/common.sh"
require_cmd podman
require_cmd awk
require_cmd sed
if [[ -z "$SPIRE_STATE_DIR" ]]; then
    SPIRE_STATE_DIR="$(mktemp -d)"
fi
if ! PODMAN_SOCKET="$(detect_podman_socket)"; then
    printf "could not find a Podman API socket; set PODMAN_SOCKET\n" >&2
    exit 1
fi
reset_env_file
ensure_network
agent_dir="${SPIRE_STATE_DIR}/agent"
mount_dir="${SPIRE_STATE_DIR}/mounts"
agent_conf_mount="${mount_dir}/agent.conf"
SPIRE_AGENT_SOCKET_HOST_PATH="${SPIRE_AGENT_SOCKET_HOST_PATH:-${agent_dir}/sockets/agent.sock}"
mkdir -p "${agent_dir}/data" "${agent_dir}/sockets" "$mount_dir"
chmod 0777 "$SPIRE_STATE_DIR" "$agent_dir" "${agent_dir}/data" "${agent_dir}/sockets"
copy_config "${SPIRE_SCRIPT_DIR}/agent.conf" "$agent_conf_mount"
if [[ "$CLEANUP_EXISTING" == "1" ]]; then
    cleanup_container "$SPIRE_AGENT_CONTAINER"
fi
join_token="$(
    podman exec "$SPIRE_SERVER_CONTAINER" "$SPIRE_SERVER_BIN" token generate \
        -socketPath /run/spire/server/private/api.sock \
        -spiffeID "$SPIRE_AGENT_PARENT_ID" |
        awk '/Token:/ { print $2; exit }'
... (30 lines truncated)
</file>

<file path="examples/spiffe-token-exchange-demo/podman/spire/start-server-oidc.sh">
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${SCRIPT_DIR}/common.sh"
require_cmd podman
require_cmd curl
if [[ -z "$SPIRE_STATE_DIR" ]]; then
    SPIRE_STATE_DIR="$(mktemp -d)"
fi
reset_env_file
ensure_network
server_dir="${SPIRE_STATE_DIR}/server"
mount_dir="${SPIRE_STATE_DIR}/mounts"
server_conf_mount="${mount_dir}/server.conf"
oidc_conf_mount="${mount_dir}/oidc-discovery-provider.conf"
server_socket_host_path="${server_dir}/private/api.sock"
mkdir -p "${server_dir}/data" "${server_dir}/private" "$mount_dir"
chmod 0777 "$SPIRE_STATE_DIR" "$server_dir" "${server_dir}/data" "${server_dir}/private"
copy_config "${SPIRE_SCRIPT_DIR}/server.conf" "$server_conf_mount"
copy_config "${SPIRE_SCRIPT_DIR}/oidc-discovery-provider.conf" "$oidc_conf_mount"
if [[ "$CLEANUP_EXISTING" == "1" ]]; then
    cleanup_container "$SPIRE_OIDC_CONTAINER"
    cleanup_container "$SPIRE_SERVER_CONTAINER"
fi
printf "Starting SPIRE server container: %s\n" "$SPIRE_SERVER_CONTAINER" >&2
run podman run -d \
    --name "$SPIRE_SERVER_CONTAINER" \
    --network "$PODMAN_NETWORK" \
    --network-alias spire-server \
    -v "${server_conf_mount}:/run/spire/config/server.conf:ro,z" \
    -v "${server_dir}:/run/spire/server:z" \
... (32 lines truncated)
</file>

<file path="examples/spiffe-token-exchange-demo/podman/demo.sh">
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
DEMO_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
PROFILE_TEMPLATE="${SCRIPT_DIR}/provider-profile.yaml"
TOKEN_ISSUER_JS="${DEMO_ROOT}/k8s/token-issuer.js"
PROTECTED_SERVICE_JS="${DEMO_ROOT}/k8s/protected-service.js"
SANDBOX_NAME="${SANDBOX_NAME:-spiffe-podman-demo}"
PROVIDER_NAME="${PROVIDER_NAME:-spiffe-token-exchange-demo-podman}"
PROFILE_ID="${PROFILE_ID:-spiffe-token-exchange-demo-podman}"
START_GATEWAY="${START_GATEWAY:-0}"
MANAGED_GATEWAY_PORT="${MANAGED_GATEWAY_PORT:-18082}"
MANAGED_GATEWAY_HEALTH_PORT="${MANAGED_GATEWAY_HEALTH_PORT:-18083}"
if [[ -z "${GATEWAY_ENDPOINT:-}" ]]; then
    if [[ "$START_GATEWAY" == "1" ]]; then
        GATEWAY_ENDPOINT="http://127.0.0.1:${MANAGED_GATEWAY_PORT}"
    else
        GATEWAY_ENDPOINT="http://127.0.0.1:8080"
    fi
fi
PODMAN_NETWORK="${PODMAN_NETWORK:-openshell}"
TOKEN_ISSUER_PORT="${TOKEN_ISSUER_PORT:-18080}"
OIDC_PORT="${OIDC_PORT:-18081}"
TOKEN_ISSUER_SERVICE_HOST="${TOKEN_ISSUER_SERVICE_HOST:-token-exchange-issuer.default.svc.cluster.local}"
KEEP_SANDBOX="${KEEP_SANDBOX:-0}"
KEEP_DEMO="${KEEP_DEMO:-0}"
START_SPIRE="${START_SPIRE:-1}"
ACCESS_TOKEN_SECRET="${ACCESS_TOKEN_SECRET:-$(openssl rand -hex 32)}"
TRUST_DOMAIN="${TRUST_DOMAIN:-openshell.local}"
SPIRE_AGENT_PARENT_ID="${SPIRE_AGENT_PARENT_ID:-spiffe://${TRUST_DOMAIN}/openshell/spire-agent/demo}"
SPIRE_AGENT_SOCKET_HOST_PATH="${SPIRE_AGENT_SOCKET_HOST_PATH:-}"
... (559 lines truncated)
</file>

<file path="examples/spiffe-token-exchange-demo/podman/provider-profile.yaml">
id: spiffe-token-exchange-demo-podman
display_name: SPIFFE token exchange demo (Podman)
description: Dynamic token exchange for local Podman alpha/beta demo services using stored user subject tokens and SPIFFE JWT-SVID authentication
category: other
credentials:
  - name: subject_token
    description: Demo user subject token stored for gateway-side token exchange only
    required: true
  - name: access_token
    description: Access token obtained via RFC 8693 token exchange
    required: false
    auth_style: bearer
    header_name: Authorization
    token_grant:
      grant_type: token_exchange
      token_endpoint: __TOKEN_ISSUER_BASE_URL__/token
      audience: demo-default
      jwt_svid_audience: __TOKEN_ISSUER_BASE_URL__
      client_assertion_type: urn:ietf:params:oauth:client-assertion-type:jwt-spiffe
      scopes: [demo]
      cache_ttl_seconds: 60
      subject_token:
        source: provider_credential
        credential: subject_token
        subject_token_type: urn:ietf:params:oauth:token-type:access_token
      audience_overrides:
        - host: alpha-exchange
          port: 8080
          audience: alpha
          scopes: [alpha]
... (21 lines truncated)
</file>

<file path="examples/spiffe-token-exchange-demo/podman/README.md">
# Podman SPIFFE Token Exchange Demo

This variant runs the SPIFFE token exchange demo with local Podman containers
instead of Kubernetes workloads.

The first version is intentionally single-sandbox. The script creates one
concrete SPIRE registration entry for the sandbox after OpenShell creates it.
It does not rely on SPIRE templating one entry into many per-sandbox SPIFFE IDs.

## What Runs

`demo.sh` starts these local Podman containers on the `openshell` network by
default:

| Container | Purpose |
|---|---|
| `openshell-spiffe-demo-spire-server` | Local SPIRE server |
| `openshell-spiffe-demo-spire-agent` | Local SPIRE agent with a Workload API socket |
| `openshell-spiffe-demo-spire-oidc` | SPIRE OIDC discovery provider for JWKS |
| `openshell-spiffe-demo-token-issuer` | Dummy IdP/token exchange endpoint |
| `openshell-spiffe-demo-alpha` | Protected alpha service |
| `openshell-spiffe-demo-beta` | Protected beta service |

The OpenShell gateway is not started by this script. Start it separately with
the Podman driver and SPIFFE provider token grant settings.

For the most self-contained path, set `START_GATEWAY=1`. The script starts a
gateway container on the same Podman network as the token issuer and protected
services. That makes Podman's DNS alias
`token-exchange-issuer.default.svc.cluster.local` resolve inside the gateway
... (287 lines truncated)
</file>

<file path="examples/spiffe-token-exchange-demo/podman/start-gateway.sh">
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${SCRIPT_DIR}/spire/common.sh"
require_cmd podman
require_cmd curl
require_cmd openssl
if [[ -n "${SPIRE_AGENT_ENV_FILE:-}" ]]; then
    source "$SPIRE_AGENT_ENV_FILE"
fi
GATEWAY_CONTAINER="${GATEWAY_CONTAINER:-openshell-spiffe-demo-gateway}"
GATEWAY_IMAGE="${GATEWAY_IMAGE:-ghcr.io/nvidia/openshell/gateway:latest}"
GATEWAY_ID="${GATEWAY_ID:-podman-spiffe-demo}"
GATEWAY_PORT="${GATEWAY_PORT:-8888}"
GATEWAY_HEALTH_PORT="${GATEWAY_HEALTH_PORT:-8889}"
GATEWAY_STATE_DIR="${GATEWAY_STATE_DIR:-}"
GATEWAY_ENV_FILE="${GATEWAY_ENV_FILE:-}"
SANDBOX_IMAGE="${SANDBOX_IMAGE:-}"
SUPERVISOR_IMAGE="${SUPERVISOR_IMAGE:-}"
SANDBOX_IMAGE_PULL_POLICY="${SANDBOX_IMAGE_PULL_POLICY:-if_not_present}"
PODMAN_STOP_TIMEOUT_SECS="${PODMAN_STOP_TIMEOUT_SECS:-3}"
GATEWAY_OIDC_ISSUER="${GATEWAY_OIDC_ISSUER:-}"
GATEWAY_OIDC_AUDIENCE="${GATEWAY_OIDC_AUDIENCE:-openshell-cli}"
GATEWAY_OIDC_JWKS_TTL_SECS="${GATEWAY_OIDC_JWKS_TTL_SECS:-3600}"
GATEWAY_OIDC_ROLES_CLAIM="${GATEWAY_OIDC_ROLES_CLAIM:-realm_access.roles}"
GATEWAY_OIDC_ADMIN_ROLE="${GATEWAY_OIDC_ADMIN_ROLE:-openshell-admin}"
GATEWAY_OIDC_USER_ROLE="${GATEWAY_OIDC_USER_ROLE:-openshell-user}"
GATEWAY_OIDC_SCOPES_CLAIM="${GATEWAY_OIDC_SCOPES_CLAIM:-}"
GATEWAY_OIDC_CLIENT_ID="${GATEWAY_OIDC_CLIENT_ID:-openshell-cli}"
GATEWAY_OIDC_LOGIN_SCOPES="${GATEWAY_OIDC_LOGIN_SCOPES:-}"
if [[ -z "${GATEWAY_ALLOW_UNAUTHENTICATED_USERS:-}" ]]; then
... (174 lines truncated)
</file>

<file path="examples/spiffe-token-exchange-demo/demo.sh">
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROFILE_FILE="${SCRIPT_DIR}/provider-profile.yaml"
K8S_DIR="${SCRIPT_DIR}/k8s"
SANDBOX_NAME="${SANDBOX_NAME:-spiffe-token-demo}"
PROVIDER_NAME="${PROVIDER_NAME:-spiffe-token-exchange-demo}"
PROFILE_ID="${PROFILE_ID:-spiffe-token-exchange-demo}"
PORT_FORWARD_PORT="${PORT_FORWARD_PORT:-8097}"
TOKEN_ISSUER_PORT="${TOKEN_ISSUER_PORT:-18080}"
GATEWAY_ENDPOINT="${GATEWAY_ENDPOINT:-https://127.0.0.1:${PORT_FORWARD_PORT}}"
KEEP_SANDBOX="${KEEP_SANDBOX:-0}"
ISOLATED_CONFIG="${ISOLATED_CONFIG:-0}"
ACCESS_TOKEN_SECRET="${ACCESS_TOKEN_SECRET:-$(openssl rand -hex 32)}"
TEMP_CONFIG_HOME=""
if [[ "$ISOLATED_CONFIG" == "1" ]]; then
    TEMP_CONFIG_HOME="$(mktemp -d)"
    export XDG_CONFIG_HOME="$TEMP_CONFIG_HOME"
fi
default_gateway_name() {
    if [[ -n "${GATEWAY_NAME:-}" ]]; then
        printf "%s\n" "$GATEWAY_NAME"
        return
    fi
    if [[ -n "${OPENSHELL_GATEWAY:-}" ]]; then
        printf "%s\n" "$OPENSHELL_GATEWAY"
        return
    fi
    local config_home="${XDG_CONFIG_HOME:-$HOME/.config}"
    if [[ -s "${config_home}/openshell/active_gateway" ]]; then
        head -n1 "${config_home}/openshell/active_gateway"
... (156 lines truncated)
</file>

<file path="examples/spiffe-token-exchange-demo/provider-profile.yaml">
id: spiffe-token-exchange-demo
display_name: SPIFFE token exchange demo
description: Dynamic token exchange for alpha/beta demo services using stored user subject tokens and SPIFFE JWT-SVID authentication
category: other
credentials:
  - name: subject_token
    description: Demo user subject token stored for gateway-side token exchange only
    required: true
  - name: access_token
    description: Access token obtained via RFC 8693 token exchange
    required: false
    auth_style: bearer
    header_name: Authorization
    token_grant:
      grant_type: token_exchange
      token_endpoint: http://token-exchange-issuer.default.svc.cluster.local/token
      audience: demo-default
      jwt_svid_audience: http://token-exchange-issuer.default.svc.cluster.local
      client_assertion_type: urn:ietf:params:oauth:client-assertion-type:jwt-spiffe
      scopes: [demo]
      cache_ttl_seconds: 60
      subject_token:
        source: provider_credential
        credential: subject_token
        subject_token_type: urn:ietf:params:oauth:token-type:access_token
      audience_overrides:
        - host: alpha-exchange.default.svc.cluster.local
          port: 80
          audience: alpha
          scopes: [alpha]
... (21 lines truncated)
</file>

<file path="examples/spiffe-token-exchange-demo/README.md">
# SPIFFE Token Exchange Demo

This example validates provider dynamic token exchange using SPIFFE JWT-SVIDs.
It runs alongside `examples/spiffe-token-grant-demo` but exercises the
`token_exchange` grant type instead of `client_credentials`.

The demo deploys three in-cluster workloads:

| Workload | Purpose |
|---|---|
| `token-exchange-issuer` | Issues a demo user subject token, performs the gateway intermediate token exchange, and performs the supervisor final token exchange |
| `alpha-exchange` | Requires a final bearer token with audience and scope `alpha` |
| `beta-exchange` | Requires a final bearer token with audience and scope `beta` |

The OpenShell provider profile in `provider-profile.yaml` declares a stored
`subject_token` credential and a runtime `access_token` credential with
`token_grant.grant_type: token_exchange`. The subject token is stored for
gateway-side exchange only and is not injected into the sandbox environment.

The profile declares exact Kubernetes service hostnames for `alpha-exchange`
and `beta-exchange`. It intentionally does not set `allowed_ips`, because
cluster service CIDRs vary across Kubernetes installations.

When a sandbox curls `alpha-exchange` or `beta-exchange`:

1. The supervisor fetches its SPIFFE JWT-SVID.
2. The supervisor asks the gateway for an intermediate token.
3. The gateway verifies the supervisor SVID, fetches its own gateway JWT-SVID,
   and exchanges the stored provider `subject_token` at `token-exchange-issuer`.
   The requested intermediate audience is the supervisor SPIFFE ID.
... (199 lines truncated)
</file>

<file path="examples/spiffe-token-grant-demo/k8s/kustomization.yaml">
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
generatorOptions:
  disableNameSuffixHash: true
configMapGenerator:
  - name: openshell-spiffe-token-demo-scripts
    files:
      - token-issuer.js
      - protected-service.js
resources:
  - workloads.yaml
</file>

<file path="examples/spiffe-token-grant-demo/k8s/protected-service.js">
function b64urlDecode(value)
⋮----
function b64urlEncode(value)
⋮----
function parseJwt(jwt)
⋮----
function verifyAccessToken(jwt)
⋮----
function text(res, status, body)
</file>

<file path="examples/spiffe-token-grant-demo/k8s/token-issuer.js">
function b64urlDecode(value)
⋮----
function b64urlEncode(value)
⋮----
function parseJwt(jwt)
⋮----
async function jwks()
⋮----
function hasAudience(payload, expected)
⋮----
async function verifyJwtSvid(jwt)
⋮----
function signAccessToken(payload)
⋮----
function json(res, status, body)
⋮----
async function bodyText(req)
⋮----
async function handleToken(req, res)
</file>

<file path="examples/spiffe-token-grant-demo/k8s/workloads.yaml">
apiVersion: apps/v1
kind: Deployment
metadata:
  name: token-issuer
  namespace: default
  labels:
    app: token-issuer
spec:
  replicas: 1
  selector:
    matchLabels:
      app: token-issuer
  template:
    metadata:
      labels:
        app: token-issuer
    spec:
      containers:
        - name: token-issuer
          image: node:22-alpine
          imagePullPolicy: IfNotPresent
          command: ["node", "/demo/token-issuer.js"]
          ports:
            - name: http
              containerPort: 8080
          env:
            - name: ACCESS_TOKEN_SECRET
              valueFrom:
                secretKeyRef:
                  name: openshell-spiffe-token-demo
... (167 lines truncated)
</file>

<file path="examples/spiffe-token-grant-demo/demo.sh">
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROFILE_FILE="${SCRIPT_DIR}/provider-profile.yaml"
K8S_DIR="${SCRIPT_DIR}/k8s"
SANDBOX_NAME="${SANDBOX_NAME:-spiffe-token-demo}"
PROVIDER_NAME="${PROVIDER_NAME:-spiffe-token-demo}"
PROFILE_ID="${PROFILE_ID:-spiffe-token-demo}"
PORT_FORWARD_PORT="${PORT_FORWARD_PORT:-8097}"
GATEWAY_ENDPOINT="${GATEWAY_ENDPOINT:-http://127.0.0.1:${PORT_FORWARD_PORT}}"
KEEP_SANDBOX="${KEEP_SANDBOX:-0}"
ACCESS_TOKEN_SECRET="${ACCESS_TOKEN_SECRET:-$(openssl rand -hex 32)}"
TEMP_CONFIG_HOME=""
if [[ -z "${XDG_CONFIG_HOME:-}" ]]; then
    TEMP_CONFIG_HOME="$(mktemp -d)"
    export XDG_CONFIG_HOME="$TEMP_CONFIG_HOME"
fi
PF_PID=""
cleanup() {
    if [[ "$KEEP_SANDBOX" != "1" ]]; then
        openshell --gateway-endpoint "$GATEWAY_ENDPOINT" sandbox delete "$SANDBOX_NAME" >/dev/null 2>&1 || true
    fi
    if [[ -n "$PF_PID" ]]; then
        kill "$PF_PID" >/dev/null 2>&1 || true
    fi
    if [[ -n "$TEMP_CONFIG_HOME" ]]; then
        rm -rf "$TEMP_CONFIG_HOME"
    fi
}
trap cleanup EXIT
run() {
... (84 lines truncated)
</file>

<file path="examples/spiffe-token-grant-demo/provider-profile.yaml">
id: spiffe-token-demo
display_name: SPIFFE token grant demo
description: Dynamic token grant for alpha/beta demo services using SPIFFE JWT-SVID authentication
category: other
credentials:
  - name: access_token
    description: Access token obtained via SPIFFE JWT client assertion grant
    required: false
    auth_style: bearer
    header_name: Authorization
    token_grant:
      token_endpoint: http://token-issuer.default.svc.cluster.local/token
      audience: demo-default
      jwt_svid_audience: http://token-issuer.default.svc.cluster.local
      client_assertion_type: urn:ietf:params:oauth:client-assertion-type:jwt-spiffe
      scopes: [demo]
      cache_ttl_seconds: 60
      audience_overrides:
        - host: alpha.default.svc.cluster.local
          port: 80
          audience: alpha
          scopes: [alpha]
        - host: beta.default.svc.cluster.local
          port: 80
          audience: beta
          scopes: [beta]
endpoints:
  - host: alpha.default.svc.cluster.local
    port: 80
    protocol: rest
... (17 lines truncated)
</file>

<file path="examples/spiffe-token-grant-demo/README.md">
# SPIFFE Token Grant Demo

This example validates provider dynamic token grants using SPIFFE JWT-SVIDs.
It mirrors the PR 1781 alpha/beta flow without configuring OpenShell gateway
OIDC authentication.

The demo deploys three in-cluster workloads:

| Workload | Purpose |
|---|---|
| `token-issuer` | Accepts a SPIFFE JWT-SVID client assertion and returns a short-lived demo access token |
| `alpha` | Requires a bearer token with audience and scope `alpha` |
| `beta` | Requires a bearer token with audience and scope `beta` |

The OpenShell provider profile in `provider-profile.yaml` configures a dynamic
credential with `token_grant`. When a sandbox curls `alpha` or `beta`, the
sandbox supervisor fetches a JWT-SVID from the SPIFFE Workload API, exchanges it
at `token-issuer`, and injects the returned access token into the outbound HTTP
request.

## Prerequisites

- A Kubernetes OpenShell dev cluster.
- SPIRE enabled for provider token grants.
- OpenShell configured with the Kubernetes ServiceAccount supervisor bootstrap
  path. Gateway end-user OIDC is not required for this demo.

For the Helm dev environment, deploy with the SPIRE releases and
`ci/values-spire.yaml` enabled in `deploy/helm/openshell/skaffold.yaml`.

... (109 lines truncated)
</file>

<file path="examples/supervisor-middleware-content-guard/src/main.rs">
use std::net::SocketAddr;
use std::ops::Range;
⋮----
use clap::Parser;
⋮----
use prost_types::Struct;
use prost_types::value::Kind;
use tokio::sync::mpsc;
use tokio_stream::wrappers::ReceiverStream;
⋮----
use tonic::transport::Server;
⋮----
struct Cli {
⋮----
enum Mode {
⋮----
struct GuardConfig {
⋮----
impl GuardConfig {
fn parse(config: Option<&Struct>) -> Result<Self, String> {
let config = config.ok_or_else(|| "config is required".to_string())?;
⋮----
.keys()
.find(|field| !matches!(field.as_str(), "mode" | "terms" | "replacement"))
⋮----
return Err(format!("unsupported config field '{field}'"));
⋮----
let mode = match optional_string_field(config, "mode")?.unwrap_or("redact") {
⋮----
_ => return Err("config.mode must be 'redact' or 'deny'".into()),
... (481 lines truncated)
</file>

<file path="examples/supervisor-middleware-content-guard/Cargo.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

[workspace]

[package]
name = "openshell-supervisor-middleware-content-guard"
description = "Example OpenShell supervisor middleware service"
version = "0.0.0"
edition = "2024"
rust-version = "1.94"
license = "Apache-2.0"
publish = false

[dependencies]
clap = { version = "4.5", features = ["derive"] }
openshell-core = { path = "../../crates/openshell-core", default-features = false }
prost-types = "0.14"
tokio = { version = "1.43", features = ["macros", "rt-multi-thread"] }
tokio-stream = "0.1"
tonic = { version = "0.14", features = ["transport"] }

[dev-dependencies]
openshell-policy = { path = "../../crates/openshell-policy" }

[[bin]]
name = "supervisor-middleware-content-guard"
path = "src/main.rs"
</file>

<file path="examples/supervisor-middleware-content-guard/policy.yaml">
version: 1
network_middlewares:
  prototype-content-guard:
    name: Prototype content guard
    middleware: content-guard-example
    order: 10
    config:
      mode: redact
      terms:
        - prototype-secret
        - internal-only
      replacement: "[FILTERED]"
    on_error: fail_closed
    endpoints:
      include:
        - httpbin.org
        - host.openshell.internal
network_policies:
  httpbin:
    name: httpbin
    endpoints:
      - host: httpbin.org
        port: 443
        protocol: rest
        rules:
          - allow:
              method: POST
              path: /anything
    binaries:
      - path: /usr/bin/curl
... (28 lines truncated)
</file>

<file path="examples/supervisor-middleware-content-guard/README.md">
<!--
SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
SPDX-License-Identifier: Apache-2.0
-->

# Supervisor Middleware Content Guard

> [!WARNING]
> Supervisor middleware is a research preview. Its policy and service contracts may change without compatibility guarantees. Use it only to prototype and evaluate middleware integrations.

This configured-literal guard applies the same case-sensitive terms to UTF-8 HTTP request bodies, complete HTTP response bodies, and client WebSocket text messages. It is not a general PII detector.

> [!WARNING]
> This intentionally simple implementation demonstrates the supervisor middleware service contract. It is not a complete or reliable content guard and must not be used as a security control. It handles only UTF-8 HTTP request and response bodies and WebSocket text messages with case-sensitive literal terms, merges overlapping literal match ranges before redaction, and does not address encodings, transformations, normalization, binary WebSocket messages, upstream-to-client messages, or adversarial inputs that a production content guard must handle.

## Prerequisites

Install `cargo`, `curl`, `jq`, `openssl`, `mise`, and `uv` with Python 3 on the host before running the smoke script. Start Docker or Podman. The supervisor image build uses the repository's Linux cross-compilation toolchain, including `cargo-zigbuild` and Zig on macOS. Install the repository's mise tools before running it.

## Run the smoke example

Run the end-to-end smoke suite to build a local gateway and sandbox supervisor, start the content-guard service, create a sandbox, and send the same request body to two destinations:

```shell
./examples/supervisor-middleware-content-guard/smoke.sh --test-suite
```

The first request goes to `httpbin.org`, which matches the middleware endpoint selector. The response contains `[FILTERED]` instead of `prototype-secret`. The second request goes to `httpbingo.org`, which is allowed by network policy but does not match the middleware selector. Its response contains the original `prototype-secret` value. The smoke suite asserts both results and cleans up the sandbox, gateway, and middleware processes.

Run the script without flags to leave the local stack running for interactive use:
... (120 lines truncated)
</file>

<file path="examples/supervisor-middleware-content-guard/smoke.sh">
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
EXAMPLE_DIR="$ROOT/examples/supervisor-middleware-content-guard"
RUN_TEST_SUITE=0
PRINT_CONFIG=0
usage() {
  cat <<EOF
usage: $0 [--test-suite|--test|--print-config]
Without flags, starts a local gateway and content-guard service, creates an
example sandbox, and keeps the stack running for interactive use.
Options:
  --test-suite, --test  Run guarded and unguarded request checks, then stop.
  --print-config        Print the generated middleware gateway config, then stop.
  -h, --help            Show this help.
Environment:
  CONTENT_GUARD_SMOKE_HOST  Non-loopback host address reachable from both the
                            gateway and sandbox containers.
  CONTENT_GUARD_SMOKE_DRIVER
                            Compute driver: docker (default) or podman.
EOF
}
while [[ "$#" -gt 0 ]]; do
  case "$1" in
    --test-suite | --test)
      RUN_TEST_SUITE=1
      shift
      ;;
    --print-config)
      PRINT_CONFIG=1
      shift
... (461 lines truncated)
</file>

<file path="examples/supervisor-middleware-content-guard/upstream.py">
class Handler(BaseHTTPRequestHandler)
⋮----
def do_GET(self)
⋮----
bodies = {
body = bodies.get(self.path, b"not found")
</file>

<file path="examples/transparent-tcp-redis/demo.sh">
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
POLICY_FILE="${SCRIPT_DIR}/policy.yaml"
CLIENT_FILE="${SCRIPT_DIR}/redis_client.py"
SANDBOX_NAME="${SANDBOX_NAME:-tcp-redis-demo}"
REDIS_CONTAINER="${REDIS_CONTAINER:-openshell-transparent-tcp-redis-demo}"
DOCKER_NETWORK="${OPENSHELL_DOCKER_NETWORK:-openshell-docker}"
REDIS_IMAGE="${REDIS_IMAGE:-redis:7-alpine}"
REDIS_REAL_IP=""
SANDBOX_CREATED=0
REDIS_CREATED=0
cleanup() {
    local status=$?
    local ocsf_pattern
    local relevant_logs
    local sandbox_logs
    trap - EXIT
    if [[ "$SANDBOX_CREATED" == "1" ]]; then
        printf '\nRelevant OCSF events:\n'
        ocsf_pattern='\[OCSF \].*(Policy DNS mapped|Transparent TCP mapping_id=|policy_dns_ineligible|transparent_tcp_port_mismatch|BYPASS_DETECT)'
        sleep 1
        if sandbox_logs="$(openshell logs "$SANDBOX_NAME" \
            --source sandbox \
            --since 10m \
            -n 500 2>&1)"; then
            if relevant_logs="$(printf '%s\n' "$sandbox_logs" | grep -E "$ocsf_pattern")"; then
                printf '%s\n' "$relevant_logs"
            else
                printf 'No relevant policy DNS or transparent TCP events found.\n'
            fi
... (91 lines truncated)
</file>

<file path="examples/transparent-tcp-redis/policy.yaml">
version: 1
filesystem_policy:
  include_workdir: true
  read_only: [/usr, /lib, /proc, /dev/urandom, /app, /etc, /var/log]
  read_write: [/sandbox, /tmp, /dev/null]
landlock:
  compatibility: best_effort
network_policies:
  redis:
    name: redis-native-tcp
    endpoints:
      - host: redis.openshell.demo
        port: 6379
        protocol: tcp
        allowed_ips:
          - 10.0.0.0/8
          - 172.16.0.0/12
          - 192.168.0.0/16
    binaries:
      - { path: "/**" }
</file>

<file path="examples/transparent-tcp-redis/README.md">
# Transparent TCP Redis

This example connects a Docker-backed OpenShell sandbox to Redis with a native
TCP client. It does not use the HTTP forward proxy.

The demo:

1. Starts Redis on the OpenShell-managed Docker network.
2. Creates a sandbox with an endpoint that explicitly uses `protocol: tcp`.
3. Resolves the policy hostname to an ephemeral synthetic address.
4. Opens a native TCP socket and runs Redis `PING`, `SET`, `GET`, and `DEL` commands.
5. Confirms that policy blocks an unapproved hostname, the approved hostname
   on the wrong port, and a direct connection to Redis's real IP.
6. Prints the sandbox log stream, including OCSF DNS and TCP decisions.
7. Deletes the sandbox and Redis container, including after a failure.

OpenShell authorizes the hostname and port before policy DNS publishes the
synthetic address. When the client connects, OpenShell maps that address back
to the approved endpoint, rechecks the process and policy, and dials a pinned
real Redis address. A direct connection to the Redis container IP remains
blocked.

## Prerequisites

- A Docker-backed OpenShell gateway built from the transparent TCP branch
- The `openshell` and `docker` commands
- Access to pull `redis:7-alpine`

The Docker compute driver creates and uses the `openshell-docker` bridge by
default. The gateway process itself runs on the host; only sandbox supervisors
... (61 lines truncated)
</file>

<file path="examples/transparent-tcp-redis/redis_client.py">
HOST = "redis.openshell.demo"
PORT = 6379
KEY = "openshell:transparent-tcp-demo"
⋮----
def encode_command(*parts: str) -> bytes
⋮----
encoded = [part.encode() for part in parts]
request = [f"*{len(encoded)}\r\n".encode()]
⋮----
def read_response(stream)
⋮----
marker = stream.read(1)
⋮----
line = stream.readline().removesuffix(b"\r\n")
⋮----
length = int(line)
⋮----
value = stream.read(length)
⋮----
def command(connection: socket.socket, stream, *parts: str)
⋮----
result = read_response(stream)
⋮----
def expect_connection_blocked(label: str, host: str, port: int) -> None
⋮----
response = read_response(stream)
⋮----
def main() -> None
⋮----
addresses = sorted(
... (1 lines truncated)
</file>

<file path="examples/aws-s3-sts.md">
# Manual E2E Test: S3 Access via STS Credentials

This guide walks through an end-to-end test of an OpenShell sandbox accessing
AWS S3 using gateway-minted STS temporary credentials with proxy-side SigV4
re-signing. The sandbox never sees real AWS credentials — the proxy resolves
placeholders and signs requests on the fly.

## Prerequisites

- AWS CLI authenticated (`aws sts get-caller-identity` succeeds)
- Podman running (`podman info` succeeds)
- OpenShell built from source with AWS STS refresh and SigV4 signing support

## 1. Create AWS test resources

Create an S3 bucket and an IAM role the gateway can assume:

```shell
BUCKET="openshell-sts-test-$(date +%s)"
ACCOUNT=$(aws sts get-caller-identity --query Account --output text)

aws s3 mb "s3://${BUCKET}" --region us-east-1

aws iam create-role \
  --role-name openshell-sts-test-role \
  --assume-role-policy-document '{
    "Version": "2012-10-17",
    "Statement": [{
      "Effect": "Allow",
      "Principal": {"AWS": "arn:aws:iam::'${ACCOUNT}':root"},
... (247 lines truncated)
</file>

<file path="examples/gateway-deploy-connect.md">
# Deploying and Connecting to a Gateway

Deploy or register an OpenShell gateway, verify it is reachable, and run your first sandbox. This example covers Helm-managed Kubernetes gateways, existing gateway endpoints, and Cloudflare-fronted deployments.

## Prerequisites

- OpenShell CLI installed (`openshell`)
- A reachable gateway endpoint, or access to a Kubernetes cluster where you can install the Helm chart
- For Kubernetes installs, a CNI that enforces ingress and egress `NetworkPolicy` in sandbox namespaces

## Helm Deployment

Install the gateway into a Kubernetes cluster you manage:

```bash
kubectl create namespace openshell
helm upgrade --install openshell deploy/helm/openshell \
  --namespace openshell \
  --set server.disableTls=true \
  --set service.type=ClusterIP
```

For local evaluation, forward the service and register the forwarded endpoint:

```bash
kubectl -n openshell port-forward svc/openshell 8080:8080
openshell gateway add http://127.0.0.1:8080 --local --name local
```

Production deployments should keep TLS enabled or place the gateway behind a trusted TLS-terminating ingress, load balancer, or access proxy.
... (101 lines truncated)
</file>

<file path="examples/sync-files.md">
# Syncing Files To and From a Sandbox

Move code, data, and artifacts between your local machine and an OpenShell
sandbox using `openshell sandbox upload` and `openshell sandbox download`.

## Push local files into a sandbox

Upload your current project directory into `/sandbox` on the sandbox:

```bash
openshell sandbox upload my-sandbox .
```

Push a specific directory to a custom destination:

```bash
openshell sandbox upload my-sandbox ./src /sandbox/src
```

Push a single file:

```bash
openshell sandbox upload my-sandbox ./config.yaml /sandbox/config.yaml
```

## Pull files from a sandbox

Download sandbox output to your local machine:

```bash
... (44 lines truncated)
</file>

<file path="examples/vscode-remote-sandbox.md">
# Open VSCode in a Sandbox

Connect VSCode to a running sandbox using the
[Remote - SSH](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-ssh)
extension so you get a full IDE experience inside the sandbox environment.

## Prerequisites

- A running OpenShell gateway (`mise run gateway:docker` for local development)
- [VSCode](https://code.visualstudio.com/) with the
  [Remote - SSH](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-ssh)
  extension installed
- The `openshell` CLI on your `PATH`

## Quick start

### 1. Create and open the sandbox in VS Code

```bash
openshell sandbox create --editor vscode --name my-sandbox
```

This launches VS Code directly into `/sandbox`, keeps the sandbox alive for the
remote session, and installs an OpenShell-managed SSH include file so your main
`~/.ssh/config` stays clean.

### 2. Reconnect later

To reopen an existing sandbox in VS Code:

... (49 lines truncated)
</file>

<file path="fern/components/CustomFooter.tsx">

</file>

<file path="fern/docs.yml">
instances:
  - url: openshell.docs.buildwithfern.com/openshell
    custom-domain: docs.nvidia.com/openshell
    multi-source: true
title: NVIDIA OpenShell
global-theme: nvidia
footer: ./components/CustomFooter.tsx
layout:
  searchbar-placement: header
  page-width: 1376px
  sidebar-width: 248px
  content-width: 812px
  tabs-placement: header
  hide-feedback: true
colors:
  accentPrimary:
    dark: "#76B900"
    light: "#76B900"
  background:
    light: "#FFFFFF"
    dark: "#000000"
theme:
  page-actions: toolbar
  footer-nav: minimal
logo:
  dark: ./assets/NVIDIA_dark.svg
  light: ./assets/NVIDIA_light.svg
  height: 20
  href: /openshell
  right-text: OpenShell
... (74 lines truncated)
</file>

<file path="fern/fern.config.json">
{
  "organization": "nvidia",
  "version": "5.112.0"
}
</file>

<file path="fern/README.md">
# Fern documentation site

OpenShell uses [Fern](https://buildwithfern.com/) to validate, preview, and publish the documentation at [docs.nvidia.com/openshell](https://docs.nvidia.com/openshell/). This directory contains the site configuration and presentation files. The documentation content lives in `docs/`.

## Repository layout

| Path | Purpose |
|---|---|
| `docs/` | MDX pages, navigation in `docs/index.yml`, and page-specific components. |
| `fern/docs.yml` | Site, theme, version, redirect, and navigation configuration. |
| `fern/fern.config.json` | Fern organization and pinned CLI version. |
| `fern/components/` | Shared site components. |
| `fern/assets/` | Logos and other shared assets. |
| `fern/main.css` | Site-wide styles. |

In a normal source checkout, `fern/docs.yml` points the `dev` version at `docs/index.yml`. Release automation builds the multi-version configuration on the generated `docs-website` branch and maps the source documentation to the channel being published.

## Local development

Start a local Fern server from the repository root:

```shell
mise run docs:serve
```

Validate the configuration, navigation, and links without starting a server:

```shell
mise run docs
```
... (45 lines truncated)
</file>

<file path="nix/test-guest/configuration/tasks/podman-rootless/fedora.yml">
---
- name: Install Fedora rootless Podman prerequisites
  ansible.builtin.dnf:
    name:
      - fuse-overlayfs
      - passt
      - shadow-utils
      - shadow-utils-subid
    state: present
</file>

<file path="nix/test-guest/configuration/tasks/podman-rootless/shared.yml">
---
- name: Verify test user subordinate ID mappings
  ansible.builtin.command:
    argv:
      - awk
      - "-F:"
      - >-
        $1 == "openshell" && $2 ~ /^[0-9]+$/ &&
        $3 ~ /^[1-9][0-9]*$/ && $3 >= 65536 { found = 1 }
        END { exit !found }
      - "{{ item }}"
  loop:
    - /etc/subuid
    - /etc/subgid
  changed_when: false
- name: Enable the rootless Podman API socket
  ansible.builtin.systemd_service:
    name: podman.socket
    scope: user
    enabled: true
    state: started
  become: false
- name: Verify rootless Podman
  ansible.builtin.command:
    cmd: podman info
  become: false
  changed_when: false
- name: Verify rootless Podman mode
  ansible.builtin.command:
    argv:
... (20 lines truncated)
</file>

<file path="nix/test-guest/configuration/tasks/podman-rootless/ubuntu.yml">
---
- name: Install Ubuntu rootless Podman prerequisites
  ansible.builtin.apt:
    name:
      - apparmor
      - fuse-overlayfs
      - passt
      - uidmap
    state: present
- name: Allow pasta to receive Podman stop signals
  ansible.builtin.lineinfile:
    path: /etc/apparmor.d/usr.bin.pasta
    insertafter: "^  include <abstractions/pasta>$"
    line: "  signal (receive) peer=podman,"
    state: present
  register: pasta_apparmor_profile
- name: Reload pasta AppArmor profile
  ansible.builtin.command:
    argv:
      - apparmor_parser
      - --replace
      - /etc/apparmor.d/usr.bin.pasta
  when: pasta_apparmor_profile.changed
  changed_when: pasta_apparmor_profile.changed
</file>

<file path="nix/test-guest/configuration/tasks/podman-common.yml">
---
- name: Refresh Ubuntu package metadata
  ansible.builtin.apt:
    update_cache: true
  when: ansible_facts.distribution == "Ubuntu"
- name: Install Podman
  ansible.builtin.package:
    name: podman
    state: present
- name: Create test-guest state directory
  ansible.builtin.file:
    path: /etc/openshell-test-guest
    state: directory
    mode: "0755"
</file>

<file path="nix/test-guest/configuration/docker.yml">
---
- name: Configure Docker
  hosts: test_vm
  become: true
  gather_facts: true
  tasks:
    - name: Validate Docker support
      ansible.builtin.assert:
        that:
          - ansible_facts.distribution in ["Ubuntu", "Rocky"]
        fail_msg: >-
          Docker is supported on Ubuntu and Rocky in this prototype,
          not {{ ansible_facts.distribution }}.
    - name: Refresh Ubuntu package metadata
      ansible.builtin.apt:
        update_cache: true
      when: ansible_facts.distribution == "Ubuntu"
    - name: Install Docker on Ubuntu
      ansible.builtin.apt:
        name: docker.io
        state: present
        install_recommends: false
      when: ansible_facts.distribution == "Ubuntu"
    - name: Configure the Docker CE repository on Rocky
      ansible.builtin.get_url:
        url: https://download.docker.com/linux/centos/docker-ce.repo
        dest: /etc/yum.repos.d/docker-ce.repo
        mode: "0644"
      when: ansible_facts.distribution == "Rocky"
    - name: Install Docker on Rocky
... (30 lines truncated)
</file>

<file path="nix/test-guest/configuration/podman-rootful.yml">
---
- name: Configure rootful Podman
  hosts: test_vm
  become: true
  gather_facts: true
  tasks:
    - name: Install common Podman prerequisites
      ansible.builtin.import_tasks: tasks/podman-common.yml
    - name: Enable the rootful Podman API socket
      ansible.builtin.systemd_service:
        name: podman.socket
        enabled: true
        state: started
    - name: Verify rootful Podman mode
      ansible.builtin.command:
        argv:
          - podman
          - --url
          - unix:///run/podman/podman.sock
          - info
          - --format
          - "{% raw %}{{.Host.Security.Rootless}}{% endraw %}"
      changed_when: false
      register: podman_rootful_info
      failed_when: podman_rootful_info.stdout != "false"
    - name: Record rootful Podman mode
      ansible.builtin.copy:
        dest: /etc/openshell-test-guest/podman-mode
        content: "rootful\n"
        mode: "0644"
... (1 lines truncated)
</file>

<file path="nix/test-guest/configuration/podman-rootless.yml">
---
- name: Configure rootless Podman
  hosts: test_vm
  become: true
  gather_facts: true
  tasks:
    - name: Validate rootless Podman support
      ansible.builtin.assert:
        that:
          - >-
            ansible_facts.distribution == "Fedora" or
            (ansible_facts.distribution == "Ubuntu" and
             ansible_facts.distribution_version is version("26.04", ">="))
        fail_msg: >-
          Rootless Podman requires Fedora or Ubuntu 26.04 or newer, not
          {{ ansible_facts.distribution }} {{ ansible_facts.distribution_version }}.
    - name: Install common Podman prerequisites
      ansible.builtin.import_tasks: tasks/podman-common.yml
    - name: Configure rootless Podman on Ubuntu
      ansible.builtin.import_tasks: tasks/podman-rootless/ubuntu.yml
      when: ansible_facts.distribution == "Ubuntu"
    - name: Configure rootless Podman on Fedora
      ansible.builtin.import_tasks: tasks/podman-rootless/fedora.yml
      when: ansible_facts.distribution == "Fedora"
    - name: Configure shared rootless Podman settings
      ansible.builtin.import_tasks: tasks/podman-rootless/shared.yml
    - name: Record rootless Podman mode
      ansible.builtin.copy:
        dest: /etc/openshell-test-guest/podman-mode
        content: "rootless\n"
... (2 lines truncated)
</file>

<file path="nix/test-guest/configuration/selinux.yml">
---
- name: Configure SELinux
  hosts: test_vm
  become: true
  gather_facts: true
  tasks:
    - name: Validate SELinux support
      ansible.builtin.assert:
        that:
          - ansible_facts.os_family == "RedHat"
        fail_msg: >-
          SELinux configuration is supported only on CentOS, Fedora, and Rocky,
          not {{ ansible_facts.distribution }}.
    - name: Install SELinux tools
      ansible.builtin.package:
        name: policycoreutils
        state: present
    - name: Read the current SELinux mode
      ansible.builtin.command:
        cmd: getenforce
      register: selinux_current
      changed_when: false
    - name: Reject a fully disabled SELinux system
      ansible.builtin.assert:
        that:
          - selinux_current.stdout != "Disabled"
        fail_msg: >-
          SELinux is disabled and cannot be enabled live. Set SELINUX=enforcing
          and reboot the guest before applying this configuration.
    - name: Persist enforcing mode
... (20 lines truncated)
</file>

<file path="nix/test-guest/configuration/snapd.yml">
---
- name: Configure snapd
  hosts: test_vm
  become: true
  gather_facts: true
  tasks:
    - name: Validate snapd support
      ansible.builtin.assert:
        that:
          - ansible_facts.distribution == "Ubuntu"
        fail_msg: >-
          snapd is currently configured only for Ubuntu test guests,
          not {{ ansible_facts.distribution }}.
    - name: Refresh Ubuntu package metadata
      ansible.builtin.apt:
        update_cache: true
    - name: Install snapd
      ansible.builtin.apt:
        name: snapd
        state: present
        install_recommends: false
    - name: Start snapd socket activation
      ansible.builtin.systemd_service:
        name: snapd.socket
        enabled: true
        state: started
    - name: Wait for snapd seed
      ansible.builtin.command:
        cmd: snap wait system seed.loaded
      changed_when: false
... (1 lines truncated)
</file>

<file path="nix/test-guest/provisioners/roles/gateway-podman/tasks/development-gateway.yml">
---
- name: Publish development gateway paths
  ansible.builtin.set_fact:
    openshell_gateway_state_root: "{{ openshell_gateway_service_home }}/.local/share/openshell-test-guest"
    openshell_gateway_config_home: "{{ openshell_gateway_service_home }}/.config"
- name: Create development gateway directories
  ansible.builtin.file:
    path: "{{ item }}"
    state: directory
    mode: "0700"
    owner: "{{ openshell_gateway_service_user }}"
    group: "{{ openshell_gateway_service_user }}"
  loop:
    - "{{ openshell_gateway_state_root }}"
    - "{{ openshell_gateway_state_root }}/xdg/config"
    - "{{ openshell_gateway_state_root }}/xdg/cache"
    - "{{ openshell_gateway_state_root }}/xdg/data"
    - "{{ openshell_gateway_state_root }}/xdg/state"
    - "{{ openshell_gateway_config_home }}/systemd/user"
  become: true
- name: Generate development gateway credentials
  ansible.builtin.command:
    cmd: "{{ openshell_gateway_bin }} generate-certs --output-dir {{ openshell_gateway_state_root }}/pki"
    creates: "{{ openshell_gateway_state_root }}/pki/jwt/signing.pem"
  become: true
  become_user: "{{ openshell_gateway_service_user }}"
- name: Write development Podman gateway configuration
  ansible.builtin.copy:
    dest: "{{ openshell_gateway_state_root }}/gateway.toml"
    mode: "0600"
... (61 lines truncated)
</file>

<file path="nix/test-guest/provisioners/roles/gateway-podman/tasks/lifecycle.yml">
---
- name: Publish gateway user-manager environment
  ansible.builtin.set_fact:
    openshell_gateway_user_environment:
      HOME: "{{ openshell_gateway_service_home }}"
      XDG_RUNTIME_DIR: "/run/user/{{ openshell_gateway_service_uid }}"
      DBUS_SESSION_BUS_ADDRESS: "unix:path=/run/user/{{ openshell_gateway_service_uid }}/bus"
- name: Reload gateway user services
  ansible.builtin.systemd_service:
    daemon_reload: true
    scope: user
  environment: "{{ openshell_gateway_user_environment }}"
  become: true
  become_user: "{{ openshell_gateway_service_user }}"
- name: Start the gateway user service
  ansible.builtin.systemd_service:
    name: "{{ openshell_gateway_service }}"
    enabled: true
    state: started
    scope: user
  environment: "{{ openshell_gateway_user_environment }}"
  become: true
  become_user: "{{ openshell_gateway_service_user }}"
- name: Register the provisioned gateway with its service account
  ansible.builtin.command:
    cmd: "{{ openshell_cli_bin }} gateway add {{ openshell_gateway_endpoint }} --local --name test-guest"
  environment: "{{ openshell_gateway_user_environment }}"
  become: true
  become_user: "{{ openshell_gateway_service_user }}"
- name: Wait for gateway CLI health
... (42 lines truncated)
</file>

<file path="nix/test-guest/provisioners/roles/gateway-podman/tasks/main.yml">
---
- name: Read the configured Podman mode
  ansible.builtin.command:
    argv:
      - cat
      - /etc/openshell-test-guest/podman-mode
  register: openshell_podman_mode_command
  changed_when: false
- name: Publish the configured Podman mode
  ansible.builtin.set_fact:
    openshell_podman_mode: "{{ openshell_podman_mode_command.stdout | trim }}"
- name: Require an OpenShell installation
  ansible.builtin.assert:
    that:
      - openshell_install_source is defined
      - openshell_cli_bin is defined
      - openshell_gateway_bin is defined
      - openshell_gateway_service is defined
      - openshell_gateway_endpoint is defined
      - openshell_install_source in ['development', 'rpm']
      - openshell_podman_mode in ['rootless', 'rootful']
    fail_msg: >-
      gateway-podman requires an earlier OpenShell installation role and a
      podman-rootless or podman-rootful test-guest configuration.
- name: Select the Podman service account
  ansible.builtin.set_fact:
    openshell_podman_service_user: >-
      {{ 'root' if openshell_podman_mode == 'rootful' else 'openshell' }}
- name: Resolve the gateway service account
  ansible.builtin.getent:
... (29 lines truncated)
</file>

<file path="nix/test-guest/provisioners/roles/openshell-development/defaults/main.yml">
---
openshell_development_cli_bin: /usr/local/bin/openshell
openshell_development_gateway_bin: /usr/local/bin/openshell-gateway
openshell_development_sandbox_archive: /usr/local/lib/openshell-sandbox.tar
openshell_development_gateway_service: openshell-test-guest-gateway.service
openshell_development_gateway_endpoint: http://127.0.0.1:8080
openshell_development_supervisor_image: localhost/openshell/supervisor:test-guest
</file>

<file path="nix/test-guest/provisioners/roles/openshell-development/tasks/main.yml">
---
- name: Verify copied development artifacts
  ansible.builtin.stat:
    path: "{{ item }}"
  loop:
    - "{{ openshell_development_cli_bin }}"
    - "{{ openshell_development_gateway_bin }}"
    - "{{ openshell_development_sandbox_archive }}"
  register: openshell_development_artifacts
- name: Require copied development artifacts
  ansible.builtin.assert:
    that: item.stat.exists
    fail_msg: "missing required development artifact: {{ item.item }}"
  loop: "{{ openshell_development_artifacts.results }}"
  loop_control:
    label: "{{ item.item }}"
- name: Publish development OpenShell installation
  ansible.builtin.set_fact:
    openshell_install_source: development
    openshell_cli_bin: "{{ openshell_development_cli_bin }}"
    openshell_gateway_bin: "{{ openshell_development_gateway_bin }}"
    openshell_gateway_service: "{{ openshell_development_gateway_service }}"
    openshell_gateway_endpoint: "{{ openshell_development_gateway_endpoint }}"
    openshell_supervisor_source: archive
    openshell_supervisor_archive: "{{ openshell_development_sandbox_archive }}"
    openshell_supervisor_image: "{{ openshell_development_supervisor_image }}"
</file>

<file path="nix/test-guest/provisioners/roles/openshell-rpm/defaults/main.yml">
---
openshell_rpm_cli_bin: /usr/bin/openshell
openshell_rpm_gateway_bin: /usr/bin/openshell-gateway
openshell_rpm_gateway_service: openshell-gateway.service
openshell_rpm_gateway_endpoint: https://127.0.0.1:17670
</file>

<file path="nix/test-guest/provisioners/roles/openshell-rpm/tasks/main.yml">
---
- name: Verify RPM-provided OpenShell files
  ansible.builtin.stat:
    path: "{{ item }}"
  loop:
    - "{{ openshell_rpm_cli_bin }}"
    - "{{ openshell_rpm_gateway_bin }}"
    - /usr/lib/systemd/user/openshell-gateway.service
  register: openshell_rpm_files
- name: Require the installed OpenShell RPM
  ansible.builtin.assert:
    that: item.stat.exists
    fail_msg: "missing required RPM-provided file: {{ item.item }}"
  loop: "{{ openshell_rpm_files.results }}"
  loop_control:
    label: "{{ item.item }}"
- name: Publish RPM OpenShell installation
  ansible.builtin.set_fact:
    openshell_install_source: rpm
    openshell_cli_bin: "{{ openshell_rpm_cli_bin }}"
    openshell_gateway_bin: "{{ openshell_rpm_gateway_bin }}"
    openshell_gateway_service: "{{ openshell_rpm_gateway_service }}"
    openshell_gateway_endpoint: "{{ openshell_rpm_gateway_endpoint }}"
    openshell_supervisor_source: package
</file>

<file path="nix/test-guest/scripts/snap-gateway-repro.sh">
set -uo pipefail
usage() {
	cat <<'EOF'
Usage: snap-gateway-repro.sh INSTALL_SCRIPT MODE [ATTEMPTS]
MODE is system-docker, missing-docker, or docker-snap. The system-docker mode requires an
existing non-Snap Docker daemon, verifies that install.sh does not install the
Docker snap, and exercises a sandbox. The missing-docker mode requires Docker
to be absent and verifies that install.sh fails before installing either snap.
The docker-snap mode requires the Docker snap and verifies that install.sh
rejects it before installing OpenShell. ATTEMPTS defaults to 1; repeated
system-docker attempts exercise idempotent OpenShell Snap refreshes. Every
failed attempt prints service, connection, snap-change, journal, gateway-log,
and listener diagnostics.
EOF
}
if [ "$#" -lt 2 ] || [ "$#" -gt 3 ]; then
	usage >&2
	exit 2
fi
install_script=$1
mode=$2
attempts=${3:-1}
if [ ! -f "${install_script}" ]; then
	echo "Install script does not exist: ${install_script}" >&2
	exit 2
fi
if [[ ! ${attempts} =~ ^[1-9][0-9]*$ ]]; then
	echo "ATTEMPTS must be a positive integer: ${attempts}" >&2
	exit 2
fi
... (109 lines truncated)
</file>

<file path="nix/test-guest/cache-lib.sh">
TEST_GUEST_CACHE_SCHEMA_VERSION=1
TEST_GUEST_CACHE_DISK_LAYOUT=standalone-qcow2-zstd-v1
TEST_GUEST_CACHE_ARTIFACT_TYPE=application/vnd.nvidia.openshell.test-guest.cache.v1
TEST_GUEST_CACHE_METADATA_TYPE=application/vnd.nvidia.openshell.test-guest.cache.metadata.v1+json
TEST_GUEST_CACHE_DISK_TYPE=application/vnd.nvidia.openshell.test-guest.cache.disk.qcow2.v1+zstd
test_vm_cache_root() {
	if [ -n "${OPENSHELL_TEST_GUEST_CACHE_DIR:-}" ]; then
		printf '%s\n' "${OPENSHELL_TEST_GUEST_CACHE_DIR}"
	else
		printf '%s\n' "${XDG_CACHE_HOME:-${HOME}/.cache}/openshell/test-guest"
	fi
}
test_vm_cache_oci_architecture() {
	case "${TEST_GUEST_ARCHITECTURE}" in
	x86_64) printf '%s\n' amd64 ;;
	aarch64) printf '%s\n' arm64 ;;
	*)
		echo "unsupported cache architecture: ${TEST_GUEST_ARCHITECTURE}" >&2
		return 1
		;;
	esac
}
test_vm_cache_sha256() {
	if [ ! -r "$1" ]; then
		echo "cache identity input is not readable: $1" >&2
		return 1
	fi
	sha256sum "$1" | cut -d ' ' -f 1
}
test_vm_cache_key() {
... (105 lines truncated)
</file>

<file path="nix/test-guest/cache-seal.sh">
set -Eeuo pipefail
if [ "$(id -u)" -ne 0 ]; then
	echo "cache sealing must run as root" >&2
	exit 1
fi
rm -f /home/openshell/.ssh/authorized_keys
rm -f /root/.ssh/authorized_keys
rm -f /etc/ssh/ssh_host_*_key /etc/ssh/ssh_host_*_key.pub
if command -v cloud-init >/dev/null 2>&1; then
	cloud-init clean --logs --machine-id || true
fi
rm -rf /var/lib/cloud/instance /var/lib/cloud/instances /var/lib/cloud/seed
mkdir -p /var/lib/cloud/instances
: >/etc/machine-id
rm -f /var/lib/dbus/machine-id
rm -f /var/lib/systemd/random-seed
rm -f /var/lib/NetworkManager/*lease* /var/lib/dhcp/*lease* 2>/dev/null || true
rm -f /root/.bash_history /home/openshell/.bash_history
rm -f /root/.docker/config.json /home/openshell/.docker/config.json
rm -f /root/.config/containers/auth.json
rm -f /home/openshell/.config/containers/auth.json
if command -v apt-get >/dev/null 2>&1; then
	apt-get clean
fi
if command -v dnf >/dev/null 2>&1; then
	dnf clean all
fi
journalctl --rotate >/dev/null 2>&1 || true
journalctl --vacuum-time=1s >/dev/null 2>&1 || true
find /var/log -type f -exec truncate -s 0 {} + 2>/dev/null || true
... (11 lines truncated)
</file>

<file path="nix/test-guest/cache.sh">
set -Eeuo pipefail
usage() {
	cat <<'EOF'
Usage:
  nix run .
Options:
  --distro NAME       Base distro: ubuntu-24-04, ubuntu-26-04, centos, fedora, or rocky
  --with NAME         Apply a configuration; repeatable (docker, podman-rootful, podman-rootless, selinux, snapd)
  --repository REF    OCI repository without a tag
  --digest DIGEST     Trusted OCI manifest digest required for pulls
  --cache-dir PATH    Override the local prepared-disk cache directory
  --push              Publish a newly built or local entry to the repository
  -h, --help          Show this help
The command ensures one exact distro, architecture, and ordered configuration
combination exists locally. OCI pulls require a trusted manifest digest.
Otherwise, the command builds and validates a prepared disk on a miss.
Publishing is explicit and requires both --repository and --push.
EOF
}
if [ "${OPENSHELL_TEST_GUEST_RUNTIME:-}" != 1 ] ||
	[ ! -d "${OPENSHELL_TEST_GUEST_DISTROS:-}" ] ||
	[ ! -d "${OPENSHELL_TEST_GUEST_CONFIGURATIONS:-}" ] ||
	[ ! -r "${OPENSHELL_TEST_GUEST_CACHE_LIB:-}" ] ||
	[ ! -r "${OPENSHELL_TEST_GUEST_CACHE_SEAL:-}" ] ||
	[ ! -r "${OPENSHELL_TEST_GUEST_RUNNER:-}" ]; then
	echo "run this script through 'nix run .#test-guest-cache -- ...'" >&2
	exit 2
fi
. "${OPENSHELL_TEST_GUEST_CACHE_LIB}"
require_value() {
... (435 lines truncated)
</file>

<file path="nix/test-guest/README.md">
<!--
SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
SPDX-License-Identifier: Apache-2.0
-->

# Test Guests

This prototype uses Nix, QEMU, and Ansible to boot and configure disposable Linux VMs for testing OpenShell packages and binaries. It supports HVF on Apple Silicon macOS, KVM on native-architecture Linux hosts, and a slower TCG fallback on Linux when KVM is unavailable.

## Requirements

- Nix with flakes enabled.
- Apple Silicon macOS with HVF, or a native-architecture Linux host. Linux uses KVM when `/dev/kvm` is available and falls back to QEMU TCG otherwise.
- Enough local capacity for a four-vCPU, 4 GiB guest and a disposable disk overlay.
- Native-architecture artifacts. TCG emulates the guest CPU on Linux but does not enable cross-architecture guests.

The first run downloads the selected cloud image and VM runtime. Nix reuses those immutable inputs on later runs, while each guest starts from a fresh writable overlay.

On Apple Silicon, test guests deliberately take QEMU 11.0.2 and its matching OVMF
firmware from a separately pinned Nixpkgs revision. All other guest-runtime tools,
development dependencies, and cross-toolchain dependencies continue to use the main
current Nixpkgs input. This avoids a QEMU 11.1 HVF guest boot regression. Update
this pair only after validating an ARM64 Ubuntu guest boot with HVF.

## Directory structure

```text
nix/test-guest/
├── README.md
├── default.nix
... (357 lines truncated)
</file>

<file path="nix/test-guest/run.sh">
set -Eeuo pipefail
usage() {
	cat <<'EOF'
Usage:
  nix run .
Options:
  --distro NAME       Base distro: ubuntu-24-04, ubuntu-26-04, centos, fedora, or rocky
  --with NAME         Apply a configuration; repeatable (docker, podman-rootful, podman-rootless, selinux, snapd)
  --provision NAME    Apply a post-artifact system provisioner; repeatable
  --install PATH      Install a .deb or .rpm package; repeatable
  --copy SRC:DEST[:MODE]
                      Copy a regular file to an absolute guest path, using MODE
                      when provided, otherwise preserving its host mode; repeatable
  --ssh-port PORT     Use a specific loopback SSH forwarding port
  --forward-port HOST_PORT:GUEST_PORT
                      Forward a loopback host port to a guest port; repeatable
  --keep              Keep the disposable disk and logs after shutdown
  --list              List distros, configurations, and provisioners
  -h, --help          Show this help
With no COMMAND, the runner opens an interactive SSH session.
EOF
}
if [ "${OPENSHELL_TEST_GUEST_RUNTIME:-}" != 1 ] ||
	[ ! -d "${OPENSHELL_TEST_GUEST_DISTROS:-}" ] ||
	[ ! -d "${OPENSHELL_TEST_GUEST_CONFIGURATIONS:-}" ] ||
	[ ! -d "${OPENSHELL_TEST_GUEST_PROVISIONERS:-}" ] ||
	[ ! -r "${OPENSHELL_TEST_GUEST_CACHE_LIB:-}" ] ||
	[ ! -r "${OPENSHELL_TEST_GUEST_CACHE_RUNNER:-}" ]; then
	echo "run this script through 'nix run .#test-guest -- ...'" >&2
	exit 2
... (655 lines truncated)
</file>

<file path="providers/anthropic.yaml">
id: anthropic
display_name: Anthropic
description: Anthropic inference API
category: inference
inference_capable: true
credentials:
  - name: api_key
    description: Anthropic API key
    env_vars: [ANTHROPIC_API_KEY]
    required: true
    auth_style: header
    header_name: x-api-key
discovery:
  credentials: [api_key]
endpoints:
  - host: api.anthropic.com
    port: 443
    protocol: rest
    access: read-write
    enforcement: enforce
binaries: [/usr/bin/curl, /usr/local/bin/curl]
</file>

<file path="providers/aws-bedrock.yaml">
id: aws-bedrock
display_name: AWS Bedrock
description: |
  Anthropic + Mistral + Llama models served via the AWS Bedrock InvokeModel API.
  This profile supports a bridge-fronted shape only: operators point
  `BEDROCK_BASE_URL` at a translating bridge or Bedrock-compatible
  proxy that handles AWS auth in its own pod, and the bridge — not
  this profile — is responsible for declaring its own egress endpoint
  and binary attribution. As a result the profile is intentionally
  non-egress-granting: `endpoints` and `binaries` are empty so that
  selecting `aws-bedrock` does not implicitly punch a hole to AWS for
  any sandbox.
  Direct AWS Bedrock with router-side SigV4 signing is a separate
  follow-up; until that lands the AWS_* credentials below are
  declarative schema only — none are required, none are
  auto-discovered, and the router does not consume them. The SigV4
  follow-up will populate `endpoints` and `binaries` once the router
  can sign outbound requests itself.
category: inference
inference_capable: true
credentials:
  - name: aws_access_key_id
    description: AWS access key id (used by the SigV4 signer follow-up; unused today)
    env_vars: [AWS_ACCESS_KEY_ID]
    required: false
  - name: aws_secret_access_key
    description: AWS secret access key (used by the SigV4 signer follow-up; unused today)
    env_vars: [AWS_SECRET_ACCESS_KEY]
    required: false
  - name: aws_session_token
... (12 lines truncated)
</file>

<file path="providers/aws-s3.yaml">
id: aws-s3
display_name: AWS S3
description: AWS S3 storage via STS temporary credentials
category: other
credentials:
  - name: access_key_id
    description: AWS access key ID (gateway-minted via STS)
    env_vars: [AWS_ACCESS_KEY_ID]
    required: true
    refresh:
      strategy: aws_sts_assume_role
      refresh_before_seconds: 300
      max_lifetime_seconds: 3600
      additional_outputs:
        - output: secret_access_key
          credential: secret_access_key
        - output: session_token
          credential: session_token
      material:
        - name: role_arn
          description: ARN of the IAM role to assume
          required: true
          secret: false
        - name: session_name
          description: Session name for CloudTrail attribution
          required: false
          secret: false
        - name: external_id
          description: External ID for cross-account role assumption
          required: false
... (78 lines truncated)
</file>

<file path="providers/aws.yaml">
id: aws
display_name: AWS
description: Generic AWS access via STS temporary credentials
category: other
credentials:
  - name: access_key_id
    description: AWS access key ID (gateway-minted via STS)
    env_vars: [AWS_ACCESS_KEY_ID]
    required: true
    refresh:
      strategy: aws_sts_assume_role
      refresh_before_seconds: 300
      max_lifetime_seconds: 3600
      additional_outputs:
        - output: secret_access_key
          credential: secret_access_key
        - output: session_token
          credential: session_token
      material:
        - name: role_arn
          description: ARN of the IAM role to assume
          required: true
          secret: false
        - name: session_name
          description: Session name for CloudTrail attribution
          required: false
          secret: false
        - name: external_id
          description: External ID for cross-account role assumption
          required: false
... (26 lines truncated)
</file>

<file path="providers/claude-code.yaml">
id: claude-code
display_name: Claude Code
description: Claude Code CLI
category: agent
inference_capable: true
credentials:
  - name: api_key
    description: Anthropic API key used by Claude Code
    env_vars: [ANTHROPIC_API_KEY, CLAUDE_API_KEY]
    required: true
    auth_style: header
    header_name: x-api-key
discovery:
  credentials: [api_key]
endpoints:
  - host: api.anthropic.com
    port: 443
    protocol: rest
    access: read-write
    enforcement: enforce
  - host: statsig.anthropic.com
    port: 443
    protocol: rest
    access: read-write
    enforcement: enforce
  - host: sentry.io
    port: 443
    protocol: rest
    access: read-write
    enforcement: enforce
... (2 lines truncated)
</file>

<file path="providers/codex.yaml">
id: codex
display_name: Codex
description: OpenAI Codex CLI
category: agent
inference_capable: true
credentials:
  - name: access_token
    description: Codex OAuth access token
    env_vars: [CODEX_AUTH_ACCESS_TOKEN]
    required: true
  - name: refresh_token
    description: Codex OAuth refresh token
    env_vars: [CODEX_AUTH_REFRESH_TOKEN]
    required: true
  - name: account_id
    description: Codex account identifier
    env_vars: [CODEX_AUTH_ACCOUNT_ID]
    required: true
  - name: id_token
    description: Codex OAuth ID token
    env_vars: [CODEX_AUTH_ID_TOKEN]
discovery:
  credentials: [access_token, refresh_token, account_id, id_token]
endpoints:
  - host: api.openai.com
    port: 443
    protocol: rest
    access: read-write
    enforcement: enforce
  - host: auth.openai.com
... (16 lines truncated)
</file>

<file path="providers/copilot.yaml">
id: copilot
display_name: GitHub Copilot
description: GitHub Copilot CLI and Copilot service APIs
category: agent
credentials:
  - name: api_token
    description: GitHub token used by Copilot
    env_vars: [COPILOT_GITHUB_TOKEN, GH_TOKEN, GITHUB_TOKEN]
    required: true
    auth_style: bearer
    header_name: authorization
discovery:
  credentials: [api_token]
endpoints:
  - host: api.githubcopilot.com
    port: 443
    protocol: rest
    access: read-write
    enforcement: enforce
  - host: api.individual.githubcopilot.com
    port: 443
    protocol: rest
    access: read-write
    enforcement: enforce
  - host: api.business.githubcopilot.com
    port: 443
    protocol: rest
    access: read-write
    enforcement: enforce
  - host: api.enterprise.githubcopilot.com
... (19 lines truncated)
</file>

<file path="providers/cursor.yaml">
id: cursor
display_name: Cursor
description: Cursor editor server bootstrap and update endpoints
category: agent
endpoints:
  - host: cursor.blob.core.windows.net
    port: 443
  - host: api2.cursor.sh
    port: 443
  - host: repo.cursor.sh
    port: 443
  - host: download.cursor.sh
    port: 443
  - host: cursor.download.prss.microsoft.com
    port: 443
binaries:
  - /usr/bin/curl
  - /usr/bin/wget
  - /sandbox/.cursor-server/**
</file>

<file path="providers/deepinfra.yaml">
id: deepinfra
display_name: DeepInfra
description: DeepInfra inference endpoints
category: inference
inference_capable: true
credentials:
  - name: api_key
    description: DeepInfra API key
    env_vars: [DEEPINFRA_API_KEY]
    required: true
    auth_style: bearer
    header_name: authorization
discovery:
  credentials: [api_key]
endpoints:
  - host: api.deepinfra.com
    port: 443
    protocol: rest
    access: read-write
    enforcement: enforce
binaries: [/usr/bin/curl, /usr/local/bin/curl]
</file>

<file path="providers/github.yaml">
id: github
display_name: GitHub
description: GitHub API and Git operations
category: source_control
credentials:
  - name: api_token
    description: GitHub token
    env_vars: [GITHUB_TOKEN, GH_TOKEN]
    required: true
    auth_style: bearer
    header_name: authorization
discovery:
  credentials: [api_token]
endpoints:
  - host: api.github.com
    port: 443
    protocol: rest
    access: read-only
    enforcement: enforce
  - host: api.github.com
    port: 443
    path: /graphql
    protocol: graphql
    access: read-only
    enforcement: enforce
  - host: github.com
    port: 443
    protocol: rest
    enforcement: enforce
    rules:
... (6 lines truncated)
</file>

<file path="providers/google-cloud.yaml">
id: google-cloud
display_name: Google Cloud (GCP APIs)
description: Native GCP SDK credentials for sandboxes via metadata emulator
category: other
inference_capable: false
credentials:
  - name: service_account_token
    description: GCP access token minted from service account JWT
    env_vars: [GCP_SA_ACCESS_TOKEN]
    required: false
    auth_style: bearer
    header_name: authorization
    refresh:
      strategy: google_service_account_jwt
      token_url: https://oauth2.googleapis.com/token
      scopes: [https://www.googleapis.com/auth/cloud-platform]
      refresh_before_seconds: 300
      max_lifetime_seconds: 3600
      material:
        - name: client_email
          description: Service account email address
          required: true
        - name: private_key
          description: Service account RSA private key (PEM)
          required: true
          secret: true
        - name: subject
          description: Email for domain-wide delegation (optional)
  - name: adc_token
    description: GCP access token from gcloud application default credentials
... (25 lines truncated)
</file>

<file path="providers/google-vertex-ai.yaml">
id: google-vertex-ai
display_name: Google Vertex AI
description: Google Vertex AI inference provider (Anthropic Claude, Gemini, and third-party models)
category: inference
inference_capable: true
credentials:
  - name: service_account_key
    description: Google service account JSON refresh bootstrap material; not injected into sandboxes
    env_vars: [GOOGLE_SERVICE_ACCOUNT_KEY]
    required: false
  - name: service_account_token
    description: Google Cloud access token refreshed from service account JWT material
    env_vars: [GOOGLE_VERTEX_AI_SERVICE_ACCOUNT_TOKEN, VERTEX_AI_SERVICE_ACCOUNT_TOKEN]
    required: false
    auth_style: bearer
    header_name: authorization
    refresh:
      strategy: google_service_account_jwt
      token_url: https://oauth2.googleapis.com/token
      scopes: [https://www.googleapis.com/auth/cloud-platform]
      refresh_before_seconds: 300
      max_lifetime_seconds: 3600
      material:
        - name: client_email
          description: Google service account email
          required: true
        - name: private_key
          description: Google service account private key
          required: true
          secret: true
... (50 lines truncated)
</file>

<file path="providers/nvidia.yaml">
id: nvidia
display_name: NVIDIA
description: NVIDIA inference endpoints
category: inference
inference_capable: true
credentials:
  - name: api_key
    description: NVIDIA API key
    env_vars: [NVIDIA_API_KEY]
    required: true
    auth_style: bearer
    header_name: authorization
discovery:
  credentials: [api_key]
endpoints:
  - host: integrate.api.nvidia.com
    port: 443
    protocol: rest
    access: read-write
    enforcement: enforce
binaries: [/usr/bin/curl, /usr/local/bin/curl]
</file>

<file path="providers/oci-genai.yaml">
id: oci-genai
display_name: OCI Generative AI
description: OCI Generative AI inference through the OpenAI-compatible endpoint with a compartment-scoped Generative AI API key
category: inference
inference_capable: true
credentials:
  - name: api_key
    description: OCI Generative AI API key (compartment-scoped, sent as a bearer token)
    env_vars: [OCI_GENAI_API_KEY]
    required: true
    auth_style: bearer
    header_name: authorization
discovery:
  credentials: [api_key]
endpoints:
  - host: "inference.generativeai.*.oci.oraclecloud.com"
    port: 443
    protocol: rest
    enforcement: enforce
    rules:
      - allow: { method: POST, path: "/openai/v1/**" }
      - allow: { method: GET, path: "/openai/v1/**" }
      - allow: { method: DELETE, path: "/openai/v1/**" }
binaries: [/usr/bin/curl, /usr/local/bin/curl]
</file>

<file path="providers/openai.yaml">
id: openai
display_name: OpenAI
description: OpenAI inference API
category: inference
inference_capable: true
credentials:
  - name: api_key
    description: OpenAI API key
    env_vars: [OPENAI_API_KEY]
    required: true
    auth_style: bearer
    header_name: authorization
discovery:
  credentials: [api_key]
endpoints:
  - host: api.openai.com
    port: 443
    protocol: rest
    access: read-write
    enforcement: enforce
binaries: [/usr/bin/curl, /usr/local/bin/curl]
</file>

<file path="providers/openrouter.yaml">
id: openrouter
display_name: OpenRouter
description: OpenRouter inference API
category: inference
inference_capable: true
credentials:
  - name: api_key
    description: OpenRouter API key
    env_vars: [OPENROUTER_API_KEY]
    required: true
    auth_style: bearer
    header_name: authorization
discovery:
  credentials: [api_key]
endpoints:
  - host: openrouter.ai
    port: 443
    protocol: rest
    access: read-write
    enforcement: enforce
binaries: [/usr/local/bin/opencode]
</file>

<file path="providers/pypi.yaml">
id: pypi
display_name: PyPI
description: Python package installation from PyPI and related package sources
category: data
endpoints:
  - host: pypi.org
    port: 443
  - host: files.pythonhosted.org
    port: 443
  - host: github.com
    port: 443
  - host: objects.githubusercontent.com
    port: 443
  - host: api.github.com
    port: 443
  - host: downloads.python.org
    port: 443
binaries:
  - /sandbox/.venv/bin/python
  - /sandbox/.venv/bin/python3
  - /app/.venv/bin/python
  - /app/.venv/bin/python3
  - /usr/local/bin/uv
  - /sandbox/.uv/python/**
</file>

<file path="providers/README.md">
<!--
SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
SPDX-License-Identifier: Apache-2.0
-->

# Example provider profiles

These files are reviewable examples. OpenShell does not compile them into any
binary and no gateway loads them on its own: a gateway's profile catalog
contains exactly what an operator imported.

Import one at platform scope:

```shell
openshell provider profile lint   -f providers/github.yaml
openshell provider profile import -f providers/github.yaml --global
```

Or import the whole directory:

```shell
openshell provider profile import --from providers --global
```

Drop `--global` to import into the current workspace instead.

## Read the header before importing

Every file opens with a comment block naming its expected client binaries, the
image layout those paths assume, the credential scope, the endpoint access it
... (25 lines truncated)
</file>

<file path="python/openshell/_proto/__init__.py">

</file>

<file path="python/openshell/__init__.py">
__version__ = version("openshell")
⋮----
__version__ = "0.0.0"
⋮----
__all__ = [
</file>

<file path="python/openshell/errors_test.py">
def rich_status()
⋮----
status = status_pb2.Status(
retry = error_details_pb2.RetryInfo()
⋮----
detail = status.details.add()
⋮----
@pytest.mark.parametrize("streaming", [False, True])
def test_maps_real_rpc_errors_without_losing_details(streaming)
⋮----
status = rich_status()
⋮----
def fail(_request, context)
⋮----
server = grpc.server(futures.ThreadPoolExecutor(max_workers=1))
handler = (
⋮----
port = server.add_insecure_port("127.0.0.1:0")
⋮----
call = channel.unary_stream if streaming else channel.unary_unary
⋮----
response = call("/test.Errors/Fail")(b"", timeout=5)
⋮----
error = caught.value
⋮----
class RawError(grpc.RpcError)
⋮----
def __init__(self, details)
⋮----
def code(self)
... (14 lines truncated)
</file>

<file path="python/openshell/errors.py">
@dataclass(frozen=True)
class FieldViolation
⋮----
field: str
description: str
⋮----
@dataclass(frozen=True)
class ErrorInfo
⋮----
reason: str
domain: str
metadata: dict[str, str]
⋮----
class GatewayError(grpc.RpcError)
⋮----
def __init__(self, error: grpc.RpcError) -> None
⋮----
trailing = getattr(error, "trailing_metadata", lambda: None)() or ()
⋮----
status = status_pb2.Status.FromString(value)
⋮----
code = self.code()
⋮----
violations = []
⋮----
bad_request = error_details_pb2.BadRequest()
⋮----
info = error_details_pb2.ErrorInfo()
⋮----
retry = error_details_pb2.RetryInfo()
... (30 lines truncated)
</file>

<file path="python/openshell/gateway_config_fixture_test.py">
REPO_ROOT = Path(__file__).resolve().parents[2]
FIXTURE_DIR = REPO_ROOT / "e2e/configs/gateway"
TEST_GUEST_ROLE_PATH = (
⋮----
config = tomllib.loads((FIXTURE_DIR / fixture_name).read_text(encoding="utf-8"))
gateway = config["openshell"]["gateway"]
⋮----
def test_podman_test_guest_producer_uses_schema_v2() -> None
⋮----
tasks = yaml.safe_load(TEST_GUEST_ROLE_PATH.read_text(encoding="utf-8"))
producer = next(
content = producer["ansible.builtin.copy"]["content"]
config = tomllib.loads(content)
⋮----
def test_docker_e2e_gateway_fixture_uses_canonical_policy_and_label() -> None
⋮----
config = tomllib.loads((FIXTURE_DIR / "docker.toml").read_text(encoding="utf-8"))
docker = config["openshell"]["drivers"]["docker"]
⋮----
def test_podman_e2e_gateway_fixture_uses_canonical_policy_and_callbacks() -> None
⋮----
config = tomllib.loads((FIXTURE_DIR / "podman.toml").read_text(encoding="utf-8"))
podman = config["openshell"]["drivers"]["podman"]
</file>

<file path="python/openshell/gateway_schema_v2_capability_parity_test.py">
REPO_ROOT = Path(__file__).resolve().parents[2]
MANIFEST_PATH = REPO_ROOT / "e2e/configs/gateway/schema-v2-capability-parity.toml"
⋮----
REQUIRED_MANIFEST_FIELDS = {
REQUIRED_CAPABILITY_FIELDS = {
REQUIRED_TOPICS = {
REQUIRED_CAPABILITY_IDS = {
ALLOWED_LANES = {
⋮----
ALLOWED_STATUSES = {"not_run", "blocked", "planned"}
⋮----
def load_manifest() -> dict[str, Any]
⋮----
def require_nonempty_string(value: Any, field: str, entry_id: str) -> None
⋮----
def require_string_list(value: Any, field: str, entry_id: str) -> None
⋮----
def validate_manifest(manifest: dict[str, Any]) -> None
⋮----
capabilities = manifest["capabilities"]
⋮----
ids: list[str] = []
topics: set[str] = set()
⋮----
entry_id = capability["id"]
⋮----
def capability_by_id(manifest: dict[str, Any], capability_id: str) -> dict[str, Any]
⋮----
def test_schema_v2_capability_parity_manifest_is_well_formed() -> None
⋮----
... (30 lines truncated)
</file>

<file path="python/openshell/gateway_schema_v2_compute_boundary_verifier_test.py">
REPO_ROOT = Path(__file__).resolve().parents[2]
VERIFIER_PATH = REPO_ROOT / "e2e/parity/verify-results.py"
BASELINE_SHA = "1" * 40
CANDIDATE_SHA = "2" * 40
IMAGE_ID = "3" * 64
IMAGE_DIGEST = f"sha256:{'4' * 64}"
RUNTIME_IMAGE = f"localhost/openshell/supervisor@{IMAGE_DIGEST}"
BOUNDARY_IMAGE = f"localhost/openshell/sandbox@{IMAGE_DIGEST}"
BASE_RUNTIME_IMAGE = f"docker.io/library/alpine@{IMAGE_DIGEST}"
⋮----
def load_verifier() -> ModuleType
⋮----
spec = importlib.util.spec_from_file_location("parity_verifier", VERIFIER_PATH)
⋮----
module = importlib.util.module_from_spec(spec)
⋮----
def write_json(path: Path, value: object) -> None
⋮----
artifact_dir = results_dir / "artifacts" / variant
⋮----
artifacts = {
⋮----
selector = (
⋮----
policy = "missing" if schema_version == 1 else "if_not_present"
package_hash = verifier.sha256(artifact_dir / "supervisor.packages.txt")
result = json.loads((results_dir / f"{variant}.json").read_text(encoding="utf-8"))
legacy_tls_environment = {}
⋮----
legacy_tls_environment = {
... (55 lines truncated)
</file>

<file path="python/openshell/gateway_schema_v2_cross_cutting_dispositions_test.py">
REPO_ROOT = Path(__file__).resolve().parents[2]
DISPOSITIONS_PATH = (
CAPABILITY_PATH = REPO_ROOT / "e2e/configs/gateway/schema-v2-capability-parity.toml"
INTENTIONAL_CHANGES_PATH = (
⋮----
STEP_11_CAPABILITY_IDS = {
EXPECTED_SUITES = {
EXPECTED_CANDIDATE_COMMIT = "363d8540830b2ea294d43198daa2b7a283a2face"
EXPECTED_INTENTIONAL_CHANGES = {
⋮----
def load_toml(path: Path) -> dict[str, Any]
⋮----
def assert_full_sha(value: object, field: str) -> str
⋮----
def test_step_11_dispositions_cover_exact_cross_cutting_capabilities() -> None
⋮----
manifest = load_toml(DISPOSITIONS_PATH)
⋮----
capabilities = manifest["capabilities"]
⋮----
def test_step_11_capability_ids_exist_in_inventory() -> None
⋮----
inventory_ids = {
⋮----
def test_deterministic_preflight_is_not_reported_as_live_parity() -> None
⋮----
preflight = manifest["deterministic_preflight"]
⋮----
attestations = {
⋮----
... (16 lines truncated)
</file>

<file path="python/openshell/gateway_schema_v2_intentional_changes_test.py">
REPO_ROOT = Path(__file__).resolve().parents[2]
LEDGER_PATH = REPO_ROOT / "e2e/configs/gateway/schema-v2-intentional-changes.toml"
CAPABILITY_PATH = REPO_ROOT / "e2e/configs/gateway/schema-v2-capability-parity.toml"
⋮----
REQUIRED_HEADER_FIELDS = {
REQUIRED_CHANGE_FIELDS = {
REQUIRED_CHANGE_IDS = {
ALLOWED_CATEGORIES = {
⋮----
def load_toml(path: Path) -> dict[str, Any]
⋮----
def require_nonempty_string(value: Any, field: str, change_id: str) -> None
⋮----
def test_intentional_change_ledger_is_complete_and_well_formed() -> None
⋮----
ledger = load_toml(LEDGER_PATH)
⋮----
changes = ledger["intentional_changes"]
⋮----
ids: list[str] = []
⋮----
change_id = change["id"]
⋮----
capability_ids = change["validation_capability_ids"]
⋮----
def test_every_intentional_change_links_to_known_capabilities() -> None
⋮----
capabilities = load_toml(CAPABILITY_PATH)["capabilities"]
known_capability_ids = {capability["id"] for capability in capabilities}
⋮----
... (14 lines truncated)
</file>

<file path="python/openshell/gateway_schema_v2_kubernetes_option_dispositions_test.py">
ROOT = Path(__file__).resolve().parents[2]
LEDGER = (
CAPABILITIES = ROOT / "e2e" / "configs" / "gateway" / "schema-v2-capability-parity.toml"
LIVE_RESULTS = ROOT / "e2e" / "configs" / "gateway" / "schema-v2-live-results.toml"
KUBERNETES_CAPABILITY_IDS = {
FIELD_GROUP = re.compile(
⋮----
def load_ledger() -> dict
⋮----
def manifest_kubernetes_fields() -> set[str]
⋮----
capabilities = tomllib.load(handle)["capabilities"]
fields: set[str] = set()
⋮----
table = match.group("table")
⋮----
prefix = (
⋮----
def test_kubernetes_ledger_covers_every_manifest_driver_field_once() -> None
⋮----
ledger = load_ledger()
coverage = ledger["coverage"]
observed = [field for entry in coverage for field in entry["fields"]]
⋮----
def test_kubernetes_core_pass_is_paired_and_qualified_checks_stay_blocked() -> None
⋮----
core = next(entry for entry in ledger["coverage"] if entry["status"] == "pass")
⋮----
comparison_path = ROOT / ledger["core_comparison"]
comparison = json.loads(comparison_path.read_text())
... (11 lines truncated)
</file>

<file path="python/openshell/gateway_schema_v2_live_results_test.py">
REPO_ROOT = Path(__file__).resolve().parents[2]
RESULTS_PATH = REPO_ROOT / "e2e/configs/gateway/schema-v2-live-results.toml"
CAPABILITY_PATH = REPO_ROOT / "e2e/configs/gateway/schema-v2-capability-parity.toml"
COMPUTE_BOUNDARY_PATH = (
CROSS_CUTTING_DISPOSITIONS_PATH = (
⋮----
REQUIRED_HEADER_FIELDS = {
REQUIRED_STEP_5_IDS = {
REQUIRED_STEP_6_IDS = {
REQUIRED_STEP_7_IDS = {
REQUIRED_STEP_8_IDS = {
REQUIRED_STEP_9_IDS = {
REQUIRED_STEP_10_IDS = {"compute-driver-boundary-parity"}
REQUIRED_STEP_11_IDS = {
REQUIRED_STEP_12_IDS = {
EXPECTED_EXECUTED_CANDIDATE_COMMITS = {
STEP_10_CANDIDATE_COMMIT = EXPECTED_EXECUTED_CANDIDATE_COMMITS[
STEP_10_REPORT_SHA256 = (
STEP_10_EVIDENCE_BUNDLES = {
ALLOWED_STATUSES = {
BASE_FIELDS = {"id", "step", "capability", "driver", "status", "lane"}
PASS_FIELDS = {
BLOCKED_FIELDS = {"owner", "blocker"}
⋮----
def load_toml(path: Path) -> dict[str, Any]
⋮----
def assert_full_sha(value: object, field: str) -> str
⋮----
def test_live_results_manifest_is_well_formed() -> None
⋮----
... (85 lines truncated)
</file>

<file path="python/openshell/gateway_schema_v2_parity_gap_dispositions_test.py">
REPO_ROOT = Path(__file__).resolve().parents[2]
GAP_LEDGER_PATH = (
LIVE_RESULTS_PATH = REPO_ROOT / "e2e/configs/gateway/schema-v2-live-results.toml"
⋮----
REQUIRED_HEADER_FIELDS = {
REQUIRED_GAP_FIELDS = {
REQUIRED_GAP_IDS = {
ALLOWED_SEVERITIES = {"blocker", "major", "minor", "none"}
ALLOWED_RELATIONS = {
ALLOWED_DISPOSITIONS = {
⋮----
def load_ledger() -> dict[str, Any]
⋮----
def test_gap_disposition_ledger_is_complete_and_well_formed() -> None
⋮----
ledger = load_ledger()
⋮----
gaps = ledger["gaps"]
⋮----
ids: list[str] = []
⋮----
gap_id = gap["id"]
⋮----
def test_every_blocker_has_a_required_fix_and_validation() -> None
⋮----
def test_non_findings_do_not_require_product_changes() -> None
⋮----
def test_security_sensitive_tls_gap_records_reviewed_resolution() -> None
⋮----
tls_gap = next(
... (15 lines truncated)
</file>

<file path="python/openshell/mutations.py">
class DeletionOutcome(IntEnum)
⋮----
UNSPECIFIED = 0
COMPLETED = 1
ACCEPTED = 2
ALREADY_ABSENT = 3
⋮----
@classmethod
    def _missing_(cls, value)
⋮----
member = int.__new__(cls, value)
⋮----
@dataclass(frozen=True)
class DeletionResult
⋮----
"""Outcome for the original target; unknown outcomes never imply completion."""
⋮----
outcome: DeletionOutcome
sandbox_id: str | None = None
</file>

<file path="python/openshell/openshell_test.py">
def test_version() -> None
⋮----
def test_sandbox_template_client_exported() -> None
</file>

<file path="python/openshell/py.typed">

</file>

<file path="python/openshell/release_formula_test.py">
release_dir = tmp_path / "release"
⋮----
repo_root = Path(__file__).resolve().parents[2]
output = tmp_path / "openshell.rb"
⋮----
formula = output.read_text(encoding="utf-8")
⋮----
generated_config = re.search(
⋮----
legacy_empty_config = re.search(
⋮----
legacy_ipv6_config = re.search(
⋮----
def test_snap_wrapper_uses_optional_gateway_config_without_generating_toml() -> None
⋮----
wrapper = (repo_root / "tasks/scripts/snap-gateway-wrapper.sh").read_text(
⋮----
def test_snap_docker_connect_hook_restarts_gateway() -> None
⋮----
hook = repo_root / "snap/hooks/connect-plug-docker"
⋮----
def test_rpm_spec_seeds_and_migrates_gateway_defaults() -> None
⋮----
spec = (repo_root / "openshell.spec").read_text(encoding="utf-8")
⋮----
def test_deb_user_service_uses_gateway_defaults_without_config_helper() -> None
⋮----
unit = (repo_root / "deploy/deb/openshell-gateway.service").read_text(
⋮----
def test_rpm_exec_start_pre_argument_and_execution_order() -> None
... (9 lines truncated)
</file>

<file path="python/openshell/rpm_gateway_config_migration_test.py">
REPO_ROOT = Path(__file__).resolve().parents[2]
MIGRATOR = REPO_ROOT / "deploy/rpm/migrate-gateway-config.sh"
CURRENT = REPO_ROOT / "deploy/rpm/gateway.toml.default"
LEGACY = REPO_ROOT / "deploy/rpm/gateway.toml.default.v1"
SHIPPED_V1_FIXTURE = b"""# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
⋮----
def test_migrator_seeds_missing_config_and_is_idempotent(tmp_path: Path) -> None
⋮----
destination = tmp_path / "config/openshell/gateway.toml"
⋮----
def test_migrator_replaces_only_exact_legacy_default(tmp_path: Path) -> None
⋮----
destination = tmp_path / "gateway.toml"
shipped_v1 = SHIPPED_V1_FIXTURE
⋮----
def test_migrator_preserves_edited_legacy_and_current_configs(tmp_path: Path) -> None
⋮----
edited = LEGACY.read_text(encoding="utf-8") + "# operator edit\n"
⋮----
def test_migrator_refuses_symlink_destination(tmp_path: Path) -> None
⋮----
target = tmp_path / "target.toml"
⋮----
result = run_migrator(destination, check=False)
⋮----
def test_shipped_rpm_defaults_have_expected_schema_shapes() -> None
⋮----
current = tomllib.loads(CURRENT.read_text(encoding="utf-8"))
legacy = tomllib.loads(LEGACY.read_text(encoding="utf-8"))
⋮----
... (28 lines truncated)
</file>

<file path="python/openshell/sandbox_cleanup_test.py">
@pytest.fixture
def cleanup_client()
⋮----
state = SimpleNamespace(
⋮----
def fail(context)
⋮----
def get(request, context)
⋮----
response = openshell_pb2.SandboxResponse()
⋮----
def delete(request, context)
⋮----
server = grpc.server(futures.ThreadPoolExecutor(max_workers=1))
⋮----
port = server.add_insecure_port("127.0.0.1:0")
⋮----
client = SandboxClient(
⋮----
def assert_original_call(error, code)
⋮----
def test_wait_deleted_handles_intercepted_status(cleanup_client, code)
⋮----
expected = (
⋮----
managed = Sandbox(workspace="default", sandbox="cleanup-test")
</file>

<file path="python/openshell/sandbox_test.py">
def _request_workspace(request: Any) -> str | None
⋮----
scope = request.workspace_scope
⋮----
def _request_selects_all_workspaces(request: Any) -> bool
⋮----
def _request_sandbox(request: Any) -> str
⋮----
name = getattr(request, "name", "")
⋮----
def _client_credentials_fixture() -> dict[str, Any]
⋮----
def test_oauth_client_credentials_conformance_fixture() -> None
⋮----
fixture = _client_credentials_fixture()
⋮----
def test_client_credentials_auth_exact_form_cache_and_redaction() -> None
⋮----
seen: list[tuple[str, bytes]] = []
⋮----
def handler(request: Any) -> Any
⋮----
auth = ClientCredentialsAuth(
⋮----
form = dict(__import__("urllib.parse").parse.parse_qsl(seen[1][1].decode()))
⋮----
def test_client_credentials_auth_preserves_explicit_empty_scopes() -> None
⋮----
form: dict[str, str] = {}
⋮----
... (521 lines truncated)
</file>

<file path="python/openshell/sandbox.py">
_ClientCallDetailsBase = namedtuple(
⋮----
_OAUTH_MAX_RESPONSE_BYTES = 1 << 20
_PAGER_MAX_CONSUMED_TOKENS = 10_000
_PAGER_MAX_CONSUMED_TOKEN_BYTES = 1 << 20
T = TypeVar("T")
⋮----
@dataclass(frozen=True)
class Page(Generic[T])
⋮----
items: builtins.list[T]
next_page_token: str
⋮----
class Pager(Generic[T])
⋮----
def __init__(self, fetch: Callable[[str], Page[T]], page_token: str = "") -> None
⋮----
def __iter__(self) -> Pager[T]
⋮----
def _validate_page_token_budget(self, page_token: str) -> int
⋮----
token_bytes = len(page_token.encode("utf-8"))
⋮----
def __next__(self) -> Page[T]
⋮----
page_token = self._page_token
token_bytes = self._validate_page_token_budget(page_token)
page = self._fetch(page_token)
⋮----
next_page_token = page.next_page_token
... (496 lines truncated)
</file>

<file path="python/release_tooling_test.py">
def _load_release_module()
⋮----
path = Path(__file__).resolve().parents[1] / "tasks/scripts/release.py"
spec = importlib.util.spec_from_file_location("openshell_release_tooling", path)
⋮----
module = importlib.util.module_from_spec(spec)
⋮----
release = _load_release_module()
⋮----
def test_exact_tag_versions_are_stable_release_versions() -> None
⋮----
versions = release._versions_from_parts((0, 0, 37), 0, "152d05940", "v0.0.37")
⋮----
def test_dev_versions_share_one_build_identity() -> None
⋮----
versions = release._versions_from_parts((0, 0, 37), 108, "152d05940", "v0.0.37")
⋮----
def test_prerelease_versions_share_tag_identity() -> None
⋮----
versions = release._versions_from_prerelease(
⋮----
def test_semver_tag_parser_excludes_vm_tags() -> None
⋮----
def test_prerelease_tag_parser_requires_positive_sequence() -> None
⋮----
def test_dev_versions_ignore_exact_prerelease_tag(monkeypatch) -> None
⋮----
def fake_git(args: list[str]) -> str
⋮----
versions = release._compute_dev_versions()
... (1 lines truncated)
</file>

<file path="python/wheel_verifier_test.py">
def _load_verifier_module()
⋮----
path = Path(__file__).resolve().parents[1] / "tasks/scripts/verify-python-wheel.py"
spec = importlib.util.spec_from_file_location("openshell_wheel_verifier", path)
⋮----
module = importlib.util.module_from_spec(spec)
⋮----
verifier = _load_verifier_module()
⋮----
def _wheel_files() -> set[str]
⋮----
files = {
⋮----
wheel = directory / f"openshell-{version}-{tag}.whl"
dist_info = f"openshell-{version}.dist-info"
⋮----
def test_accepts_pure_python_sdk_wheel(tmp_path: Path) -> None
⋮----
wheel = _write_wheel(tmp_path)
⋮----
def test_requires_exactly_one_wheel_in_directory(tmp_path: Path) -> None
⋮----
def test_rejects_missing_generated_proto(tmp_path: Path) -> None
⋮----
files = _wheel_files() - {"openshell/_proto/sandbox_pb2.py"}
wheel = _write_wheel(tmp_path, files=files)
⋮----
def test_rejects_bundled_cli(tmp_path: Path) -> None
⋮----
files = _wheel_files() | {"openshell-1.2.3.data/scripts/openshell"}
... (23 lines truncated)
</file>

<file path="rfc/0000-template/README.md">
---
authors:
  - "@your-github-username"
state: accepted
links:
  - (originating GitHub issue where maintainers assigned this RFC number)
---

# RFC NNNN - Your Title Here

<!--
See rfc/README.md for the full RFC process and state definitions. Do not
create an RFC until a GitHub issue exists and maintainers have assigned the
RFC number from that issue.
-->

## Summary

Provide a brief overview of the change in one or two paragraphs. Focus on what
the RFC proposes and the outcome it is intended to enable. Avoid diving into the
full background, implementation detail, or tradeoff analysis here.

A reader should be able to understand the intent of the RFC from this section
alone.

## Motivation

Explain why this change is necessary now. Describe the current problem, who it
affects, and the workflows that are not well served today.

... (118 lines truncated)
</file>

<file path="rfc/0001-core-architecture/README.md">
---
authors:
  - "@drew"
state: accepted
---

# RFC 0001 - Core Architecture

## Summary

This RFC proposes a composable core architecture for OpenShell built around three runtime components -- the **CLI**, the **Gateway**, and the **Supervisor** -- with infrastructure-specific behavior moved behind explicit driver interfaces.

The RFC proposes organizing the gateway around four internal subsystems: **compute** for sandbox lifecycle, **credentials** for secret resolution, **control-plane identity** for gateway authentication and authorization, and **sandbox identity** for supervisor and sandbox workload identity. Each delegates platform-specific operations to a pluggable **driver**, allowing the core gateway to stay stable while different deployment environments provide their own infrastructure adapters.

The RFC also proposes three control-plane constraints: supervisors connect outbound to the gateway rather than being dialed by it, sandbox-to-sandbox traffic is relayed through the gateway in the initial design, and the gateway scales as an active-active multi-replica service with leased ownership of live supervisor sessions.

## Motivation

OpenShell should not be tied to a single infrastructure environment. The core value of OpenShell -- safe, policy-enforced sandboxes for autonomous agents -- should be portable across deployment targets.

Today, the gateway is tightly coupled to Kubernetes. The `SandboxClient` struct directly creates AgentSandbox CRDs via `kube-rs`, watches Kubernetes events, and resolves pod IPs. That coupling makes alternative deployment targets harder to support and forces infrastructure concerns into the core gateway.

At the same time, the coupling surface is narrower than the full system. The gateway depends on Kubernetes for sandbox provisioning, lifecycle watching, and network address resolution, but the rest of the gateway -- persisting state, validating policy, managing SSH sessions, routing inference, and serving the gRPC API -- is not inherently tied to Kubernetes. The supervisor is even less coupled: it runs inside the environment it is given, connects back to the gateway over gRPC, and enforces the security boundary.

This RFC proposes moving those infrastructure-specific responsibilities behind explicit driver interfaces. If we extract drivers at that boundary, the CLI, Gateway, and Supervisor can remain stable while platform-specific behavior lives behind compute, credentials, control-plane identity, and sandbox identity drivers. That keeps the core architecture focused on OpenShell semantics while allowing different deployment environments to provide their own infrastructure adapters.

## Non-goals

- **Rewriting the supervisor.** The supervisor is already platform-aware. This RFC is about the boundary between the gateway and infrastructure, not the internals of the sandbox runtime.
- **Providing first-party drivers for every deployment target.** We define the interfaces and ship reference implementations, but OpenShell's first-party focus is Kubernetes-based deployments. Other environments can be supported by third-party drivers.
... (269 lines truncated)
</file>

<file path="rfc/0002-agent-driven-policy-management/README.md">
---
authors:
  - "@alwatson"
state: accepted
links:
  - https://github.com/NVIDIA/OpenShell/issues/1062
  - https://github.com/NVIDIA/OpenShell/blob/main/architecture/policy-advisor.md
---

# RFC 0002 - Agent-Driven Policy Management

<!--
See rfc/README.md for the full RFC process and state definitions.
-->

## Summary

Evolve OpenShell's existing Policy Advisor into an agent-driven policy management system that lets agents inspect current sandbox policy, draft narrow policy changes, submit them for review, and apply approved updates without restarting the sandbox. The safety model stays the same: sandbox-side analysis, gateway-side validation and persistence, and explicit approval boundaries. The main change is the authoring and review experience: every sandbox should expose local policy guidance and APIs, and every developer surface should expose a responsive inbox for reviewing proposals.

## Motivation

OpenShell already has the core of a dynamic policy editing experience:

- The sandbox proxy emits deny events.
- The sandbox-side `DenialAggregator` and mechanistic mapper convert those into draft `PolicyChunk` proposals.
- The gateway persists proposals and merges approved rules into the active policy.
- The TUI and CLI already provide review and approval flows.
- Running sandboxes already hot-reload dynamic policy updates.

That is a strong foundation, but the current experience is still fundamentally operator-driven and network-centric. It is excellent for "observe a deny, approve a generated endpoint rule" but incomplete for the broader product promise: an agent should be able to understand what is blocked, discover what policy language is available, generate the narrowest valid policy change, and submit it to the developer with enough rationale and verification signal that approval is fast and trustworthy.
... (694 lines truncated)
</file>

<file path="rfc/0003-gateway-configuration/README.md">
---
authors:
  - "@TaylorMutch"
state: implemented
---

# RFC 0003 - Gateway Configuration File

## Summary

Introduce a TOML-based configuration file for the OpenShell gateway that unifies gateway settings — core server options, TLS, OIDC, observability listeners, and per-driver parameters — under a single structured file. CLI flags and supported `OPENSHELL_*` environment variables retain higher precedence. Schema version 2 intentionally rejects legacy file fields and locations.

## Motivation

Before this RFC, the gateway was configured exclusively through CLI flags and `OPENSHELL_*` environment variables. This worked for simple single-node deployments but broke down as deployments grew:

- **Too many flags** — the gateway exposed roughly 40 configurable parameters (TLS, OIDC, four compute drivers, three listeners). Long `docker run` commands and `args:` arrays in Kubernetes manifests were hard to read, diff, and audit.
- **Driver coupling** — Docker, Podman, Kubernetes, and VM drivers shared one flat CLI namespace with no structural separation. Most flags applied to only one driver, but CLI syntax did not express that ownership.
- **Helm friction** — The chart's `statefulset.yaml` carried a long `env:` block of `OPENSHELL_*` variables that each mapped to a `values.yaml` key. A mounted configuration file reduces the chart's templating surface.
- **Secrets management** — Environment-only configuration did not compose naturally with Kubernetes `ConfigMap` and projected `Secret` volumes.

## Non-goals

- Sandbox workload policy (OPA rules, network rules) — sandboxes receive policy from the gateway over the control-plane API; this RFC does not change that.
- Hot-reload of configuration without restarting the gateway process.
- Support for config formats other than TOML. JSON or YAML variants are not planned.
- A new configuration schema for the CLI client (`openshell` binary) — this RFC covers the server process (`openshell-gateway`) only.
- Auto-detection logic for compute drivers. The gateway already auto-detects an active driver when none is configured (Kubernetes → Podman → Docker); the file simply provides another way to specify drivers explicitly.

## Proposal
... (253 lines truncated)
</file>

<file path="rfc/0004-sandbox-resource-requirements/README.md">
---
authors:
  - "@elezar"
state: accepted
links:
  - https://github.com/NVIDIA/OpenShell/issues/1338
  - https://github.com/NVIDIA/OpenShell/pull/1340
  - https://github.com/NVIDIA/OpenShell/pull/1360
  - https://github.com/NVIDIA/OpenShell/issues/1492
  - https://github.com/NVIDIA/OpenShell/pull/1675
  - https://github.com/NVIDIA/OpenShell/pull/1815
---

# RFC 0004 - Sandbox Resource Requirements

## Summary

This RFC proposes replacing GPU-specific sandbox request fields with typed
resource requirements on `SandboxSpec`. Resource requirements describe portable
workload needs that influence driver selection and provisioning:

- **compute** requirements for CPU and memory.
- **device** requirements for GPUs and other accelerator-like resources.
- future typed domains such as datasets when their semantics are defined.

The gateway uses resource requirements to prefilter configured compute drivers,
then relies on the selected driver to validate and provision the request.
`SandboxTemplate.resources` remains a platform-native realization layer and
escape hatch. It is not the portable driver-selection interface.

... (828 lines truncated)
</file>

<file path="rfc/0005-sandbox-proxy-egress-adapter/current-shape.md">
# Current Shape Appendix

This appendix records the current proxy shape and the review findings that
motivate the adapter model. The main RFC intentionally keeps these details out
of the direction document.

## Current Runtime Split

The proxy is no longer only a large module inside `openshell-sandbox`.
Current main has three relevant runtime owners:

```mermaid
flowchart TD
    Sandbox["openshell-sandbox<br/>orchestrator"]
    Network["openshell-supervisor-network<br/>proxy, OPA, L7, TLS, inference,<br/>policy.local, token grants"]
    Process["openshell-supervisor-process<br/>process leaf, SSH, netns,<br/>nftables, bypass monitor"]
    Denials["Denial/activity aggregators"]
    Gateway["Gateway policy/provider APIs"]

    Sandbox --> Network
    Sandbox --> Process
    Network --> Denials
    Process --> Denials
    Sandbox --> Gateway
    Network --> Gateway
```

`openshell-sandbox` creates the shared network namespace, owns denial/activity
channels, starts the policy poll loop, starts networking, starts the metadata
loopback server when needed, and then optionally starts the process leaf. If
... (252 lines truncated)
</file>

<file path="rfc/0005-sandbox-proxy-egress-adapter/implementation-plan.md">
# Implementation Plan

This plan is intentionally separate from the main RFC so the proposal can stay
direction-focused. The RFC is an incremental roadmap, not one pull request.
Phases 0 through 7 form the compatibility foundation: they restructure current
CONNECT, forward HTTP, raw TCP, and local-service behavior without adding a new
user-facing transport. Phases 8 and later add the forward-looking capabilities
after the shared contracts are authoritative.

## Phase 0 - Compatibility Baseline

- Cover CONNECT and forward HTTP allow/deny responses, including exact status,
  headers, and adapter-specific error bodies.
- Cover forward HTTP pipelining, keep-alive follow-on requests, the current
  `Connection: close` mitigation, `https://` absolute-form rejection, and h2c
  rejection on inspected endpoints.
- Cover the current overlapping-policy outcomes separately for matched policy,
  L7 route selection, TLS, `allowed_ips`, and exact-declared-host.
- Inject failures into L7, TLS, `allowed_ips`, and exact-declared-host queries.
  Record the current fail-open or fail-closed result for each query rather than
  treating all endpoint metadata errors as equivalent.
- Cover control-plane ports, cloud metadata, always-blocked addresses, exact
  declared private endpoints, IP-literal synthesis, trusted gateway aliases,
  and explicit `allowed_ips` through CONNECT and forward HTTP.
- Cover identity-required success/failure, unsupported-platform behavior where
  possible, and intentional endpoint-only evaluation. Prove an empty
  `exec.path` cannot satisfy binary-scoped policy while identity is required.
- Cover static credential injection, token grants, REST body rewrite,
  WebSocket text-frame rewrite and policy, GraphQL, JSON-RPC, and MCP behavior.
- Cover `policy.local`, metadata loopback, and unchanged nftables bypass
... (248 lines truncated)
</file>

<file path="rfc/0005-sandbox-proxy-egress-adapter/README.md">
---
authors:
  - "@johntmyers"
state: review
links:
  - https://github.com/NVIDIA/OpenShell/issues/1107
  - https://github.com/NVIDIA/OpenShell/pull/2155
  - https://github.com/NVIDIA/OpenShell/pull/1083
  - https://github.com/NVIDIA/OpenShell/pull/1151
  - https://github.com/NVIDIA/OpenShell/pull/1286
  - https://github.com/NVIDIA/OpenShell/pull/1511
  - https://github.com/NVIDIA/OpenShell/pull/1738
  - https://github.com/NVIDIA/OpenShell/pull/2027
  - https://github.com/NVIDIA/OpenShell/pull/1865
  - https://github.com/NVIDIA/OpenShell/pull/1938
---

# RFC 0005 - Sandbox Proxy Egress Adapter Model

<!--
See rfc/README.md for the full RFC process and state definitions.
-->

## Summary

Refactor sandbox egress around shared authorization, destination-validation,
and relay boundaries. CONNECT, forward HTTP, native TCP capture, policy DNS,
`policy.local`, and metadata loopback become narrow adapters
that translate userland entry points into common runtime intents. Policy
evaluation, destination validation, supervisor middleware, credential
... (553 lines truncated)
</file>

<file path="rfc/0005-sandbox-proxy-egress-adapter/technical-design.md">
# Technical Design Appendix

This appendix carries implementation-level design details behind the main RFC.

## Existing Runtime Boundary

`openshell-supervisor-network::run::run_networking` is the current networking
startup boundary. It builds policy-local context, waits for policy binary
symlink resolution, creates the identity cache, writes the TLS CA, builds TLS
state, resolves inference routes, wires provider credentials and token grants,
and starts the proxy. The supervisor middleware work extends this boundary with
middleware registry construction and reload behavior.

This is a useful outer boundary, but it is not yet the proxy adapter boundary.
The proxy still needs internal `EgressIntent` and `EgressDecision` boundaries
so CONNECT, forward HTTP, local routes, and future native TCP capture do not
duplicate policy and relay orchestration. The first implementation milestone
wires only current surfaces; later milestones add new adapters to the same
contract.

## Shared Data Boundaries

### EgressIntent

`EgressIntent` is the normalized description of what userland is trying to do.

It should carry:

- entry transport: CONNECT, forward HTTP, transparent TCP, local HTTP, policy
  DNS, or metadata loopback;
... (562 lines truncated)
</file>

<file path="rfc/0006-driver-config-passthrough/README.md">
---
authors:
  - "@elezar"
state: implemented
links:
  - https://github.com/NVIDIA/OpenShell/issues/1492
  - https://github.com/NVIDIA/OpenShell/pull/1589
  - https://github.com/NVIDIA/OpenShell/pull/1744
  - https://github.com/NVIDIA/OpenShell/pull/1785
  - https://github.com/NVIDIA/OpenShell/pull/1815
  - https://github.com/NVIDIA/OpenShell/pull/1861
  - https://github.com/NVIDIA/OpenShell/pull/2086
  - https://github.com/NVIDIA/OpenShell/pull/2092
---

# RFC 0006 - Driver Config Passthrough

## Summary

OpenShell sandbox creation supports caller-provided `driver_config` for
compute-driver-specific settings that do not belong in the portable public API.
The public API carries a driver-keyed envelope on `SandboxTemplate`; the gateway
selects the block for the active compute driver and forwards only that inner
block to `DriverSandboxTemplate.driver_config`.

The selected driver owns the nested schema, validation, safety policy, and
compatibility behavior for its config block. The gateway owns only the stable
envelope, driver selection, and the separation between caller-provided
`driver_config` and gateway-computed `platform_config`.

... (387 lines truncated)
</file>

<file path="rfc/0009-supervisor-middleware/appendices/deployment-options.md">
# Appendix: Deployment Options

> This is an appendix to the [RFC](../README.md). Please familiarize yourself with the RFC before reading this.

This appendix records why the first version of supervisor middleware supports in-process built-ins plus externally managed network service endpoints, and what deployment modes remain open for later evaluation. Supporting every deployment mode is an explicit non-goal of the main RFC; this document preserves the analysis so the decision is not lost.

## Decision: built-ins and externally managed service endpoints

The first version runs first-party built-ins inside the supervisor and routes selected external evaluations to operator-run services reachable by the gateway and supervisors. Built-ins need no registration or network transport. For external services, OpenShell holds only the connection details, body limit, transport settings, and operation-specific evaluation/result contract. It does not package, deploy, or manage the service lifecycle.

Rationale:

- **Minimal new infrastructure.** Built-ins reuse the supervisor process. External middleware does not require OpenShell to build image packaging, process supervision, or a new runtime. The first iteration can focus on the contract, failure behavior, and supervisor integration.
- **Portable across compute drivers.** A network endpoint is reachable from supervisors regardless of whether the sandbox workload runs as a container, a VM, or a local process. Other endpoint shapes do not have a universal way to be shared with every relevant supervisor environment yet, so a network endpoint is the portable choice that works the same way everywhere.
- **Independent iteration.** The middleware is an integration point with another team. An external service lets them deploy, scale, and update it on their own cadence, without coupling releases to OpenShell.
- **Heavy compute friendly.** Detection work may need GPUs or significant memory. An external service can live wherever those resources are, and can be scaled separately from the sandbox fleet.

Tradeoffs:

- The middleware is a trusted component with raw access to request content. As a standalone network service it sits outside OpenShell's isolation boundary, typically with its own connectivity and credentials. The main RFC calls out trust in the middleware as a non-goal; this deployment shape leans on that assumption.
- The operator is responsible for deploying, securing, and maintaining the service.

## Future options

These are recorded as directions, not committed designs. They have no committed timeline in this RFC; sequencing depends on the initial external-service implementation, adoption feedback, and the availability of supporting primitives such as sandbox-to-sandbox communication.

### Middleware running inside its own sandbox

Package the middleware as a container image and run it inside an OpenShell sandbox, then route egress content to it. The middleware would inherit sandbox isolation: policy-enforced egress, filesystem and syscall constraints, and no open internet access unless explicitly granted.

... (12 lines truncated)
</file>

<file path="rfc/0009-supervisor-middleware/appendices/extension-authentication.md">
# Appendix: Extension Authentication (Alpha)

> This is an appendix to the [RFC](../README.md). Please familiarize yourself with the RFC before reading this.

The RFC body left the authenticated-transport mechanism as follow-up protocol work: it required confidentiality plus authentication of the intended middleware service, described a phase 1 `allow_insecure` escape hatch, and deferred the phase 2 choice between mTLS, TLS plus explicit caller authentication, or an equivalent. This appendix records the mechanism that was actually built for alpha. It supersedes the body's transport-authentication and `allow_insecure` paragraphs; the rest of the body is unchanged.

Related: [protocol-extensions.md](protocol-extensions.md#middleware-authentication).

## What ships in alpha

Transport is HTTPS with either platform trust roots or an operator-provided CA bundle, with normal certificate and endpoint-hostname verification. A middleware endpoint must be reachable from every sandbox supervisor as well as the gateway, so a gateway-local Unix socket is not an option for this mechanism.

Caller identity is a short-lived Ed25519 JWT minted by the gateway's existing sandbox signing authority. The gateway attaches one to its own `Describe` and `ValidateConfig` calls; sandbox supervisors attach one to `Describe` and `EvaluateHttpRequest`. Both directions of the RFC's stated requirement are covered: TLS and the configured trust roots authenticate the middleware service to OpenShell, and the exact-audience JWT proves to the middleware that a gateway or a policy-authorized sandbox supervisor made the call.

## Claim contract

| Claim | Meaning |
|---|---|
| `iss` | Exactly `openshell-gateway:<gateway_id>`. |
| `aud` | The exact audience for one registration. Never a list. |
| `sub` | Gateway identity for gateway callers; `spiffe://openshell/sandbox/<id>` for supervisor callers. |
| `caller_kind` | `gateway` or `supervisor`. |
| `sandbox_id` | Present only for supervisor callers. |
| `jti` | Unique per token. OpenShell does not track it. |
| `iat`, `exp` | Bounded lifetime, at most one hour. |

The JOSE header carries `alg: EdDSA`, the signing `kid`, and `typ: openshell-ext+jwt`.

Explicit typing exists because extension tokens and sandbox-to-gateway admission tokens are signed by the same key and would otherwise be separated by audience alone. A verifier that requires this `typ` cannot accept a sandbox bootstrap credential even if it neglects to check `aud`. This is defense in depth for the most likely verifier mistake, not a replacement for audience validation.

... (37 lines truncated)
</file>

<file path="rfc/0009-supervisor-middleware/appendices/protocol-extensions.md">
# Appendix: Protocol Extensions

> This is an appendix to the [RFC](../README.md). Please familiarize yourself with the RFC before reading this.

**Update in PR #2477 - WebSocket middleware:** V1 now includes a forward-text WebSocket operation. The updated text below separates this implemented operation from future HTTP streaming and WebSocket return-path operations.

The v1 contract is intentionally minimal: one buffered unary HTTP request hook and one forward-text WebSocket message hook, each with an `allow`/`deny` decision plus optional transformed content, findings, and metadata. This appendix records extensions the proto should not preclude, so v1 stays small without painting future work into a corner. None of these are committed; they exist to validate that the v1 shape is forward-compatible.

## Streaming

The v1 `EvaluateHttpRequest` RPC is unary. The supervisor buffers the bounded request body, sends one `HttpRequestEvaluation`, and receives one `HttpRequestResult`. Streaming is deliberately left out of that method: if OpenShell later needs chunked payload transport or incremental processing, it should add a separate operation-specific method rather than changing `EvaluateHttpRequest` cardinality.

This section records what such a future streaming operation would need to consider, and importantly what streaming does and does not buy, since the distinction is easy to get wrong.

### Transport streaming vs processing streaming

These are different concepts and are easy to conflate:

- **Transport streaming** - a separate gRPC operation carries multiple messages (chunks). This is what a service would advertise in its manifest and what the supervisor would negotiate.
- **Processing streaming** - the middleware can act on partial content before it has the whole body.

The manifest field would govern only the transport. It would not promise the middleware can process incrementally.

### Full-body guards still buffer

Many guards need the entire body to do anything: a JSON-aware redactor must parse the whole document, and a PII scan must see all of it. Such a guard, even over a streaming transport, accumulates every chunk internally, then parses, then emits a single response at end-of-stream - the decision still arrives after the last byte. Incremental processing only helps narrower cases such as byte-level regex redaction or secret scanning over a text stream.

### Why add a streaming operation later

Even when the middleware must buffer the full body, a separate chunked transport operation would buy two things:
... (64 lines truncated)
</file>

<file path="rfc/0009-supervisor-middleware/README.md">
---
authors:
  - "@pimlock"
state: accepted
links:
  - https://github.com/NVIDIA/OpenShell/issues/1043
  - https://github.com/NVIDIA/OpenShell/issues/1733
  - https://github.com/NVIDIA/OpenShell/issues/1734
  - https://github.com/NVIDIA/OpenShell/issues/1919
  - https://github.com/NVIDIA/OpenShell/issues/2010
  - https://github.com/NVIDIA/OpenShell/pull/2027
---

# RFC 0009 - Supervisor Middleware

## Revision history

| Date | References | Change |
|------|------------|--------|
| 2026-07-17 | [#2010](https://github.com/NVIDIA/OpenShell/issues/2010) | Added unary HTTP request middleware with built-in and operator-run services. |
| 2026-07-28 | [#2428](https://github.com/NVIDIA/OpenShell/issues/2428) | Added WebSocket preflight and text-message evaluation, and aligned the middleware API names, limits, and diagnostics. |

## Summary

This RFC proposes the introduction of supervisor middleware: a supervisor-side extension system for hooks that can inspect, transform, block, and annotate supervisor-managed operations at specific operation phases. The first hook family is supervisor egress middleware for outbound sandbox HTTP requests, but the framework is intentionally named and shaped so later supervisor hooks can cover other protocols or supervisor operations without renaming the feature.

## Motivation

OpenShell already controls *where* a sandbox can connect. The supervisor enforces network policy on every outbound connection and only allows egress to approved endpoints. Today, that control stops at the destination: once a connection is allowed, the request can carry any payload. Network policy can decide whether a sandbox may talk to `api.openai.com`, but it cannot decide whether a particular request to `api.openai.com` should be allowed based on what that request contains.

... (520 lines truncated)
</file>

<file path="rfc/0010-gateway-interceptors/appendices/extension-authentication.md">
# Appendix: Extension Authentication (Alpha)

> This is an appendix to the [RFC](../README.md). Please familiarize yourself with the RFC before reading this.

The RFC body states that all gateway interceptor connections require authentication, leaves the model out of scope, and suggests implementations should support mTLS and bearer-token authentication. This appendix records the mechanism that was actually built for alpha. It supersedes that paragraph; the rest of the body is unchanged.

Gateway interceptors and supervisor middleware share one implementation. The full claim contract, authorization model, key distribution, and residual risks are documented once in [RFC 0009's appendix](../../0009-supervisor-middleware/appendices/extension-authentication.md). This appendix records only what differs for interceptors.

## What ships in alpha

The bearer-token half of the body's suggestion, not the mTLS half. The gateway attaches a short-lived, exact-audience Ed25519 JWT to `Describe`, `Evaluate`, and provider-profile snapshot calls. mTLS remains deferred hardening.

Interceptors are called only by the gateway, so every token carries `caller_kind: gateway` and no `sandbox_id`. There is no supervisor-side distribution path and no policy-based authorization step: the gateway mints its own credentials at startup from configuration and rotates them in place.

## Transport

Unlike middleware, interceptors keep the body's Unix domain socket option. A gateway-local socket is reachable by the only caller that exists, so both `https://` and `unix://` are accepted when gateway JWT signing is configured. HTTPS endpoints may pin an operator-provided CA bundle and retain normal hostname verification.

## Audience agreement

The audience defaults to `urn:openshell:extension:interceptor:<name>` and may be set explicitly per interceptor. An interceptor may advertise the audience it verifies in the `expected_audience` field of its `Describe` manifest. After authenticated `Describe` succeeds, the gateway treats that value as a consistency assertion and refuses to start when it differs from the configured audience. A strict verifier may reject an incorrect audience before returning the manifest, so this does not provide audience discovery.

Because the body already makes an unavailable service, invalid manifest, or unauthorized binding a startup failure, this fits the existing posture: interceptor configuration problems surface before the gateway serves traffic.

## Compatibility

An interceptor may set `allow_insecure_transport = true` to keep a plaintext `http://` endpoint with no credential attached. The gateway logs a warning naming the interceptor at every startup. This exists for local development and for deployments configured before extension authentication existed.

## Deferred

... (2 lines truncated)
</file>

<file path="rfc/0010-gateway-interceptors/README.md">
---
authors:
  - "@anewberry"
state: accepted
links:
  - https://github.com/NVIDIA/OpenShell/issues/1919
---

# RFC 0010 - Gateway Interceptors

## Summary

Operators and external integrators need a flexible way to customize gateway API
behavior to fit their own requirements — for example, enforcing tenancy,
quotas, naming conventions, or policy authority. Today any such customization
has to be hardcoded into gateway handlers or pushed into drivers, which mixes
responsibilities and does not scale to deployment-specific requirements.

This RFC proposes a first-class extension system that lets external services
observe, modify, validate, reject, or audit gateway operations at well-defined
phases. We call these **Gateway Interceptors**.

Gateway interceptors and drivers serve different extension needs. The gateway
interceptor role adds business logic around gateway operations. Drivers replace
or provide implementation for platform functionality, such as how sandboxes are
provisioned on Docker, Kubernetes, or VMs.

This RFC scopes gateway interceptors to gateway API operations. A gateway
interceptor can observe, modify, validate, reject, or audit a gateway operation
at well-defined phases. Future RFCs may extend gateway interceptors to other
... (567 lines truncated)
</file>

<file path="rfc/0011-multi-player-design/README.md">
---
authors:
  - "@derekwaynecarr"
state: draft
links:
  - https://github.com/NVIDIA/OpenShell/issues/1977
---

# RFC 0011 - Multi-Player Support

## Summary

This RFC proposes adding multi-user support to OpenShell. Today, sandboxes and
providers are gateway-global with no ownership tracking or isolation between
users. This proposal introduces workspaces as hard isolation boundaries, an
expanded role model (Platform Admin, Workspace Admin, User), workspace-scoped
access, per-workspace quota enforcement, and audit trail enhancements. The Sandbox Supervisor remains a separate principal type
with sandbox-scoped authentication distinct from the user role model. A
`default` workspace preserves backwards compatibility for single-player
deployments.

## Motivation

OpenShell is currently a single-player experience. Every authenticated user sees
every sandbox and every provider. There is no concept of resource ownership,
tenant isolation, or delegated administration. This blocks several adoption
scenarios:

- **Enterprise teams** cannot share a gateway without seeing each other's
  sandboxes, credentials, and activity. There is no way to scope visibility
... (1547 lines truncated)
</file>

<file path="rfc/0012-isolation-backend/README.md">
---
authors:
  - "@jganoff"
state: review
links:
  - https://github.com/NVIDIA/OpenShell/issues/1737
  - https://github.com/NVIDIA/OpenShell/pull/2048
  - https://github.com/NVIDIA/OpenShell/issues/899
  - https://github.com/NVIDIA/OpenShell/issues/981
  - https://github.com/NVIDIA/OpenShell/issues/1511
  - https://github.com/NVIDIA/OpenShell/issues/1650
  - https://github.com/NVIDIA/OpenShell/issues/1680
  - https://github.com/NVIDIA/OpenShell/pull/2606
---

# RFC 0012 - Isolation Backend Interface

## Summary

Today the supervisor both builds the workload's isolation boundary and applies its network policy. Because the supervisor runs inside the agent container, the privilege needed to build that boundary sits beside the code it confines. This RFC moves boundary construction and process operations behind a pluggable **Isolation Backend**. The supervisor continues to apply approved network policy through network mediation.

The compute driver orchestrates the workload, supervisor, sandbox runtime, protected channel, and outer network fence. The supervisor is the trusted bridge between the gateway and the workload: it maintains the gateway connection, handles authorized requests, and drives the backend. The backend establishes the isolation controls, manages workload processes, and routes egress to network mediation. The same lifecycle supports different compute drivers and backend implementations without driver-specific supervisor paths.

## Motivation

Boundary construction is embedded in the supervisor, so moving it anywhere else means changing the supervisor. That placement creates three problems:

- A compromise reaches the boundary-building privilege in the same container.
- Building the boundary inside the agent container requires capabilities that conflict with restricted deployments. Delegating construction removes that requirement but does not guarantee Pod Security Standards compliance. See #899 for background.
- Each new placement adds another branch to the supervisor.
... (378 lines truncated)
</file>

<file path="rfc/0013-native-windows-mxc/README.md">
---
authors:
  - "@shailendra-nv"
state: review
links:
  - https://github.com/NVIDIA/OpenShell/issues/2050
  - https://github.com/NVIDIA/OpenShell/pull/2071
---

# RFC 0013 - Native Windows Support via the MXC Compute Driver

<!--
See rfc/README.md for the full RFC process and state definitions.
-->

## Summary

This RFC proposes extending OpenShell to run natively on Windows 11 (x64 and
ARM64) without a Linux VM, Docker Desktop, or WSL. It will produce a new
compute driver, `openshell-driver-mxc`, that will use Microsoft
Execution Containers (MXC, via `wxc-exec.exe`) as the sandbox primitive.

The central architectural conclusion is that OpenShell rejects porting its Linux
in-sandbox supervisor to Windows as part of this design. The value layers the
supervisor delivers on Linux — egress policy enforcement (OPA), L7 HTTP
inspection — are relocated to the host by running OpenShell's existing CONNECT
proxy inside the driver process and pointing MXC's built-in `network.proxy`
redirect at it. The integration therefore collapses to three moving parts: the
native Windows OpenShell gateway, a Windows-only MXC compute driver crate, and an
unmodified `wxc-exec` binary, with no OpenShell binary running inside the
... (436 lines truncated)
</file>

<file path="rfc/0014-release-stability/build-matrix.md">
# RFC 0014 Supplement - Build Matrix

This supplement defines the build targets for the release system described by
RFC 0014. The targets follow the structure of the
[proposed support matrix](https://github.com/NVIDIA/OpenShell/blob/d575cf85f8c520774cc3e307ec1bcdabf57cd682/docs/reference/support-matrix.mdx)
and describe the intended final state.

These tables enumerate build and capability targets. They do not imply that
every cross-product of platform, architecture, installation method, driver,
topology, and capability is supported. The
[release qualification supplement](release-qualification.md) defines the
minimal blocking release gate. It contains one conformance workflow per compute
driver, one Kubernetes conformance workflow per supported gateway topology, and
one upgrade workflow per installation package, plus one breaking API change
review and one security review per pre-release. Other supported dimensions are
exercised as subcases or separate CI controls rather than as a Cartesian product
of release jobs.

## Platforms

| Platform | Installation methods | Requirements |
| --- | --- | --- |
| macOS (Apple Silicon) | Homebrew | macOS 13.3 or later |
| Linux (x86_64, arm64) | APT/DEB, RPM, Snap | glibc 2.28 or later |
| Windows (x86_64, arm64) | MSI, WinGet | Documented minimum Windows version and MSVC toolchain |

Package installers include the CLI, TUI, gateway, and supported local drivers.
Standalone CLI and TUI binaries are also published for remote gateway access.

## Compute drivers
... (41 lines truncated)
</file>

<file path="rfc/0014-release-stability/README.md">
---
authors:
  - "@drew"
state: review
links:
  - https://github.com/NVIDIA/OpenShell/pull/2148
  - https://github.com/NVIDIA/OpenShell/pull/2695
---

# RFC 0014 - Alpha Exit Criteria and Stable Release Policy

## Summary

The goal of this RFC is to define OpenShell's exit from alpha and establish a
predictable release cycle for production users and ecosystem developers.

We propose

- Development releases for every commit to `main`, nightly pre-releases, and
  qualified stable releases every Tuesday.
- Stable and Experimental API maturity, compatibility, and versioning
  rules, and maintenance for the latest and N-1 minor release lines.
- A release qualification pipeline covering conformance, upgrades,
  API changes, and security reviews across the supported release matrix.

## Motivation

The goal is to exit alpha without slowing OpenShell's development. Releases
should remain frequent and automated, and Experimental APIs should be able to
evolve quickly enough to keep pace with the ecosystem. At the same time, users
... (196 lines truncated)
</file>

<file path="rfc/0014-release-stability/release-qualification.md">
# RFC 0014 Supplement - Release Qualification

A pre-release is eligible for stable publication only after its artifacts pass
every required [conformance test](#conformance-tests) and
[upgrade test](#upgrade-tests), its
[breaking API change review](#breaking-api-change-review), and its
[security review](#security-review).

## Conformance tests

Conformance tests run for different OpenShell driver, gateway, and host
configurations. Each workflow installs the pre-release in one representative
environment and verifies the supported OpenShell behavior for that
configuration.

For each driver, the suite:

1. Installs the pre-release artifacts and starts the gateway and selected runtime.
2. Verifies gateway health, version reporting, TLS, authentication, and
   authorization.
3. Creates a sandbox, connects to it, executes commands, and exercises stop,
   restart, and restore behavior where supported.
4. Exercises filesystem, process, network, credential, and inference policy
   enforcement, including expected denial behavior.
5. Verifies the configured compute driver, credential driver, interceptor, and
   middleware contracts, including capability discovery, validation, errors,
   restart reconciliation, and cleanup.
6. Deletes the sandbox and confirms that runtime, network, credential, and
   persisted resources are removed.

... (86 lines truncated)
</file>

<file path="rfc/0014-release-stability/release-version-selection.md">
# RFC 0014 Supplement - Release Version Selection

This supplement defines how OpenShell selects the next pre-release version
after a stable release during the `0.x` series.

## Algorithm

1. Find the latest stable tag and collect commits after it on the target branch.
2. Classify commits using Conventional Commits:
   - `feat:` requests a minor release.
   - A commit marked with `!` or a `BREAKING CHANGE` footer requests a minor
     release during `0.x`.
   - `fix:` and `deps:` request a patch release.
   - Other commit types do not request a release by default.
3. Select the highest requested bump. Minor takes precedence over patch. If no
   commit requests a release, do not create a pre-release.
4. Increment the stable version to obtain the pre-release base version. From
   `0.2.0`, a patch becomes `0.2.1` and a minor becomes `0.3.0`.
5. Create a `-pre.1` Git tag before building and qualifying a new base version.
   If that base already has a pre-release, increment the pre-release number.
6. Treat that base version as fixed for the weekly train. If a patch train has
   started, stage any later breaking change that requires a minor release for
   the following week's train.
7. Fail the branch check if the pre-release base version is not greater than the
   latest stable version.

| Latest stable | Commits since stable | Next pre-release |
| --- | --- | --- |
| `0.2.0` | `fix:` | `0.2.1-pre.1` |
| `0.2.0` | `feat:` | `0.3.0-pre.1` |
... (26 lines truncated)
</file>

<file path="rfc/README.md">
# OpenShell RFCs

Substantial changes to OpenShell should be proposed in writing before implementation begins. New features always start as a GitHub issue using the [feature request template](https://github.com/NVIDIA/OpenShell/issues/new/choose), not as an RFC pull request. RFCs drive nuanced discussions that need structured iteration, broad stakeholder input, and a durable record of the reasoning beyond what issue comments can fully capture.

An RFC provides a consistent way to collect broad feedback, build consensus, and document the decision for future contributors. An RFC is created only when maintainers decide the originating issue needs that level of design review.

## Start with a GitHub issue

Before writing an RFC, you must open a [GitHub issue](https://github.com/NVIDIA/OpenShell/issues/new/choose) to scope the problem, gauge interest, and get early feedback. For new features, use the feature request template. This helps:

- Validate that the problem is worth solving
- Surface potential concerns early
- Build consensus before investing in a detailed proposal
- Identify the right reviewers and stakeholders

If the ticket shows sufficient interest and maintainers decide the idea needs broad design review, they will ask for an RFC from that issue. Maintainers assign the RFC number and add the `needs-rfc` label in the issue before the RFC is created, preventing number clashes across branches and making pending RFC work searchable.

## RFCs vs other artifacts

OpenShell has several places where design information lives. Use this guide to pick the right one:

| Artifact | Purpose | When to use |
|----------|---------|-------------|
| **GitHub issue** | Track and scope a bug, feature request, or rough idea | Always start here; new features use the feature request template |
| **Spike issue** (`create-spike`) | Investigate implementation feasibility for a scoped change | You need to explore the codebase and produce a buildable issue for a specific component or feature |
| **RFC** | Propose a cross-cutting decision that needs broad consensus | Maintainers requested an RFC from an existing issue and assigned an RFC number |

The key distinction: **spikes investigate whether and how something can be done; RFCs propose that we should do it and seek agreement on the approach.** A spike may precede an RFC (to gather data) or follow one (to flesh out implementation details).

## When to use an RFC
... (133 lines truncated)
</file>

<file path="scripts/agents/gator/prompts/gator.md">
You are running inside an OpenShell sandbox as the gator gate agent.

Active harness: {{HARNESS}}.
Runtime mode: {{RUN_MODE}}.
Gator payload version: {{PAYLOAD_VERSION}}.

Load and follow this skill exactly:

/etc/openshell/agent-payload/skills/gator-gate/SKILL.md

Important sandbox constraints:

- GitHub REST write access is scoped to NVIDIA/OpenShell.
- GitHub GraphQL access is read-only except for the named
  `ResolveGatorReviewThread` mutation used by
  `resolve-gator-review-threads`. Prefer REST endpoints for all other write
  actions and use GraphQL-backed `gh` reads when useful.
- Keep watching active PRs until they close, merge, or the operator stops the sandbox.
- At the start of every watch cycle, read `payload_version` from
  `scripts/agents/gator/agent.yaml` on the default branch through the GitHub
  contents API. If the published integer is greater than
  `{{PAYLOAD_VERSION}}`, do not write to GitHub or run the reviewer. Finish with
  `OPENSHELL_AGENT_RESULT {"status":"terminal_failure","reason":"stale_gator_payload","notes":"This sandbox is using an outdated Gator payload. Relaunch it before monitoring continues."}` so the operator relaunches the immutable watcher.
- Keep discovery scoped to the operator request. For requests such as "my open non-draft PRs", closed/merged cleanup may include only matching PRs with active `gator:*` labels; query each gator label separately and de-dupe results. Do not scan or mutate all gator-labeled PRs unless the operator explicitly requested repo-wide scope.
- In `watch` runtime mode, do not run passive sleep or polling loops inside Codex. Perform one bounded reconciliation cycle, then print one `OPENSHELL_AGENT_RESULT` line as the final line of output and stop. The in-sandbox supervisor will sleep and relaunch the harness for the next cycle.
- Every result sentinel must include `notes` containing one or two concise, plain-language sentences that a human can read aloud. Summarize the current diagnosis, name any notable issue or unanswered question, and state the next useful action or owner. Do not repeat mechanical metadata, dump raw logs, or include secrets; mention a SHA only when it is essential to the diagnosis.
- In `watch` runtime mode, when the next action is to keep waiting, use this exact final-line format with a reason, poll interval, and curated notes: `OPENSHELL_AGENT_RESULT {"status":"waiting","next_poll_seconds":{{POLL_INTERVAL_SECONDS}},"reason":"checks_pending","notes":"Required checks are still running on the current head. Gator will inspect the results next cycle."}`. Use `blocked` when waiting on a human/process blocker, `complete` when the issue or PR reached a terminal state, `terminal_failure` for unrecoverable errors, and `transient_failure` only when the supervisor should retry soon.
- If required GitHub REST reads or writes fail with `EOF`, `Empty reply from server`, or sandbox `NET:FAIL` after policy allowed the endpoint, stop the cycle with `OPENSHELL_AGENT_RESULT {"status":"transient_failure","next_poll_seconds":120,"reason":"github_transport_eof","notes":"GitHub transport failed after policy allowed the request. The supervisor should retry without changing the PR state."}` rather than marking the issue or PR blocked.
- If the `principal-engineer-reviewer` sub-agent fails before producing usable review output, stop the cycle with `OPENSHELL_AGENT_RESULT {"status":"transient_failure","next_poll_seconds":120,"reason":"reviewer_subagent_failed","notes":"The reviewer did not produce usable feedback, so no PR state was changed. The supervisor should retry the review."}`. Do not post a marked gator comment or PR review, do not apply `gator:blocked`, and do not consume the one-disposition-per-head-SHA slot for sub-agent auth, token-refresh, transport, command, empty-output, malformed-output, or sub-agent-only policy failures.
- In `once` runtime mode, run one bounded cycle unless the operator explicitly asks you to watch inline. Still print `OPENSHELL_AGENT_RESULT {"status":"complete","reason":"one_shot_complete","notes":"The requested one-shot reconciliation is complete."}` when finished.
... (24 lines truncated)
</file>

<file path="scripts/agents/gator/providers/codex-gator.yaml">
id: codex-gator
display_name: Codex Gator
description: OpenAI Codex CLI profile for gator with gateway-managed access-token refresh
category: agent
inference_capable: true
credentials:
  - name: access_token
    description: Codex OAuth access token refreshed by the gateway from refresh material
    env_vars: [CODEX_AUTH_ACCESS_TOKEN]
    required: true
    auth_style: bearer
    header_name: authorization
    refresh:
      strategy: oauth2_refresh_token
      token_url: https://auth.openai.com/oauth/token
      refresh_before_seconds: 300
      max_lifetime_seconds: 3600
      material:
        - name: client_id
          description: Codex OAuth client ID
          required: true
        - name: refresh_token
          description: Codex OAuth refresh token from local auth.json
          required: true
          secret: true
  - name: account_id
    description: Codex account identifier
    env_vars: [CODEX_AUTH_ACCOUNT_ID]
    required: true
discovery:
... (29 lines truncated)
</file>

<file path="scripts/agents/gator/providers/github-gator.yaml">
id: github-gator
display_name: GitHub Gator
description: Repo-scoped GitHub access for the OpenShell gator gate agent
category: source_control
credentials:
  - name: GITHUB_TOKEN
    description: GitHub token used by the gator gate agent
    env_vars: [GITHUB_TOKEN, GH_TOKEN]
    required: true
    auth_style: bearer
    header_name: authorization
discovery:
  credentials: [GITHUB_TOKEN]
endpoints:
  - host: api.github.com
    port: 443
    protocol: rest
    enforcement: enforce
    rules:
      - allow: { method: GET, path: /user }
      - allow:
          method: GET
          path: /search/issues
          query:
            q:
              any:
                - "*repo:NVIDIA/OpenShell*"
      - allow: { method: GET, path: /repos/NVIDIA/OpenShell }
      - allow: { method: GET, path: /repos/NVIDIA/OpenShell/** }
      - allow: { method: POST, path: /repos/NVIDIA/OpenShell/issues/*/comments }
... (56 lines truncated)
</file>

<file path="scripts/agents/gator/skills/gator-gate/references/review-findings-schema.md">
# Review findings contract

Before invoking the reviewer, require JSON with this envelope:

```json
{
  "schema_version": 1,
  "reviewed_head_sha": "<40-character head SHA>",
  "review_mode": "<initial|follow_up|critical_only>",
  "findings": []
}
```

Each proposed finding uses these fields:

```json
{
  "id": "GATOR-12345678-01",
  "severity": "Critical",
  "invariant": "The complete contract shared by equivalent cases.",
  "attacker_or_operator_prerequisite": "Capability required to reach the case.",
  "supported_entry_point": "Supported API, CLI, protocol, or runtime path.",
  "sink": "Operation where the defect becomes observable.",
  "changed_location": {
    "path": "path/to/file.rs",
    "line": 123
  },
  "base_behavior": "Behavior at the reviewed base or previous reviewed tree.",
  "head_behavior": "Behavior introduced or materially worsened at this head.",
  "observable_impact": "Concrete security, data-loss, correctness, or maintainability impact.",
... (41 lines truncated)
</file>

<file path="scripts/agents/gator/skills/gator-gate/SKILL.md">
---
name: gator-gate
description: Validate and monitor OpenShell GitHub issues and PRs using the gator:* state machine. Use when asked to triage issues/PRs for project validity, gate PRs, run gator, validate submissions, or monitor PRs toward merge readiness.
---

# Gator Gate

Validate OpenShell GitHub issues and pull requests for project fit, then monitor valid PRs until they are ready for maintainer approval.

This skill is a gating workflow. It can start from any issue or PR state, inspect the current `gator:*` label, and continue the correct next action.

## Skill Location

Codex and other agent harnesses should load this skill from the repository path `scripts/agents/gator/skills/gator-gate/SKILL.md`. After this branch is merged, the canonical GitHub location is <https://github.com/NVIDIA/OpenShell/blob/main/scripts/agents/gator/skills/gator-gate/SKILL.md>.

## Prerequisites

- The `gh` CLI must be able to call GitHub APIs (`gh api user --jq '.login'`)
- You must be in the OpenShell repository root
- GitHub write permissions are required to apply labels, comment, close issues/PRs, or post `/ok to test`

Do not use `gh auth status` as the authentication health check inside provider-backed sandboxes. Scoped provider tokens may be exposed as `openshell:resolve:env:*` placeholders and `gh auth status` probes endpoints outside the gator policy, causing false "token is invalid" reports even when allowed `gh api` and `gh pr` calls succeed. Use `gh api user --jq '.login'` and a repo-scoped probe instead.

Use REST-backed `gh api` for GitHub write actions inside gator sandboxes. Do not rely on `gh issue edit`, `gh pr edit`, or other high-level write commands when a REST path is available, because some of them use GraphQL mutations and gator policy allows GraphQL reads only. Do not fall back to `curl` for credentialed GitHub writes unless the active provider policy explicitly allows the `curl` binary for the same scoped endpoint. Preferred write shapes:

```bash
jq -Rs '{body:.}' comment.md > /tmp/comment.json
gh api --method POST repos/NVIDIA/OpenShell/issues/<number>/comments --input /tmp/comment.json --jq .html_url
gh api --method POST repos/NVIDIA/OpenShell/issues/<number>/labels -f labels[]="gator:<state>"
gh api --method DELETE repos/NVIDIA/OpenShell/issues/<number>/labels/gator%3Ablocked --silent || true
... (1282 lines truncated)
</file>

<file path="scripts/agents/gator/agent.yaml">
id: gator
payload_version: 9
display_name: Gator Gate Agent
description: Validate and monitor OpenShell GitHub issues and pull requests through the gator state machine.
sandbox:
  name_prefix: gtr
  from: agent://.
  gateway: docker-dev
harness:
  default: codex
  supported:
    codex:
      model: gpt-5.6-sol
      reasoning: medium
runtime:
  mode: watch
  poll_interval_seconds: 900
  max_transient_failures: 5
profile_paths:
  - providers
settings:
  - key: agent_policy_proposals_enabled
    value: true
  - key: proposal_approval_mode
    value: auto
providers:
  - id: github
    name: github-gator
    profile: github-gator
    credential_mode: explicit
... (51 lines truncated)
</file>

<file path="scripts/agents/gator/Dockerfile">
# syntax=docker/dockerfile:1

# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

# Gator sandbox image.
#
# This installs the core system and developer
# tooling, but keeps the initial agent surface focused on Codex + GitHub tooling
# for the gator-gate workflow.

FROM nvcr.io/nvidia/base/ubuntu:noble-20251013 AS system

ENV DEBIAN_FRONTEND=noninteractive \
    PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1

WORKDIR /sandbox

# Core system dependencies required by the gator workload.
# iproute2: network namespace management (ip netns, veth pairs)
# iptables: legacy bypass detection (kept for transition)
# nftables: bypass detection; log + reject rules for direct connection diagnostics
# dnsutils: dig, nslookup
RUN apt-get update && apt-get install -y --no-install-recommends \
        ca-certificates \
        curl \
        dnsutils \
        iproute2 \
        iptables \
... (74 lines truncated)
</file>

<file path="scripts/agents/gator/policy.yaml">
version: 1
filesystem_policy:
  include_workdir: true
  read_only: [/usr, /lib, /proc, /dev/urandom, /app, /etc, /var/log]
  read_write: [/sandbox, /tmp, /dev/null]
landlock:
  compatibility: best_effort
process:
  run_as_user: sandbox
  run_as_group: sandbox
network_policies: {}
</file>

<file path="scripts/agents/gator/README.md">
# Gator Agent

Launch a headless sandbox agent that runs the `gator-gate` skill against OpenShell issues and pull requests. The default and currently only supported harness is Codex.

## Prerequisites

- `gh` is authenticated on the host and has access to `NVIDIA/OpenShell`.
- For `--harness codex`, `codex login` has created `$HOME/.codex/auth.json`.
- For `--harness codex`, local Codex auth must include an access token, refresh token, and account ID.
- A local gateway and either Docker or Podman are available to build the
  default sandbox image.

## Usage

```shell
./scripts/agents/run.sh \
  --agent gator \
  --gateway docker-dev \
  --harness codex \
  "Run gator on PR 1536 and keep watching until it closes or merges."
```

By default the launcher uses `scripts/agents/gator/Dockerfile` as the sandbox image source. It builds `scripts/agents/gator/` as the image context, so gator-specific image files such as `policy.yaml` and `bin/gh` stay with the gator agent. The launcher bakes rendered prompts, skills, subagents, and shared runtime files into `/etc/openshell/agent-payload`, then passes the resulting image reference to `openshell sandbox create`.

The launcher queries the selected gateway and builds with its Docker or Podman
compute driver. If `CONTAINER_ENGINE` is set, it must match that driver. Other
gateway drivers cannot run this local-image launcher.

Use `--harness codex` to select Codex explicitly. Other harness names are rejected until their support is added to `agent.yaml` and `scripts/agents/runtime/harnesses/<name>/`. Agent directories do not carry their own harness implementations; they provide prompt templates and optional skills or subagents for the shared runtime to inject.

... (43 lines truncated)
</file>

<file path="scripts/agents/runtime/harnesses/codex/exec_test.sh">
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TMP_DIR="$(mktemp -d)"
trap 'rm -rf "$TMP_DIR"' EXIT
ACCESS_PLACEHOLDER="openshell:resolve:env:s$(printf 'a%.0s' {1..64})_CODEX_AUTH_ACCESS_TOKEN"
ACCOUNT_PLACEHOLDER="openshell:resolve:env:v42_CODEX_AUTH_ACCOUNT_ID"
cat > "$TMP_DIR/codex" <<'MOCK'
set -euo pipefail
if [[ "${1:-}" == "exec" && "${2:-}" == "--help" ]]; then
    exit 0
fi
access="$(jq -r '.tokens.access_token' "$HOME/.codex/auth.json")"
account="$(jq -r '.tokens.account_id' "$HOME/.codex/auth.json")"
[[ "$access" == "$EXPECTED_ACCESS_PLACEHOLDER" ]]
[[ "$account" == "$EXPECTED_ACCOUNT_PLACEHOLDER" ]]
printf '%s\n' 'ok - Codex auth preserves opaque provider placeholders'
MOCK
chmod +x "$TMP_DIR/codex"
printf '%s\n' 'test prompt' > "$TMP_DIR/prompt.md"
OPENSHELL_AGENT_HOME="$TMP_DIR/home" \
CODEX_BIN="$TMP_DIR/codex" \
CODEX_AUTH_ACCESS_TOKEN="$ACCESS_PLACEHOLDER" \
CODEX_AUTH_ACCOUNT_ID="$ACCOUNT_PLACEHOLDER" \
GITHUB_TOKEN="openshell:resolve:env:v42_GITHUB_TOKEN" \
EXPECTED_ACCESS_PLACEHOLDER="$ACCESS_PLACEHOLDER" \
EXPECTED_ACCOUNT_PLACEHOLDER="$ACCOUNT_PLACEHOLDER" \
    bash "$SCRIPT_DIR/exec.sh" "$TMP_DIR/prompt.md"
</file>

<file path="scripts/agents/runtime/harnesses/codex/exec.sh">
set -euo pipefail
if [[ $
    echo "usage: exec.sh <prompt-file>" >&2
    exit 2
fi
require_env() {
    local name="$1"
    [[ -n "${!name:-}" ]] || { echo "missing required env: $name" >&2; exit 1; }
}
require_env CODEX_AUTH_ACCESS_TOKEN
require_env CODEX_AUTH_ACCOUNT_ID
require_env GITHUB_TOKEN
PROMPT_FILE="$1"
export GH_TOKEN="$GITHUB_TOKEN"
export GH_PROMPT_DISABLED=1
export GH_NO_UPDATE_NOTIFIER=1
export GH_NO_EXTENSION_UPDATE_NOTIFIER=1
export GH_TELEMETRY=false
export DO_NOT_TRACK=1
export HOME="${OPENSHELL_AGENT_HOME:-/sandbox/home}"
echo "openshell-agent: preparing Codex harness auth and workspace" >&2
mkdir -p "$HOME/.codex"
node - <<'NODE'
const fs = require("fs");
const path = `${process.env.HOME}/.codex/auth.json`;
const b64u = (obj) => Buffer.from(JSON.stringify(obj)).toString("base64url");
// Preserve gateway-issued revision and stable-handle placeholders verbatim.
// Endpoint-bound credentials reject identityless aliases by design.
const providerValue = (envName) => process.env[envName];
const now = Math.floor(Date.now() / 1000);
... (54 lines truncated)
</file>

<file path="scripts/agents/runtime/harnesses/codex/install-codex.sh">
set -euo pipefail
version="${1:-${CODEX_VERSION:-latest}}"
if [[ "$version" != "latest" && ! "$version" =~ ^[0-9]+(\.[0-9]+){0,2}(-[0-9A-Za-z.-]+)?$ ]]; then
    echo "unsupported Codex version: $version" >&2
    exit 2
fi
npm install -g "@openai/codex@${version}"
npm cache clean --force >/dev/null 2>&1 || true
codex --version
</file>

<file path="scripts/agents/runtime/harnesses/codex/subagent.sh">
set -euo pipefail
if [[ $
    echo "usage: subagent.sh <subagent-id> < task.md" >&2
    exit 2
fi
SUBAGENT_ID="$1"
ADAPTER_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PAYLOAD_DIR="$(cd "$ADAPTER_DIR/../../.." && pwd)"
SUBAGENT_PROMPT="$PAYLOAD_DIR/subagents/$SUBAGENT_ID.md"
[[ -f "$SUBAGENT_PROMPT" ]] || {
    echo "missing subagent prompt: $SUBAGENT_PROMPT" >&2
    exit 1
}
CODEX_BIN="${CODEX_BIN:-codex}"
if [[ -x "$PAYLOAD_DIR/runtime/harnesses/codex/codex" ]]; then
    CODEX_BIN="$PAYLOAD_DIR/runtime/harnesses/codex/codex"
fi
CODEX_MODEL="${CODEX_MODEL:-gpt-5.5}"
CODEX_REASONING="${CODEX_REASONING:-high}"
TASK_FILE="$(mktemp)"
PROMPT_FILE="$(mktemp)"
cleanup() {
    rm -f "$TASK_FILE" "$PROMPT_FILE"
}
trap cleanup EXIT
cat >"$TASK_FILE"
{
    printf '%s\n\n' "You are running as the $SUBAGENT_ID sub-agent inside an OpenShell sandbox."
    printf '%s\n\n' 'Follow this agent definition exactly:'
    cat "$SUBAGENT_PROMPT"
... (22 lines truncated)
</file>

<file path="scripts/agents/runtime/entrypoint.sh">
set -euo pipefail
require_env() {
    local name="$1"
    [[ -n "${!name:-}" ]] || { echo "missing required env: $name" >&2; exit 1; }
}
require_env OPENSHELL_AGENT_HARNESS
RUNTIME_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PAYLOAD_DIR="$(cd "$RUNTIME_DIR/.." && pwd)"
SUPERVISOR="$PAYLOAD_DIR/runtime/supervisor.sh"
[[ -x "$SUPERVISOR" ]] || { echo "missing agent supervisor: $SUPERVISOR" >&2; exit 1; }
exec bash "$SUPERVISOR"
</file>

<file path="scripts/agents/runtime/subagent.sh">
set -euo pipefail
if [[ $
    echo "usage: subagent.sh <subagent-id> < task.md" >&2
    exit 2
fi
HARNESS="${OPENSHELL_AGENT_HARNESS:-}"
[[ -n "$HARNESS" ]] || { echo "missing required env: OPENSHELL_AGENT_HARNESS" >&2; exit 1; }
RUNTIME_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PAYLOAD_DIR="$(cd "$RUNTIME_DIR/.." && pwd)"
ADAPTER="$PAYLOAD_DIR/runtime/harnesses/$HARNESS/subagent.sh"
[[ -x "$ADAPTER" ]] || { echo "missing subagent adapter: $ADAPTER" >&2; exit 1; }
exec bash "$ADAPTER" "$1"
</file>

<file path="scripts/agents/runtime/supervisor_test.sh">
set -euo pipefail
SUPERVISOR_UNDER_TEST="${SUPERVISOR_UNDER_TEST:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/supervisor.sh}"
fail() {
    printf 'not ok - %s\n' "$*" >&2
    exit 1
}
assert_contains() {
    local file="$1"
    local expected="$2"
    if ! grep -Fq "$expected" "$file"; then
        printf 'missing expected text: %s\n' "$expected" >&2
        printf '%s\n' '--- output ---' >&2
        sed -n '1,200p' "$file" >&2
        fail "assert_contains failed"
    fi
}
make_payload() {
    local dir="$1"
    local adapter_body="$2"
    mkdir -p "$dir/runtime/harnesses/test"
    printf 'test prompt\n' > "$dir/agent-prompt.md"
    cp "$SUPERVISOR_UNDER_TEST" "$dir/runtime/supervisor.sh"
    cat > "$dir/runtime/harnesses/test/exec.sh" <<EOF
set -euo pipefail
$adapter_body
EOF
    chmod +x "$dir/runtime/harnesses/test/exec.sh"
}
run_supervisor() {
    local payload_dir="$1"
... (205 lines truncated)
</file>

<file path="scripts/agents/runtime/supervisor.sh">
set -euo pipefail
require_env() {
    local name="$1"
    [[ -n "${!name:-}" ]] || { echo "missing required env: $name" >&2; exit 1; }
}
require_env OPENSHELL_AGENT_HARNESS
RUNTIME_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PAYLOAD_DIR="$(cd "$RUNTIME_DIR/.." && pwd)"
PROMPT_FILE="$PAYLOAD_DIR/agent-prompt.md"
ADAPTER="$PAYLOAD_DIR/runtime/harnesses/$OPENSHELL_AGENT_HARNESS/exec.sh"
RUN_MODE="${OPENSHELL_AGENT_RUN_MODE:-once}"
POLL_INTERVAL_SECONDS="${OPENSHELL_AGENT_POLL_INTERVAL_SECONDS:-900}"
MAX_TRANSIENT_FAILURES="${OPENSHELL_AGENT_MAX_TRANSIENT_FAILURES:-5}"
HEARTBEAT_SECONDS="${OPENSHELL_AGENT_HEARTBEAT_SECONDS:-60}"
STATE_DIR="${OPENSHELL_AGENT_STATE_DIR:-/sandbox/.openshell-agent}"
STATE_HISTORY_LIMIT="${OPENSHELL_AGENT_STATE_HISTORY_LIMIT:-100}"
MAX_NOTES_LENGTH="${OPENSHELL_AGENT_MAX_NOTES_LENGTH:-2048}"
MAX_SLEEP_SECONDS=86400
[[ -f "$PROMPT_FILE" ]] || { echo "missing agent prompt: $PROMPT_FILE" >&2; exit 1; }
[[ -x "$ADAPTER" ]] || { echo "missing harness adapter: $ADAPTER" >&2; exit 1; }
case "$RUN_MODE" in
    once|watch) ;;
    *) echo "unsupported agent run mode: $RUN_MODE" >&2; exit 2 ;;
esac
[[ "$POLL_INTERVAL_SECONDS" =~ ^[0-9]+$ ]] || { echo "OPENSHELL_AGENT_POLL_INTERVAL_SECONDS must be an integer" >&2; exit 2; }
[[ "$MAX_TRANSIENT_FAILURES" =~ ^[0-9]+$ ]] || { echo "OPENSHELL_AGENT_MAX_TRANSIENT_FAILURES must be an integer" >&2; exit 2; }
[[ "$HEARTBEAT_SECONDS" =~ ^[0-9]+$ ]] || { echo "OPENSHELL_AGENT_HEARTBEAT_SECONDS must be an integer" >&2; exit 2; }
[[ "$STATE_HISTORY_LIMIT" =~ ^[0-9]+$ ]] || { echo "OPENSHELL_AGENT_STATE_HISTORY_LIMIT must be an integer" >&2; exit 2; }
[[ "$MAX_NOTES_LENGTH" =~ ^[0-9]+$ ]] || { echo "OPENSHELL_AGENT_MAX_NOTES_LENGTH must be an integer" >&2; exit 2; }
[[ "$POLL_INTERVAL_SECONDS" -gt 0 ]] || { echo "OPENSHELL_AGENT_POLL_INTERVAL_SECONDS must be greater than zero" >&2; exit 2; }
... (311 lines truncated)
</file>

<file path="scripts/agents/README.md">
# OpenShell Agents

`scripts/agents/` contains repository-owned agent launchers. An agent is a
manifest plus prompt assets that the shared launcher turns into an OpenShell
sandbox run. Agents do not own harness implementations. Harness-specific setup
and execution live in `runtime/harnesses/<name>/`.

## Directory Layout

```text
scripts/agents/
  run.sh                    # Generic manifest-driven launcher
  runtime/                  # Shared in-sandbox runtime
    entrypoint.sh           # Starts the in-sandbox supervisor
    supervisor.sh           # Runs bounded harness cycles in once/watch mode
    subagent.sh             # Generic subagent dispatcher
    harnesses/
      codex/                # Codex install and execution adapter
  <agent>/
    agent.yaml              # Agent manifest
    prompts/                # Prompt templates rendered at launch
    providers/              # Provider profile YAML files for this agent
    policy.yaml             # Optional image policy source
```

Agent directories should contain agent-specific intent and payloads: manifests,
prompt templates, provider profiles, policies, and references to skills or
subagents. They should not contain `harnesses/codex`, `harnesses/opencode`, or
similar runtime code.

... (181 lines truncated)
</file>

<file path="scripts/agents/run.sh">
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT_DIR="$(cd "$SCRIPT_DIR/../.." && pwd)"
OPENSHELL_BIN="${OPENSHELL_BIN:-openshell}"
AGENT_ARG="${OPENSHELL_AGENT_DIR:-}"
GATEWAY_OVERRIDE=""
SANDBOX_NAME_OVERRIDE=""
SANDBOX_FROM_OVERRIDE=""
HARNESS_OVERRIDE="${GATOR_HARNESS:-}"
GITHUB_PROVIDER_OVERRIDE="${GATOR_GITHUB_PROVIDER:-}"
CODEX_PROVIDER_OVERRIDE="${GATOR_CODEX_PROVIDER:-}"
CODEX_PROVIDER_PROFILE_OVERRIDE="${GATOR_CODEX_PROVIDER_PROFILE:-}"
CODEX_ACCESS_KEY_OVERRIDE="${GATOR_CODEX_ACCESS_CREDENTIAL_KEY:-}"
CODEX_LOCAL_BIN="${GATOR_CODEX_LOCAL_BIN:-}"
RUN_MODE_OVERRIDE="${OPENSHELL_AGENT_RUN_MODE:-}"
POLL_INTERVAL_OVERRIDE="${OPENSHELL_AGENT_POLL_INTERVAL_SECONDS:-}"
MAX_TRANSIENT_FAILURES_OVERRIDE="${OPENSHELL_AGENT_MAX_TRANSIENT_FAILURES:-}"
RESET_REFRESH="${OPENSHELL_AGENT_RESET_REFRESH:-0}"
KEEP_SANDBOX=0
usage() {
    printf '%s\n' 'Usage: scripts/agents/run.sh --agent <name-or-path> [options] "agent prompt"'
    cat <<'EOF'
Options:
  --agent NAME|PATH       Agent manifest directory or name under scripts/agents/
  --gateway NAME          Gateway name to use
  --name NAME             Sandbox name
  --from DOCKERFILE|DIR   Local Dockerfile source for the sandbox image
  --harness NAME          Agent harness to run
  --github-provider NAME  Override the github-gator provider instance name
  --codex-provider NAME   Override the codex-gator provider instance name
... (711 lines truncated)
</file>

<file path="scripts/lint-mermaid/lint-mermaid.mjs">
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
⋮----
// Validate ```mermaid fenced blocks in Markdown/MDX files using the official
// mermaid parser. Line numbers in error output are offset back to the source
// file so editors can jump to them.
//
// Why this approach (load the real `mermaid` npm package in Node + jsdom):
//
// - `@mermaid-js/mermaid-cli` (mmdc): uses the official parser/renderer, but
//   pulls Puppeteer + Chromium (~300MB) because it also produces SVGs. Way
//   too heavy for pre-commit; usable only as a CI backstop.
// - `@probelabs/maid`: fast, Chevrotain-based, single small package. In
//   practice it produced false positives AND missed real errors in this
//   repo (notably the `exec()s` sequence-diagram bug in
//   `architecture/sandbox-connect.md`). Dropped for unreliability.
// - `go-mermaid`: pure Go single binary — attractive, but a custom parser
//   that lags the official Mermaid grammar; would drift silently.
// - `@mermaid-js/parser` (Langium, official): library only, and as of
//   writing covers only a subset of diagram types (flowchart, sequence,
//   class, state still partially on the legacy Jison grammar inside the
//   main `mermaid` package). Incomplete for our mix of diagrams.
// - `mermaid.parse()` from the `mermaid` package (this approach): uses the
//   SAME grammar that actually renders on GitHub and in Fern previews, so
//   "passes here" == "renders there". Needs a DOM shim because mermaid
//   loads DOMPurify at import time, hence jsdom. Runs in ~2s across the
//   repo with no browser dependency.
⋮----
async function* walk(root)
⋮----
... (16 lines truncated)
</file>

<file path="scripts/lint-mermaid/package.json">
{
  "name": "openshell-lint-mermaid",
  "private": true,
  "version": "0.0.0",
  "description": "Mermaid diagram validation for OpenShell docs. Not published.",
  "type": "module",
  "dependencies": {
    "jsdom": "^25.0.1",
    "mermaid": "^11.4.0"
  },
  "overrides": {
    "dompurify": "3.4.15"
  }
}
</file>

<file path="scripts/baseline_workflow_metrics.py">
REPO = "NVIDIA/OpenShell"
⋮----
WORKFLOWS: list[str] = [
⋮----
REUSABLE_WORKFLOWS: set[str] = {
⋮----
RUN_TIME_CONCLUSIONS: set[str] = {"success", "failure"}
⋮----
@dataclasses.dataclass
class RunSummary
⋮----
id: int
created_at: dt.datetime
run_started_at: dt.datetime | None
updated_at: dt.datetime
conclusion: str | None
event: str
⋮----
@property
    def queue_seconds(self) -> float | None
⋮----
@property
    def wall_seconds(self) -> float | None
⋮----
start = self.run_started_at or self.created_at
⋮----
@dataclasses.dataclass
class WorkflowStats
⋮----
workflow: str
... (114 lines truncated)
</file>

<file path="scripts/docker-cleanup.sh">
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${SCRIPT_DIR}/../tasks/scripts/container-engine.sh"
DRY_RUN=false
SKIP_CACHE=false
FORCE=false
usage() {
  sed -n '/^# Usage:/,/^$/p' "$0" | sed 's/^# \?//'
  exit 0
}
for arg in "$@"; do
  case "$arg" in
    --dry-run)    DRY_RUN=true ;;
    --skip-cache) SKIP_CACHE=true ;;
    --force)      FORCE=true ;;
    -h|--help)    usage ;;
    *) echo "Unknown option: $arg"; usage ;;
  esac
done
BOLD='\033[1m'
DIM='\033[2m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
RED='\033[0;31m'
RESET='\033[0m'
info()  { echo -e "${BOLD}==> $*${RESET}"; }
note()  { echo -e "    ${DIM}$*${RESET}"; }
ok()    { echo -e "    ${GREEN}$*${RESET}"; }
warn()  { echo -e "    ${YELLOW}$*${RESET}"; }
err()   { echo -e "    ${RED}$*${RESET}"; }
... (162 lines truncated)
</file>

<file path="scripts/generate_third_party_notices.py">
WORKSPACE_CRATES = frozenset(
⋮----
OWN_PYTHON_PACKAGES = frozenset(
⋮----
SEPARATOR = "=" * 80
THIN_SEP = "-" * 80
⋮----
def find_repo_root() -> Path
⋮----
path = Path.cwd()
⋮----
path = path.parent
⋮----
def get_rust_notices() -> list[dict]
⋮----
result = subprocess.run(
⋮----
data = json.loads(result.stdout)
groups: list[dict] = []
⋮----
crates = []
⋮----
crate = entry.get("crate", {})
name = crate.get("name", "")
⋮----
# ---------------------------------------------------------------------------
# Python dependencies via pip-licenses
⋮----
def get_python_notices() -> list[dict]
⋮----
... (36 lines truncated)
</file>

<file path="scripts/junit-to-html.xsl">
<?xml version="1.0" encoding="UTF-8"?>
<!-- SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -->
<!-- SPDX-License-Identifier: Apache-2.0 -->
<!--
  Convert a nextest JUnit report into a standalone HTML report (XSLT 1.0).

  Usage:
    xsltproc junit-to-html.xsl report.xml > report.html
    xsltproc -stringparam title "my suite report" junit-to-html.xsl report.xml > report.html

  Renders a summary plus a per-suite table with pass/fail/skip rows. The report
  heading is the `title` parameter (default "Test report").
-->
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="html" indent="yes" encoding="UTF-8"
      doctype-system="about:legacy-compat"/>

  <!-- Report heading; override via the xsltproc `title` string parameter. -->
  <xsl:param name="title" select="'Test report'"/>

  <xsl:template match="/testsuites">
    <html lang="en">
      <head>
        <meta charset="UTF-8"/>
        <title><xsl:value-of select="$title"/></title>
        <style>
          :root {
            --bg: #f6f7f9; --card: #fff; --ink: #1f2328; --muted: #656d76;
            --border: #d7dbe0; --pass: #1a7f37; --fail: #cf222e; --skip: #9a6700;
... (143 lines truncated)
</file>

<file path="scripts/keycloak-dev.sh">
set -euo pipefail
CONTAINER_NAME="openshell-keycloak"
KEYCLOAK_IMAGE="quay.io/keycloak/keycloak:24.0"
KEYCLOAK_PORT="${KEYCLOAK_PORT:-8180}"
REALM_FILE="$(cd "$(dirname "$0")" && pwd)/keycloak-realm.json"
HEALTH_TIMEOUT=90
if [ -n "${CONTAINER_RUNTIME:-}" ]; then
    CTR="$CONTAINER_RUNTIME"
elif command -v docker &>/dev/null; then
    CTR=docker
elif command -v podman &>/dev/null; then
    CTR=podman
else
    echo "Error: neither docker nor podman found in PATH" >&2
    exit 1
fi
cmd_start() {
    if $CTR inspect "$CONTAINER_NAME" &>/dev/null; then
        if $CTR inspect --format '{{.State.Running}}' "$CONTAINER_NAME" 2>/dev/null | grep -q true; then
            echo "Keycloak is already running on port $KEYCLOAK_PORT"
            print_info
            return 0
        fi
        echo "Removing stopped container $CONTAINER_NAME..."
        $CTR rm "$CONTAINER_NAME" >/dev/null
    fi
    if [ ! -f "$REALM_FILE" ]; then
        echo "Error: realm file not found: $REALM_FILE" >&2
        exit 1
    fi
... (108 lines truncated)
</file>

<file path="scripts/keycloak-realm.json">
{
  "realm": "openshell",
  "enabled": true,
  "sslRequired": "none",
  "registrationAllowed": false,
  "loginWithEmailAllowed": true,
  "duplicateEmailsAllowed": false,
  "resetPasswordAllowed": false,
  "editUsernameAllowed": false,
  "bruteForceProtected": false,
  "accessTokenLifespan": 300,
  "ssoSessionIdleTimeout": 1800,
  "ssoSessionMaxLifespan": 36000,
  "offlineSessionIdleTimeout": 2592000,
  "roles": {
    "realm": [
      {
        "name": "openshell-admin",
        "description": "Full administrative access to OpenShell"
      },
      {
        "name": "openshell-user",
        "description": "Standard user access to OpenShell"
      }
    ]
  },
  "defaultRoles": ["openshell-user"],
  "clientScopes": [
    {
      "name": "openid",
... (365 lines truncated)
</file>

<file path="scripts/keycloak-realm.json.license">
SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
SPDX-License-Identifier: Apache-2.0
</file>

<file path="scripts/smoke-test-network-policy.sh">
set -uo pipefail
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
BOLD='\033[1m'
RESET='\033[0m'
PASS_COUNT=0
FAIL_COUNT=0
pass() { ((PASS_COUNT++)); echo -e "  ${GREEN}PASS${RESET} $1"; }
fail() { ((FAIL_COUNT++)); echo -e "  ${RED}FAIL${RESET} $1\n       $2"; }
header() { echo -e "\n${BOLD}=== $1 ===${RESET}"; }
PROVIDER_NAME="smoke-test-github"
SANDBOXES=()
POLICY_DIR=""
# Resolve token from GITHUB_TOKEN or GH_TOKEN
TOKEN="${GITHUB_TOKEN:-${GH_TOKEN:-}}"
# ---------------------------------------------------------------------------
# Preflight
# ---------------------------------------------------------------------------
header "Preflight"
if [[ -z "$TOKEN" ]]; then
    echo -e "${RED}Error: GITHUB_TOKEN or GH_TOKEN env var is required${RESET}"
    exit 1
fi
echo "  Token is set"
if ! openshell status >/dev/null 2>&1; then
    echo -e "${RED}Error: No healthy gateway. Run: mise run gateway:docker${RESET}"
    exit 1
fi
echo "  Gateway is healthy"
... (295 lines truncated)
</file>

<file path="scripts/test-release-tag.sh">
set -euo pipefail
TAG="v0.0.1"
REPO="$(gh repo view --json nameWithOwner -q .nameWithOwner)"
cleanup() {
  echo
  echo "=== Cleanup ==="
  if git ls-remote --tags origin | grep -q "refs/tags/${TAG}$"; then
    echo "Deleting remote tag ${TAG}..."
    git push origin --delete "${TAG}"
  else
    echo "Remote tag ${TAG} not found, skipping."
  fi
  if git tag -l "${TAG}" | grep -q "${TAG}"; then
    echo "Deleting local tag ${TAG}..."
    git tag -d "${TAG}"
  else
    echo "Local tag ${TAG} not found, skipping."
  fi
  if gh release view "${TAG}" &>/dev/null; then
    echo "Deleting GitHub release ${TAG}..."
    gh release delete "${TAG}" --yes --cleanup-tag
  else
    echo "GitHub release ${TAG} not found, skipping."
  fi
  echo "Done."
}
if [[ "${1:-}" == "--clean" ]]; then
  cleanup
  exit 0
fi
... (33 lines truncated)
</file>

<file path="scripts/update_license_headers.py">
COPYRIGHT_TEXT = (
LICENSE_ID = "Apache-2.0"
⋮----
COMMENT_STYLES: dict[str, str] = {
⋮----
FILE_COMMENT_STYLES: dict[str, str] = {
⋮----
SIDECAR_LICENSE_FILES: set[str] = {
⋮----
EXCLUDE_DIRS: set[str] = {
⋮----
EXCLUDE_FILES: set[str] = {
⋮----
EXCLUDE_DIR_PREFIXES: tuple[str, ...] = (
⋮----
def make_header(comment: str) -> str
⋮----
def find_repo_root() -> Path
⋮----
path = Path.cwd()
⋮----
path = path.parent
⋮----
def is_excluded(rel: Path) -> bool
⋮----
rel_str = rel.as_posix()
⋮----
def git_candidate_files(root: Path) -> list[Path] | None
⋮----
result = subprocess.run(
... (91 lines truncated)
</file>

<file path="sdk/conformance/oauth-client-credentials.json">
{
  "request": {
    "grant_type": "client_credentials",
    "client_id": "service-client",
    "client_secret": "conformance-secret",
    "scopes": ["sandbox:read", "sandbox:write"],
    "scope": "sandbox:read sandbox:write",
    "audience": "openshell-gateway",
    "forbidden_implicit_scopes": ["openid", "profile", "email"]
  },
  "expiry": {
    "leeway_seconds": 30,
    "valid_expires_in": 120,
    "invalid_expires_in": [0, -1, "NaN", null]
  },
  "discovery": {
    "configured_issuer": "https://issuer.example.com",
    "matching_issuer": "https://issuer.example.com/",
    "mismatched_issuer": "https://attacker.example.com",
    "redirect_statuses": [301, 302, 307, 308]
  },
  "limits": {
    "max_response_bytes": 1048576
  },
  "urls": {
    "allowed": [
      "https://issuer.example.com",
      "http://localhost:8080",
      "http://127.0.0.1:8080",
      "http://127.42.0.1:8080",
... (15 lines truncated)
</file>

<file path="sdk/conformance/oauth-client-credentials.json.license">
SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
SPDX-License-Identifier: Apache-2.0
</file>

<file path="sdk/go/docs/src/api/client.md">
# Client

Constructor: `v1.NewClient(config)`

`Client` is the root entry point for SDK operations. It provides typed accessors
for each resource domain and manages the underlying gRPC connection. The
`ClientInterface` covers the stable core accessors; additive helpers such as
`SandboxTemplates()` are available on the concrete client.

## Methods

| Accessor | Returns | Description |
|----------|---------|-------------|
| `Sandboxes()` | `SandboxInterface` | Sandbox lifecycle management |
| `SandboxTemplates()` | `SandboxTemplateInterface` | Reusable sandbox template management |
| `Providers()` | `ProviderInterface` | Provider CRUD and idempotent ensure |
| `Services()` | `ServiceInterface` | Service exposure and management |
| `Exec()` | `ExecInterface` | Command execution (run, stream, interactive) |
| `Files()` | `FileInterface` | File upload and download |
| `Health()` | `HealthInterface` | Gateway health checking |
| `SSH()` | `SSHInterface` | SSH session and tunnel management |
| `TCP()` | `TCPInterface` | TCP port forwarding |
| `Config()` | `ConfigInterface` | Sandbox and gateway configuration |
| `Policy()` | `PolicyInterface` | Draft policy review workflow |
| `Close()` | `error` | Close the gRPC connection |

Sub-client hierarchy: `Providers()` has two nested accessors:
- `client.Providers().Profiles()` returns `ProfileInterface`
- `client.Providers().Refresh()` returns `RefreshInterface`

... (50 lines truncated)
</file>

<file path="sdk/go/docs/src/api/config.md">
# Config

Accessor: `client.Config()`

Retrieve and update configuration for sandboxes and the gateway.

## GetSandbox

Retrieve the current configuration for a specific sandbox.

```go
config, err := client.Config().GetSandbox(ctx, "default", "sandbox-123")
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Sandbox config: policy_version=%d, revision=%d\n",
    config.PolicyVersion, config.ConfigRevision)
```

## GetGateway

Retrieve the gateway-level configuration.

```go
config, err := client.Config().GetGateway(ctx)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Gateway settings revision: %d\n", config.SettingsRevision)
```
... (23 lines truncated)
</file>

<file path="sdk/go/docs/src/api/edge.md">
# Edge

Package: `openshell/v1/edge`

The edge package provides utilities for connecting to OpenShell gateways
through edge proxies such as Cloudflare Access. It includes auth wrappers
for edge proxy headers and a WebSocket tunnel proxy for gRPC transport
through HTTP/1.1-only proxies.

## Cloudflare Access

Wrap any `AuthProvider` with Cloudflare Access headers
(`cf-access-jwt-assertion` and `CF_Authorization` cookie):

```go
import "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/edge"

base := v1.StaticToken("my-gateway-token")
auth, err := edge.CloudflareAccess(base, os.Getenv("CF_ACCESS_TOKEN"))
if err != nil {
    log.Fatal(err)
}
client, err := v1.NewClient(v1.Config{
    Address: "gateway.example.com:443",
    Auth:    auth,
})
```

CloudflareAccess composes with any auth provider, including `RefreshableToken`
for automatic token refresh:
... (62 lines truncated)
</file>

<file path="sdk/go/docs/src/api/exec.md">
# Exec

Accessor: `client.Exec()`

Execute commands in a sandbox with three modes: one-shot (`Run`), streaming
(`Stream`), or interactive terminal (`Interactive`).

## Run

Execute a command and collect all output into a single result.

```go
result, err := client.Exec().Run(ctx, "default", "sbx-123", []string{"ls", "-la"})
if err != nil {
    log.Fatal(err)
}

fmt.Println("Exit code:", result.ExitCode)
fmt.Println("Stdout:", result.Stdout)
fmt.Println("Stderr:", result.Stderr)
```

The SDK collects all streamed events, assembles stdout/stderr, and returns a single `ExecResult`.

`ExecResult` contains the complete output after the command finishes:

| Field      | Type   | Description                  |
|------------|--------|------------------------------|
| `Stdout`   | string | Captured standard output     |
| `Stderr`   | string | Captured standard error      |
... (146 lines truncated)
</file>

<file path="sdk/go/docs/src/api/fake.md">
# Fake

Package: `openshell/v1/fake`

The fake package provides an in-memory fake implementation of all SDK
client interfaces for use in consumer test suites. It follows the
`client-go/kubernetes/fake` pattern: in-memory stores, watch event
broadcasting, and matching `StatusError` codes for equivalent error
conditions (`NotFound`, `AlreadyExists`, `Unavailable`, `Unimplemented`).

## Quick Start

```go
import "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/fake"

func TestSandboxLifecycle(t *testing.T) {
    client := fake.NewClient()
    defer client.Close()

    ctx := context.Background()

    sb, err := client.Sandboxes().Create(ctx, "default", "my-sandbox", &v1.SandboxSpec{}, nil)
    require.NoError(t, err)
    assert.Equal(t, types.SandboxProvisioning, sb.Status.Phase)

    sb, err = client.Sandboxes().WaitReady(ctx, "default", "my-sandbox")
    require.NoError(t, err)
    assert.Equal(t, types.SandboxReady, sb.Status.Phase)

    deletion, err := client.Sandboxes().Delete(ctx, "default", "my-sandbox")
... (93 lines truncated)
</file>

<file path="sdk/go/docs/src/api/files.md">
# Files

Accessor: `client.Files()`

`FileInterface` reserves the upload and download API while keeping sandbox lookup
and SSH-session lifecycle behavior stable. The standalone SDK does not currently
ship an SSH file-transfer transport, so both operations return
`v1.ErrTransportNotAvailable` before performing local validation or gateway RPCs.

## Upload

Detect transport availability programmatically:

```go
err := client.Files().Upload(ctx, "default", "sandbox-123", "./data/config.yaml", "/app/config.yaml")
if errors.Is(err, v1.ErrTransportNotAvailable) {
    // Use another transfer mechanism until an SSH transport is available.
} else if err != nil {
    log.Fatal(err)
}
```

## Download

`Download` has the same capability gate:

```go
err := client.Files().Download(ctx, "default", "sandbox-123", "/app/output.log", "./output.log")
if errors.Is(err, v1.ErrTransportNotAvailable) {
    // Use another transfer mechanism until an SSH transport is available.
... (7 lines truncated)
</file>

<file path="sdk/go/docs/src/api/gateway.md">
# Gateway

Package: `openshell/v1/gateway`

The gateway package reads on-disk gateway configurations created by the
OpenShell Rust CLI and constructs fully wired SDK clients. It eliminates
the boilerplate of locating config files, parsing metadata, loading
tokens, and wiring auth providers.

## Quick Start

```go
import "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/gateway"

// Connect to a named gateway
client, err := gateway.NewClient("prod")
if err != nil {
    log.Fatal(err)
}
defer client.Close()
```

## Functions

| Function | Description |
|----------|-------------|
| `NewClient(name, opts...)` | Create a fully wired SDK client from gateway config |
| `LoadConfig(name)` | Parse gateway config without connecting |
| `ListGateways()` | Enumerate all available gateways |

... (157 lines truncated)
</file>

<file path="sdk/go/docs/src/api/health.md">
# Health

Accessor: `client.Health()`

Check the health status of the connected OpenShell gateway.

## Check

Perform a health check against the gateway. Returns the overall status and
component-level details.

```go
result, err := client.Health().Check(ctx)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Gateway healthy: %v\n", result.Healthy)
```

This is useful for readiness probes or verifying connectivity before executing
other operations.

```go
// Quick connectivity check before starting work
if result, err := client.Health().Check(ctx); err != nil {
    log.Fatalf("Gateway unreachable: %v", err)
} else if !result.Healthy {
    log.Fatal("Gateway is not healthy")
}
```
... (3 lines truncated)
</file>

<file path="sdk/go/docs/src/api/oidc.md">
# OIDC Login

Package: `openshell/v1/oidc`

The oidc package provides OIDC authentication for OpenShell gateways.
It supports four OAuth2 flows: browser-based authorization code with
PKCE, keyboard fallback, device code (RFC 8628), and client credentials.

## Quick Start

```go
import "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/oidc"

// Gateway-aware login (reads OIDC config from gateway metadata)
token, err := oidc.Login(ctx, "my-gateway")
if err != nil {
    log.Fatal(err)
}
```

## Functions

| Function | Description |
|----------|-------------|
| `Login(ctx, gatewayName, opts...)` | Interactive login via browser or keyboard flow |
| `DeviceLogin(ctx, opts...)` | Device authorization grant (RFC 8628) |
| `ClientCredentials(ctx, opts...)` | Non-interactive client credentials grant |

### Login

... (141 lines truncated)
</file>

<file path="sdk/go/docs/src/api/overview.md">
# API Overview

The OpenShell Go SDK exposes typed interfaces through the sub-client pattern.
You access each interface through a typed accessor on the concrete `Client`.

## Interface Summary

### Top-Level Interfaces

| Interface | Accessor | Description |
|-----------|----------|-------------|
| [SandboxInterface](sandboxes.md) | `client.Sandboxes()` | Create, manage, and watch sandbox lifecycle |
| [SandboxTemplateInterface](sandbox-templates.md) | `client.SandboxTemplates()` | Manage reusable sandbox templates |
| [ExecInterface](exec.md) | `client.Exec()` | Run commands, stream output, interactive sessions |
| [ProviderInterface](providers.md) | `client.Providers()` | Manage compute providers and their lifecycle |
| [ServiceInterface](services.md) | `client.Services()` | Expose and manage HTTP services inside sandboxes |
| [FileInterface](files.md) | `client.Files()` | Upload and download files to/from sandboxes |
| [HealthInterface](health.md) | `client.Health()` | Check gateway health status |
| [SSHInterface](ssh.md) | `client.SSH()` | Create SSH sessions and tunnels to sandboxes |
| [TCPInterface](tcp.md) | `client.TCP()` | Forward TCP connections to sandbox ports |
| [ConfigInterface](config.md) | `client.Config()` | Read and update sandbox and gateway configuration |
| [PolicyInterface](policy.md) | `client.Policy()` | Manage draft policy recommendations |

### Convenience Packages

| Package | Entry Point | Description |
|---------|-------------|-------------|
| [gateway](gateway.md) | `gateway.NewClient(name)` | Read CLI gateway configs and auto-wire clients |

### Provider Sub-Interfaces
... (36 lines truncated)
</file>

<file path="sdk/go/docs/src/api/policy.md">
# Policy

Accessor: `client.Policy()`

Manage network policies for sandboxes through a draft-based workflow. Policies
go through a draft, review, and approval cycle before being applied.

## GetDraft

Retrieve the current draft policy for a sandbox.

```go
draft, err := client.Policy().GetDraft(ctx, "default", "my-sandbox")
if err != nil {
    log.Fatal(err)
}
for _, chunk := range draft.Chunks {
    fmt.Printf("Chunk %s: rule=%s, status=%s, confidence=%.1f\n",
        chunk.ID, chunk.RuleName, chunk.Status, chunk.Confidence)
}
```

## ApproveAllDraftChunks

Approve all pending chunks in a single operation.

```go
result, err := client.Policy().ApproveAllDraftChunks(ctx, "default", "my-sandbox")
if err != nil {
    log.Fatal(err)
... (99 lines truncated)
</file>

<file path="sdk/go/docs/src/api/profiles.md">
# Profiles

Accessor: `client.Providers().Profiles()`

Manage provider profiles for AI model providers. Profiles define connection details,
credentials, and model mappings for providers like OpenAI, Anthropic, or custom endpoints.

## List

`List` returns a lazy pager over visible provider profiles. Use `ListAll` to
collect every page.

```go
profiles, err := client.Providers().Profiles().ListAll(ctx, "default")
if err != nil {
    log.Fatal(err)
}
for _, p := range profiles {
    fmt.Printf("Profile: %s (%s)\n", p.ID, p.DisplayName)
}
```

## Import

Import one or more provider profiles from configuration items.

```go
result, err := client.Providers().Profiles().Import(ctx, "default", []v1.ProfileImportItem{
    {
        Profile: v1.ProviderProfile{
... (57 lines truncated)
</file>

<file path="sdk/go/docs/src/api/providers.md">
# Providers

Accessor: `client.Providers()`

Register and manage compute providers (AI inference endpoints). Exposes
sub-clients for [Profiles](profiles.md) and [Refresh](refresh.md).

## Create

Register a new provider with the gateway.

```go
provider, err := client.Providers().Create(ctx, "default", &v1.Provider{
    Name: "my-openai",
    Type: "openai",
    Spec: v1.ProviderSpec{
        Credentials: map[string]string{
            "api_key": "sk-...",
        },
        Config: map[string]string{
            "base_url": "https://api.openai.com/v1",
        },
    },
})
if err != nil {
    log.Fatal(err)
}
fmt.Println("Created provider:", provider.Name)
```

... (132 lines truncated)
</file>

<file path="sdk/go/docs/src/api/refresh.md">
# Refresh

Accessor: `client.Providers().Refresh()`

Manage credential refresh schedules for provider profiles. Configure automatic
rotation of API keys and monitor refresh status.

## GetStatus

Check the refresh status for a specific provider credential.

```go
statuses, err := client.Providers().Refresh().GetStatus(ctx, "default", "openai", "default")
if err != nil {
    log.Fatal(err)
}
for _, s := range statuses {
    fmt.Printf("Key: %s, Last refresh: %s, Next: %s\n",
        s.CredentialKey, s.LastRefreshAt, s.NextRefreshAt)
}
```

## Configure

Set up automatic credential refresh with a defined strategy and material.

```go
status, err := client.Providers().Refresh().Configure(ctx, "default", &v1.RefreshConfig{
    Provider:      "openai",
    CredentialKey:  "default",
... (28 lines truncated)
</file>

<file path="sdk/go/docs/src/api/sandbox-templates.md">
# Sandbox Templates

Accessor: `client.SandboxTemplates()`

Manage reusable, workspace-scoped sandbox workload templates. Templates own the
portable workload shape and optional driver-specific config. Sandbox creation
can reference a template by name while supplying only governance fields such as
providers or policy.

The Go SDK names the reusable resource `SandboxWorkloadTemplate` because
`SandboxTemplate` already represents the legacy inline compute template inside
`SandboxSpec`.

## Create

Creates a reusable template in a workspace.

```go
gpuCount := uint32(1)

template, err := client.SandboxTemplates().Create(ctx, "default", &v1.SandboxWorkloadTemplate{
    Name: "gpu-kata",
    Labels: map[string]string{
        "team": "platform",
    },
    Spec: v1.SandboxWorkloadTemplateSpec{
        Workload: &v1.SandboxWorkloadConfig{
            Image: "nvcr.io/nvidia/openshell:latest",
            Environment: map[string]string{
                "NVIDIA_VISIBLE_DEVICES": "all",
... (98 lines truncated)
</file>

<file path="sdk/go/docs/src/api/sandboxes.md">
# Sandboxes

Accessor: `client.Sandboxes()`

Manage sandbox lifecycle: create, inspect, delete, attach/detach providers,
wait for readiness, watch state changes, and retrieve logs.

## Create

Creates a new sandbox with the given name, spec, and labels.

```go
sb, err := client.Sandboxes().Create(ctx, "default", "my-sandbox", &v1.SandboxSpec{
    Template: &v1.SandboxTemplate{
        Image: "nvcr.io/nvidia/openshell:latest",
    },
    Providers: []string{"openai"},
}, map[string]string{
    "team": "platform",
}, v1.CreateOptions{ServiceExposures: []v1.ServiceExposure{
    {TargetPort: 8080},
}})
fmt.Println(sb.ServiceURLs[""])
```

Create-time service exposures register loopback HTTP endpoints with the
sandbox. Leave `Service` empty for the unnamed endpoint or set it to create a
named endpoint. Routing begins when the sandbox is ready.
`ServiceURLs` returns the routed URLs keyed by service name; the empty key is
the unnamed endpoint.
... (248 lines truncated)
</file>

<file path="sdk/go/docs/src/api/services.md">
# Services

Accessor: `client.Services()`

Expose, inspect, and manage network services attached to sandboxes. Services provide
external access to ports running inside a sandbox via managed endpoints.

## Expose

Expose a port from a sandbox as a named service endpoint. Set `domain` to `true`
to assign a DNS-routable domain name to the service.

```go
endpoint, err := client.Services().Expose(ctx, "default", "my-sandbox", "web", 8080, true)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Service available at: %s\n", endpoint.URL)
```

## List

`List` returns a lazy pager over exposed services. Use `ListAll` to collect
every page.

```go
services, err := client.Services().ListAll(ctx, "default", "my-sandbox")
if err != nil {
    log.Fatal(err)
}
... (24 lines truncated)
</file>

<file path="sdk/go/docs/src/api/ssh.md">
# SSH

Accessor: `client.SSH()`

Create and manage SSH sessions for sandboxes. Supports direct SSH access and
TCP tunneling through SSH connections.

## CreateSession

Create a new SSH session for a sandbox. Returns connection details including
host, port, and authentication credentials.

```go
session, err := client.SSH().CreateSession(ctx, "default", "sandbox-123")
if err != nil {
    log.Fatal(err)
}
fmt.Printf("SSH via %s://%s:%d\n", session.GatewayScheme, session.GatewayHost, session.GatewayPort)
```

## RevokeSession

Revoke an active SSH session, immediately terminating any connections using it.

```go
deletion, err := client.SSH().RevokeSession(ctx, "default", session.Token)
if err != nil {
    log.Fatal(err)
}
if deletion.Outcome == v1.DeletionCompleted {
... (26 lines truncated)
</file>

<file path="sdk/go/docs/src/api/tcp.md">
# TCP

Accessor: `client.TCP()`

Forward TCP connections to sandbox ports using bidirectional gRPC streaming.

## Forward

Open a bidirectional TCP forwarding stream to a specific port inside a sandbox.
Returns an `io.ReadWriteCloser` that proxies data between the caller and the
sandbox port over gRPC streaming.

```go
conn, err := client.TCP().Forward(ctx, "default", "sandbox-123", 8080)
if err != nil {
    log.Fatal(err)
}
defer conn.Close()

// Exchange protocol bytes with the service through the tunnel.
_, err = conn.Write([]byte("ping\n"))
if err != nil {
    log.Fatal(err)
}

buf := make([]byte, 4096)
n, err := conn.Read(buf)
if err != nil {
    log.Fatal(err)
}
... (31 lines truncated)
</file>

<file path="sdk/go/docs/src/architecture.md">
# Architecture

This page explains how the OpenShell Go SDK is structured internally. Understanding the design helps you navigate the API surface and write idiomatic code.

## Client Hierarchy

The SDK follows the Kubernetes client-go sub-client pattern. A single `Client` provides typed accessors for each API domain:

```text
Client
├── Sandboxes()   → SandboxInterface
├── Exec()        → ExecInterface
├── Providers()   → ProviderInterface
│   ├── Profiles()  → ProfileInterface
│   └── Refresh()   → RefreshInterface
├── Services()    → ServiceInterface
├── Files()       → FileInterface
├── Health()      → HealthInterface
├── SSH()         → SSHInterface
├── TCP()         → TCPInterface
├── Config()      → ConfigInterface
└── Policy()      → PolicyInterface
```

Each accessor returns an interface. You work with the interface, not the concrete implementation. This makes the sub-clients easy to mock and test.

## Creating a Client

All interaction starts with `NewClient`:

... (110 lines truncated)
</file>

<file path="sdk/go/docs/src/error-handling.md">
# Error Handling

Gateway status failures and SDK validation failures use `*v1.StatusError`, which carries a machine-readable `Code` and a human-readable `Message`. Local I/O, transport setup, and sentinel errors may use other Go error types. The SDK provides predicate functions for classified status errors.

## StatusError

When an operation returns a classified status error, inspect it directly or use the convenience predicates below. Use `errors.Is` for documented sentinel errors such as `ErrTransportNotAvailable`.

```go
var se *v1.StatusError
if errors.As(err, &se) {
    fmt.Printf("code: %s, message: %s\n", se.Code, se.Message)
    // se.ErrorInfo and se.FieldViolations contain optional structured details.
}
```

| Field     | Type              | Description                          |
|-----------|-------------------|--------------------------------------|
| `Code`    | `ErrorCode`       | Machine-readable error classification |
| `Message` | `string`          | Human-readable error description      |
| `GRPCCode` | `int32` | Original gRPC code before SDK classification |
| `FieldViolations` | `[]FieldViolation` | Rejected request fields and descriptions |
| `ErrorInfo` | `*ErrorInfo` | Server reason, domain, and metadata |
| `RetryDelay` | `*time.Duration` | Suggested minimum delay for an otherwise safe retry |
| `Cause` | `error` | Original gRPC error, including unknown details |

Use `status.FromError(err)` to inspect the complete gRPC status through the SDK's
error wrapper. A delay does not prove that a timed-out mutation was not applied.

## Predicate Functions
... (173 lines truncated)
</file>

<file path="sdk/go/docs/src/getting-started.md">
# Quick Start

This guide walks you through installing the OpenShell Go SDK, connecting to a gateway, creating a sandbox, running a command, and cleaning up. You should be up and running in under 5 minutes.

## Prerequisites

- Go 1.25.13 or later
- Access to an OpenShell gateway (address and authentication token)

## Installation

Add the SDK to your Go module:

```bash
go get github.com/NVIDIA/OpenShell/sdk/go@latest
```

## Connect to the Gateway

Create a client by providing the gateway address and authentication credentials:

```go
package main

import (
    "context"
    "fmt"
    "log"

    v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
... (94 lines truncated)
</file>

<file path="sdk/go/docs/src/introduction.md">
# OpenShell Go SDK

The OpenShell Go SDK provides an idiomatic Go client for the OpenShell gateway API. It wraps the underlying gRPC protocol behind typed interfaces, making it straightforward to manage sandboxes, execute commands, handle providers, and more.

## Key Features

- **Sub-client pattern**: A single `Client` provides typed accessors for each API domain (Sandboxes, SandboxTemplates, Exec, Providers, Files, Health, SSH, TCP, Config, Policy, Services)
- **Clean types**: SDK types are self-contained, so your code works with idiomatic Go types without extra dependencies
- **Fake client for testing**: An in-memory implementation of the full `ClientInterface` for testing without a live gateway
- **Watch and streaming**: First-class support for watching sandbox state changes and streaming command output
- **Typed error handling**: Functions like `IsNotFound`, `IsAlreadyExists`, and `IsConflict` for precise error classification

## Where to Start

If you are new to the SDK, the [Quick Start](getting-started.md) guide walks you through installation, connecting to a gateway, creating your first sandbox, running a command, and cleaning up.

For a deeper understanding of how the SDK is structured, see the [Architecture](architecture.md) overview.

## API Reference

Every SDK interface has a dedicated reference page with method signatures and code examples.

Browse the full [API Overview](api/overview.md) to see all 13 interfaces at a glance.

## Guides

- [Error Handling](error-handling.md): StatusError, typed error checks, retry patterns
- [Testing](testing.md): Fake client usage, fixture seeding, watch event testing

## Related Projects
... (5 lines truncated)
</file>

<file path="sdk/go/docs/src/SUMMARY.md">
# Summary

[Introduction](introduction.md)

# Getting Started

- [Quick Start](getting-started.md)

# Architecture

- [Overview](architecture.md)

# API Reference

- [Overview](api/overview.md)
- [Client](api/client.md)
- [Sandboxes](api/sandboxes.md)
- [Sandbox Templates](api/sandbox-templates.md)
- [Exec](api/exec.md)
- [Providers](api/providers.md)
- [Profiles](api/profiles.md)
- [Refresh](api/refresh.md)
- [Services](api/services.md)
- [Files](api/files.md)
- [Health](api/health.md)
- [SSH](api/ssh.md)
- [TCP](api/tcp.md)
- [Config](api/config.md)
- [Policy](api/policy.md)
- [Gateway](api/gateway.md)
... (9 lines truncated)
</file>

<file path="sdk/go/docs/src/testing.md">
# Testing

The SDK ships a `fake` package that provides an in-memory implementation of all client interfaces. Use it in your test suites to exercise SDK interactions without a real gateway.

```go
import "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/fake"
```

The fake client follows the same pattern as `k8s.io/client-go/kubernetes/fake`: it maintains in-memory stores, supports watch event broadcasting, and returns the same `StatusError` codes as the real client.

## Creating a Fake Client

```go
func TestMyOperator(t *testing.T) {
    client := fake.NewClient()
    defer client.Close()

    ctx := context.Background()

    // Use client exactly like the real SDK
    sb, err := client.Sandboxes().Create(ctx, "default", "test-sandbox", &v1.SandboxSpec{}, nil)
    require.NoError(t, err)
    assert.Equal(t, "Provisioning", string(sb.Status.Phase))
}
```

The returned `*fake.Client` satisfies `v1.ClientInterface`, so you can pass it anywhere your code accepts the interface.

## Fixture Seeding

... (155 lines truncated)
</file>

<file path="sdk/go/docs/book.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

[book]
title = "OpenShell Go SDK"
authors = ["NVIDIA Corporation"]
language = "en"
src = "src"

[build]
build-dir = "book"
create-missing = false

[output.html]
default-theme = "ayu"
preferred-dark-theme = "navy"
additional-css = ["theme/custom.css"]
git-repository-url = "https://github.com/NVIDIA/OpenShell/sdk/go"
edit-url-template = "https://github.com/NVIDIA/OpenShell/sdk/go/edit/main/docs/src/{path}"

[output.html.search]
enable = true
limit-results = 20
</file>

<file path="sdk/go/openshell/v1/edge/cloudflare_test.go">
package edge
⋮----
import (
	"context"
	"testing"
	v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)
⋮----
"context"
"testing"
⋮----
v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
⋮----
func TestCloudflareAccess_ValidToken(t *testing.T)
⋮----
func TestCloudflareAccess_EmptyToken(t *testing.T)
⋮----
func TestCloudflareAccess_NilBase(t *testing.T)
⋮----
func TestCloudflareAccess_WithNoAuth(t *testing.T)
⋮----
func TestCloudflareAccess_RequireTransportSecurity_Delegates(t *testing.T)
⋮----
func TestCloudflareAccess_TokenNotInError(t *testing.T)
⋮----
// The error should mention the parameter name, not any token value.
... (1 lines truncated)
</file>

<file path="sdk/go/openshell/v1/edge/cloudflare.go">
package edge
⋮----
import (
	"errors"
	"fmt"
	v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
)
⋮----
"errors"
"fmt"
⋮----
v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
⋮----
func CloudflareAccess(baseAuth v1.AuthProvider, edgeToken string) (v1.AuthProvider, error)
</file>

<file path="sdk/go/openshell/v1/edge/doc.go">
package edge
</file>

<file path="sdk/go/openshell/v1/edge/options_nil_test.go">
package edge
⋮----
import (
	"testing"
	"time"
	"github.com/stretchr/testify/assert"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/options"
)
⋮----
"testing"
"time"
⋮----
"github.com/stretchr/testify/assert"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/options"
⋮----
func TestTunnelOption_NilIgnored(t *testing.T)
</file>

<file path="sdk/go/openshell/v1/edge/tunnel_test.go">
package edge
⋮----
import (
	"crypto/tls"
	"crypto/x509"
	"fmt"
	"io"
	"net"
	"net/http"
	"net/http/httptest"
	"runtime"
	"slices"
	"sync"
	"testing"
	"time"
	"github.com/coder/websocket"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)
⋮----
"crypto/tls"
"crypto/x509"
"fmt"
"io"
"net"
"net/http"
"net/http/httptest"
"runtime"
"slices"
"sync"
... (68 lines truncated)
</file>

<file path="sdk/go/openshell/v1/edge/tunnel.go">
package edge
⋮----
import (
	"context"
	"crypto/tls"
	"errors"
	"fmt"
	"io"
	"net"
	"net/http"
	"net/url"
	"sync"
	"time"
	"github.com/coder/websocket"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/options"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"context"
"crypto/tls"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/url"
"sync"
"time"
⋮----
"github.com/coder/websocket"
... (50 lines truncated)
</file>

<file path="sdk/go/openshell/v1/fake/broadcaster_test.go">
package fake
⋮----
import (
	"fmt"
	"testing"
	"time"
	"github.com/stretchr/testify/assert"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"fmt"
"testing"
"time"
⋮----
"github.com/stretchr/testify/assert"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
func TestWatchBroadcaster_Watch_ReceivesEvents(t *testing.T)
⋮----
func TestWatchBroadcaster_DoesNotDropBurstEvents(t *testing.T)
⋮----
const count = watchChannelBuffer + 50
⋮----
func TestWatchBroadcaster_Watch_NameFiltering(t *testing.T)
⋮----
func TestWatchBroadcaster_Watch_EmptyNameReceivesAll(t *testing.T)
⋮----
func TestWatchBroadcaster_MultipleWatchers(t *testing.T)
⋮----
... (18 lines truncated)
</file>

<file path="sdk/go/openshell/v1/fake/broadcaster.go">
package fake
⋮----
import (
	"sync"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"sync"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
const watchChannelBuffer = 100
⋮----
type watchBroadcaster[T any] struct {
	mu       sync.Mutex
	watchers []*fakeWatcher[T]
}
⋮----
func newWatchBroadcaster[T any]() *watchBroadcaster[T]
⋮----
func (b *watchBroadcaster[T]) Watch(name string) types.WatchInterface[T]
⋮----
func (b *watchBroadcaster[T]) Broadcast(event types.Event[T], name string)
⋮----
func (b *watchBroadcaster[T]) StopAll()
⋮----
type fakeWatcher[T any] struct {
	ch      chan types.Event[T]
	name    string
	once    sync.Once
... (15 lines truncated)
</file>

<file path="sdk/go/openshell/v1/fake/config_test.go">
package fake
⋮----
import (
	"context"
	"testing"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"context"
"testing"
⋮----
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
func TestFakeConfig_GetSandbox_ReturnsUnimplemented(t *testing.T)
⋮----
func TestFakeConfig_GetGateway_ReturnsUnimplemented(t *testing.T)
⋮----
func TestFakeConfig_Update_ReturnsUnimplemented(t *testing.T)
⋮----
func TestFakeConfig_GetSandbox_ClosedReturnsUnavailable(t *testing.T)
⋮----
func TestFakeConfig_GetGateway_ClosedReturnsUnavailable(t *testing.T)
⋮----
func TestFakeConfig_Update_ClosedReturnsUnavailable(t *testing.T)
⋮----
... (2 lines truncated)
</file>

<file path="sdk/go/openshell/v1/fake/config.go">
package fake
⋮----
import (
	"context"
	v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"context"
⋮----
v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
type fakeConfigClient struct {
	closedFunc func() bool
}
⋮----
func newFakeConfigClient(closedFunc func() bool) *fakeConfigClient
⋮----
func (c *fakeConfigClient) GetSandbox(_ context.Context, _, sandboxName string) (*types.SandboxConfig, error)
⋮----
func (c *fakeConfigClient) GetGateway(_ context.Context) (*types.GatewayConfig, error)
⋮----
func (c *fakeConfigClient) Update(_ context.Context, _ string, update *types.ConfigUpdate) (*types.ConfigUpdateResult, error)
⋮----
var _ v1.ConfigInterface = (*fakeConfigClient)(nil)
</file>

<file path="sdk/go/openshell/v1/fake/doc.go">
package fake
</file>

<file path="sdk/go/openshell/v1/fake/exec_test.go">
package fake
⋮----
import (
	"context"
	"testing"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"context"
"testing"
⋮----
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
func TestExec_Run_Unimplemented(t *testing.T)
⋮----
func TestExec_Stream_Unimplemented(t *testing.T)
⋮----
func TestExec_Interactive_Unimplemented(t *testing.T)
⋮----
func TestExec_Run_ClosedClient(t *testing.T)
⋮----
func TestExec_Stream_ClosedClient(t *testing.T)
⋮----
func TestExec_Interactive_ClosedClient(t *testing.T)
</file>

<file path="sdk/go/openshell/v1/fake/exec.go">
package fake
⋮----
import (
	"context"
	v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"context"
⋮----
v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
var _ v1.ExecInterface = (*fakeExecClient)(nil)
⋮----
type fakeExecClient struct {
	closedFunc func() bool
}
⋮----
func newFakeExecClient(closedFunc func() bool) *fakeExecClient
⋮----
func (c *fakeExecClient) Run(_ context.Context, _, sandboxName string, _ []string, _ ...v1.ExecOptions) (*types.ExecResult, error)
⋮----
func (c *fakeExecClient) Stream(_ context.Context, _, sandboxName string, _ []string, _ ...v1.ExecOptions) (v1.ExecStream, error)
⋮----
func (c *fakeExecClient) Interactive(_ context.Context, _, sandboxName string, _ []string, _, _ uint32, _ ...v1.ExecOptions) (v1.InteractiveSession, error)
</file>

<file path="sdk/go/openshell/v1/fake/fake_test.go">
package fake
⋮----
import (
	"context"
	"testing"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"context"
"testing"
⋮----
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
func TestFakeClient_Close(t *testing.T)
⋮----
func TestFakeClient_Close_Idempotent(t *testing.T)
⋮----
func TestFakeClient_Sandboxes_AfterClose(t *testing.T)
⋮----
func TestFakeClient_Providers_AfterClose(t *testing.T)
⋮----
func TestFakeClient_Health_AfterClose(t *testing.T)
⋮----
func TestFakeClient_Exec_AfterClose(t *testing.T)
⋮----
... (24 lines truncated)
</file>

<file path="sdk/go/openshell/v1/fake/fake.go">
package fake
⋮----
import (
	"context"
	"sync"
	v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/options"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"context"
"sync"
⋮----
v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/options"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
type Client struct {
	sandboxStore       *objectStore[*types.Sandbox]
	templateStore      *objectStore[*types.SandboxWorkloadTemplate]
	providerStore      *objectStore[*types.Provider]
	workspaceStore     *objectStore[*types.Workspace]
	memberStore        *objectStore[*types.WorkspaceMember]
	sandboxBroadcaster *watchBroadcaster[*types.Sandbox]
	sandboxes      v1.SandboxInterface
	templateCreate v1.SandboxTemplateCreateInterface
	templates      v1.SandboxTemplateInterface
	providers      v1.ProviderInterface
	services       v1.ServiceInterface
	exec           v1.ExecInterface
... (68 lines truncated)
</file>

<file path="sdk/go/openshell/v1/fake/file_test.go">
package fake
⋮----
import (
	"context"
	"testing"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"context"
"testing"
⋮----
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
func TestFile_Upload_Unimplemented(t *testing.T)
⋮----
func TestFile_Download_Unimplemented(t *testing.T)
⋮----
func TestFile_Upload_ClosedClient(t *testing.T)
⋮----
func TestFile_Download_ClosedClient(t *testing.T)
</file>

<file path="sdk/go/openshell/v1/fake/file.go">
package fake
⋮----
import (
	"context"
	v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"context"
⋮----
v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
var _ v1.FileInterface = (*fakeFileClient)(nil)
⋮----
type fakeFileClient struct {
	closedFunc func() bool
}
⋮----
func newFakeFileClient(closedFunc func() bool) *fakeFileClient
⋮----
func (c *fakeFileClient) Upload(_ context.Context, _, sandboxName, _, remotePath string) error
⋮----
func (c *fakeFileClient) Download(_ context.Context, _, sandboxName, remotePath, _ string) error
</file>

<file path="sdk/go/openshell/v1/fake/health_test.go">
package fake
⋮----
import (
	"context"
	"testing"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"context"
"testing"
⋮----
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
func TestHealth_DefaultHealthy(t *testing.T)
⋮----
func TestHealth_ConfigurableResult(t *testing.T)
⋮----
func TestHealth_ClosedClient(t *testing.T)
⋮----
func TestHealth_GetGatewayInfo_Default(t *testing.T)
⋮----
func TestHealth_GetGatewayInfo_Custom(t *testing.T)
⋮----
func TestHealth_GetGatewayInfo_DeepCopy(t *testing.T)
⋮----
... (10 lines truncated)
</file>

<file path="sdk/go/openshell/v1/fake/health.go">
package fake
⋮----
import (
	"context"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"context"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
type fakeHealthClient struct {
	result      *types.HealthResult
	gatewayInfo *types.GatewayInfo
	currentUser *types.CurrentUser
	closedFunc  func() bool
}
⋮----
func newFakeHealthClient(result *types.HealthResult, closedFunc func() bool) *fakeHealthClient
⋮----
func (c *fakeHealthClient) Check(_ context.Context) (*types.HealthResult, error)
⋮----
func (c *fakeHealthClient) GetGatewayInfo(_ context.Context) (*types.GatewayInfo, error)
⋮----
func (c *fakeHealthClient) GetCurrentUser(_ context.Context) (*types.CurrentUser, error)
⋮----
func copyGatewayInfo(info *types.GatewayInfo) *types.GatewayInfo
⋮----
func copyCurrentUser(user *types.CurrentUser) *types.CurrentUser
</file>

<file path="sdk/go/openshell/v1/fake/mutations.go">
package fake
⋮----
import (
	v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
func deletionResult(existed bool, sandboxID string, opts []v1.DeleteOptions) (*types.DeletionResult, error)
</file>

<file path="sdk/go/openshell/v1/fake/options_nil_test.go">
package fake
⋮----
import (
	"testing"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"testing"
⋮----
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
func TestClientOption_NilIgnored(t *testing.T)
</file>

<file path="sdk/go/openshell/v1/fake/pager.go">
package fake
⋮----
import (
	"context"
	"strconv"
	v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"context"
"strconv"
⋮----
v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
func newSlicePager[T any](items []T, pageSize int, pageToken string) (*v1.Pager[T], error)
⋮----
func parsePageOffset(token string, length int) (int, error)
</file>

<file path="sdk/go/openshell/v1/fake/policy_test.go">
package fake
⋮----
import (
	"context"
	"testing"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"context"
"testing"
⋮----
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
func TestFakePolicy_GetDraft_ReturnsUnimplemented(t *testing.T)
⋮----
func TestFakePolicy_ApproveDraftChunk_ReturnsUnimplemented(t *testing.T)
⋮----
func TestFakePolicy_RejectDraftChunk_ReturnsUnimplemented(t *testing.T)
⋮----
func TestFakePolicy_ApproveAllDraftChunks_ReturnsUnimplemented(t *testing.T)
⋮----
func TestFakePolicy_ClearDraftChunks_ReturnsUnimplemented(t *testing.T)
⋮----
func TestFakePolicy_GetDraftHistory_ReturnsUnimplemented(t *testing.T)
⋮----
... (42 lines truncated)
</file>

<file path="sdk/go/openshell/v1/fake/policy.go">
package fake
⋮----
import (
	"context"
	"maps"
	"slices"
	"sync"
	v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"context"
"maps"
"slices"
"sync"
⋮----
v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
func copySandboxPolicyRevision(r types.SandboxPolicyRevision) types.SandboxPolicyRevision
⋮----
type fakePolicyClient struct {
	mu         sync.RWMutex
	closedFunc func() bool
	globalRevisions []types.SandboxPolicyRevision
	sandboxRevisions map[string][]types.SandboxPolicyRevision
}
⋮----
func newFakePolicyClient(closedFunc func() bool) *fakePolicyClient
⋮----
... (35 lines truncated)
</file>

<file path="sdk/go/openshell/v1/fake/profile_test.go">
package fake
⋮----
import (
	"context"
	"testing"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"context"
"testing"
⋮----
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
func TestFakeProfile_List_ReturnsUnimplemented(t *testing.T)
⋮----
func TestFakeProfile_Get_ReturnsUnimplemented(t *testing.T)
⋮----
func TestFakeProfile_Import_ReturnsUnimplemented(t *testing.T)
⋮----
func TestFakeProfile_Update_ReturnsUnimplemented(t *testing.T)
⋮----
func TestFakeProfile_Lint_ReturnsUnimplemented(t *testing.T)
⋮----
func TestFakeProfile_Delete_ReturnsUnimplemented(t *testing.T)
⋮----
... (12 lines truncated)
</file>

<file path="sdk/go/openshell/v1/fake/profile.go">
package fake
⋮----
import (
	"context"
	v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"context"
⋮----
v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
type fakeProfileClient struct {
	closedFunc func() bool
}
⋮----
func newFakeProfileClient(closedFunc func() bool) *fakeProfileClient
⋮----
func (c *fakeProfileClient) List(_ string, _ ...v1.ListOptions) (*v1.Pager[*types.ProviderProfile], error)
⋮----
func (c *fakeProfileClient) ListAll(_ context.Context, _ string, _ ...v1.ListOptions) ([]*types.ProviderProfile, error)
⋮----
func (c *fakeProfileClient) Get(_ context.Context, _, _ string) (*types.ProviderProfile, error)
⋮----
func (c *fakeProfileClient) Import(_ context.Context, _ string, _ []types.ProfileImportItem) (*types.ImportResult, error)
⋮----
func (c *fakeProfileClient) Update(_ context.Context, _, _ string, _ uint64, _ types.ProfileImportItem) (*types.UpdateResult, error)
⋮----
func (c *fakeProfileClient) Lint(_ context.Context, _ string, _ []types.ProfileImportItem) (*types.LintResult, error)
... (5 lines truncated)
</file>

<file path="sdk/go/openshell/v1/fake/provider_test.go">
package fake
⋮----
import (
	"context"
	"fmt"
	"sync"
	"testing"
	"time"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"context"
"fmt"
"sync"
"testing"
"time"
⋮----
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
func newTestProviderClient() *fakeProviderClient
⋮----
func TestProvider_Create(t *testing.T)
⋮----
func TestProvider_Create_AlreadyExists(t *testing.T)
⋮----
... (31 lines truncated)
</file>

<file path="sdk/go/openshell/v1/fake/provider.go">
package fake
⋮----
import (
	"context"
	"time"
	v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"context"
"time"
⋮----
v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
func providerName(p *types.Provider) string
⋮----
func copyProvider(p *types.Provider) *types.Provider
⋮----
func copyProviderSpec(s types.ProviderSpec) types.ProviderSpec
⋮----
func copyTimeMap(m map[string]time.Time) map[string]time.Time
⋮----
type fakeProviderClient struct {
	store      *objectStore[*types.Provider]
	closedFunc func() bool
	profiles   *fakeProfileClient
	refresh    *fakeRefreshClient
}
⋮----
... (26 lines truncated)
</file>

<file path="sdk/go/openshell/v1/fake/refresh_test.go">
package fake
⋮----
import (
	"context"
	"testing"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"context"
"testing"
⋮----
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
func TestFakeRefresh_GetStatus_ReturnsUnimplemented(t *testing.T)
⋮----
func TestFakeRefresh_Configure_ReturnsUnimplemented(t *testing.T)
⋮----
func TestFakeRefresh_Rotate_ReturnsUnimplemented(t *testing.T)
⋮----
func TestFakeRefresh_Delete_ReturnsUnimplemented(t *testing.T)
⋮----
func TestFakeRefresh_GetStatus_ClosedReturnsUnavailable(t *testing.T)
⋮----
func TestFakeRefresh_Configure_ClosedReturnsUnavailable(t *testing.T)
⋮----
... (4 lines truncated)
</file>

<file path="sdk/go/openshell/v1/fake/refresh.go">
package fake
⋮----
import (
	"context"
	v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"context"
⋮----
v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
type fakeRefreshClient struct {
	closedFunc func() bool
}
⋮----
func newFakeRefreshClient(closedFunc func() bool) *fakeRefreshClient
⋮----
func (c *fakeRefreshClient) GetStatus(_ context.Context, _, _, _ string) ([]*types.RefreshStatus, error)
⋮----
func (c *fakeRefreshClient) Configure(_ context.Context, _ string, _ *types.RefreshConfig) (*types.RefreshStatus, error)
⋮----
func (c *fakeRefreshClient) Rotate(_ context.Context, _, _, _ string) (*types.RefreshStatus, error)
⋮----
func (c *fakeRefreshClient) Delete(_ context.Context, _, _, _ string, _ ...v1.DeleteOptions) (*types.DeletionResult, error)
⋮----
var _ v1.RefreshInterface = (*fakeRefreshClient)(nil)
</file>

<file path="sdk/go/openshell/v1/fake/sandbox_template_test.go">
package fake
⋮----
import (
	"context"
	"testing"
	"time"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)
⋮----
"context"
"testing"
"time"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
⋮----
func newTestSandboxTemplateClient() *fakeSandboxTemplateClient
⋮----
func testSandboxWorkloadTemplate(name string) *types.SandboxWorkloadTemplate
⋮----
func TestIsDNS1123Label(t *testing.T)
⋮----
func TestSandboxTemplate_CreateGetListDelete(t *testing.T)
⋮----
func TestSandboxTemplate_CreateAlreadyExists(t *testing.T)
⋮----
func TestSandboxTemplate_ListAllWorkspaces(t *testing.T)
... (25 lines truncated)
</file>

<file path="sdk/go/openshell/v1/fake/sandbox_template.go">
package fake
⋮----
import (
	"context"
	"slices"
	"strings"
	"time"
	v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"context"
"slices"
"strings"
"time"
⋮----
v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
func sandboxWorkloadTemplate(template *types.SandboxWorkloadTemplate) string
⋮----
func copySandboxWorkloadTemplate(template *types.SandboxWorkloadTemplate) *types.SandboxWorkloadTemplate
⋮----
func copySandboxWorkloadTemplateSpec(spec types.SandboxWorkloadTemplateSpec) types.SandboxWorkloadTemplateSpec
⋮----
type fakeSandboxTemplateClient struct {
	store      *objectStore[*types.SandboxWorkloadTemplate]
	closedFunc func() bool
}
⋮----
... (44 lines truncated)
</file>

<file path="sdk/go/openshell/v1/fake/sandbox_test.go">
package fake
⋮----
import (
	"context"
	"fmt"
	"sync"
	"testing"
	"time"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"context"
"fmt"
"sync"
"testing"
"time"
⋮----
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
⋮----
v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
func newTestSandboxClient() *fakeSandboxClient
⋮----
func TestSandbox_Create(t *testing.T)
⋮----
... (107 lines truncated)
</file>

<file path="sdk/go/openshell/v1/fake/sandbox.go">
package fake
⋮----
import (
	"context"
	"fmt"
	"slices"
	"sync"
	"time"
	v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"context"
"fmt"
"slices"
"sync"
"time"
⋮----
v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
func sandboxName(sb *types.Sandbox) string
⋮----
func copySandbox(sb *types.Sandbox) *types.Sandbox
⋮----
func copySandboxSpec(s types.SandboxSpec) types.SandboxSpec
⋮----
func copySandboxPolicy(p *types.SandboxPolicy) *types.SandboxPolicy
⋮----
func copyPolicyNetworkEndpoint(ep types.PolicyNetworkEndpoint) types.PolicyNetworkEndpoint
... (91 lines truncated)
</file>

<file path="sdk/go/openshell/v1/fake/service_test.go">
package fake
⋮----
import (
	"context"
	"testing"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"context"
"testing"
⋮----
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
func TestFakeService_Expose_ReturnsUnimplemented(t *testing.T)
⋮----
func TestFakeService_Get_ReturnsUnimplemented(t *testing.T)
⋮----
func TestFakeService_List_ReturnsUnimplemented(t *testing.T)
⋮----
func TestFakeService_Delete_ReturnsUnimplemented(t *testing.T)
⋮----
func TestFakeService_Expose_ClosedReturnsUnavailable(t *testing.T)
⋮----
func TestFakeService_Get_ClosedReturnsUnavailable(t *testing.T)
⋮----
... (4 lines truncated)
</file>

<file path="sdk/go/openshell/v1/fake/service.go">
package fake
⋮----
import (
	"context"
	v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"context"
⋮----
v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
type fakeServiceClient struct {
	closedFunc func() bool
}
⋮----
func newFakeServiceClient(closedFunc func() bool) *fakeServiceClient
⋮----
func (c *fakeServiceClient) Expose(_ context.Context, _, _, _ string, _ uint32, _ bool, _ ...v1.ExposeServiceOptions) (*types.ServiceEndpoint, error)
⋮----
func (c *fakeServiceClient) Get(_ context.Context, _, _, _ string) (*types.ServiceEndpoint, error)
⋮----
func (c *fakeServiceClient) List(_, _ string, _ ...v1.ListOptions) (*v1.Pager[*types.ServiceEndpoint], error)
⋮----
func (c *fakeServiceClient) ListAll(_ context.Context, _, _ string, _ ...v1.ListOptions) ([]*types.ServiceEndpoint, error)
⋮----
func (c *fakeServiceClient) Delete(_ context.Context, _, _, _ string, _ ...v1.DeleteOptions) (*types.DeletionResult, error)
⋮----
var _ v1.ServiceInterface = (*fakeServiceClient)(nil)
... (1 lines truncated)
</file>

<file path="sdk/go/openshell/v1/fake/ssh_test.go">
package fake
⋮----
import (
	"context"
	"testing"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"context"
"testing"
⋮----
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
⋮----
v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
func TestFakeSSH_CreateSession_ReturnsUnimplemented(t *testing.T)
⋮----
func TestFakeSSH_RevokeSession_ReturnsUnimplemented(t *testing.T)
⋮----
func TestFakeSSH_CreateSession_ClosedReturnsUnavailable(t *testing.T)
⋮----
func TestFakeSSH_RevokeSession_ClosedReturnsUnavailable(t *testing.T)
⋮----
func TestFakeSSH_Tunnel_ReturnsUnimplemented(t *testing.T)
⋮----
... (8 lines truncated)
</file>

<file path="sdk/go/openshell/v1/fake/ssh.go">
package fake
⋮----
import (
	"context"
	"fmt"
	"io"
	v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"context"
"fmt"
"io"
⋮----
v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
type fakeSSHClient struct {
	closedFunc func() bool
}
⋮----
func newFakeSSHClient(closedFunc func() bool) *fakeSSHClient
⋮----
func (c *fakeSSHClient) CreateSession(_ context.Context, _, _ string) (*types.SSHSession, error)
⋮----
func (c *fakeSSHClient) RevokeSession(_ context.Context, _, _ string, _ ...v1.DeleteOptions) (*types.DeletionResult, error)
⋮----
func (c *fakeSSHClient) Tunnel(_ context.Context, _, sandboxName string, port uint32, _ ...v1.TunnelOption) (io.ReadWriteCloser, error)
⋮----
var _ v1.SSHInterface = (*fakeSSHClient)(nil)
... (1 lines truncated)
</file>

<file path="sdk/go/openshell/v1/fake/store_test.go">
package fake
⋮----
import (
	"sort"
	"testing"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"sort"
"testing"
⋮----
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
type testItem struct {
	Name  string
	Value string
	Tags  map[string]string
}
⋮----
func testItemName(t *testItem) string
⋮----
func copyTestItem(t *testItem) *testItem
⋮----
func newTestStore() *objectStore[*testItem]
⋮----
... (42 lines truncated)
</file>

<file path="sdk/go/openshell/v1/fake/store.go">
package fake
⋮----
import (
	"fmt"
	"strings"
	"sync"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"fmt"
"strings"
"sync"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
func compositeKey(workspace, name string) string
⋮----
type objectStore[T any] struct {
	mu       sync.RWMutex
	items    map[string]T
	nameFunc func(T) string
	copyFunc func(T) T
}
⋮----
func newobjectStore[T any](nameFunc func(T) string, copyFunc func(T) T) *objectStore[T]
⋮----
func (s *objectStore[T]) Create(workspace string, obj T) (T, error)
⋮----
var zero T
⋮----
... (16 lines truncated)
</file>

<file path="sdk/go/openshell/v1/fake/tcp_test.go">
package fake
⋮----
import (
	"context"
	"testing"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"context"
"testing"
⋮----
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
⋮----
v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
func TestFakeTCP_Forward_ReturnsUnimplemented(t *testing.T)
⋮----
func TestFakeTCP_Forward_ClosedReturnsUnavailable(t *testing.T)
⋮----
func TestFakeTCP_Forward_WithForwardOption(t *testing.T)
⋮----
func TestFakeTCP_Forward_InvalidPort(t *testing.T)
⋮----
func TestFakeTCP_Listen_EmptySandboxName(t *testing.T)
⋮----
... (8 lines truncated)
</file>

<file path="sdk/go/openshell/v1/fake/tcp.go">
package fake
⋮----
import (
	"context"
	"fmt"
	"io"
	v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"context"
"fmt"
"io"
⋮----
v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
type fakeTCPClient struct {
	closedFunc func() bool
}
⋮----
func newFakeTCPClient(closedFunc func() bool) *fakeTCPClient
⋮----
func (c *fakeTCPClient) Forward(_ context.Context, _, sandboxName string, port uint32, _ ...v1.ForwardOption) (io.ReadWriteCloser, error)
⋮----
func (c *fakeTCPClient) Listen(_ context.Context, _, sandboxName string, remotePort uint32, localPort uint32, _ ...v1.ListenOption) (v1.ForwardListener, error)
⋮----
var _ v1.TCPInterface = (*fakeTCPClient)(nil)
</file>

<file path="sdk/go/openshell/v1/fake/workspace_test.go">
package fake
⋮----
import (
	"context"
	"testing"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)
⋮----
"context"
"testing"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
⋮----
func TestWorkspaceDelete_RemovesMembers(t *testing.T)
⋮----
func TestFakeWorkspace_Create(t *testing.T)
⋮----
func TestFakeWorkspace_Create_EmptyName(t *testing.T)
⋮----
func TestFakeWorkspace_Create_AlreadyExists(t *testing.T)
⋮----
func TestFakeWorkspace_Create_DeepCopy(t *testing.T)
⋮----
func TestFakeWorkspace_Get(t *testing.T)
⋮----
func TestFakeWorkspace_Get_EmptyName(t *testing.T)
... (41 lines truncated)
</file>

<file path="sdk/go/openshell/v1/fake/workspace.go">
package fake
⋮----
import (
	"context"
	"time"
	v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"context"
"time"
⋮----
v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
func workspaceName(ws *types.Workspace) string
⋮----
func copyWorkspace(ws *types.Workspace) *types.Workspace
⋮----
func memberName(m *types.WorkspaceMember) string
⋮----
func copyMember(m *types.WorkspaceMember) *types.WorkspaceMember
⋮----
type fakeWorkspaceClient struct {
	workspaceStore *objectStore[*types.Workspace]
	memberStore    *objectStore[*types.WorkspaceMember]
	closedFunc     func() bool
}
⋮----
func newFakeWorkspaceClient(
... (27 lines truncated)
</file>

<file path="sdk/go/openshell/v1/gateway/config_test.go">
package gateway
⋮----
import (
	"os"
	"path/filepath"
	"testing"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)
⋮----
"os"
"path/filepath"
"testing"
⋮----
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
⋮----
func TestParseMetadata_ValidConfig(t *testing.T)
⋮----
func TestParseMetadata_EmptyAuthMode(t *testing.T)
⋮----
func TestParseMetadata_AllAuthModes(t *testing.T)
⋮----
func TestParseMetadata_MissingEndpoint(t *testing.T)
⋮----
func TestParseMetadata_MissingFile(t *testing.T)
⋮----
func TestParseMetadata_MalformedJSON(t *testing.T)
⋮----
func TestParseMetadata_UnknownFieldsIgnored(t *testing.T)
... (24 lines truncated)
</file>

<file path="sdk/go/openshell/v1/gateway/config.go">
package gateway
⋮----
import (
	"encoding/json"
	"fmt"
	"os"
	"path/filepath"
)
⋮----
"encoding/json"
"fmt"
"os"
"path/filepath"
⋮----
type AuthMode string
⋮----
const (
	AuthModeNone AuthMode = ""
	// AuthModePlaintext indicates an insecure plaintext connection with
	// no TLS and no authentication.
	AuthModePlaintext AuthMode = "plaintext"
	AuthModeCloudflareJWT AuthMode = "cloudflare_jwt"
	AuthModeOIDC AuthMode = "oidc"
	AuthModeMTLS AuthMode = "mtls"
)
⋮----
// AuthModePlaintext indicates an insecure plaintext connection with
// no TLS and no authentication.
⋮----
type ConfigSource string
... (40 lines truncated)
</file>

<file path="sdk/go/openshell/v1/gateway/doc.go">
package gateway
</file>

<file path="sdk/go/openshell/v1/gateway/errors_test.go">
package gateway
⋮----
import (
	"errors"
	"fmt"
	"testing"
	"github.com/stretchr/testify/assert"
)
⋮----
"errors"
"fmt"
"testing"
⋮----
"github.com/stretchr/testify/assert"
⋮----
func TestSentinelErrors_ErrorsIs(t *testing.T)
⋮----
func TestSentinelErrors_NotConfused(t *testing.T)
⋮----
func TestSentinelErrors_HaveMessages(t *testing.T)
</file>

<file path="sdk/go/openshell/v1/gateway/errors.go">
package gateway
⋮----
import "errors"
⋮----
var (
	ErrGatewayNotFound = errors.New("gateway: not found")
</file>

<file path="sdk/go/openshell/v1/gateway/gateway_test.go">
package gateway
⋮----
import (
	"context"
	"os"
	"path/filepath"
	"testing"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"context"
"os"
"path/filepath"
"testing"
⋮----
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
func setupGateway(t *testing.T, name, metadataJSON string) string
⋮----
func setupGatewayWithTokens(t *testing.T, name, metadataJSON string, tokens map[string]string) string
⋮----
func TestNewClient_AuthModeNone(t *testing.T)
⋮----
func TestNewClient_AuthModePlaintext(t *testing.T)
⋮----
... (60 lines truncated)
</file>

<file path="sdk/go/openshell/v1/gateway/gateway.go">
package gateway
⋮----
import (
	"fmt"
	v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/options"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"fmt"
⋮----
v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/options"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
func NewClient(name string, opts ...ClientOption) (*v1.Client, error)
⋮----
func LoadConfig(name string) (*Config, error)
⋮----
func loadConfigInternal(name string) (*Config, error)
⋮----
// Override name from directory (validated) rather than metadata.json.
⋮----
// ListGateways enumerates all available gateways from user and system
// directories. User gateways appear first. If the same name exists in
// both directories, only the user gateway is returned (user precedence).
// Returns an empty slice (not an error) when no gateways are configured.
//
// ListGateways is safe for concurrent use from multiple goroutines.
func ListGateways() ([]Info, error)
... (11 lines truncated)
</file>

<file path="sdk/go/openshell/v1/gateway/options_nil_test.go">
package gateway
⋮----
import (
	"testing"
	"time"
	"github.com/stretchr/testify/assert"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/options"
)
⋮----
"testing"
"time"
⋮----
"github.com/stretchr/testify/assert"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/options"
⋮----
func TestClientOption_NilIgnored(t *testing.T)
⋮----
var cfg clientConfig
</file>

<file path="sdk/go/openshell/v1/gateway/options.go">
package gateway
⋮----
import (
	"time"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"time"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
type clientConfig struct {
	logger      types.Logger
	timeout     time.Duration
	tls         *types.TLSConfig
	auth        types.AuthProvider
	retryPolicy *types.RetryPolicy
}
⋮----
type ClientOption func(*clientConfig)
⋮----
func WithLogger(l types.Logger) ClientOption
⋮----
func WithTimeout(d time.Duration) ClientOption
⋮----
func WithTLS(cfg *types.TLSConfig) ClientOption
⋮----
func WithAuth(provider types.AuthProvider) ClientOption
⋮----
func WithRetryPolicy(p *types.RetryPolicy) ClientOption
... (1 lines truncated)
</file>

<file path="sdk/go/openshell/v1/gateway/paths_test.go">
package gateway
⋮----
import (
	"os"
	"path/filepath"
	"testing"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)
⋮----
"os"
"path/filepath"
"testing"
⋮----
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
⋮----
func TestUserConfigDir_XDGSet(t *testing.T)
⋮----
func TestUserConfigDir_XDGUnset(t *testing.T)
⋮----
func TestSystemGatewayDir(t *testing.T)
⋮----
func TestResolveGatewayDir_UserDir(t *testing.T)
⋮----
func TestResolveGatewayDir_NotFound(t *testing.T)
⋮----
func TestResolveGatewayDir_InvalidName(t *testing.T)
⋮----
func TestResolveGatewayDir_UserPrecedenceOverSystem(t *testing.T)
... (19 lines truncated)
</file>

<file path="sdk/go/openshell/v1/gateway/paths.go">
package gateway
⋮----
import (
	"fmt"
	"os"
	"path/filepath"
	"strings"
	"unicode"
)
⋮----
"fmt"
"os"
"path/filepath"
"strings"
"unicode"
⋮----
const (
	appName = "openshell"
	gatewaySubdir = "gateways"
	activeGatewayFile = "active_gateway"
	systemConfigBase = "/etc/openshell"
)
⋮----
func userConfigDir() (string, error)
⋮----
func systemGatewayDir() string
⋮----
func resolveGatewayDir(name string) (string, ConfigSource, error)
⋮----
// Check user config dir first.
... (13 lines truncated)
</file>

<file path="sdk/go/openshell/v1/gateway/token_test.go">
package gateway
⋮----
import (
	"os"
	"path/filepath"
	"testing"
	"time"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)
⋮----
"os"
"path/filepath"
"testing"
"time"
⋮----
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
⋮----
func TestReadEdgeToken_PrimaryFile(t *testing.T)
⋮----
func TestReadEdgeToken_PrimaryFileWithWhitespace(t *testing.T)
⋮----
func TestReadEdgeToken_CfTokenFallback(t *testing.T)
⋮----
func TestReadEdgeToken_PrimaryTakesPrecedence(t *testing.T)
⋮----
func TestReadEdgeToken_MissingBothFiles(t *testing.T)
⋮----
func TestReadEdgeToken_EmptyPrimaryFile(t *testing.T)
... (29 lines truncated)
</file>

<file path="sdk/go/openshell/v1/gateway/token.go">
package gateway
⋮----
import (
	"context"
	"encoding/json"
	"fmt"
	"os"
	"path/filepath"
	"strings"
	"sync"
	"time"
	"golang.org/x/oauth2"
)
⋮----
"context"
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"time"
⋮----
"golang.org/x/oauth2"
⋮----
const (
	edgeTokenFile = "edge_token"
	cfTokenFile = "cf_token"
	oidcTokenFile = "oidc_token.json"
)
... (41 lines truncated)
</file>

<file path="sdk/go/openshell/v1/internal/converter/copy.go">
package converter
⋮----
func CopyStringMap(m map[string]string) map[string]string
⋮----
func CopyBoolPtr(p *bool) *bool
⋮----
func CopyInt32Ptr(p *int32) *int32
⋮----
func CopyStringSlice(s []string) []string
⋮----
func CopyByteSlice(b []byte) []byte
⋮----
func boolCount(flags ...bool) int
</file>

<file path="sdk/go/openshell/v1/internal/converter/coverage_test.go">
package converter
⋮----
import (
	"testing"
	dm "github.com/NVIDIA/OpenShell/sdk/go/proto/datamodelv1"
	pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
	sandboxpb "github.com/NVIDIA/OpenShell/sdk/go/proto/sandboxv1"
	"google.golang.org/protobuf/reflect/protoreflect"
)
⋮----
"testing"
⋮----
dm "github.com/NVIDIA/OpenShell/sdk/go/proto/datamodelv1"
pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
sandboxpb "github.com/NVIDIA/OpenShell/sdk/go/proto/sandboxv1"
"google.golang.org/protobuf/reflect/protoreflect"
⋮----
func TestConverterCoversAllProtoFields_SandboxSpec(t *testing.T)
⋮----
func TestConverterCoversAllProtoFields_SandboxTemplate(t *testing.T)
⋮----
func TestConverterCoversAllProtoFields_SandboxWorkloadTemplate(t *testing.T)
⋮----
func TestConverterCoversAllProtoFields_SandboxWorkloadTemplateSpec(t *testing.T)
⋮----
func TestConverterCoversAllProtoFields_SandboxWorkloadConfig(t *testing.T)
⋮----
func TestConverterCoversAllProtoFields_SandboxResources(t *testing.T)
⋮----
func TestConverterCoversAllProtoFields_SandboxServiceLevel(t *testing.T)
... (46 lines truncated)
</file>

<file path="sdk/go/openshell/v1/internal/converter/errors_test.go">
package converter
⋮----
import (
	"testing"
	"time"
	v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"google.golang.org/genproto/googleapis/rpc/errdetails"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"google.golang.org/protobuf/types/known/durationpb"
	"google.golang.org/protobuf/types/known/wrapperspb"
)
⋮----
"testing"
"time"
⋮----
v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/genproto/googleapis/rpc/errdetails"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/durationpb"
"google.golang.org/protobuf/types/known/wrapperspb"
⋮----
func TestFromGRPCError_PreservesStructuredAndUnknownDetails(t *testing.T)
⋮----
var typed *v1.StatusError
... (33 lines truncated)
</file>

<file path="sdk/go/openshell/v1/internal/converter/errors.go">
package converter
⋮----
import (
	"maps"
	"time"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
	"google.golang.org/genproto/googleapis/rpc/errdetails"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)
⋮----
"maps"
"time"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
"google.golang.org/genproto/googleapis/rpc/errdetails"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
⋮----
var grpcToSDK = map[codes.Code]types.ErrorCode{
	codes.NotFound:           types.ErrorNotFound,
	codes.AlreadyExists:      types.ErrorAlreadyExists,
	codes.Unavailable:        types.ErrorUnavailable,
	codes.PermissionDenied:   types.ErrorPermissionDenied,
	codes.InvalidArgument:    types.ErrorInvalidArgument,
	codes.DeadlineExceeded:   types.ErrorDeadlineExceeded,
	codes.Canceled:           types.ErrorCancelled,
	codes.Internal:           types.ErrorInternal,
	codes.Unimplemented:      types.ErrorUnimplemented,
	codes.Aborted:            types.ErrorConflict,
... (8 lines truncated)
</file>

<file path="sdk/go/openshell/v1/internal/converter/exec_test.go">
package converter
⋮----
import (
	"testing"
	v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
	pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)
⋮----
"testing"
⋮----
v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
⋮----
func TestExecChunkFromEvent_Stdout(t *testing.T)
⋮----
func TestExecChunkFromEvent_Stderr(t *testing.T)
⋮----
func TestExecChunkFromEvent_Exit(t *testing.T)
⋮----
func TestExecChunkFromEvent_ExitZero(t *testing.T)
⋮----
func TestExecChunkFromEvent_NilEvent(t *testing.T)
⋮----
func TestExecChunkFromEvent_NilPayload(t *testing.T)
⋮----
func TestExecChunkFromEvent_EmptyStdout(t *testing.T)
... (15 lines truncated)
</file>

<file path="sdk/go/openshell/v1/internal/converter/exec.go">
package converter
⋮----
import (
	"fmt"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
	pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
)
⋮----
"fmt"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
⋮----
func ExecChunkFromEvent(event *pb.ExecSandboxEvent) (*types.ExecChunk, int, error)
⋮----
func ExecRequestToProto(sandboxName string, command []string, opts *types.ExecOptions) *pb.ExecSandboxRequest
⋮----
func ExecInteractiveRequestToProto(sandboxName string, command []string, cols, rows uint32, opts *types.ExecOptions) *pb.ExecSandboxRequest
⋮----
func ExecResultFromEvents(events []*pb.ExecSandboxEvent) (*types.ExecResult, error)
⋮----
var stdout, stderr []byte
</file>

<file path="sdk/go/openshell/v1/internal/converter/health_test.go">
package converter
⋮----
import (
	"testing"
	v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
	pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)
⋮----
"testing"
⋮----
v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
⋮----
func TestGatewayInfoFromProto(t *testing.T)
⋮----
func TestGatewayInfoFromProto_NoDrivers(t *testing.T)
⋮----
func TestGatewayInfoFromProto_Nil(t *testing.T)
⋮----
func TestGatewayInfoFromProto_DeepCopy(t *testing.T)
⋮----
func TestServiceStatusFromProto(t *testing.T)
⋮----
func TestComputeDriverInfoFromProto_NilCapabilities(t *testing.T)
⋮----
func TestCurrentUserFromProto(t *testing.T)
... (7 lines truncated)
</file>

<file path="sdk/go/openshell/v1/internal/converter/health.go">
package converter
⋮----
import (
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
	pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
)
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
⋮----
func GatewayInfoFromProto(resp *pb.GetGatewayInfoResponse) *types.GatewayInfo
⋮----
func ExtensionInfoFromProto(extension *pb.NegotiatedExtensionInfo) types.ExtensionInfo
⋮----
func ExtensionKindFromProto(kind pb.ExtensionKind) types.ExtensionKind
⋮----
func ServiceStatusFromProto(status pb.ServiceStatus) types.ServiceStatus
⋮----
func ComputeDriverInfoFromProto(d *pb.ComputeDriverInfo) types.ComputeDriverInfo
⋮----
func CurrentUserFromProto(resp *pb.GetCurrentUserResponse) *types.CurrentUser
</file>

<file path="sdk/go/openshell/v1/internal/converter/log_test.go">
package converter
⋮----
import (
	"testing"
	pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)
⋮----
"testing"
⋮----
pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
⋮----
func TestLogLineFromProto(t *testing.T)
⋮----
func TestLogLineFromProto_Nil(t *testing.T)
⋮----
func TestLogLineDeepCopy(t *testing.T)
⋮----
func TestLogResultFromProto(t *testing.T)
⋮----
func TestLogResultFromProto_Nil(t *testing.T)
⋮----
func TestLogResultFromProto_EmptyLogs(t *testing.T)
</file>

<file path="sdk/go/openshell/v1/internal/converter/log.go">
package converter
⋮----
import (
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
	pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
)
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
⋮----
func LogLineFromProto(l *pb.SandboxLogLine) *types.LogLine
⋮----
func LogResultFromProto(r *pb.GetSandboxLogsResponse) *types.LogResult
</file>

<file path="sdk/go/openshell/v1/internal/converter/network_policy_test.go">
package converter
⋮----
import (
	"testing"
	v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
	sbv1 "github.com/NVIDIA/OpenShell/sdk/go/proto/sandboxv1"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)
⋮----
"testing"
⋮----
v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
sbv1 "github.com/NVIDIA/OpenShell/sdk/go/proto/sandboxv1"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
⋮----
func TestNetworkPolicyRuleFromProto(t *testing.T)
⋮----
func TestNetworkPolicyRuleFromProto_Nil(t *testing.T)
⋮----
func TestNetworkPolicyRuleRoundTrip(t *testing.T)
⋮----
func TestNetworkPolicyRuleToProto_Nil(t *testing.T)
⋮----
func TestNetworkPolicyRuleDeepCopy(t *testing.T)
⋮----
func TestL7RuleFromProto_NilAllow(t *testing.T)
⋮----
func boolPtr(v bool) *bool
... (1 lines truncated)
</file>

<file path="sdk/go/openshell/v1/internal/converter/network_policy.go">
package converter
⋮----
import (
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
	sbv1 "github.com/NVIDIA/OpenShell/sdk/go/proto/sandboxv1"
)
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
sbv1 "github.com/NVIDIA/OpenShell/sdk/go/proto/sandboxv1"
⋮----
func NetworkPolicyRuleFromProto(r *sbv1.NetworkPolicyRule) *types.NetworkPolicyRule
⋮----
func NetworkPolicyRuleToProto(r *types.NetworkPolicyRule) *sbv1.NetworkPolicyRule
⋮----
func policyNetworkEndpointFromProto(ep *sbv1.NetworkEndpoint) types.PolicyNetworkEndpoint
⋮----
func policyNetworkEndpointToProto(ep *types.PolicyNetworkEndpoint) *sbv1.NetworkEndpoint
⋮----
func mcpOptionsFromProto(m *sbv1.McpOptions) *types.McpOptions
⋮----
func mcpOptionsToProto(m *types.McpOptions) *sbv1.McpOptions
⋮----
func l7RuleFromProto(r *sbv1.L7Rule) types.L7Rule
⋮----
func l7RuleToProto(r *types.L7Rule) *sbv1.L7Rule
⋮----
func l7DenyRuleFromProto(r *sbv1.L7DenyRule) types.L7DenyRule
⋮----
func l7DenyRuleToProto(r *types.L7DenyRule) *sbv1.L7DenyRule
⋮----
... (8 lines truncated)
</file>

<file path="sdk/go/openshell/v1/internal/converter/policy_test.go">
package converter
⋮----
import (
	"testing"
	v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
	pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
	sbv1 "github.com/NVIDIA/OpenShell/sdk/go/proto/sandboxv1"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"google.golang.org/protobuf/types/known/structpb"
)
⋮----
"testing"
⋮----
v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
sbv1 "github.com/NVIDIA/OpenShell/sdk/go/proto/sandboxv1"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/types/known/structpb"
⋮----
func TestPolicyLoadStatusFromProto(t *testing.T)
⋮----
func TestPolicyLoadStatusToProto(t *testing.T)
⋮----
func TestPolicyLoadStatusRoundTrip(t *testing.T)
⋮----
func TestPolicyChunkFromProto(t *testing.T)
⋮----
func TestPolicyChunkFromProto_Nil(t *testing.T)
... (67 lines truncated)
</file>

<file path="sdk/go/openshell/v1/internal/converter/policy.go">
package converter
⋮----
import (
	"fmt"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
	pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
	sbv1 "github.com/NVIDIA/OpenShell/sdk/go/proto/sandboxv1"
	"google.golang.org/protobuf/types/known/structpb"
)
⋮----
"fmt"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
sbv1 "github.com/NVIDIA/OpenShell/sdk/go/proto/sandboxv1"
"google.golang.org/protobuf/types/known/structpb"
⋮----
func PolicyLoadStatusFromProto(s pb.PolicyStatus) types.PolicyLoadStatus
⋮----
func PolicyLoadStatusToProto(s types.PolicyLoadStatus) pb.PolicyStatus
⋮----
func PolicyChunkFromProto(c *pb.PolicyChunk) *types.PolicyChunk
⋮----
func DraftPolicyFromProto(r *pb.GetDraftPolicyResponse) *types.DraftPolicy
⋮----
func SandboxPolicyFromProto(p *sbv1.SandboxPolicy) *types.SandboxPolicy
⋮----
func SandboxPolicyToProto(p *types.SandboxPolicy) *sbv1.SandboxPolicy
⋮----
func SandboxPolicyToProtoChecked(p *types.SandboxPolicy) (*sbv1.SandboxPolicy, error)
... (31 lines truncated)
</file>

<file path="sdk/go/openshell/v1/internal/converter/profile_test.go">
package converter
⋮----
import (
	"testing"
	v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
	pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
	sbv1 "github.com/NVIDIA/OpenShell/sdk/go/proto/sandboxv1"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"google.golang.org/protobuf/types/known/durationpb"
)
⋮----
"testing"
⋮----
v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
sbv1 "github.com/NVIDIA/OpenShell/sdk/go/proto/sandboxv1"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/types/known/durationpb"
⋮----
func TestProfileCategoryFromProto(t *testing.T)
⋮----
func TestProfileCategoryToProto(t *testing.T)
⋮----
func TestNetworkEndpointFromProto(t *testing.T)
⋮----
func TestNetworkEndpointFromProto_Nil(t *testing.T)
⋮----
func TestNetworkEndpointToProto(t *testing.T)
... (59 lines truncated)
</file>

<file path="sdk/go/openshell/v1/internal/converter/profile.go">
package converter
⋮----
import (
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
	pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
	sbv1 "github.com/NVIDIA/OpenShell/sdk/go/proto/sandboxv1"
	"google.golang.org/protobuf/types/known/durationpb"
)
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
sbv1 "github.com/NVIDIA/OpenShell/sdk/go/proto/sandboxv1"
"google.golang.org/protobuf/types/known/durationpb"
⋮----
func ProfileCategoryFromProto(c pb.ProviderProfileCategory) types.ProfileCategory
⋮----
// ProfileCategoryToProto converts an SDK ProfileCategory to a proto ProviderProfileCategory.
func ProfileCategoryToProto(c types.ProfileCategory) pb.ProviderProfileCategory
⋮----
// CredentialTokenGrantTypeFromProto converts a proto token grant type to an SDK token grant type.
func CredentialTokenGrantTypeFromProto(t pb.ProviderCredentialTokenGrantType) types.CredentialTokenGrantType
⋮----
func CredentialTokenGrantTypeToProto(t types.CredentialTokenGrantType) pb.ProviderCredentialTokenGrantType
⋮----
func NetworkEndpointFromProto(ep *sbv1.NetworkEndpoint) *types.NetworkEndpoint
⋮----
func NetworkEndpointToProto(ep *types.NetworkEndpoint) *sbv1.NetworkEndpoint
⋮----
func NetworkBinaryFromProto(b *sbv1.NetworkBinary) *types.NetworkBinary
⋮----
... (36 lines truncated)
</file>

<file path="sdk/go/openshell/v1/internal/converter/provider_test.go">
package converter
⋮----
import (
	"testing"
	"time"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
	dm "github.com/NVIDIA/OpenShell/sdk/go/proto/datamodelv1"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"google.golang.org/protobuf/types/known/timestamppb"
)
⋮----
"testing"
"time"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
dm "github.com/NVIDIA/OpenShell/sdk/go/proto/datamodelv1"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/types/known/timestamppb"
⋮----
func TestProviderFromProto_Nil(t *testing.T)
⋮----
func TestProviderFromProto_Full(t *testing.T)
⋮----
func TestProviderFromProto_NilMetadata(t *testing.T)
⋮----
func TestProviderFromProto_EmptyHandles(t *testing.T)
⋮----
func TestProviderToProto_Nil(t *testing.T)
... (11 lines truncated)
</file>

<file path="sdk/go/openshell/v1/internal/converter/provider.go">
package converter
⋮----
import (
	"time"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
	dm "github.com/NVIDIA/OpenShell/sdk/go/proto/datamodelv1"
	"google.golang.org/protobuf/types/known/timestamppb"
)
⋮----
"time"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
dm "github.com/NVIDIA/OpenShell/sdk/go/proto/datamodelv1"
"google.golang.org/protobuf/types/known/timestamppb"
⋮----
func ProviderFromProto(p *dm.Provider) *types.Provider
⋮----
func ProviderToProto(p *types.Provider) *dm.Provider
</file>

<file path="sdk/go/openshell/v1/internal/converter/refresh_test.go">
package converter
⋮----
import (
	"math"
	"testing"
	"time"
	v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
	pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)
⋮----
"math"
"testing"
"time"
⋮----
v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
⋮----
func TestRefreshStrategyFromProto(t *testing.T)
⋮----
func TestRefreshRecoveryActionFromProto(t *testing.T)
⋮----
func TestRefreshStrategyToProto(t *testing.T)
⋮----
func TestRefreshStatusFromProto(t *testing.T)
⋮----
func TestRefreshStatusFromProto_Nil(t *testing.T)
... (11 lines truncated)
</file>

<file path="sdk/go/openshell/v1/internal/converter/refresh.go">
package converter
⋮----
import (
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
	pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
)
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
⋮----
func RefreshStrategyFromProto(s pb.ProviderCredentialRefreshStrategy) types.RefreshStrategy
⋮----
func RefreshRecoveryActionFromProto(a pb.ProviderCredentialRefreshRecoveryAction) types.RefreshRecoveryAction
⋮----
func RefreshStrategyToProto(s types.RefreshStrategy) pb.ProviderCredentialRefreshStrategy
⋮----
func RefreshStatusFromProto(s *pb.ProviderCredentialRefreshStatus) *types.RefreshStatus
⋮----
func RefreshConfigToProto(c *types.RefreshConfig) *pb.ConfigureProviderRefreshRequest
</file>

<file path="sdk/go/openshell/v1/internal/converter/sandbox_test.go">
package converter
⋮----
import (
	"testing"
	"time"
	v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
	dm "github.com/NVIDIA/OpenShell/sdk/go/proto/datamodelv1"
	pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
	sandboxpb "github.com/NVIDIA/OpenShell/sdk/go/proto/sandboxv1"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"google.golang.org/protobuf/proto"
	"google.golang.org/protobuf/types/known/durationpb"
	"google.golang.org/protobuf/types/known/structpb"
	"google.golang.org/protobuf/types/known/timestamppb"
)
⋮----
"testing"
"time"
⋮----
v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
dm "github.com/NVIDIA/OpenShell/sdk/go/proto/datamodelv1"
pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
sandboxpb "github.com/NVIDIA/OpenShell/sdk/go/proto/sandboxv1"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/durationpb"
"google.golang.org/protobuf/types/known/structpb"
"google.golang.org/protobuf/types/known/timestamppb"
... (47 lines truncated)
</file>

<file path="sdk/go/openshell/v1/internal/converter/sandbox.go">
package converter
⋮----
import (
	"fmt"
	"slices"
	"time"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
	dm "github.com/NVIDIA/OpenShell/sdk/go/proto/datamodelv1"
	pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
	"google.golang.org/protobuf/types/known/durationpb"
	"google.golang.org/protobuf/types/known/structpb"
)
⋮----
"fmt"
"slices"
"time"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
dm "github.com/NVIDIA/OpenShell/sdk/go/proto/datamodelv1"
pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
"google.golang.org/protobuf/types/known/durationpb"
"google.golang.org/protobuf/types/known/structpb"
⋮----
func SandboxFromProto(s *pb.Sandbox) *types.Sandbox
⋮----
func sandboxSpecFromProto(spec *pb.SandboxSpec) types.SandboxSpec
⋮----
func sandboxStatusFromProto(status *pb.SandboxStatus) types.SandboxStatus
⋮----
func endpointResultFromProto(result pb.EndpointResult) types.EndpointResult
... (51 lines truncated)
</file>

<file path="sdk/go/openshell/v1/internal/converter/service_test.go">
package converter
⋮----
import (
	"testing"
	v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
	dm "github.com/NVIDIA/OpenShell/sdk/go/proto/datamodelv1"
	pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)
⋮----
"testing"
⋮----
v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
dm "github.com/NVIDIA/OpenShell/sdk/go/proto/datamodelv1"
pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
⋮----
func TestServiceEndpointFromProto(t *testing.T)
⋮----
func TestServiceEndpointFromProto_NilEndpoint(t *testing.T)
⋮----
func TestServiceEndpointFromProto_NilMetadata(t *testing.T)
⋮----
func TestServiceEndpointFromProto_Nil(t *testing.T)
⋮----
func TestServiceEndpointToProto(t *testing.T)
⋮----
func TestServiceEndpointToProto_Nil(t *testing.T)
... (3 lines truncated)
</file>

<file path="sdk/go/openshell/v1/internal/converter/service.go">
package converter
⋮----
import (
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
	dm "github.com/NVIDIA/OpenShell/sdk/go/proto/datamodelv1"
	pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
)
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
dm "github.com/NVIDIA/OpenShell/sdk/go/proto/datamodelv1"
pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
⋮----
func ServiceEndpointFromProto(resp *pb.ServiceEndpointResponse) *types.ServiceEndpoint
⋮----
func ServiceEndpointToProto(se *types.ServiceEndpoint) *pb.ServiceEndpointResponse
⋮----
func serviceAuthorizationModeToProto(mode types.ServiceAuthorizationMode) pb.ServiceAuthorizationMode
⋮----
func serviceAuthorizationModeFromProto(mode pb.ServiceAuthorizationMode) types.ServiceAuthorizationMode
</file>

<file path="sdk/go/openshell/v1/internal/converter/setting_test.go">
package converter
⋮----
import (
	"testing"
	v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
	pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
	sbv1 "github.com/NVIDIA/OpenShell/sdk/go/proto/sandboxv1"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)
⋮----
"testing"
⋮----
v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
sbv1 "github.com/NVIDIA/OpenShell/sdk/go/proto/sandboxv1"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
⋮----
func TestSettingValueFromProto_StringValue(t *testing.T)
⋮----
func TestSettingValueFromProto_BoolValue(t *testing.T)
⋮----
func TestSettingValueFromProto_IntValue(t *testing.T)
⋮----
func TestSettingValueFromProto_BytesValue(t *testing.T)
⋮----
func TestSettingValueFromProto_BytesDeepCopy(t *testing.T)
⋮----
func TestSettingValueFromProto_NilOneof(t *testing.T)
... (97 lines truncated)
</file>

<file path="sdk/go/openshell/v1/internal/converter/setting.go">
package converter
⋮----
import (
	"fmt"
	"slices"
	v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
	pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
	sbv1 "github.com/NVIDIA/OpenShell/sdk/go/proto/sandboxv1"
)
⋮----
"fmt"
"slices"
⋮----
v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
sbv1 "github.com/NVIDIA/OpenShell/sdk/go/proto/sandboxv1"
⋮----
func SettingValueFromProto(pv *sbv1.SettingValue) *v1.SettingValue
⋮----
func SettingValueToProto(sv *v1.SettingValue) *sbv1.SettingValue
⋮----
func SettingScopeFromProto(ps sbv1.SettingScope) v1.SettingScope
⋮----
// SettingScopeToProto converts an SDK SettingScope to a proto SettingScope enum.
func SettingScopeToProto(s v1.SettingScope) sbv1.SettingScope
⋮----
// PolicySourceFromProto converts a proto PolicySource enum to an SDK PolicySource.
func PolicySourceFromProto(ps sbv1.PolicySource) v1.PolicySource
⋮----
// --- EffectiveSetting ---
... (37 lines truncated)
</file>

<file path="sdk/go/openshell/v1/internal/converter/ssh_test.go">
package converter
⋮----
import (
	"testing"
	v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
	pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)
⋮----
"testing"
⋮----
v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
⋮----
func TestSSHSessionFromProto(t *testing.T)
⋮----
func TestSSHSessionFromProto_MinimalFields(t *testing.T)
⋮----
func TestSSHSessionFromProto_Nil(t *testing.T)
⋮----
func TestSSHSessionToProto(t *testing.T)
⋮----
func TestSSHSessionToProto_Nil(t *testing.T)
⋮----
func TestSSHSessionRoundTrip(t *testing.T)
</file>

<file path="sdk/go/openshell/v1/internal/converter/ssh.go">
package converter
⋮----
import (
	v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
	pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
)
⋮----
v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
⋮----
func SSHSessionFromProto(resp *pb.CreateSshSessionResponse) *v1.SSHSession
⋮----
func SSHSessionToProto(session *v1.SSHSession) *pb.CreateSshSessionResponse
</file>

<file path="sdk/go/openshell/v1/internal/converter/time_test.go">
package converter
⋮----
import (
	"testing"
	"time"
	"github.com/stretchr/testify/assert"
	"google.golang.org/protobuf/types/known/timestamppb"
)
⋮----
"testing"
"time"
⋮----
"github.com/stretchr/testify/assert"
"google.golang.org/protobuf/types/known/timestamppb"
⋮----
func TestTimePtrProtoRoundTripPreservesMinimumTimestamp(t *testing.T)
⋮----
func TestTimestampStringFromProtoPreservesMinimumTimestamp(t *testing.T)
⋮----
func TestTimeFromMillis(t *testing.T)
⋮----
func TestTimeFromMillis_Zero(t *testing.T)
⋮----
func TestMillisFromTime(t *testing.T)
⋮----
func TestMillisFromTime_Zero(t *testing.T)
⋮----
func TestRoundTrip(t *testing.T)
⋮----
func TestTimeFromMillisPtr_NonZero(t *testing.T)
... (9 lines truncated)
</file>

<file path="sdk/go/openshell/v1/internal/converter/time.go">
package converter
⋮----
import (
	"time"
	"google.golang.org/protobuf/types/known/durationpb"
	"google.golang.org/protobuf/types/known/timestamppb"
)
⋮----
"time"
⋮----
"google.golang.org/protobuf/types/known/durationpb"
"google.golang.org/protobuf/types/known/timestamppb"
⋮----
func TimeFromProto(value *timestamppb.Timestamp) time.Time
⋮----
func TimePtrFromProto(value *timestamppb.Timestamp) *time.Time
⋮----
func TimestampFromTime(value time.Time) *timestamppb.Timestamp
⋮----
func TimestampFromTimePtr(value *time.Time) *timestamppb.Timestamp
⋮----
func MillisFromProto(value *timestamppb.Timestamp) int64
⋮----
func TimestampFromMillis(value int64) *timestamppb.Timestamp
⋮----
func TimestampStringFromProto(value *timestamppb.Timestamp) string
⋮----
func DurationSecondsFromProto(value *durationpb.Duration) uint64
⋮----
func DurationFromSeconds(value uint64) *durationpb.Duration
... (9 lines truncated)
</file>

<file path="sdk/go/openshell/v1/internal/converter/workspace_test.go">
package converter
⋮----
import (
	"testing"
	"time"
	v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
	dm "github.com/NVIDIA/OpenShell/sdk/go/proto/datamodelv1"
	pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)
⋮----
"testing"
"time"
⋮----
v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
dm "github.com/NVIDIA/OpenShell/sdk/go/proto/datamodelv1"
pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
⋮----
func TestWorkspaceFromProto(t *testing.T)
⋮----
func TestWorkspaceFromProto_DeepCopy(t *testing.T)
⋮----
func TestWorkspaceFromProto_NilMetadata(t *testing.T)
⋮----
func TestWorkspaceFromProto_NilStatus(t *testing.T)
⋮----
func TestWorkspaceFromProto_Nil(t *testing.T)
... (17 lines truncated)
</file>

<file path="sdk/go/openshell/v1/internal/converter/workspace.go">
package converter
⋮----
import (
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
	dm "github.com/NVIDIA/OpenShell/sdk/go/proto/datamodelv1"
	pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
)
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
dm "github.com/NVIDIA/OpenShell/sdk/go/proto/datamodelv1"
pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
⋮----
func WorkspaceFromProto(w *dm.Workspace) *types.Workspace
⋮----
func WorkspacePhaseFromProto(phase dm.WorkspacePhase) types.WorkspacePhase
⋮----
func WorkspaceMemberFromProto(m *pb.WorkspaceMember) *types.WorkspaceMember
⋮----
func WorkspaceRoleFromProto(role pb.WorkspaceRole) types.WorkspaceRole
⋮----
func WorkspaceRoleToProto(role types.WorkspaceRole) pb.WorkspaceRole
</file>

<file path="sdk/go/openshell/v1/internal/grpc/conn_test.go">
package grpc
⋮----
import (
	"context"
	"net"
	"testing"
	"github.com/stretchr/testify/require"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
)
⋮----
"context"
"net"
"testing"
⋮----
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
⋮----
func TestNewConnectionHTTPSchemeUsesPlaintext(t *testing.T)
⋮----
func TestNewConnectionHTTPSSchemeUsesTLS(t *testing.T)
⋮----
func TestNewConnectionNoSchemeUsesTLS(t *testing.T)
⋮----
func TestNewConnectionInsecureTLSConfig(t *testing.T)
⋮----
func TestNewConnectionHTTPWithSecureAuthRejects(t *testing.T)
⋮----
func TestNewConnectionHTTPWithInsecureAuth(t *testing.T)
... (14 lines truncated)
</file>

<file path="sdk/go/openshell/v1/internal/grpc/conn.go">
package grpc
⋮----
import (
	"crypto/tls"
	"crypto/x509"
	"fmt"
	"os"
	"strings"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
	"google.golang.org/grpc/credentials/insecure"
)
⋮----
"crypto/tls"
"crypto/x509"
"fmt"
"os"
"strings"
⋮----
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/credentials/insecure"
⋮----
type TLSParams struct {
	CertFile string
	KeyFile  string
	CAFile   string
	Insecure bool
}
⋮----
... (4 lines truncated)
</file>

<file path="sdk/go/openshell/v1/internal/options/options_test.go">
package options
⋮----
import (
	"testing"
	"github.com/stretchr/testify/assert"
)
⋮----
"testing"
⋮----
"github.com/stretchr/testify/assert"
⋮----
type testConfig struct {
	a int
	b string
}
⋮----
type testOption func(*testConfig)
⋮----
func TestApply_EmptySlice(t *testing.T)
⋮----
var cfg testConfig
⋮----
func TestApply_NilSlice(t *testing.T)
⋮----
func TestApply_AllNil(t *testing.T)
⋮----
func TestApply_NilFirst(t *testing.T)
⋮----
func TestApply_NilMiddle(t *testing.T)
⋮----
... (13 lines truncated)
</file>

<file path="sdk/go/openshell/v1/internal/options/options.go">
package options
⋮----
func Apply[T any, O ~func(*T)](target *T, opts []O)
</file>

<file path="sdk/go/openshell/v1/oidc/authcode_test.go">
package oidc
⋮----
import (
	"context"
	"errors"
	"fmt"
	"net/http"
	"net/http/httptest"
	"net/url"
	"testing"
	"time"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)
⋮----
"context"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"testing"
"time"
⋮----
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
⋮----
func TestGenerateCodeVerifier_Length(t *testing.T)
⋮----
func TestGenerateCodeVerifier_Base64URLSafe(t *testing.T)
... (41 lines truncated)
</file>

<file path="sdk/go/openshell/v1/oidc/authcode.go">
package oidc
⋮----
import (
	"context"
	"crypto/rand"
	"crypto/sha256"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io"
	"net"
	"net/http"
	"net/url"
	"strings"
	"sync"
	"time"
	"golang.org/x/oauth2"
)
⋮----
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"net/url"
"strings"
... (37 lines truncated)
</file>

<file path="sdk/go/openshell/v1/oidc/browser_test.go">
package oidc
⋮----
import (
	"runtime"
	"slices"
	"testing"
	"github.com/stretchr/testify/assert"
)
⋮----
"runtime"
"slices"
"testing"
⋮----
"github.com/stretchr/testify/assert"
⋮----
func TestBrowserCommand_Platform(t *testing.T)
⋮----
func TestBrowserCommand_URLPassedAsArg(t *testing.T)
⋮----
func TestBrowserCommandForOS_WindowsDoesNotUseCommandShell(t *testing.T)
⋮----
func TestOpenBrowser_InvalidCommand(t *testing.T)
</file>

<file path="sdk/go/openshell/v1/oidc/browser.go">
package oidc
⋮----
import (
	"fmt"
	"net/url"
	"os/exec"
	"runtime"
)
⋮----
"fmt"
"net/url"
"os/exec"
"runtime"
⋮----
func browserCommand(url string) (string, []string)
⋮----
func browserCommandForOS(goos, url string) (string, []string)
⋮----
func openBrowser(rawURL string) error
⋮----
func openBrowserWith(name string, args ...string) error
</file>

<file path="sdk/go/openshell/v1/oidc/credentials_auth.go">
package oidc
⋮----
import (
	"context"
	"sync"
	"time"
	"golang.org/x/oauth2"
	"golang.org/x/sync/singleflight"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"context"
"sync"
"time"
⋮----
"golang.org/x/oauth2"
"golang.org/x/sync/singleflight"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
const clientCredentialsLeeway = 30 * time.Second
⋮----
type clientCredentialsAuth struct {
	cfg   *loginConfig
	mu    sync.Mutex
	token *oauth2.Token
	group singleflight.Group
}
⋮----
func NewClientCredentialsAuth(opts ...LoginOption) (types.AuthProvider, error)
... (17 lines truncated)
</file>

<file path="sdk/go/openshell/v1/oidc/credentials_test.go">
package oidc
⋮----
import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
	"net/http/httptest"
	"net/url"
	"os"
	"path/filepath"
	"sync"
	"sync/atomic"
	"testing"
	"time"
	"golang.org/x/oauth2"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/gateway"
)
⋮----
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"os"
... (88 lines truncated)
</file>

<file path="sdk/go/openshell/v1/oidc/credentials.go">
package oidc
⋮----
import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"strings"
	"time"
	"golang.org/x/oauth2"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/gateway"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/options"
)
⋮----
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
⋮----
"golang.org/x/oauth2"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/gateway"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/options"
⋮----
... (14 lines truncated)
</file>

<file path="sdk/go/openshell/v1/oidc/device_test.go">
package oidc
⋮----
import (
	"context"
	"encoding/json"
	"errors"
	"net/http"
	"net/http/httptest"
	"sync/atomic"
	"testing"
	"time"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/gateway"
)
⋮----
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"sync/atomic"
"testing"
"time"
⋮----
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/gateway"
⋮----
... (44 lines truncated)
</file>

<file path="sdk/go/openshell/v1/oidc/device.go">
package oidc
⋮----
import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"strings"
	"time"
	"golang.org/x/oauth2"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/gateway"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/options"
)
⋮----
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
⋮----
"golang.org/x/oauth2"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/gateway"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/options"
⋮----
... (37 lines truncated)
</file>

<file path="sdk/go/openshell/v1/oidc/discovery_test.go">
package oidc
⋮----
import (
	"context"
	"errors"
	"net/http"
	"net/http/httptest"
	"sync"
	"testing"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)
⋮----
"context"
"errors"
"net/http"
"net/http/httptest"
"sync"
"testing"
⋮----
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
⋮----
func wellKnownJSON(issuer string) string
⋮----
func TestDiscover_ValidDocument(t *testing.T)
⋮----
var srv *httptest.Server
⋮----
func TestDiscover_CachesResult(t *testing.T)
... (25 lines truncated)
</file>

<file path="sdk/go/openshell/v1/oidc/discovery.go">
package oidc
⋮----
import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"net"
	"net/http"
	"net/url"
	"strings"
	"sync"
	"time"
)
⋮----
"context"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"net/url"
"strings"
"sync"
"time"
⋮----
var oidcHTTPClient = &http.Client{
	Timeout: 30 * time.Second,
	CheckRedirect: func(*http.Request, []*http.Request) error {
		return http.ErrUseLastResponse
... (39 lines truncated)
</file>

<file path="sdk/go/openshell/v1/oidc/doc.go">
package oidc
</file>

<file path="sdk/go/openshell/v1/oidc/errors_test.go">
package oidc
⋮----
import (
	"errors"
	"fmt"
	"testing"
	"github.com/stretchr/testify/assert"
)
⋮----
"errors"
"fmt"
"testing"
⋮----
"github.com/stretchr/testify/assert"
⋮----
func TestSentinelErrors_AreDistinct(t *testing.T)
⋮----
func TestSentinelErrors_MatchSelf(t *testing.T)
⋮----
func TestSentinelErrors_WrappedMatchViIs(t *testing.T)
⋮----
func TestSentinelErrors_HaveDescriptiveMessages(t *testing.T)
⋮----
func TestSentinelErrors_DoubleWrapped(t *testing.T)
</file>

<file path="sdk/go/openshell/v1/oidc/errors.go">
package oidc
⋮----
import "errors"
⋮----
var (
	ErrDiscovery = errors.New("oidc: discovery failed")
</file>

<file path="sdk/go/openshell/v1/oidc/example_test.go">
package oidc_test
⋮----
import (
	"context"
	"fmt"
	"log"
	"time"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/oidc"
)
⋮----
"context"
"fmt"
"log"
"time"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/oidc"
⋮----
func ExampleLogin_gateway()
⋮----
func ExampleLogin_standalone()
⋮----
func ExampleDeviceLogin()
⋮----
func ExampleDeviceLogin_customDisplay()
⋮----
func ExampleClientCredentials()
⋮----
func ExampleClientCredentials_gateway()
</file>

<file path="sdk/go/openshell/v1/oidc/keyboard_test.go">
package oidc
⋮----
import (
	"bytes"
	"context"
	"errors"
	"io"
	"strings"
	"sync/atomic"
	"testing"
	"time"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)
⋮----
"bytes"
"context"
"errors"
"io"
"strings"
"sync/atomic"
"testing"
"time"
⋮----
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
⋮----
func TestKeyboardFlow_ReadsCode(t *testing.T)
⋮----
func TestInputDispatcher_BoundsBlockedReads(t *testing.T)
... (22 lines truncated)
</file>

<file path="sdk/go/openshell/v1/oidc/keyboard.go">
package oidc
⋮----
import (
	"bufio"
	"context"
	"fmt"
	"io"
	"strings"
)
⋮----
"bufio"
"context"
"fmt"
"io"
"strings"
⋮----
type readResult struct {
	code string
	err  error
}
⋮----
func keyboardFlow(ctx context.Context, authURL string, input io.Reader, output io.Writer) (string, error)
⋮----
type inputRequest struct {
	input  io.Reader
	result chan readResult
}
⋮----
type inputDispatcher struct {
	requests chan inputRequest
... (10 lines truncated)
</file>

<file path="sdk/go/openshell/v1/oidc/oidc_test.go">
package oidc
⋮----
import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"net"
	"net/http"
	"net/http/httptest"
	"os"
	"path/filepath"
	"strings"
	"testing"
	"time"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"golang.org/x/oauth2"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/gateway"
)
⋮----
"context"
"encoding/json"
"errors"
"fmt"
"net"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
... (18 lines truncated)
</file>

<file path="sdk/go/openshell/v1/oidc/oidc.go">
package oidc
⋮----
import (
	"context"
	"fmt"
	"io"
	"os"
	"slices"
	"golang.org/x/oauth2"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/gateway"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/options"
)
⋮----
"context"
"fmt"
"io"
"os"
"slices"
⋮----
"golang.org/x/oauth2"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/gateway"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/options"
⋮----
func Login(ctx context.Context, gatewayName string, opts ...LoginOption) (*oauth2.Token, error)
⋮----
var cancel context.CancelFunc
⋮----
// If readErr is a non-NotExist error, we log and proceed.
// Stale/expired tokens or missing files are not errors; we
... (27 lines truncated)
</file>

<file path="sdk/go/openshell/v1/oidc/options_nil_test.go">
package oidc
⋮----
import (
	"testing"
	"github.com/stretchr/testify/assert"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/options"
)
⋮----
"testing"
⋮----
"github.com/stretchr/testify/assert"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/options"
⋮----
func TestLoginOption_NilIgnored(t *testing.T)
⋮----
var cfg loginConfig
</file>

<file path="sdk/go/openshell/v1/oidc/options_test.go">
package oidc
⋮----
import (
	"testing"
	"time"
	"github.com/stretchr/testify/assert"
)
⋮----
"testing"
"time"
⋮----
"github.com/stretchr/testify/assert"
⋮----
func TestLoginConfig_Defaults(t *testing.T)
⋮----
var cfg loginConfig
⋮----
func TestWithIssuer(t *testing.T)
⋮----
func TestWithClientID(t *testing.T)
⋮----
func TestWithClientSecret(t *testing.T)
⋮----
func TestWithScopes(t *testing.T)
⋮----
func TestWithScopes_DeepCopy(t *testing.T)
⋮----
func TestWithCallbackPort(t *testing.T)
⋮----
func TestWithTimeout(t *testing.T)
... (15 lines truncated)
</file>

<file path="sdk/go/openshell/v1/oidc/options.go">
package oidc
⋮----
import (
	"context"
	"io"
	"time"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/gateway"
)
⋮----
"context"
"io"
"time"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/gateway"
⋮----
var defaultScopes = []string{"openid", "profile", "email"}
⋮----
const defaultTimeout = 2 * time.Minute
⋮----
type loginConfig struct {
	issuer         string
	clientID       string
	clientSecret   string
	secretProvider func(context.Context) (string, error)
	audience       string
	audienceSet    bool
	scopes         []string
	scopesSet      bool
	callbackPort   int
	timeout        time.Duration
... (44 lines truncated)
</file>

<file path="sdk/go/openshell/v1/oidc/token_test.go">
package oidc
⋮----
import (
	"errors"
	"os"
	"path/filepath"
	"runtime"
	"testing"
	"time"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"golang.org/x/oauth2"
)
⋮----
"errors"
"os"
"path/filepath"
"runtime"
"testing"
"time"
⋮----
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/oauth2"
⋮----
func TestWriteToken_Success(t *testing.T)
⋮----
func TestWriteToken_ReplacesInsecureExistingFileWithOwnerOnlyFile(t *testing.T)
⋮----
func TestWriteToken_ExpiresInCalculated(t *testing.T)
... (21 lines truncated)
</file>

<file path="sdk/go/openshell/v1/oidc/token.go">
package oidc
⋮----
import (
	"encoding/json"
	"fmt"
	"os"
	"path/filepath"
	"time"
	"golang.org/x/oauth2"
)
⋮----
"encoding/json"
"fmt"
"os"
"path/filepath"
"time"
⋮----
"golang.org/x/oauth2"
⋮----
const oidcTokenFile = "oidc_token.json"
⋮----
const tokenExpiryLeeway = 10 * time.Second
⋮----
type oidcBundle struct {
	AccessToken  string `json:"access_token"`
	RefreshToken string `json:"refresh_token"`
	Expiry       string `json:"expiry"`
	ExpiresIn    int64  `json:"expires_in"`
}
⋮----
... (6 lines truncated)
</file>

<file path="sdk/go/openshell/v1/types/auth.go">
package types
⋮----
import "context"
⋮----
type AuthProvider interface {
	GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error)
	RequireTransportSecurity() bool
}
</file>

<file path="sdk/go/openshell/v1/types/config.go">
package types
⋮----
import "time"
⋮----
type Config struct {
	Address     string
	TLS         *TLSConfig
	Auth        AuthProvider
	Timeout     time.Duration
	RetryPolicy *RetryPolicy
	Logger      Logger
}
</file>

<file path="sdk/go/openshell/v1/types/doc.go">
package types
</file>

<file path="sdk/go/openshell/v1/types/errors.go">
package types
⋮----
import (
	"errors"
	"fmt"
	"time"
)
⋮----
"errors"
"fmt"
"time"
⋮----
type ErrorCode int
⋮----
const (
	ErrorNotFound ErrorCode = iota + 1
	ErrorAlreadyExists
	ErrorUnavailable
	ErrorPermissionDenied
	ErrorInvalidArgument
	ErrorDeadlineExceeded
	ErrorCancelled
	ErrorInternal
	ErrorUnimplemented
	ErrorConflict
	ErrorUnauthenticated
)
⋮----
func (c ErrorCode) String() string
⋮----
... (49 lines truncated)
</file>

<file path="sdk/go/openshell/v1/types/exec.go">
package types
⋮----
type ExecResult struct {
	ExitCode int
	Stdout   []byte
	Stderr   []byte
}
⋮----
type ExecChunk struct {
	Stream StreamType
	Data   []byte
}
</file>

<file path="sdk/go/openshell/v1/types/health.go">
package types
⋮----
type HealthResult struct {
	Healthy bool
	Version string
}
⋮----
type ServiceStatus string
⋮----
const (
	ServiceStatusHealthy   ServiceStatus = "Healthy"
	ServiceStatusDegraded  ServiceStatus = "Degraded"
	ServiceStatusUnhealthy ServiceStatus = "Unhealthy"
	ServiceStatusUnknown   ServiceStatus = "Unknown"
)
⋮----
type GatewayInfo struct {
	Status         ServiceStatus
	Version        string
	ComputeDrivers []ComputeDriverInfo
	Extensions     []ExtensionInfo
}
⋮----
type ExtensionKind string
⋮----
const (
	ExtensionKindComputeDriver        ExtensionKind = "ComputeDriver"
	ExtensionKindCredentialDriver     ExtensionKind = "CredentialDriver"
	ExtensionKindGatewayInterceptor   ExtensionKind = "GatewayInterceptor"
	ExtensionKindSupervisorMiddleware ExtensionKind = "SupervisorMiddleware"
... (28 lines truncated)
</file>

<file path="sdk/go/openshell/v1/types/log.go">
package types
⋮----
import (
	"time"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/options"
)
⋮----
"time"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/options"
⋮----
type LogLine struct {
	Timestamp time.Time
	Level string
	Target string
	Message string
	Source string
	Fields map[string]string
}
⋮----
type LogResult struct {
	Lines []LogLine
	BufferTotal uint32
}
⋮----
type logConfig struct {
	lines    uint32
	since    time.Time
	sources  []string
	minLevel string
... (24 lines truncated)
</file>

<file path="sdk/go/openshell/v1/types/logger.go">
package types
⋮----
type Logger interface {
	Debug(msg string, keysAndValues ...any)
	Info(msg string, keysAndValues ...any)
	Error(err error, msg string, keysAndValues ...any)
}
</file>

<file path="sdk/go/openshell/v1/types/mutations.go">
package types
⋮----
type DeletionOutcome int32
⋮----
const (
	DeletionUnspecified DeletionOutcome = iota
	DeletionCompleted
	DeletionAccepted
	DeletionAlreadyAbsent
)
⋮----
type DeletionResult struct {
	Outcome DeletionOutcome
	SandboxID string
}
⋮----
type DeleteOptions struct {
	AllowMissing bool
}
</file>

<file path="sdk/go/openshell/v1/types/network_policy.go">
package types
⋮----
type NetworkPolicyRule struct {
	Name string
	Endpoints []PolicyNetworkEndpoint
	Binaries []PolicyNetworkBinary
}
⋮----
type NetworkTLSMode int32
⋮----
const (
	NetworkTLSModeUnspecified NetworkTLSMode = 0
	NetworkTLSModeSkip NetworkTLSMode = 1
	NetworkTLSModeTerminate NetworkTLSMode = 2
	NetworkTLSModePassthrough NetworkTLSMode = 3
)
⋮----
type NetworkEnforcementMode int32
⋮----
const (
	NetworkEnforcementModeUnspecified NetworkEnforcementMode = 0
	NetworkEnforcementModeEnforce NetworkEnforcementMode = 1
	NetworkEnforcementModeAudit NetworkEnforcementMode = 2
)
⋮----
type NetworkAccessPreset int32
⋮----
const (
	NetworkAccessPresetUnspecified NetworkAccessPreset = 0
	NetworkAccessPresetReadOnly NetworkAccessPreset = 1
... (132 lines truncated)
</file>

<file path="sdk/go/openshell/v1/types/options_nil_test.go">
package types
⋮----
import (
	"testing"
	"github.com/stretchr/testify/assert"
)
⋮----
"testing"
⋮----
"github.com/stretchr/testify/assert"
⋮----
func TestLogOption_NilIgnored(t *testing.T)
⋮----
func TestGetDraftOption_NilIgnored(t *testing.T)
</file>

<file path="sdk/go/openshell/v1/types/options.go">
package types
⋮----
import "time"
⋮----
type CreateOptions struct {
	Annotations map[string]string
	ServiceExposures []ServiceExposure
}
⋮----
type ListOptions struct {
	PageSize int
	PageToken     string
	LabelSelector string
	AllWorkspaces bool
}
⋮----
type WatchOptions struct {
	StopOnTerminal bool
}
⋮----
type WaitOptions struct {
	PollInterval time.Duration
}
⋮----
type ExecOptions struct {
	Env     map[string]string
	WorkDir string
	NoLoginShell bool
}
</file>

<file path="sdk/go/openshell/v1/types/policy.go">
package types
⋮----
import (
	"time"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/options"
)
⋮----
"time"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/options"
⋮----
type PolicyLoadStatus int
⋮----
const (
	PolicyLoadStatusUnspecified PolicyLoadStatus = iota
	PolicyLoadStatusPending
	PolicyLoadStatusLoaded
	PolicyLoadStatusFailed
	PolicyLoadStatusSuperseded
)
⋮----
func (s PolicyLoadStatus) String() string
⋮----
type PolicyChunk struct {
	ID string
	Status string
	RuleName string
	ProposedRule *NetworkPolicyRule
	Rationale string
	SecurityNotes string
... (188 lines truncated)
</file>

<file path="sdk/go/openshell/v1/types/profile.go">
package types
⋮----
type ProfileCategory string
⋮----
const (
	ProfileCategoryOther         ProfileCategory = "Other"
	ProfileCategoryInference     ProfileCategory = "Inference"
	ProfileCategoryAgent         ProfileCategory = "Agent"
	ProfileCategorySourceControl ProfileCategory = "SourceControl"
	ProfileCategoryMessaging     ProfileCategory = "Messaging"
	ProfileCategoryData          ProfileCategory = "Data"
	ProfileCategoryKnowledge     ProfileCategory = "Knowledge"
)
⋮----
type ProviderProfile struct {
	ID          string
	DisplayName string
	Description string
	Category    ProfileCategory
	Credentials []ProfileCredential
	Files            []ProfileFile
	Endpoints        []NetworkEndpoint
	Binaries         []NetworkBinary
	InferenceCapable bool
	Discovery        ProfileDiscovery
	ResourceVersion  uint64
	Annotations      map[string]string
	Source           string
	Scope            string
}
... (126 lines truncated)
</file>

<file path="sdk/go/openshell/v1/types/provider.go">
package types
⋮----
import "time"
⋮----
type Provider struct {
	ID                string
	Name              string
	Type              string
	CreatedAt         time.Time
	Labels            map[string]string
	Annotations       map[string]string
	ResourceVersion   uint64
	Workspace         string
	DeletionTimestamp *time.Time
	Spec              ProviderSpec
}
⋮----
type ProviderSpec struct {
	Credentials         map[string]string
	Config              map[string]string
	CredentialExpiresAt map[string]time.Time
	ProfileWorkspace    string
	CredentialHandles   map[string]CredentialHandle
}
⋮----
type CredentialHandle struct {
	Driver   string
	Handle   string
	Metadata map[string]string
}
... (1 lines truncated)
</file>

<file path="sdk/go/openshell/v1/types/refresh.go">
package types
⋮----
import "time"
⋮----
type RefreshStrategy string
⋮----
const (
	RefreshStrategyStatic                  RefreshStrategy = "Static"
	RefreshStrategyExternal                RefreshStrategy = "External"
	RefreshStrategyOAuth2RefreshToken      RefreshStrategy = "OAuth2RefreshToken"
	RefreshStrategyOAuth2ClientCredentials RefreshStrategy = "OAuth2ClientCredentials"
	RefreshStrategyGoogleServiceAccountJWT RefreshStrategy = "GoogleServiceAccountJWT"
	RefreshStrategyAWSStsAssumeRole        RefreshStrategy = "AWSStsAssumeRole"
)
⋮----
type RefreshRecoveryAction int
⋮----
const (
	RefreshRecoveryActionUnspecified RefreshRecoveryAction = iota
	RefreshRecoveryActionRetry
	RefreshRecoveryActionReauthorize
	RefreshRecoveryActionFixConfiguration
	RefreshRecoveryActionInvestigate
)
⋮----
func (a RefreshRecoveryAction) String() string
⋮----
type RefreshStatus struct {
	Provider      string
	ProviderID    string
... (22 lines truncated)
</file>

<file path="sdk/go/openshell/v1/types/sandbox.go">
package types
⋮----
import "time"
⋮----
type Sandbox struct {
	ID                          string
	Name                        string
	CreatedAt                   time.Time
	Labels                      map[string]string
	Annotations                 map[string]string
	ResourceVersion             uint64
	Workspace                   string
	DeletionTimestamp           *time.Time
	CreatedFromWorkloadTemplate *SandboxWorkloadTemplateProvenance
	Spec                        SandboxSpec
	Status                      SandboxStatus
	ServiceURLs map[string]string
}
⋮----
type SandboxSpec struct {
	LogLevel    string
	Environment map[string]string
	Template    *SandboxTemplate
	Providers   []string
	GPU      bool
	GPUCount *uint32
	Policy        *SandboxPolicy
	Command       []string
	TTY           bool
	RestartPolicy SandboxRestartPolicy
... (135 lines truncated)
</file>

<file path="sdk/go/openshell/v1/types/service.go">
package types
⋮----
type ServiceAuthorizationMode int32
⋮----
const (
	ServiceAuthorizationModeStrip ServiceAuthorizationMode = 1
	ServiceAuthorizationModeBearerPassthrough ServiceAuthorizationMode = 2
)
⋮----
type ServiceExposure struct {
	Service           string
	TargetPort        uint32
	AuthorizationMode ServiceAuthorizationMode
}
⋮----
type ServiceEndpoint struct {
	ID                string
	SandboxID         string
	Sandbox           string
	Name              string
	TargetPort        uint32
	Domain            bool
	URL               string
	Workspace         string
	AuthorizationMode ServiceAuthorizationMode
}
</file>

<file path="sdk/go/openshell/v1/types/setting.go">
package types
⋮----
type SettingValueType string
⋮----
const (
	SettingValueString SettingValueType = "string"
	SettingValueBool   SettingValueType = "bool"
	SettingValueInt    SettingValueType = "int"
	SettingValueBytes  SettingValueType = "bytes"
)
⋮----
type SettingValue struct {
	Type      SettingValueType
	StringVal string
	BoolVal   bool
	IntVal    int64
	BytesVal  []byte
}
⋮----
type SettingScope string
⋮----
const (
	SettingScopeUnspecified SettingScope = ""
	SettingScopeSandbox     SettingScope = "sandbox"
	SettingScopeGlobal      SettingScope = "global"
)
⋮----
type PolicySource string
⋮----
const (
... (47 lines truncated)
</file>

<file path="sdk/go/openshell/v1/types/ssh.go">
package types
⋮----
import "fmt"
⋮----
type SSHSession struct {
	SandboxID string
	Token string
	GatewayHost string
	GatewayPort uint32
	GatewayScheme string
	HostKeyFingerprint string
	ExpiresAtMs int64
}
⋮----
func (s SSHSession) String() string
</file>

<file path="sdk/go/openshell/v1/types/types.go">
package types
⋮----
import "time"
⋮----
type SandboxPhase string
⋮----
const (
	SandboxProvisioning SandboxPhase = "Provisioning"
	SandboxReady        SandboxPhase = "Ready"
	SandboxError        SandboxPhase = "Error"
	SandboxDeleting     SandboxPhase = "Deleting"
	SandboxUnknown      SandboxPhase = "Unknown"
	SandboxStopping     SandboxPhase = "Stopping"
	SandboxStopped      SandboxPhase = "Stopped"
	SandboxStarting     SandboxPhase = "Starting"
	SandboxCompleted    SandboxPhase = "Completed"
)
⋮----
type SandboxRestartPolicy string
⋮----
const (
	SandboxRestartNever     SandboxRestartPolicy = "Never"
	SandboxRestartOnFailure SandboxRestartPolicy = "OnFailure"
	SandboxRestartAlways    SandboxRestartPolicy = "Always"
)
⋮----
type EventType string
⋮----
const (
	EventAdded    EventType = "ADDED"
... (25 lines truncated)
</file>

<file path="sdk/go/openshell/v1/types/watch.go">
package types
⋮----
type Event[T any] struct {
	Type   EventType
	Object T
	Err    error
}
⋮----
type WatchInterface[T any] interface {
	ResultChan() <-chan Event[T]
	Stop()
}
</file>

<file path="sdk/go/openshell/v1/types/workspace.go">
package types
⋮----
import "time"
⋮----
type WorkspacePhase string
⋮----
const (
	WorkspaceActive      WorkspacePhase = "Active"
	WorkspaceTerminating WorkspacePhase = "Terminating"
	WorkspaceUnknown     WorkspacePhase = "Unknown"
)
⋮----
type WorkspaceRole string
⋮----
const (
	WorkspaceRoleAdmin   WorkspaceRole = "Admin"
	WorkspaceRoleUser    WorkspaceRole = "User"
	WorkspaceRoleUnknown WorkspaceRole = "Unknown"
)
⋮----
type Workspace struct {
	ID                string
	Name              string
	CreatedAt         time.Time
	Labels            map[string]string
	Annotations       map[string]string
	ResourceVersion   uint64
	Workspace         string
	DeletionTimestamp *time.Time
	Phase             WorkspacePhase
... (13 lines truncated)
</file>

<file path="sdk/go/openshell/v1/auth_extra_test.go">
package v1
⋮----
import (
	"context"
	"errors"
	"testing"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)
⋮----
"context"
"errors"
"testing"
⋮----
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
⋮----
func TestWithExtraHeaders_NilBase(t *testing.T)
⋮----
func TestWithExtraHeaders_NilHeaders(t *testing.T)
⋮----
func TestWithExtraHeaders_EmptyHeaders(t *testing.T)
⋮----
func TestWithExtraHeaders_AllEmptyValues(t *testing.T)
⋮----
func TestWithExtraHeaders_MergesWithBase(t *testing.T)
⋮----
func TestWithExtraHeaders_ExtraPrecedenceOnCollision(t *testing.T)
⋮----
func TestWithExtraHeaders_CaseInsensitiveCollision(t *testing.T)
... (21 lines truncated)
</file>

<file path="sdk/go/openshell/v1/auth_extra.go">
package v1
⋮----
import (
	"context"
	"errors"
	"maps"
	"strings"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"context"
"errors"
"maps"
"strings"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
type extraHeadersAuth struct {
	base    types.AuthProvider
	headers map[string]string
}
⋮----
func WithExtraHeaders(base AuthProvider, headers map[string]string) (AuthProvider, error)
⋮----
func (e *extraHeadersAuth) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error)
⋮----
func (e *extraHeadersAuth) RequireTransportSecurity() bool
</file>

<file path="sdk/go/openshell/v1/auth_refresh_test.go">
package v1
⋮----
import (
	"context"
	"fmt"
	"sync"
	"sync/atomic"
	"testing"
	"time"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"golang.org/x/oauth2"
)
⋮----
"context"
"fmt"
"sync"
"sync/atomic"
"testing"
"time"
⋮----
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/oauth2"
⋮----
type mockTokenSource struct {
	mu        sync.Mutex
	tokenFunc func() (*oauth2.Token, error)
	callCount int
}
... (70 lines truncated)
</file>

<file path="sdk/go/openshell/v1/auth_refresh.go">
package v1
⋮----
import (
	"context"
	"errors"
	"sync"
	"time"
	"golang.org/x/oauth2"
	"golang.org/x/sync/singleflight"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/options"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"context"
"errors"
"sync"
"time"
⋮----
"golang.org/x/oauth2"
"golang.org/x/sync/singleflight"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/options"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
const (
	defaultLeeway  = 10 * time.Second
	initialBackoff = 1 * time.Second
	maxBackoff     = 30 * time.Second
)
⋮----
... (37 lines truncated)
</file>

<file path="sdk/go/openshell/v1/auth_test.go">
package v1
⋮----
import (
	"context"
	"testing"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)
⋮----
"context"
"testing"
⋮----
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
⋮----
func TestNoAuth_GetRequestMetadata(t *testing.T)
⋮----
func TestNoAuth_RequireTransportSecurity(t *testing.T)
⋮----
func TestStaticToken_GetRequestMetadata(t *testing.T)
⋮----
func TestStaticToken_RequireTransportSecurity(t *testing.T)
</file>

<file path="sdk/go/openshell/v1/auth.go">
package v1
⋮----
import (
	"context"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"context"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
type noAuth struct{}
⋮----
func NoAuth() AuthProvider
⋮----
func (n *noAuth) GetRequestMetadata(_ context.Context, _ ...string) (map[string]string, error)
⋮----
func (n *noAuth) RequireTransportSecurity() bool
⋮----
type staticToken struct {
	token string
}
⋮----
func StaticToken(token string) AuthProvider
</file>

<file path="sdk/go/openshell/v1/client_test.go">
package v1
⋮----
import (
	"testing"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)
⋮----
"testing"
⋮----
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
⋮----
func TestNewClient_EmptyAddress(t *testing.T)
⋮----
func TestNewClient_ValidConfig(t *testing.T)
⋮----
func TestClient_CloseIdempotent(t *testing.T)
⋮----
func TestNewClient_DefaultAuth(t *testing.T)
</file>

<file path="sdk/go/openshell/v1/client.go">
package v1
⋮----
import (
	"context"
	"sync"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
	internalgrpc "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/grpc"
	"google.golang.org/grpc"
)
⋮----
"context"
"sync"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
internalgrpc "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/grpc"
"google.golang.org/grpc"
⋮----
type ClientInterface interface {
	Sandboxes() SandboxInterface
	SandboxTemplates() SandboxTemplateInterface
	CreateSandboxFromTemplate(ctx context.Context, workspace, name, templateName string, spec *SandboxSpec, labels map[string]string, opts ...CreateOptions) (*Sandbox, error)
	Providers() ProviderInterface
	Services() ServiceInterface
	Exec() ExecInterface
	Files() FileInterface
	Health() HealthInterface
	SSH() SSHInterface
	TCP() TCPInterface
	Config() ConfigInterface
... (57 lines truncated)
</file>

<file path="sdk/go/openshell/v1/config_client_test.go">
package v1
⋮----
import (
	"context"
	"net"
	"sync"
	"testing"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
	pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
	sbv1 "github.com/NVIDIA/OpenShell/sdk/go/proto/sandboxv1"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/grpc/status"
	"google.golang.org/grpc/test/bufconn"
)
⋮----
"context"
"net"
"sync"
"testing"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
sbv1 "github.com/NVIDIA/OpenShell/sdk/go/proto/sandboxv1"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
... (67 lines truncated)
</file>

<file path="sdk/go/openshell/v1/config_client.go">
package v1
⋮----
import (
	"context"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/converter"
	pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
	sbv1 "github.com/NVIDIA/OpenShell/sdk/go/proto/sandboxv1"
	"google.golang.org/grpc"
)
⋮----
"context"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/converter"
pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
sbv1 "github.com/NVIDIA/OpenShell/sdk/go/proto/sandboxv1"
"google.golang.org/grpc"
⋮----
type configClient struct {
	client    pb.OpenShellClient
	sandboxes SandboxInterface
}
⋮----
func newConfigClient(conn grpc.ClientConnInterface, sandboxes SandboxInterface) *configClient
⋮----
func (c *configClient) GetSandbox(ctx context.Context, workspace, sandboxName string) (*SandboxConfig, error)
⋮----
func (c *configClient) GetGateway(ctx context.Context) (*GatewayConfig, error)
⋮----
func (c *configClient) Update(ctx context.Context, workspace string, update *ConfigUpdate) (*ConfigUpdateResult, error)
</file>

<file path="sdk/go/openshell/v1/config.go">
package v1
⋮----
import (
	"context"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"context"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
const (
	SettingValueString = types.SettingValueString
	SettingValueBool   = types.SettingValueBool
	SettingValueInt    = types.SettingValueInt
	SettingValueBytes  = types.SettingValueBytes
)
⋮----
const (
	SettingScopeUnspecified = types.SettingScopeUnspecified
	SettingScopeSandbox     = types.SettingScopeSandbox
	SettingScopeGlobal      = types.SettingScopeGlobal
)
⋮----
const (
	PolicySourceUnspecified = types.PolicySourceUnspecified
	PolicySourceSandbox     = types.PolicySourceSandbox
	PolicySourceGlobal      = types.PolicySourceGlobal
)
⋮----
... (6 lines truncated)
</file>

<file path="sdk/go/openshell/v1/context_errors_test.go">
package v1
⋮----
import (
	"context"
	"errors"
	"testing"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)
⋮----
"context"
"errors"
"testing"
⋮----
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
⋮----
func TestContextError_Nil(t *testing.T)
⋮----
func TestContextError_DeadlineExceeded(t *testing.T)
⋮----
var se *StatusError
⋮----
func TestContextError_Canceled(t *testing.T)
⋮----
func TestContextError_Default(t *testing.T)
</file>

<file path="sdk/go/openshell/v1/context_errors.go">
package v1
⋮----
import "context"
⋮----
func contextError(err error) error
</file>

<file path="sdk/go/openshell/v1/doc.go">
package v1
</file>

<file path="sdk/go/openshell/v1/errors_test.go">
package v1
⋮----
import (
	"errors"
	"fmt"
	"testing"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)
⋮----
"errors"
"fmt"
"testing"
⋮----
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
⋮----
func TestStatusError_Error(t *testing.T)
⋮----
func TestStatusError_ErrorWithCause(t *testing.T)
⋮----
func TestIsNotFound(t *testing.T)
⋮----
func TestIsAlreadyExists(t *testing.T)
⋮----
func TestIsUnavailable(t *testing.T)
⋮----
func TestIsPermissionDenied(t *testing.T)
⋮----
func TestIsInvalidArgument(t *testing.T)
... (17 lines truncated)
</file>

<file path="sdk/go/openshell/v1/errors.go">
package v1
⋮----
import (
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
const (
	ErrorNotFound         = types.ErrorNotFound
	ErrorAlreadyExists    = types.ErrorAlreadyExists
	ErrorUnavailable      = types.ErrorUnavailable
	ErrorPermissionDenied = types.ErrorPermissionDenied
	ErrorInvalidArgument  = types.ErrorInvalidArgument
	ErrorDeadlineExceeded = types.ErrorDeadlineExceeded
	ErrorCancelled        = types.ErrorCancelled
	ErrorInternal         = types.ErrorInternal
	ErrorUnimplemented    = types.ErrorUnimplemented
	ErrorConflict         = types.ErrorConflict
	ErrorUnauthenticated  = types.ErrorUnauthenticated
)
⋮----
func IsNotFound(err error) bool
⋮----
func IsAlreadyExists(err error) bool
⋮----
func IsUnavailable(err error) bool
⋮----
func IsPermissionDenied(err error) bool
⋮----
... (12 lines truncated)
</file>

<file path="sdk/go/openshell/v1/example_fake_test.go">
package v1_test
⋮----
import (
	"context"
	"fmt"
	"log"
	v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/fake"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"context"
"fmt"
"log"
⋮----
v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/fake"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
func ExampleNewClient_addSandbox()
⋮----
func ExampleNewClient_addProvider()
⋮----
func ExampleNewClient_withHealthResult()
⋮----
func ExampleNewClient_watchEvents()
⋮----
func ExampleNewClient_stopOnTerminal()
⋮----
var count int
... (1 lines truncated)
</file>

<file path="sdk/go/openshell/v1/example_test.go">
package v1_test
⋮----
import (
	"context"
	"fmt"
	"log"
	v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/fake"
)
⋮----
"context"
"fmt"
"log"
⋮----
v1 "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/fake"
⋮----
func ExampleClient_Sandboxes()
⋮----
func ExampleClient_Providers()
⋮----
func ExampleClient_Health()
⋮----
func ExampleClient_Exec()
⋮----
func ExampleClient_TCP()
⋮----
func ExampleIsNotFound()
⋮----
func ExampleIsAlreadyExists()
... (3 lines truncated)
</file>

<file path="sdk/go/openshell/v1/exec_client_test.go">
package v1
⋮----
import (
	"context"
	"io"
	"net"
	"sync"
	"testing"
	"time"
	pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/grpc/status"
	"google.golang.org/grpc/test/bufconn"
)
⋮----
"context"
"io"
"net"
"sync"
"testing"
"time"
⋮----
pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
... (111 lines truncated)
</file>

<file path="sdk/go/openshell/v1/exec_client.go">
package v1
⋮----
import (
	"context"
	"io"
	"sync"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/converter"
	pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
	"google.golang.org/grpc"
	"google.golang.org/grpc/status"
)
⋮----
"context"
"io"
"sync"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/converter"
pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
"google.golang.org/grpc"
"google.golang.org/grpc/status"
⋮----
type execClient struct {
	client    pb.OpenShellClient
	sandboxes SandboxInterface
}
⋮----
func newExecClient(conn grpc.ClientConnInterface, sandboxes SandboxInterface) *execClient
⋮----
func (e *execClient) Run(ctx context.Context, workspace, sandboxName string, command []string, opts ...ExecOptions) (*ExecResult, error)
⋮----
... (49 lines truncated)
</file>

<file path="sdk/go/openshell/v1/exec_control_test.go">
package v1
⋮----
import (
	"errors"
	"io"
	"testing"
	"github.com/stretchr/testify/require"
)
⋮----
"errors"
"io"
"testing"
⋮----
"github.com/stretchr/testify/require"
⋮----
type legacyInteractiveSession struct {
	closed bool
	err    error
}
⋮----
var _ InteractiveSession = (*legacyInteractiveSession)(nil)
⋮----
func (*legacyInteractiveSession) Read([]byte) (int, error)
func (*legacyInteractiveSession) Write(p []byte) (int, error)
func (*legacyInteractiveSession) Resize(uint32, uint32) error
func (*legacyInteractiveSession) ExitCode() (int, error)
func (s *legacyInteractiveSession) Close() error
⋮----
type controlledInteractiveSession struct {
	legacyInteractiveSession
... (13 lines truncated)
</file>

<file path="sdk/go/openshell/v1/exec.go">
package v1
⋮----
import (
	"context"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"context"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
type ExecStream interface {
	Next() (*ExecChunk, error)
	ExitCode() (int, error)
	Close() error
}
⋮----
type InteractiveSession interface {
	Read(p []byte) (int, error)
	Write(p []byte) (int, error)
	Resize(cols, rows uint32) error
	ExitCode() (int, error)
	Close() error
}
⋮----
type InteractiveSessionControl interface {
	InteractiveSession
	CloseWrite() error
	Cancel() error
}
... (11 lines truncated)
</file>

<file path="sdk/go/openshell/v1/file_client_test.go">
package v1
⋮----
import (
	"context"
	"errors"
	"net"
	"os"
	"path/filepath"
	"testing"
	pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/grpc/status"
	"google.golang.org/grpc/test/bufconn"
)
⋮----
"context"
"errors"
"net"
"os"
"path/filepath"
"testing"
⋮----
pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
... (59 lines truncated)
</file>

<file path="sdk/go/openshell/v1/file_client.go">
package v1
⋮----
import (
	"context"
	"fmt"
	"os"
	"time"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/converter"
	pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
	"google.golang.org/grpc"
)
⋮----
"context"
"fmt"
"os"
"time"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/converter"
pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
"google.golang.org/grpc"
⋮----
type fileClient struct {
	client    pb.OpenShellClient
	sandboxes SandboxInterface
	transport sshTransport
}
⋮----
type sshTransport interface {
	available() bool
	upload(ctx context.Context, session *pb.CreateSshSessionResponse, localPath, remotePath string) error
... (17 lines truncated)
</file>

<file path="sdk/go/openshell/v1/file.go">
package v1
⋮----
import (
	"context"
	"errors"
)
⋮----
"context"
"errors"
⋮----
var ErrTransportNotAvailable = errors.New("openshell: file transport not available")
⋮----
type FileInterface interface {
	Upload(ctx context.Context, workspace, sandboxName string, localPath string, remotePath string) error
	Download(ctx context.Context, workspace, sandboxName string, remotePath string, localPath string) error
}
</file>

<file path="sdk/go/openshell/v1/health_client_test.go">
package v1
⋮----
import (
	"context"
	"net"
	"testing"
	pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/grpc/status"
	"google.golang.org/grpc/test/bufconn"
)
⋮----
"context"
"net"
"testing"
⋮----
pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/status"
"google.golang.org/grpc/test/bufconn"
⋮----
const bufSize = 1024 * 1024
... (42 lines truncated)
</file>

<file path="sdk/go/openshell/v1/health_client.go">
package v1
⋮----
import (
	"context"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/converter"
	pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
	"google.golang.org/grpc"
)
⋮----
"context"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/converter"
pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
"google.golang.org/grpc"
⋮----
type healthClient struct {
	client pb.OpenShellClient
}
⋮----
func newHealthClient(conn grpc.ClientConnInterface) *healthClient
⋮----
func (h *healthClient) Check(ctx context.Context) (*HealthResult, error)
⋮----
func (h *healthClient) GetGatewayInfo(ctx context.Context) (*GatewayInfo, error)
⋮----
func (h *healthClient) GetCurrentUser(ctx context.Context) (*CurrentUser, error)
</file>

<file path="sdk/go/openshell/v1/health.go">
package v1
⋮----
import (
	"context"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"context"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
const (
	ExtensionKindComputeDriver        = types.ExtensionKindComputeDriver
	ExtensionKindCredentialDriver     = types.ExtensionKindCredentialDriver
	ExtensionKindGatewayInterceptor   = types.ExtensionKindGatewayInterceptor
	ExtensionKindSupervisorMiddleware = types.ExtensionKindSupervisorMiddleware
	ExtensionKindUnknown              = types.ExtensionKindUnknown
)
⋮----
const (
	ServiceStatusHealthy   = types.ServiceStatusHealthy
	ServiceStatusDegraded  = types.ServiceStatusDegraded
	ServiceStatusUnhealthy = types.ServiceStatusUnhealthy
	ServiceStatusUnknown   = types.ServiceStatusUnknown
)
⋮----
type HealthInterface interface {
	Check(ctx context.Context) (*HealthResult, error)
	GetGatewayInfo(ctx context.Context) (*GatewayInfo, error)
	GetCurrentUser(ctx context.Context) (*CurrentUser, error)
... (2 lines truncated)
</file>

<file path="sdk/go/openshell/v1/integration_test.go">
//go:build integration
⋮----
package v1
⋮----
import (
	"context"
	"errors"
	"fmt"
	"os"
	"testing"
	"time"
	"github.com/stretchr/testify/require"
)
⋮----
"context"
"errors"
"fmt"
"os"
"testing"
"time"
⋮----
"github.com/stretchr/testify/require"
⋮----
func gatewayAddress(t *testing.T) string
⋮----
func TestIntegration_HealthCheck(t *testing.T)
⋮----
func TestIntegration_SandboxExecSmoke(t *testing.T)
⋮----
func TestIntegration_FileTransfer(t *testing.T)
... (1 lines truncated)
</file>

<file path="sdk/go/openshell/v1/logger.go">
package v1
⋮----
import (
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
</file>

<file path="sdk/go/openshell/v1/mutations.go">
package v1
⋮----
import "github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
const (
	DeletionUnspecified   = types.DeletionUnspecified
	DeletionCompleted     = types.DeletionCompleted
	DeletionAccepted      = types.DeletionAccepted
	DeletionAlreadyAbsent = types.DeletionAlreadyAbsent
)
⋮----
func allowMissing(opts []DeleteOptions) bool
</file>

<file path="sdk/go/openshell/v1/options_nil_test.go">
package v1
⋮----
import (
	"testing"
	"time"
	"github.com/stretchr/testify/assert"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/options"
)
⋮----
"testing"
"time"
⋮----
"github.com/stretchr/testify/assert"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/options"
⋮----
func TestRefreshOption_NilIgnored(t *testing.T)
⋮----
func TestForwardOption_NilIgnored(t *testing.T)
⋮----
var cfg forwardConfig
⋮----
func TestListenOption_NilIgnored(t *testing.T)
⋮----
func TestTunnelOption_NilIgnored(t *testing.T)
⋮----
var cfg tunnelConfig
</file>

<file path="sdk/go/openshell/v1/options.go">
package v1
⋮----
import (
	"math"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"math"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
func listPageSize(opts []ListOptions) (int32, error)
</file>

<file path="sdk/go/openshell/v1/pager_test.go">
package v1
⋮----
import (
	"context"
	"errors"
	"testing"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)
⋮----
"context"
"errors"
"testing"
⋮----
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
⋮----
func TestPagerIsLazyAndFetchesOnePageAtATime(t *testing.T)
⋮----
func TestPagerAllRetriesTheCurrentTokenAfterError(t *testing.T)
⋮----
func TestPagerRejectsRepeatedContinuationToken(t *testing.T)
⋮----
func TestPagerBoundsConsumedTokenCount(t *testing.T)
⋮----
func TestPagerBoundsConsumedTokenBytes(t *testing.T)
⋮----
func TestPagerNormalizesEmptyItems(t *testing.T)
⋮----
func TestPagerRejectsNilPage(t *testing.T)
... (1 lines truncated)
</file>

<file path="sdk/go/openshell/v1/pager.go">
package v1
⋮----
import (
	"context"
	"errors"
)
⋮----
"context"
"errors"
⋮----
const (
	maxConsumedPageTokens     = 10_000
	maxConsumedPageTokenBytes = 1 << 20
)
⋮----
type Page[T any] struct {
	Items         []T
	NextPageToken string
}
⋮----
type pageFetcher[T any] func(context.Context, string) (*Page[T], error)
⋮----
type Pager[T any] struct {
	fetch                 pageFetcher[T]
	nextPageToken         *string
	consumedTokens        map[string]struct{}
⋮----
func NewPager[T any](pageToken string, fetch func(context.Context, string) (*Page[T], error)) *Pager[T]
⋮----
func newPager[T any](pageToken string, fetch pageFetcher[T]) *Pager[T]
... (7 lines truncated)
</file>

<file path="sdk/go/openshell/v1/policy_client_test.go">
package v1
⋮----
import (
	"context"
	"net"
	"sync"
	"testing"
	"time"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
	pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
	sbv1 "github.com/NVIDIA/OpenShell/sdk/go/proto/sandboxv1"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/grpc/status"
	"google.golang.org/grpc/test/bufconn"
	"google.golang.org/protobuf/types/known/timestamppb"
)
⋮----
"context"
"net"
"sync"
"testing"
"time"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
sbv1 "github.com/NVIDIA/OpenShell/sdk/go/proto/sandboxv1"
... (140 lines truncated)
</file>

<file path="sdk/go/openshell/v1/policy_client.go">
package v1
⋮----
import (
	"context"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/converter"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
	pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
	"google.golang.org/grpc"
)
⋮----
"context"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/converter"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
"google.golang.org/grpc"
⋮----
type policyClient struct {
	client pb.OpenShellClient
}
⋮----
func newPolicyClient(conn grpc.ClientConnInterface) *policyClient
⋮----
func (p *policyClient) GetDraft(ctx context.Context, workspace, sandboxName string, opts ...GetDraftOption) (*DraftPolicy, error)
⋮----
func (p *policyClient) ApproveDraftChunk(ctx context.Context, workspace, sandboxName, chunkID, reviewToken string) (*ApproveResult, error)
⋮----
func (p *policyClient) RejectDraftChunk(ctx context.Context, workspace, sandboxName, chunkID, reason string) error
⋮----
func (p *policyClient) ApproveAllDraftChunks(ctx context.Context, workspace, sandboxName string, opts ...ApproveAllOption) (*ApproveAllResult, error)
... (15 lines truncated)
</file>

<file path="sdk/go/openshell/v1/policy.go">
package v1
⋮----
import (
	"context"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"context"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
const (
	PolicyLoadStatusUnspecified = types.PolicyLoadStatusUnspecified
	PolicyLoadStatusPending     = types.PolicyLoadStatusPending
	PolicyLoadStatusLoaded      = types.PolicyLoadStatusLoaded
	PolicyLoadStatusFailed      = types.PolicyLoadStatusFailed
	PolicyLoadStatusSuperseded  = types.PolicyLoadStatusSuperseded
)
⋮----
var WithStatusFilter = types.WithStatusFilter
⋮----
var WithIncludeSecurityFlagged = types.WithIncludeSecurityFlagged
⋮----
var WithDraftApprovals = types.WithDraftApprovals
⋮----
var WithVersion = types.WithVersion
⋮----
var WithPageSize = types.WithPageSize
⋮----
var WithPageToken = types.WithPageToken
... (19 lines truncated)
</file>

<file path="sdk/go/openshell/v1/profile_client_test.go">
package v1
⋮----
import (
	"context"
	"net"
	"sync"
	"testing"
	pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
	sbv1 "github.com/NVIDIA/OpenShell/sdk/go/proto/sandboxv1"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/grpc/status"
	"google.golang.org/grpc/test/bufconn"
)
⋮----
"context"
"net"
"sync"
"testing"
⋮----
pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
sbv1 "github.com/NVIDIA/OpenShell/sdk/go/proto/sandboxv1"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
... (80 lines truncated)
</file>

<file path="sdk/go/openshell/v1/profile_client.go">
package v1
⋮----
import (
	"context"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/converter"
	pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
	"google.golang.org/grpc"
)
⋮----
"context"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/converter"
pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
"google.golang.org/grpc"
⋮----
type profileClient struct {
	client pb.OpenShellClient
}
⋮----
func newProfileClient(conn grpc.ClientConnInterface) *profileClient
⋮----
func (p *profileClient) List(workspace string, opts ...ListOptions) (*Pager[*ProviderProfile], error)
⋮----
var pageToken string
⋮----
func (p *profileClient) ListAll(ctx context.Context, workspace string, opts ...ListOptions) ([]*ProviderProfile, error)
⋮----
func (p *profileClient) Get(ctx context.Context, workspace, id string) (*ProviderProfile, error)
⋮----
func (p *profileClient) Import(ctx context.Context, workspace string, items []ProfileImportItem) (*ImportResult, error)
... (7 lines truncated)
</file>

<file path="sdk/go/openshell/v1/profile.go">
package v1
⋮----
import (
	"context"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"context"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
const (
	ProfileCategoryOther         = types.ProfileCategoryOther
	ProfileCategoryInference     = types.ProfileCategoryInference
	ProfileCategoryAgent         = types.ProfileCategoryAgent
	ProfileCategorySourceControl = types.ProfileCategorySourceControl
	ProfileCategoryMessaging     = types.ProfileCategoryMessaging
	ProfileCategoryData          = types.ProfileCategoryData
	ProfileCategoryKnowledge     = types.ProfileCategoryKnowledge
)
⋮----
type ProfileInterface interface {
	List(workspace string, opts ...ListOptions) (*Pager[*ProviderProfile], error)
	ListAll(ctx context.Context, workspace string, opts ...ListOptions) ([]*ProviderProfile, error)
	Get(ctx context.Context, workspace, id string) (*ProviderProfile, error)
	Import(ctx context.Context, workspace string, items []ProfileImportItem) (*ImportResult, error)
	Update(ctx context.Context, workspace, id string, expectedResourceVersion uint64, item ProfileImportItem) (*UpdateResult, error)
	Lint(ctx context.Context, workspace string, items []ProfileImportItem) (*LintResult, error)
	Delete(ctx context.Context, workspace, id string, opts ...DeleteOptions) (*DeletionResult, error)
}
... (1 lines truncated)
</file>

<file path="sdk/go/openshell/v1/provider_client_test.go">
package v1
⋮----
import (
	"context"
	"net"
	"testing"
	"time"
	dm "github.com/NVIDIA/OpenShell/sdk/go/proto/datamodelv1"
	pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/grpc/status"
	"google.golang.org/grpc/test/bufconn"
)
⋮----
"context"
"net"
"testing"
"time"
⋮----
dm "github.com/NVIDIA/OpenShell/sdk/go/proto/datamodelv1"
pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
... (59 lines truncated)
</file>

<file path="sdk/go/openshell/v1/provider_client.go">
package v1
⋮----
import (
	"context"
	"sort"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/converter"
	pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
	"google.golang.org/grpc"
)
⋮----
"context"
"sort"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/converter"
pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
"google.golang.org/grpc"
⋮----
type providerClient struct {
	client   pb.OpenShellClient
	profiles *profileClient
	refresh  *refreshClient
}
⋮----
func newProviderClient(conn grpc.ClientConnInterface) *providerClient
⋮----
func (p *providerClient) Profiles() ProfileInterface
⋮----
func (p *providerClient) Refresh() RefreshInterface
⋮----
func (p *providerClient) Create(ctx context.Context, workspace string, provider *Provider) (*Provider, error)
... (16 lines truncated)
</file>

<file path="sdk/go/openshell/v1/provider.go">
package v1
⋮----
import (
	"context"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"context"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
type ProviderInterface interface {
	Create(ctx context.Context, workspace string, provider *Provider) (*Provider, error)
	Get(ctx context.Context, workspace, name string) (*Provider, error)
	List(workspace string, opts ...ListOptions) (*Pager[*Provider], error)
	ListAll(ctx context.Context, workspace string, opts ...ListOptions) ([]*Provider, error)
	Update(ctx context.Context, workspace string, provider *Provider) (*Provider, error)
	Delete(ctx context.Context, workspace, name string, opts ...DeleteOptions) (*DeletionResult, error)
	Ensure(ctx context.Context, workspace string, provider *Provider) (*Provider, error)
	Profiles() ProfileInterface
	Refresh() RefreshInterface
}
</file>

<file path="sdk/go/openshell/v1/refresh_client_test.go">
package v1
⋮----
import (
	"context"
	"net"
	"sync"
	"testing"
	"time"
	pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/grpc/status"
	"google.golang.org/grpc/test/bufconn"
	"google.golang.org/protobuf/types/known/timestamppb"
)
⋮----
"context"
"net"
"sync"
"testing"
"time"
⋮----
pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
... (63 lines truncated)
</file>

<file path="sdk/go/openshell/v1/refresh_client.go">
package v1
⋮----
import (
	"context"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/converter"
	pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
	"google.golang.org/grpc"
)
⋮----
"context"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/converter"
pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
"google.golang.org/grpc"
⋮----
type refreshClient struct {
	client pb.OpenShellClient
}
⋮----
func newRefreshClient(conn grpc.ClientConnInterface) *refreshClient
⋮----
func (r *refreshClient) GetStatus(ctx context.Context, workspace, provider, credentialKey string) ([]*RefreshStatus, error)
⋮----
func (r *refreshClient) Configure(ctx context.Context, workspace string, config *RefreshConfig) (*RefreshStatus, error)
⋮----
func (r *refreshClient) Rotate(ctx context.Context, workspace, provider, credentialKey string) (*RefreshStatus, error)
⋮----
func (r *refreshClient) Delete(ctx context.Context, workspace, provider, credentialKey string, opts ...DeleteOptions) (*DeletionResult, error)
</file>

<file path="sdk/go/openshell/v1/refresh.go">
package v1
⋮----
import (
	"context"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"context"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
const (
	RefreshStrategyStatic                  = types.RefreshStrategyStatic
	RefreshStrategyExternal                = types.RefreshStrategyExternal
	RefreshStrategyOAuth2RefreshToken      = types.RefreshStrategyOAuth2RefreshToken
	RefreshStrategyOAuth2ClientCredentials = types.RefreshStrategyOAuth2ClientCredentials
	RefreshStrategyGoogleServiceAccountJWT = types.RefreshStrategyGoogleServiceAccountJWT
)
⋮----
type RefreshInterface interface {
	GetStatus(ctx context.Context, workspace, provider, credentialKey string) ([]*RefreshStatus, error)
	Configure(ctx context.Context, workspace string, config *RefreshConfig) (*RefreshStatus, error)
	Rotate(ctx context.Context, workspace, provider, credentialKey string) (*RefreshStatus, error)
	Delete(ctx context.Context, workspace, provider, credentialKey string, opts ...DeleteOptions) (*DeletionResult, error)
}
</file>

<file path="sdk/go/openshell/v1/sandbox_client_test.go">
package v1
⋮----
import (
	"context"
	"net"
	"sync"
	"testing"
	"time"
	dm "github.com/NVIDIA/OpenShell/sdk/go/proto/datamodelv1"
	pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/grpc/status"
	"google.golang.org/grpc/test/bufconn"
	"google.golang.org/protobuf/proto"
	"google.golang.org/protobuf/types/known/timestamppb"
)
⋮----
"context"
"net"
"sync"
"testing"
"time"
⋮----
dm "github.com/NVIDIA/OpenShell/sdk/go/proto/datamodelv1"
pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
"github.com/stretchr/testify/assert"
... (173 lines truncated)
</file>

<file path="sdk/go/openshell/v1/sandbox_client.go">
package v1
⋮----
import (
	"context"
	"fmt"
	"io"
	"time"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/converter"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
	pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
	"google.golang.org/grpc"
)
⋮----
"context"
"fmt"
"io"
"time"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/converter"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
"google.golang.org/grpc"
⋮----
const defaultPollInterval = 500 * time.Millisecond
⋮----
type sandboxClient struct {
	client pb.OpenShellClient
}
⋮----
var _ SandboxInterface = (*sandboxClient)(nil)
... (53 lines truncated)
</file>

<file path="sdk/go/openshell/v1/sandbox_template_client_test.go">
package v1
⋮----
import (
	"context"
	"net"
	"sync"
	"testing"
	"time"
	dm "github.com/NVIDIA/OpenShell/sdk/go/proto/datamodelv1"
	pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/grpc/status"
	"google.golang.org/grpc/test/bufconn"
	"google.golang.org/protobuf/proto"
	"google.golang.org/protobuf/types/known/durationpb"
)
⋮----
"context"
"net"
"sync"
"testing"
"time"
⋮----
dm "github.com/NVIDIA/OpenShell/sdk/go/proto/datamodelv1"
pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
"github.com/stretchr/testify/assert"
... (47 lines truncated)
</file>

<file path="sdk/go/openshell/v1/sandbox_template_client.go">
package v1
⋮----
import (
	"context"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/converter"
	pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
	"google.golang.org/grpc"
)
⋮----
"context"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/converter"
pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
"google.golang.org/grpc"
⋮----
type sandboxTemplateClient struct {
	client pb.OpenShellClient
}
⋮----
var _ SandboxTemplateInterface = (*sandboxTemplateClient)(nil)
⋮----
func newSandboxTemplateClient(conn grpc.ClientConnInterface) *sandboxTemplateClient
⋮----
func (s *sandboxTemplateClient) Create(ctx context.Context, workspace string, template *SandboxWorkloadTemplate) (*SandboxWorkloadTemplate, error)
⋮----
func (s *sandboxTemplateClient) Get(ctx context.Context, workspace, name string) (*SandboxWorkloadTemplate, error)
⋮----
func (s *sandboxTemplateClient) List(workspace string, opts ...ListOptions) (*Pager[*SandboxWorkloadTemplate], error)
⋮----
var pageToken, labelSelector string
... (6 lines truncated)
</file>

<file path="sdk/go/openshell/v1/sandbox_template.go">
package v1
⋮----
import (
	"context"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"context"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
type SandboxTemplateInterface interface {
	Create(ctx context.Context, workspace string, template *SandboxWorkloadTemplate) (*SandboxWorkloadTemplate, error)
	Get(ctx context.Context, workspace, name string) (*SandboxWorkloadTemplate, error)
	List(workspace string, opts ...ListOptions) (*Pager[*SandboxWorkloadTemplate], error)
	ListAll(ctx context.Context, workspace string, opts ...ListOptions) ([]*SandboxWorkloadTemplate, error)
	Delete(ctx context.Context, workspace, name string, opts ...DeleteOptions) (*DeletionResult, error)
}
</file>

<file path="sdk/go/openshell/v1/sandbox.go">
package v1
⋮----
import (
	"context"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"context"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
const (
	EndpointUnspecified           = types.EndpointUnspecified
	EndpointNoObservedExchange    = types.EndpointNoObservedExchange
	EndpointHTTPResponseReceived  = types.EndpointHTTPResponseReceived
	EndpointPolicyDenied          = types.EndpointPolicyDenied
	EndpointCredentialUnavailable = types.EndpointCredentialUnavailable
	EndpointTLSFailed             = types.EndpointTLSFailed
	EndpointTransportFailed       = types.EndpointTransportFailed
	EndpointUpstreamRejected      = types.EndpointUpstreamRejected
)
⋮----
var WithLogLines = types.WithLogLines
⋮----
var WithLogSince = types.WithLogSince
⋮----
var WithLogSources = types.WithLogSources
⋮----
var WithLogMinLevel = types.WithLogMinLevel
⋮----
... (22 lines truncated)
</file>

<file path="sdk/go/openshell/v1/service_client_test.go">
package v1
⋮----
import (
	"context"
	"net"
	"sync"
	"testing"
	dm "github.com/NVIDIA/OpenShell/sdk/go/proto/datamodelv1"
	pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/grpc/status"
	"google.golang.org/grpc/test/bufconn"
)
⋮----
"context"
"net"
"sync"
"testing"
⋮----
dm "github.com/NVIDIA/OpenShell/sdk/go/proto/datamodelv1"
pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
... (58 lines truncated)
</file>

<file path="sdk/go/openshell/v1/service_client.go">
package v1
⋮----
import (
	"context"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/converter"
	pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
	"google.golang.org/grpc"
)
⋮----
"context"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/converter"
pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
"google.golang.org/grpc"
⋮----
type serviceClient struct {
	client pb.OpenShellClient
}
⋮----
func newServiceClient(conn grpc.ClientConnInterface) *serviceClient
⋮----
func (s *serviceClient) Expose(ctx context.Context, workspace, sandboxName, serviceName string, targetPort uint32, domain bool, opts ...ExposeServiceOptions) (*ServiceEndpoint, error)
⋮----
func (s *serviceClient) Get(ctx context.Context, workspace, sandboxName, serviceName string) (*ServiceEndpoint, error)
⋮----
func (s *serviceClient) List(workspace, sandboxName string, opts ...ListOptions) (*Pager[*ServiceEndpoint], error)
⋮----
var pageToken string
var allWorkspaces bool
⋮----
... (4 lines truncated)
</file>

<file path="sdk/go/openshell/v1/service.go">
package v1
⋮----
import (
	"context"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"context"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
const (
	ServiceAuthorizationModeStrip = types.ServiceAuthorizationModeStrip
	ServiceAuthorizationModeBearerPassthrough = types.ServiceAuthorizationModeBearerPassthrough
)
⋮----
type ExposeServiceOptions struct {
	AuthorizationMode ServiceAuthorizationMode
}
⋮----
type ServiceInterface interface {
	Expose(ctx context.Context, workspace, sandboxName, serviceName string, targetPort uint32, domain bool, opts ...ExposeServiceOptions) (*ServiceEndpoint, error)
	Get(ctx context.Context, workspace, sandboxName, serviceName string) (*ServiceEndpoint, error)
	List(workspace, sandboxName string, opts ...ListOptions) (*Pager[*ServiceEndpoint], error)
	ListAll(ctx context.Context, workspace, sandboxName string, opts ...ListOptions) ([]*ServiceEndpoint, error)
	Delete(ctx context.Context, workspace, sandboxName, serviceName string, opts ...DeleteOptions) (*DeletionResult, error)
}
</file>

<file path="sdk/go/openshell/v1/ssh_client_test.go">
package v1
⋮----
import (
	"context"
	"fmt"
	"net"
	"sync"
	"testing"
	"time"
	pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/grpc/status"
	"google.golang.org/grpc/test/bufconn"
	"google.golang.org/protobuf/types/known/timestamppb"
)
⋮----
"context"
"fmt"
"net"
"sync"
"testing"
"time"
⋮----
pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
... (98 lines truncated)
</file>

<file path="sdk/go/openshell/v1/ssh_client.go">
package v1
⋮----
import (
	"context"
	"fmt"
	"io"
	"sync"
	"time"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/converter"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/options"
	pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
	"google.golang.org/grpc"
)
⋮----
"context"
"fmt"
"io"
"sync"
"time"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/converter"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/options"
pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
"google.golang.org/grpc"
⋮----
const sshCleanupTimeout = 5 * time.Second
⋮----
type sshClient struct {
	client    pb.OpenShellClient
	sandboxes SandboxInterface
... (23 lines truncated)
</file>

<file path="sdk/go/openshell/v1/ssh.go">
package v1
⋮----
import (
	"context"
	"io"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"context"
"io"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
type tunnelConfig struct {
	serviceID string
}
⋮----
type TunnelOption func(*tunnelConfig)
⋮----
func WithTunnelServiceID(id string) TunnelOption
⋮----
type SSHInterface interface {
	CreateSession(ctx context.Context, workspace, sandboxName string) (*SSHSession, error)
	RevokeSession(ctx context.Context, workspace, token string, opts ...DeleteOptions) (*DeletionResult, error)
	Tunnel(ctx context.Context, workspace, sandboxName string, port uint32, opts ...TunnelOption) (io.ReadWriteCloser, error)
}
</file>

<file path="sdk/go/openshell/v1/tcp_client_test.go">
package v1
⋮----
import (
	"context"
	"fmt"
	"io"
	"net"
	"sync"
	"testing"
	"time"
	pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/grpc/status"
	"google.golang.org/grpc/test/bufconn"
)
⋮----
"context"
"fmt"
"io"
"net"
"sync"
"testing"
"time"
⋮----
pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
"github.com/stretchr/testify/assert"
... (132 lines truncated)
</file>

<file path="sdk/go/openshell/v1/tcp_client.go">
package v1
⋮----
import (
	"context"
	"fmt"
	"io"
	"net"
	"strconv"
	"sync"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/converter"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/options"
	pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
	"google.golang.org/grpc"
)
⋮----
"context"
"fmt"
"io"
"net"
"strconv"
"sync"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/converter"
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/options"
pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
"google.golang.org/grpc"
⋮----
type tcpClient struct {
	client    pb.OpenShellClient
	sandboxes SandboxInterface
... (60 lines truncated)
</file>

<file path="sdk/go/openshell/v1/tcp.go">
package v1
⋮----
import (
	"context"
	"io"
	"net"
)
⋮----
"context"
"io"
"net"
⋮----
type forwardConfig struct {
	serviceID string
}
⋮----
type ForwardOption func(*forwardConfig)
⋮----
func WithForwardServiceID(id string) ForwardOption
⋮----
type listenConfig struct {
	bindAddress  string
	useSSHTunnel bool
	serviceID    string
}
⋮----
type ListenOption func(*listenConfig)
⋮----
type ForwardListener interface {
	Addr() net.Addr
... (14 lines truncated)
</file>

<file path="sdk/go/openshell/v1/types_reexport.go">
package v1
⋮----
import (
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
const (
	NetworkTLSModeUnspecified = types.NetworkTLSModeUnspecified
	NetworkTLSModeSkip = types.NetworkTLSModeSkip
	NetworkTLSModeTerminate = types.NetworkTLSModeTerminate
	NetworkTLSModePassthrough = types.NetworkTLSModePassthrough
	NetworkEnforcementModeUnspecified = types.NetworkEnforcementModeUnspecified
	NetworkEnforcementModeEnforce = types.NetworkEnforcementModeEnforce
	NetworkEnforcementModeAudit = types.NetworkEnforcementModeAudit
	NetworkAccessPresetUnspecified = types.NetworkAccessPresetUnspecified
	NetworkAccessPresetReadOnly = types.NetworkAccessPresetReadOnly
	NetworkAccessPresetReadWrite = types.NetworkAccessPresetReadWrite
	NetworkAccessPresetFull = types.NetworkAccessPresetFull
)
</file>

<file path="sdk/go/openshell/v1/types.go">
package v1
⋮----
import (
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
const (
	SandboxProvisioning = types.SandboxProvisioning
	SandboxReady        = types.SandboxReady
	SandboxError        = types.SandboxError
	SandboxDeleting     = types.SandboxDeleting
	SandboxUnknown      = types.SandboxUnknown
	SandboxStopping     = types.SandboxStopping
	SandboxStopped      = types.SandboxStopped
	SandboxStarting     = types.SandboxStarting
	SandboxCompleted    = types.SandboxCompleted
)
⋮----
const (
	SandboxRestartNever     = types.SandboxRestartNever
	SandboxRestartOnFailure = types.SandboxRestartOnFailure
	SandboxRestartAlways    = types.SandboxRestartAlways
)
⋮----
const (
	EventAdded    = types.EventAdded
	EventModified = types.EventModified
	EventDeleted  = types.EventDeleted
... (8 lines truncated)
</file>

<file path="sdk/go/openshell/v1/watch_test.go">
package v1
⋮----
import (
	"testing"
	"time"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)
⋮----
"testing"
"time"
⋮----
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
⋮----
func newTestWatcher(src <-chan Event[string]) *watcher[string]
⋮----
func TestWatcher_DeliversEvents(t *testing.T)
⋮----
func TestWatcher_StopClosesChannel(t *testing.T)
⋮----
func TestWatcher_StopIsIdempotent(t *testing.T)
⋮----
func TestWatcher_ErrorEvent(t *testing.T)
⋮----
func TestWatcher_ChannelClosesWhenSourceEnds(t *testing.T)
⋮----
func TestWatcher_DrainAfterStop(t *testing.T)
</file>

<file path="sdk/go/openshell/v1/watch.go">
package v1
⋮----
import (
	"context"
	"sync"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"context"
"sync"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
type watcher[T any] struct {
	result   chan Event[T]
	done     chan struct{}
⋮----
func newWatcher[T any](ch chan Event[T], cancel context.CancelFunc) *watcher[T]
⋮----
func (w *watcher[T]) ResultChan() <-chan Event[T]
⋮----
func (w *watcher[T]) Stop()
</file>

<file path="sdk/go/openshell/v1/workspace_client.go">
package v1
⋮----
import (
	"context"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/converter"
	pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
	"google.golang.org/grpc"
)
⋮----
"context"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/internal/converter"
pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
"google.golang.org/grpc"
⋮----
type workspaceClient struct {
	client pb.OpenShellClient
}
⋮----
func newWorkspaceClient(conn grpc.ClientConnInterface) *workspaceClient
⋮----
func (w *workspaceClient) Create(ctx context.Context, name string, labels map[string]string) (*Workspace, error)
⋮----
func (w *workspaceClient) Get(ctx context.Context, name string) (*Workspace, error)
⋮----
func (w *workspaceClient) List(opts ...ListOptions) (*Pager[*Workspace], error)
⋮----
var pageToken, labelSelector string
⋮----
func (w *workspaceClient) ListAll(ctx context.Context, opts ...ListOptions) ([]*Workspace, error)
... (13 lines truncated)
</file>

<file path="sdk/go/openshell/v1/workspace_scope.go">
package v1
⋮----
import dm "github.com/NVIDIA/OpenShell/sdk/go/proto/datamodelv1"
⋮----
func namedWorkspaceScope(workspace string) *dm.WorkspaceSelector
⋮----
func profileWorkspaceScope(workspace string) *dm.WorkspaceSelector
⋮----
func allWorkspacesScope() *dm.WorkspaceSelector
</file>

<file path="sdk/go/openshell/v1/workspace_test.go">
package v1
⋮----
import (
	"context"
	"net"
	"testing"
	"time"
	dm "github.com/NVIDIA/OpenShell/sdk/go/proto/datamodelv1"
	pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/grpc/status"
	"google.golang.org/grpc/test/bufconn"
	"google.golang.org/protobuf/types/known/timestamppb"
)
⋮----
"context"
"net"
"testing"
"time"
⋮----
dm "github.com/NVIDIA/OpenShell/sdk/go/proto/datamodelv1"
pb "github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
... (91 lines truncated)
</file>

<file path="sdk/go/openshell/v1/workspace.go">
package v1
⋮----
import (
	"context"
	"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
)
⋮----
"context"
⋮----
"github.com/NVIDIA/OpenShell/sdk/go/openshell/v1/types"
⋮----
const (
	WorkspaceActive      = types.WorkspaceActive
	WorkspaceTerminating = types.WorkspaceTerminating
	WorkspaceUnknown     = types.WorkspaceUnknown
)
⋮----
const (
	WorkspaceRoleAdmin   = types.WorkspaceRoleAdmin
	WorkspaceRoleUser    = types.WorkspaceRoleUser
	WorkspaceRoleUnknown = types.WorkspaceRoleUnknown
)
⋮----
type WorkspaceInterface interface {
	Create(ctx context.Context, name string, labels map[string]string) (*Workspace, error)
	Get(ctx context.Context, name string) (*Workspace, error)
	List(opts ...ListOptions) (*Pager[*Workspace], error)
	ListAll(ctx context.Context, opts ...ListOptions) ([]*Workspace, error)
	Delete(ctx context.Context, name string, opts ...DeleteOptions) (*DeletionResult, error)
	AddMember(ctx context.Context, workspace, principalSubject string, role WorkspaceRole) (*WorkspaceMember, error)
... (5 lines truncated)
</file>

<file path="sdk/go/.golangci.yml">
version: "2"
run:
  timeout: 5m
linters:
  enable:
    - govet
    - errcheck
    - staticcheck
    - unused
    - ineffassign
    - revive
    - goheader
  exclusions:
    rules:
      - path: "proto/"
        linters:
          - goheader
          - revive
linters-settings:
  goheader:
    template: |-
      SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
      SPDX-License-Identifier: Apache-2.0
  revive:
    rules:
      - name: blank-imports
      - name: exported
      - name: var-naming
      - name: indent-error-flow
      - name: range
... (8 lines truncated)
</file>

<file path="sdk/go/buf.gen.yaml">
version: v2
inputs:
  - proto_file: proto/openshell.proto
plugins:
  - local: protoc-gen-go
    out: sdk/go
    include_imports: true
    opt:
      - module=github.com/NVIDIA/OpenShell/sdk/go
      - Mopenshell.proto=github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1
      - Mdatamodel.proto=github.com/NVIDIA/OpenShell/sdk/go/proto/datamodelv1
      - Msandbox.proto=github.com/NVIDIA/OpenShell/sdk/go/proto/sandboxv1
      - Moptions.proto=github.com/NVIDIA/OpenShell/sdk/go/proto/optionsv1
  - local: protoc-gen-go-grpc
    out: sdk/go
    include_imports: true
    opt:
      - module=github.com/NVIDIA/OpenShell/sdk/go
      - Mopenshell.proto=github.com/NVIDIA/OpenShell/sdk/go/proto/openshellv1
      - Mdatamodel.proto=github.com/NVIDIA/OpenShell/sdk/go/proto/datamodelv1
      - Msandbox.proto=github.com/NVIDIA/OpenShell/sdk/go/proto/sandboxv1
      - Moptions.proto=github.com/NVIDIA/OpenShell/sdk/go/proto/optionsv1
</file>

<file path="sdk/go/mise.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

[tools]
go = "1.25.14"
buf = "1.72.0"
"go:github.com/golangci/golangci-lint/v2/cmd/golangci-lint" = "2.12"
"go:google.golang.org/protobuf/cmd/protoc-gen-go" = "1.36.11"
"go:google.golang.org/grpc/cmd/protoc-gen-go-grpc" = "1.6.2"

[tasks.test]
description = "Run unit tests with coverage"
run = "go test -coverprofile=coverage.out -coverpkg=./openshell/... -race ./..."

[tasks."test:integration"]
description = "Run integration tests"
run = "go test -tags=integration -race ./..."

[tasks.lint]
description = "Run linter"
run = "golangci-lint run ./..."

[tasks.fmt]
description = "Format code"
run = "goimports -w . && go fmt ./..."

[tasks.build]
description = "Build all packages"
run = "go build ./..."

... (125 lines truncated)
</file>

<file path="sdk/go/README.md">
# OpenShell SDK for Go

[![Go Reference](https://pkg.go.dev/badge/github.com/NVIDIA/OpenShell/sdk/go.svg)](https://pkg.go.dev/github.com/NVIDIA/OpenShell/sdk/go)
[![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](../../LICENSE)

> [!IMPORTANT]
> **[Read the full documentation](https://ro14nd.de/openshell-sdk-go/)** for guides, API reference with gRPC mapping, and testing patterns.

A Go SDK for interacting with [OpenShell](https://github.com/NVIDIA/OpenShell)
servers, providing idiomatic Go bindings for shell session management, command
execution, provider configuration, and service exposure.

## Why a Go SDK?

Go is the language of the Kubernetes ecosystem. If you want to build an
operator, controller, or any automation that manages OpenShell resources as
native Kubernetes objects, you need a Go client.

This SDK is modeled after
[`k8s.io/client-go`](https://github.com/kubernetes/client-go), the standard
Kubernetes client library that every Go operator developer already knows. The
patterns will look familiar:

- **Typed sub-clients per resource**: `client.Sandboxes()`, `client.Providers()`,
  `client.Exec()`, just like `clientset.CoreV1().Pods()`
- **Domain types separated from wire formats**: clean Go structs in a `types`
  package, no proto leakage into the public API (like `k8s.io/api`)
- **Watch primitives**: channel-based watchers with `ResultChan()` and `Stop()`,
  identical to `watch.Interface` in client-go
- **Functional options**: variadic option patterns for list filtering,
... (321 lines truncated)
</file>

<file path="sdk/typescript/src/client.test.ts">
import type { MessageInitShape } from '@bufbuild/protobuf';
import { Code, ConnectError, createRouterTransport, type ServiceImpl, type Transport } from '@connectrpc/connect';
import { describe, expect, it } from 'vitest';
import {
  errorCode,
  Pager,
  PHASE_NAMES,
  POLICY_SOURCE_NAMES,
  Pushable,
  SandboxClient,
  SandboxTemplateClient,
  SCOPE_NAMES,
  ServiceAuthorizationMode,
  STATUS_NAMES,
} from './client.js';
import {
  OpenShell,
  ServiceAuthorizationMode as ProtoServiceAuthorizationMode,
  SandboxPhase,
  SandboxRestartPolicy,
  ServiceStatus,
} from './gen/openshell_pb.js';
import { PolicySource, SettingScope } from './gen/sandbox_pb.js';
import type { ExecInteractiveSession, ExecInteractiveSessionControl } from './index.js';
⋮----
function client(impl: Partial<ServiceImpl<typeof OpenShell>>): SandboxClient
⋮----
function templateClient(impl: Partial<ServiceImpl<typeof OpenShell>>): SandboxTemplateClient
⋮----
function readySandbox(
... (33 lines truncated)
</file>

<file path="sdk/typescript/src/client.ts">
import type { AddressInfo } from 'node:net';
⋮----
import type { MessageInitShape } from '@bufbuild/protobuf';
import { durationFromMs } from '@bufbuild/protobuf/wkt';
import { type CallOptions, type Client, createClient, type Transport } from '@connectrpc/connect';
import { errorCode, fromConnect, SdkError } from './errors.js';
import type { Provider, WorkspaceSelectorSchema } from './gen/datamodel_pb.js';
import type { Sandbox, SandboxWorkloadTemplate, UpdateConfigResponse } from './gen/openshell_pb.js';
import {
  type ExecSandboxInputSchema,
  OpenShell,
  ServiceAuthorizationMode as ProtoServiceAuthorizationMode,
  SandboxPhase,
  SandboxRestartPolicy,
  type SandboxSpecSchema,
  type SandboxWorkloadTemplateSchema,
  ServiceStatus,
  type TcpForwardFrameSchema,
} from './gen/openshell_pb.js';
import type { EffectiveSetting, GetSandboxConfigResponse, SandboxPolicy, SettingValue } from './gen/sandbox_pb.js';
import { PolicySource, type SandboxPolicySchema, SettingScope, type SettingValueSchema } from './gen/sandbox_pb.js';
import { validateSshResponse } from './ssh-validate.js';
import { buildTransport, type ConnectOptions } from './transport.js';
⋮----
function durationFromSeconds(seconds: number)
⋮----
function timestampMillis(timestamp:
⋮----
export type SandboxPhaseName =
  | 'unspecified'
... (517 lines truncated)
</file>

<file path="sdk/typescript/src/errors.test.ts">
import { Code, ConnectError } from '@connectrpc/connect';
import { describe, expect, it } from 'vitest';
import { errorCode, fromConnect, SdkError, type SdkErrorCode } from './errors.js';
import { BadRequestSchema, ErrorInfoSchema, RetryInfoSchema } from './gen/google/rpc/error_details_pb.js';
</file>

<file path="sdk/typescript/src/errors.ts">
import { Code, ConnectError } from '@connectrpc/connect';
import { BadRequestSchema, ErrorInfoSchema, RetryInfoSchema } from './gen/google/rpc/error_details_pb.js';
⋮----
export interface FieldViolation {
  field: string;
  description: string;
}
⋮----
export interface ErrorInfo {
  reason: string;
  domain: string;
  metadata: Record<string, string>;
}
⋮----
export type SdkErrorCode =
  | 'invalid_config'
  | 'tls'
  | 'connect'
  | 'auth'
  | 'io'
  | 'not_found'
  | 'already_exists'
  | 'aborted'
  | 'canceled'
  | 'rpc';
⋮----
export interface SdkErrorOptions {
  cause?: unknown;
  connectCode?: Code;
}
... (9 lines truncated)
</file>

<file path="sdk/typescript/src/index.ts">

</file>

<file path="sdk/typescript/src/oidc.test.ts">
import { readFileSync } from 'node:fs';
import { createServer } from 'node:http';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { clientCredentials } from './oidc.js';
⋮----
async function providerServer(
  expiresIn: unknown = conformance.expiry.valid_expires_in,
): Promise<
</file>

<file path="sdk/typescript/src/oidc.ts">
import { isIP } from 'node:net';
import { SdkError } from './errors.js';
⋮----
export interface OidcTokenProvider {
  getToken(signal?: AbortSignal): Promise<string>;
}
⋮----
getToken(signal?: AbortSignal): Promise<string>;
⋮----
export interface ClientCredentialsOptions {
  issuer: string;
  clientId: string;
  clientSecret: string | (() => string | Promise<string>);
  scopes?: readonly string[];
  audience?: string;
  timeoutMs?: number;
}
⋮----
interface CachedToken {
  accessToken: string;
  expiresAt: number;
}
⋮----
function isLoopback(hostname: string): boolean
⋮----
function secureUrl(name: string, raw: string): URL
⋮----
function withoutTrailingSlash(raw: string): string
⋮----
async function boundedJson(response: Response, kind: string): Promise<Record<string, unknown>>
... (13 lines truncated)
</file>

<file path="sdk/typescript/src/raw.test.ts">
import type { MessageInitShape } from '@bufbuild/protobuf';
import { timestampFromDate } from '@bufbuild/protobuf/wkt';
import { createRouterTransport } from '@connectrpc/connect';
import { describe, expect, it } from 'vitest';
import { SandboxClient } from './index.js';
import { EndpointResult, type EndpointStatusSchema, OpenShell, SandboxPhase } from './raw.js';
</file>

<file path="sdk/typescript/src/raw.ts">

</file>

<file path="sdk/typescript/src/ssh-validate.ts">
import { isIP } from 'node:net';
import { SdkError } from './errors.js';
⋮----
export interface SshResponseFields {
  sandboxId: string;
  token: string;
  gatewayHost: string;
  gatewayPort: number;
  gatewayScheme: string;
  hostKeyFingerprint: string;
}
⋮----
function reject(field: string, detail: string): never
⋮----
function validGatewayHost(host: string): boolean
⋮----
export function validateSshResponse(resp: SshResponseFields, expectedSandboxId?: string): void
</file>

<file path="sdk/typescript/src/transport.test.ts">
import { describe, expect, it, vi } from 'vitest';
import { errorCode } from './errors.js';
import { authInterceptor, buildTransport } from './transport.js';
⋮----
const pem = (label: string) => Buffer.from(`-----BEGIN $
⋮----
const fn = () => buildTransport(
</file>

<file path="sdk/typescript/src/transport.ts">
import type { Interceptor, Transport } from '@connectrpc/connect';
import { createGrpcTransport } from '@connectrpc/connect-node';
import { SdkError } from './errors.js';
import type { OidcTokenProvider } from './oidc.js';
⋮----
export interface ConnectOptions {
  gateway: string;
  caCert?: Buffer;
  clientCert?: Buffer;
  clientKey?: Buffer;
  oidcToken?: string;
  oidcTokenProvider?: OidcTokenProvider;
  edgeToken?: string;
  insecureSkipVerify?: boolean;
  allowInsecureAuth?: boolean;
}
⋮----
export function authInterceptor(opts: ConnectOptions): Interceptor
⋮----
function assertMtlsPair(opts: ConnectOptions): void
⋮----
function assertTokenExclusivity(opts: ConnectOptions): void
⋮----
function assertEdgeToken(opts: ConnectOptions): void
⋮----
function isLoopbackHost(host: string): boolean
⋮----
function assertTokenTransportSecurity(opts: ConnectOptions): void
⋮----
export function buildTransport(opts: ConnectOptions): Transport
... (1 lines truncated)
</file>

<file path="sdk/typescript/biome.json">
{
  "$schema": "https://biomejs.dev/schemas/2.5.4/schema.json",
  "vcs": {
    "enabled": true,
    "clientKind": "git",
    "useIgnoreFile": true
  },
  "files": {
    "includes": ["**", "!src/gen", "!dist", "!coverage"]
  },
  "formatter": {
    "enabled": true,
    "indentStyle": "space",
    "indentWidth": 2,
    "lineWidth": 120
  },
  "linter": {
    "enabled": true,
    "rules": {
      "preset": "recommended"
    }
  },
  "javascript": {
    "formatter": {
      "quoteStyle": "single",
      "semicolons": "always"
    }
  },
  "assist": {
    "enabled": true,
... (8 lines truncated)
</file>

<file path="sdk/typescript/biome.json.license">
SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
SPDX-License-Identifier: Apache-2.0
</file>

<file path="sdk/typescript/buf.gen.yaml">
version: v2
clean: true
inputs:
  - directory: ../../proto
    paths:
      - ../../proto/openshell.proto
      - ../../proto/sandbox.proto
      - ../../proto/datamodel.proto
      - ../../proto/options.proto
  - module: buf.build/googleapis/googleapis:c17df5b2beca46928cc87d5656bd5343
    paths:
      - google/rpc/error_details.proto
plugins:
  - local: ./node_modules/.bin/protoc-gen-es
    out: src/gen
    opt:
      - target=ts
      - import_extension=js
</file>

<file path="sdk/typescript/package.json">
{
  "name": "@nvidia/openshell-sdk",
  "version": "0.0.0",
  "description": "Official TypeScript SDK for the OpenShell gateway.",
  "license": "Apache-2.0",
  "type": "module",
  "homepage": "https://github.com/NVIDIA/OpenShell",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/NVIDIA/OpenShell.git",
    "directory": "sdk/typescript"
  },
  "publishConfig": {
    "registry": "https://npm.pkg.github.com"
  },
  "main": "./dist/index.js",
  "types": "./dist/index.d.ts",
  "exports": {
    ".": {
      "types": "./dist/index.d.ts",
      "import": "./dist/index.js"
    },
    "./raw": {
      "types": "./dist/raw.d.ts",
      "import": "./dist/raw.js"
    }
  },
  "files": [
    "dist",
    "README.md"
... (29 lines truncated)
</file>

<file path="sdk/typescript/README.md">
# @nvidia/openshell-sdk

TypeScript client for the OpenShell gateway — thin, idiomatic bindings generated from the OpenShell protobufs.

Distributed via GitHub Packages. A public npm release under the same name follows once the npm org is in place; the install specifier and API are unchanged across that move.

Use the SDK and gateway from the same OpenShell release when possible. The raw
types and RPC descriptors are generated from the protobuf definitions in that
release; curated methods remain compatible while those RPC contracts remain
compatible.

## Install

Published to GitHub Packages, so point the `@nvidia` scope at it with a project `.npmrc`:

```shell
@nvidia:registry=https://npm.pkg.github.com
```

Authenticate with a GitHub token that has `read:packages`, then:

```shell
npm install @nvidia/openshell-sdk
```

## Usage

```ts
import { OpenShellClient } from '@nvidia/openshell-sdk'

... (274 lines truncated)
</file>

<file path="sdk/typescript/tsconfig.build.json">
{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "noEmit": false,
    "outDir": "dist",
    "rootDir": "src",
    "declaration": true,
    "declarationMap": true,
    "sourceMap": true
  },
  "include": ["src/**/*.ts"],
  "exclude": ["src/**/*.test.ts"]
}
</file>

<file path="sdk/typescript/tsconfig.build.json.license">
SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
SPDX-License-Identifier: Apache-2.0
</file>

<file path="sdk/typescript/tsconfig.json">
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "lib": ["ES2023"],
    "strict": true,
    "noEmit": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "types": ["node"]
  },
  "include": ["src/**/*.ts"]
}
</file>

<file path="sdk/typescript/tsconfig.json.license">
SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
SPDX-License-Identifier: Apache-2.0
</file>

<file path="sdk/typescript/vitest.config.ts">
import { defineConfig } from 'vitest/config';
</file>

<file path="skills/debug-inference/SKILL.md">
---
name: debug-inference
description: Debug inference clients that use an attached provider and its native endpoint, including hosted APIs and host-local Ollama, vLLM, SGLang, TRT-LLM, LM Studio, or NIM. Use for provider attachment, endpoint policy, credential substitution, topology, and migration from the removed managed inference endpoint. Trigger keywords - debug inference, managed inference endpoint, local inference, ollama, lm studio, vllm, sglang, trtllm, NIM, inference failing, model server unreachable, credential_endpoint_mismatch, host.openshell.internal.
---

# Debug Inference

Diagnose inference as ordinary provider-authorized network traffic. OpenShell no
longer supplies a managed inference route, rewrites request shapes, or selects a
model. The application calls the provider's native endpoint and owns its base
URL, model, request format, and timeout.

Use installed `openshell --help` output as the authority for command syntax.
Refer to the published [provider management guide](https://docs.nvidia.com/openshell/latest/how-it-works/providers/overview)
and [provider profile guide](https://docs.nvidia.com/openshell/latest/how-it-works/providers/profiles)
for current behavior.

## Diagnostic Workflow

### 1. Confirm Gateway and Sandbox Context

```bash
openshell status
openshell gateway info
openshell sandbox get <sandbox>
```

For a host-local model server, `host.openshell.internal` identifies the machine
running the gateway. It does not identify the operator's laptop when the gateway
is remote. A server listening only on `127.0.0.1` may also be unreachable from a
... (104 lines truncated)
</file>

<file path="skills/debug-openshell-cluster/references/supervisor-middleware.md">
# Supervisor middleware troubleshooting

Use this reference when the deployment registers supervisor middleware or a
sandbox policy attaches it through `network_middlewares`. Start with gateway
reachability and compute-platform checks in the [main skill](../SKILL.md).
Use installed CLI help for command syntax and the published
[gateway configuration reference](https://docs.nvidia.com/openshell/latest/how-it-works/gateways/configuration)
for registration settings.

## Collect diagnostics

For operator-run supervisor middleware, inspect `[[openshell.supervisor.middleware]]`, service reachability, and both gateway and supervisor logs:

```shell
rg -n 'supervisor|middleware|grpc_endpoint|tls_ca_cert_path|audience|allow_insecure_transport|max_payload_bytes|timeout|gateway_jwt' /etc/openshell/gateway.toml
journalctl -u <middleware-service> --no-pager --lines=200
journalctl -u openshell-gateway --no-pager --lines=200
openshell logs <sandbox-name> --tail --source sandbox
```

## Startup and authentication

The middleware service must start before the gateway and be reachable from both the gateway and sandbox supervisors. Gateway startup fails if `Describe` is unavailable, peer metadata is missing, the protocol major is incompatible, a required capability is absent, a manifest exposes duplicate operation/phase bindings, the registration claims the reserved `openshell/` namespace, or payload and timeout limits are invalid. Current services receive `MiddlewareDescribeRequest` instead of an empty request; regenerate bindings when upgrading a legacy service. Supported V1 bindings are `HTTP_REQUEST/PRE_CREDENTIALS`, `HTTP_RESPONSE/PRE_RETURN`, and `WEBSOCKET_MESSAGE/PRE_CREDENTIALS`.

When gateway JWT signing is disabled, supervisors preserve the legacy unauthenticated connector and do not request extension credentials. When signing is enabled, credential acquisition and verification failures are fail closed: check HTTPS trust and hostname validation, audience and issuer agreement, the token `kid`, gateway `RefreshSandboxToken` errors, and middleware logs. Changing a registration requires a gateway restart. A policy update can also fail before persistence if the selected implementation rejects its `network_middlewares` config.

## HTTP response failures

For response failures, distinguish a deliberate `middleware_denied` decision from `response_delivery_failed`. Before response commitment, they produce canonical 403 and 502 responses respectively. After commitment, OpenShell aborts without adding an error body, final chunk, or trailer. A whole-body accumulation timeout is one fixed, non-resetting 120-second wall-clock deadline shared across response reads and whole-body barriers; inspect the active stage's `on_error` and `whole_body_accumulation_timeout` diagnostics. Header-only stages preserve upstream body framing. Body-processing stages normalize framing and send a trailer exchange, including an empty trailer set, after the final body result.

... (25 lines truncated)
</file>

<file path="skills/debug-openshell-cluster/SKILL.md">
---
name: debug-openshell-cluster
description: Debug why an OpenShell gateway deployment is unhealthy, unreachable, or unable to create sandboxes. Use for gateway health failures, Docker/Podman runtime issues, Helm failures, Kubernetes scheduling, TLS or auth, gateway interceptors, supervisor middleware startup or runtime failures, external compute-driver sockets, VM drivers, or sandbox startup. Trigger keywords - debug gateway, gateway failing, deployment failing, helm install failing, cluster health, gateway health, gateway not starting, health check failed, sandbox pending, docker driver, podman driver, kubernetes driver, external driver, compute driver socket, gateway interceptor, supervisor middleware, middleware failed, vm driver.
---

# Debug OpenShell Gateway Deployment

Diagnose a gateway and its selected compute platform. Do not assume OpenShell provisions Kubernetes or runs a k3s container. OpenShell targets a reachable gateway endpoint backed by Docker, Podman, Kubernetes, the experimental VM driver, or an operator-managed out-of-tree compute driver.

Use `openshell` first to identify the active endpoint. Then use the platform tools that match the gateway's compute driver: `docker`, `podman`, `kubectl`/`helm`, or VM driver logs.

## Overview

The target deployment flow is:

1. Operator starts or deploys the gateway with system packages, systemd, or Helm. The CLI does not start, stop, or destroy gateway services.
2. Operator configures the compute driver.
3. Operator provides the CLI and supervisor authentication material required by the deployment mode: edge or OIDC user auth, optional CLI mTLS, and gateway-minted sandbox JWTs.
4. The CLI registers a reachable gateway endpoint with `openshell gateway add`.
5. The gateway creates sandboxes through the selected compute driver.

The `openshell-gateway` composition crate explicitly installs its compiled
Docker, Podman, Kubernetes, and VM registrations at startup; `openshell-server`
does not link compute-driver crates. Custom gateway binaries may include a
subset of those registrations. With no configured driver, the gateway probes only
installed registrations in priority order (Kubernetes, Podman, then Docker);
VM has no probe and remains opt-in. Confirm the binary's registered drivers
when auto-detection reports that no suitable driver is available. If
configuration selects a driver that was not compiled in, the gateway treats
the name as an external driver and reports a missing `socket_path` unless an
... (986 lines truncated)
</file>

<file path="skills/generate-sandbox-policy/examples.md">
# Policy Generation Examples

Examples organized by detail tier — from minimal (just host + intent) to full (complete API docs).

> **TLS note:** TLS termination is automatic. The proxy auto-detects TLS by
> peeking the first bytes of each connection, so omit `tls` on inspected
> endpoints. `skip` is the only accepted value and disables TLS interception
> for that endpoint; the removed `terminate` and `passthrough` spellings fail
> policy validation.

---

## Minimal Tier Examples (host + intent, no API docs)

### Example M1: L4 Pass-Through

**User**: "Let claude talk to api.anthropic.com and statsig.anthropic.com, just let everything through."

No API docs needed. No method or path rules.

```yaml
network_policies:
  claude_anthropic:
    name: claude_anthropic
    endpoints:
      - { host: api.anthropic.com, port: 443 }
      - { host: statsig.anthropic.com, port: 443 }
    binaries:
      - { path: /usr/local/bin/claude }
```
... (844 lines truncated)
</file>

<file path="skills/generate-sandbox-policy/SKILL.md">
---
name: generate-sandbox-policy
description: Generate sandbox security policies from plain-language requirements and optional REST API documentation. Produces L4 or fine-grained L7 network policies and ordered network middleware configuration. Use for API access rules, middleware host selection, failure behavior, or built-in and operator-run middleware attachment. Trigger keywords - generate policy, create policy, update policy, change policy, sandbox policy, network policy, API policy, security policy, allow API, restrict API, network middleware, supervisor middleware.
---

# Generate Sandbox Policy

Generate YAML sandbox network policies and network middleware configuration from API documentation and natural-language user requirements.

## Overview

This skill translates a user's plain-language policy intent into a valid sandbox policy. The amount of detail the user provides determines the granularity of the generated policy — from broad L4 or preset-based policies (just a host:port) up to fine-grained per-endpoint L7 rules (full API docs).

The output is a `network_policies` YAML block, an optional `network_middlewares` block, and optionally a full policy file that conforms to the sandbox policy schema.

## Step 1: Gather Inputs

### Determine the Detail Tier

The user's input falls into one of three tiers. Work with whatever the user provides — **do not require a higher tier than needed**.

| Tier | User provides | What you can generate |
|------|--------------|----------------------|
| **Minimal** | Host(s) and plain-language intent | L4-only policies, or L7 with access presets (`read-only`, `read-write`, `full`) |
| **Moderate** | Host(s) + some known URL paths or resources | L7 with targeted glob rules for known paths, presets for the rest |
| **Full** | Complete API docs (OpenAPI, Swagger, markdown, URL) | Fine-grained per-endpoint L7 rules with specific method+path combinations |

### Minimal Tier (host + intent only)

The user provides API endpoints and a broad intent. No API docs needed.
... (615 lines truncated)
</file>

<file path="skills/openshell-cli/SKILL.md">
---
name: openshell-cli
description: Guide agents through using the OpenShell CLI (openshell) for sandbox management, gateway registration, provider configuration and refresh, profile management, policy iteration, settings, service exposure, BYOC workflows, and attached-provider inference. Covers basic through advanced multi-step workflows. Trigger keywords - openshell, sandbox create, sandbox exec, sandbox connect, logs, provider create, profile list, profile describe, provider refresh, policy set, policy get, settings, service expose, forward, port forward, BYOC, bring your own container, inference, use openshell, run openshell, CLI usage, manage sandbox, manage provider, gateway add, gateway select.
---

# OpenShell CLI

Guide agents through using the `openshell` CLI for sandbox and platform management -- from basic operations to advanced multi-step workflows.

## Overview

The OpenShell CLI (`openshell`) is the primary interface for managing sandboxes, providers, policies, settings, exposed services, and gateway registrations. Gateway service lifecycle is handled outside the CLI by packages, systemd, or Helm. This skill teaches agents how to orchestrate CLI commands for common and complex workflows.

**Companion skill**: For creating or modifying sandbox policy YAML content (network rules, L7 inspection, access presets), use the `generate-sandbox-policy` skill. This skill covers the CLI *commands* for the policy lifecycle; `generate-sandbox-policy` covers policy *content authoring*.

**Self-teaching**: The CLI has comprehensive built-in help. When you encounter a command or option not covered in this skill, walk the help tree:

```bash
openshell --help                    # Top-level commands
openshell <group> --help            # Subcommands in a group
openshell <group> <cmd> --help      # Flags for a specific command
```

This is your primary fallback. Use it freely -- the CLI's help output is authoritative and always up-to-date.

## Prerequisites

- `openshell` is on the PATH. Follow the published [installation guide](https://docs.nvidia.com/openshell/latest/about/installation.md) when it is not installed.
- A reachable OpenShell gateway backed by Docker, Podman, Kubernetes, or the experimental VM driver
- Docker is running only when using BYOC local builds or a Docker-backed gateway
... (926 lines truncated)
</file>

<file path="snap/hooks/connect-plug-docker">
#!/bin/sh
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

# The gateway daemon can start when this plug is still disconnected. Restart it
# after Docker access becomes available so driver auto-detection runs with the
# socket exposed through the system :docker slot. This hook does not make normal
# gateway startup conditional on Docker; it runs after an automatic or manual
# Docker connection.

set -eu

snapctl restart "${SNAP_INSTANCE_NAME}.gateway"
</file>

<file path="snap/hooks/install">
#!/bin/sh
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

# Create the mTLS default and replace insecure configs on refresh.

set -eu

config_file="${SNAP_COMMON}/gateway.toml"
insecure='^[[:space:]]*(allow_unauthenticated_users|disable_tls)[[:space:]]*=[[:space:]]*true([[:space:]#]|$)'

# Keep secure operator configs, symlinks, and directories. Replace a config
# that explicitly allows plaintext or anonymous access, even if it has other
# edits.
if [ -L "$config_file" ]; then
	exit 0
elif [ -f "$config_file" ]; then
	grep -Eq "$insecure" "$config_file" || exit 0
	echo "openshell: replacing insecure gateway config with the mTLS default" >&2
elif [ -e "$config_file" ]; then
	exit 0
fi

mkdir -p "$SNAP_COMMON"
umask 077
temporary_file=$(mktemp "${config_file}.tmp.XXXXXX")
trap 'rm -f "$temporary_file"' 0 HUP INT TERM
cat >"$temporary_file" <<'CONFIG'
[openshell]
version = 2
... (6 lines truncated)
</file>

<file path="snap/hooks/post-refresh">
#!/bin/sh
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

# Replace insecure gateway configs on refresh, then restart the gateway so the
# new config takes effect even when the previous revision used
# refresh-mode: endure and kept its plaintext gateway running.

set -eu

"${SNAP}/meta/hooks/install"
snapctl restart "${SNAP_INSTANCE_NAME}.gateway"
</file>

<file path="snap/local/term.desktop">
[Desktop Entry]
Name=OpenShell
Comment=OpenShell terminal UI for managing sandboxes and gateways
Exec=openshell.term
Icon=${SNAP}/meta/gui/icon.png
Terminal=true
Type=Application
Categories=Development;
StartupNotify=true
</file>

<file path="tasks/scripts/vm/_lib.sh">
vm_lib_root() {
    cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd
}
detect_platform() {
    case "$(uname -s)-$(uname -m)" in
        Darwin-arm64)   echo "darwin-aarch64" ;;
        Linux-aarch64)  echo "linux-aarch64" ;;
        Linux-x86_64)   echo "linux-x86_64" ;;
        *)
            echo "Error: Unsupported platform: $(uname -s)-$(uname -m)" >&2
            echo "Supported: macOS ARM64, Linux ARM64, Linux x86_64" >&2
            return 1
            ;;
    esac
}
download_umoci_binary() {
    local output="$1"
    local version="$2"
    local guest_arch="$3"
    local suffix
    case "$guest_arch" in
        arm64|aarch64) suffix="arm64" ;;
        amd64|x86_64)  suffix="amd64" ;;
        *)
            echo "Error: Unsupported guest architecture for umoci: ${guest_arch}" >&2
            return 1
            ;;
    esac
    local base_url="https://github.com/opencontainers/umoci/releases/download/${version}"
    local candidates=("umoci.linux.${suffix}" "umoci.${suffix}")
... (76 lines truncated)
</file>

<file path="tasks/scripts/vm/build-libkrun-macos.sh">
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)"
source "${ROOT}/crates/openshell-driver-vm/runtime/pins.env" 2>/dev/null || true
BUILD_DIR="${ROOT}/target/libkrun-build"
OUTPUT_DIR="${BUILD_DIR}"
BREW_PREFIX="$(brew --prefix 2>/dev/null || echo /opt/homebrew)"
KERNEL_DIR=""
# Parse arguments
while [[ $# -gt 0 ]]; do
    case "$1" in
        --kernel-dir)
            KERNEL_DIR="$(cd "$2" && pwd)"; shift 2 ;;
        --help|-h)
            echo "Usage: $0 --kernel-dir <DIR>"
            echo ""
            echo "Build libkrun + libkrunfw on macOS using a pre-built kernel.c."
            echo ""
            echo "Options:"
            echo "  --kernel-dir DIR  Directory containing kernel.c and ABI_VERSION"
            exit 0
            ;;
        *)
            echo "Unknown argument: $1" >&2; exit 1 ;;
    esac
done
if [ "$(uname -s)" != "Darwin" ]; then
    echo "Error: This script only runs on macOS" >&2
    exit 1
fi
if [ "$(uname -m)" != "arm64" ]; then
... (157 lines truncated)
</file>

<file path="tasks/scripts/vm/build-libkrun.sh">
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${SCRIPT_DIR}/_lib.sh"
ROOT="$(vm_lib_root)"
source "${ROOT}/crates/openshell-driver-vm/runtime/pins.env" 2>/dev/null || true
BUILD_DIR="${ROOT}/target/libkrun-build"
OUTPUT_DIR="${BUILD_DIR}"
KERNEL_CONFIG="${ROOT}/crates/openshell-driver-vm/runtime/kernel/openshell.kconfig"
if [ "$(uname -s)" != "Linux" ]; then
  echo "Error: This script only runs on Linux" >&2
  exit 1
fi
HOST_ARCH="$(uname -m)"
echo "==> Building libkrun for Linux ${HOST_ARCH}"
echo "    Build directory: ${BUILD_DIR}"
echo "    Kernel config: ${KERNEL_CONFIG}"
echo ""
# Map host arch to kernel ARCH value
case "$HOST_ARCH" in
  aarch64) KARCH="arm64"; KERNEL_IMAGE_PATH="arch/arm64/boot/Image" ;;
  x86_64)  KARCH="x86"; KERNEL_IMAGE_PATH="arch/x86/boot/bzImage" ;;
  *)       echo "Error: Unsupported architecture: ${HOST_ARCH}" >&2; exit 1 ;;
esac
SUDO=""
if [ "$(id -u)" -ne 0 ]; then
  SUDO="sudo"
fi
install_deps() {
  echo "==> Checking/installing build dependencies..."
  if command -v apt-get &>/dev/null; then
... (287 lines truncated)
</file>

<file path="tasks/scripts/vm/build-supervisor-bundle.sh">
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)"
OUTPUT_DIR="${OPENSHELL_VM_RUNTIME_COMPRESSED_DIR:-${ROOT}/target/vm-runtime-compressed}"
source "${ROOT}/tasks/scripts/build-env.sh"
GUEST_ARCH=""
while [[ $# -gt 0 ]]; do
    case "$1" in
        --arch)
            GUEST_ARCH="$2"
            shift 2
            ;;
        --arch=*)
            GUEST_ARCH="${1#--arch=}"
            shift
            ;;
        --help|-h)
            echo "Usage: $0 [--arch aarch64|x86_64]"
            exit 0
            ;;
        *)
            echo "Unknown argument: $1" >&2
            exit 1
            ;;
    esac
done
if [ -z "${GUEST_ARCH}" ]; then
    case "$(uname -m)" in
        aarch64|arm64) GUEST_ARCH="aarch64" ;;
        x86_64|amd64)  GUEST_ARCH="x86_64" ;;
        *)
... (100 lines truncated)
</file>

<file path="tasks/scripts/vm/compress-vm-runtime.sh">
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${SCRIPT_DIR}/_lib.sh"
ROOT="$(vm_lib_root)"
source "${ROOT}/crates/openshell-driver-vm/runtime/pins.env" 2>/dev/null || true
UMOCI_VERSION="${UMOCI_VERSION:-v0.6.0}"
make_dylib_portable() {
    local dylib="$1"
    local dylib_name
    dylib_name="$(basename "$dylib")"
    # Rewrite install name
    install_name_tool -id "@loader_path/${dylib_name}" "$dylib" 2>/dev/null || true
    local krunfw_path
    krunfw_path=$(otool -L "$dylib" 2>/dev/null | grep libkrunfw | awk '{print $1}' || true)
    if [ -n "$krunfw_path" ] && [[ "$krunfw_path" != @* ]]; then
        install_name_tool -change "$krunfw_path" "@loader_path/libkrunfw.dylib" "$dylib"
    fi
    codesign -f -s - "$dylib" 2>/dev/null || true
}
WORK_DIR="${ROOT}/target/vm-runtime"
OUTPUT_DIR="${OPENSHELL_VM_RUNTIME_COMPRESSED_DIR:-${ROOT}/target/vm-runtime-compressed}"
mkdir -p "$OUTPUT_DIR"
download_umoci_for_guest() {
    local output="$1"
    local guest_arch="$2"
    download_umoci_binary "$output" "${UMOCI_VERSION}" "$guest_arch"
}
_check_compressed_artifacts() {
    local dir="$1"
    local platform
... (180 lines truncated)
</file>

<file path="tasks/scripts/vm/download-kernel-runtime.sh">
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${SCRIPT_DIR}/_lib.sh"
ROOT="$(vm_lib_root)"
source "${ROOT}/crates/openshell-driver-vm/runtime/pins.env" 2>/dev/null || true
RELEASE_TAG="${VM_RUNTIME_RELEASE_TAG:-vm-runtime}"
REPO="${GITHUB_REPOSITORY:-NVIDIA/OpenShell}"
OUTPUT_DIR="${OPENSHELL_VM_RUNTIME_COMPRESSED_DIR:-${ROOT}/target/vm-runtime-compressed}"
UMOCI_VERSION="${UMOCI_VERSION:-v0.6.0}"
PLATFORM=""
while [[ $# -gt 0 ]]; do
    case "$1" in
        --platform)
            PLATFORM="$2"; shift 2 ;;
        --help|-h)
            echo "Usage: $0 [--platform PLATFORM]"
            echo ""
            echo "Download pre-built VM kernel runtime from the vm-runtime GitHub Release."
            echo ""
            echo "Platforms: linux-aarch64, linux-x86_64, darwin-aarch64"
            echo ""
            echo "Environment:"
            echo "  VM_RUNTIME_RELEASE_TAG              Release tag (default: vm-runtime)"
            echo "  GITHUB_REPOSITORY                   owner/repo (default: NVIDIA/OpenShell)"
            echo "  OPENSHELL_VM_RUNTIME_COMPRESSED_DIR Output directory"
            exit 0
            ;;
        *)
            echo "Unknown argument: $1" >&2; exit 1 ;;
    esac
... (55 lines truncated)
</file>

<file path="tasks/scripts/vm/package-vm-runtime.sh">
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${SCRIPT_DIR}/_lib.sh"
ROOT="$(vm_lib_root)"
source "${ROOT}/crates/openshell-driver-vm/runtime/pins.env" 2>/dev/null || true
UMOCI_VERSION="${UMOCI_VERSION:-v0.6.0}"
PLATFORM=""
BUILD_DIR=""
OUTPUT=""
CUSTOM_PROVENANCE_DIR="${CUSTOM_PROVENANCE_DIR:-}"
while [[ $# -gt 0 ]]; do
    case "$1" in
        --platform)     PLATFORM="$2"; shift 2 ;;
        --build-dir)    BUILD_DIR="$2"; shift 2 ;;
        --output)       OUTPUT="$2"; shift 2 ;;
        --help|-h)
            echo "Usage: $0 --platform <PLATFORM> --build-dir <DIR> --output <FILE>"
            echo ""
            echo "Package VM runtime artifacts into a release tarball."
            echo ""
            echo "Platforms: linux-aarch64, linux-x86_64, darwin-aarch64"
            exit 0
            ;;
        *)
            echo "Unknown argument: $1" >&2; exit 1 ;;
    esac
done
if [ -z "$PLATFORM" ] || [ -z "$BUILD_DIR" ] || [ -z "$OUTPUT" ]; then
    echo "Error: --platform, --build-dir, and --output are all required" >&2
    exit 1
... (87 lines truncated)
</file>

<file path="tasks/scripts/vm/smoke-orphan-cleanup.sh">
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)"
cd "$ROOT"
PORT="${OPENSHELL_SERVER_PORT:-8091}"
XDG="${TMPDIR:-/tmp}/vm-orphan-xdg-$$"
STATE_DIR="${TMPDIR:-/tmp}/openshell-vm-orphan-$$"
LOG="${TMPDIR:-/tmp}/vm-orphan-$$.log"
cleanup_stray() {
    pkill -9 -f "openshell-vm-orphan-$$" 2>/dev/null || true
    rm -rf "$XDG" "$STATE_DIR" 2>/dev/null || true
    if [ "${EXIT_CODE:-0}" -ne 0 ]; then
        echo "(log preserved at $LOG)" >&2
    else
        rm -f "$LOG" "$LOG.create" 2>/dev/null || true
    fi
}
trap cleanup_stray EXIT
build_binaries() {
    echo "==> Ensuring binaries are built"
    if [ ! -x "$ROOT/target/debug/openshell-gateway" ] || [ ! -x "$ROOT/target/debug/openshell-driver-vm" ]; then
        cargo build -p openshell-gateway -p openshell-driver-vm >&2
    fi
    if [ "$(uname -s)" = "Darwin" ]; then
        codesign \
            --entitlements "$ROOT/crates/openshell-driver-vm/entitlements.plist" \
            --force -s - \
            "$ROOT/target/debug/openshell-driver-vm" >/dev/null 2>&1 || true
    fi
}
start_gateway() {
... (130 lines truncated)
</file>

<file path="tasks/scripts/vm/vm-setup.sh">
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${SCRIPT_DIR}/_lib.sh"
ROOT="$(vm_lib_root)"
CLI_BIN="${ROOT}/scripts/bin/openshell"
FROM_SOURCE="${FROM_SOURCE:-0}"
while [[ $
    case "$1" in
        --from-source)
            FROM_SOURCE=1
            shift
            ;;
        --help|-h)
            echo "Usage: $0 [--from-source]"
            echo ""
            echo "Set up the openshell-driver-vm runtime (libkrun, libkrunfw, umoci)."
            echo ""
            echo "Options:"
            echo "  --from-source   Build runtime from source instead of downloading (~15-45min)"
            echo ""
            echo "Environment:"
            echo "  FROM_SOURCE=1   Equivalent to --from-source"
            exit 0
            ;;
        *)
            echo "Unknown argument: $1" >&2
            echo "Use --help for usage information" >&2
            exit 1
            ;;
    esac
... (68 lines truncated)
</file>

<file path="tasks/scripts/build-env.sh">
ensure_build_nofile_limit() {
    local desired="${OPENSHELL_BUILD_NOFILE_LIMIT:-${OPENSHELL_VM_BUILD_NOFILE_LIMIT:-8192}}"
    local minimum=1024
    local current=""
    local hard=""
    local target=""
    [ "$(uname -s)" = "Darwin" ] || return 0
    command -v cargo-zigbuild >/dev/null 2>&1 || return 0
    current="$(ulimit -n 2>/dev/null || echo "")"
    case "${current}" in
        ''|*[!0-9]*)
            return 0
            ;;
    esac
    if [ "${current}" -ge "${desired}" ]; then
        return 0
    fi
    hard="$(ulimit -Hn 2>/dev/null || echo "")"
    target="${desired}"
    case "${hard}" in
        ''|unlimited|infinity)
            ;;
        *[!0-9]*)
            ;;
        *)
            if [ "${hard}" -lt "${target}" ]; then
                target="${hard}"
            fi
            ;;
    esac
... (20 lines truncated)
</file>

<file path="tasks/scripts/check_docs_nav_test.py">
FERN_CONFIG = """\
⋮----
def page(title: str, **extra: str) -> str
⋮----
lines = (
⋮----
def build(tmp_path: Path, nav: str, pages: dict[str, str], redirects: str = "") -> Path
⋮----
docs = tmp_path / "docs"
⋮----
def test_fern_slug_splits_camel_case() -> None
⋮----
def test_matching_nav_passes(tmp_path: Path) -> None
⋮----
root = build(
⋮----
def test_label_url_that_differs_from_file_path_fails(tmp_path: Path) -> None
⋮----
issues = check_docs_nav.run(root)
⋮----
def test_frontmatter_slug_can_pin_the_url_to_the_file_path(tmp_path: Path) -> None
⋮----
def test_sidebar_name_must_match_nav_label(tmp_path: Path) -> None
⋮----
def test_skip_slug_omits_navigation_level(tmp_path: Path, nav: str, rel: str) -> None
⋮----
root = build(tmp_path, nav, {rel: page("Setup")})
⋮----
def test_skip_slug_detects_url_that_differs_from_file_path(tmp_path: Path) -> None
⋮----
... (2 lines truncated)
</file>

<file path="tasks/scripts/check_docs_nav.py">
UNPUBLISHED = {"CONTRIBUTING.mdx"}
⋮----
def fern_slug(label: str) -> str
⋮----
split = re.sub(r"([a-z0-9])([A-Z])", r"\1-\2", label)
⋮----
def path_url(rel_path: str) -> str
⋮----
"""Return the URL that a docs file path implies."""
url = "/" + re.sub(r"\.mdx$", "", rel_path)
⋮----
def frontmatter(path: Path) -> dict
⋮----
match = re.match(r"---\n(.*?)\n---", path.read_text(encoding="utf-8"), re.S)
⋮----
@dataclass
class NavCheck
⋮----
docs_root: Path
urls: dict[str, str] = field(default_factory=dict)
reachable: set[str] = field(default_factory=set)
issues: list[str] = field(default_factory=list)
⋮----
def page_url(self, rel_path: str, default_url: str) -> str
⋮----
slug = frontmatter(self.docs_root / rel_path).get("slug")
⋮----
def record(self, rel_path: str, url: str, how: str) -> None
⋮----
expected = path_url(rel_path)
... (51 lines truncated)
</file>

<file path="tasks/scripts/check-cargo-lockfiles.ps1">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

$ErrorActionPreference = "Stop"

$repoRoot = (& git rev-parse --show-toplevel).Trim()
if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($repoRoot)) {
    throw "Unable to resolve the repository root"
}
Set-Location -LiteralPath $repoRoot

$lockfiles = @(& git ls-files -- ':(glob)**/Cargo.lock')
if ($LASTEXITCODE -ne 0) {
    throw "Unable to enumerate tracked Cargo.lock files"
}
if ($lockfiles.Count -eq 0) {
    throw "No tracked Cargo.lock files found"
}

$failed = $false
foreach ($lockfile in $lockfiles) {
    $lockfileDirectory = Split-Path -Parent $lockfile
    $manifest = if ([string]::IsNullOrEmpty($lockfileDirectory)) {
        "Cargo.toml"
    } else {
        Join-Path $lockfileDirectory "Cargo.toml"
    }
    if (-not (Test-Path -LiteralPath $manifest -PathType Leaf)) {
        Write-Error "Tracked lockfile $lockfile has no adjacent Cargo.toml"
        $failed = $true
... (15 lines truncated)
</file>

<file path="tasks/scripts/check-cargo-lockfiles.sh">
set -euo pipefail
check_lockfile() {
  local lockfile="$1"
  local manifest="${lockfile%Cargo.lock}Cargo.toml"
  if [[ ! -f "$manifest" ]]; then
    printf 'error: tracked lockfile %s has no adjacent Cargo.toml\n' "$lockfile" >&2
    return 1
  fi
  printf 'Checking %s\n' "$lockfile"
  if ! cargo metadata \
    --locked \
    --format-version 1 \
    --manifest-path "$manifest" \
    >/dev/null; then
    printf 'error: validation failed for %s\n' "$lockfile" >&2
    return 1
  fi
}
main() {
  local lockfile
  local found=0
  local failed=0
  cd "$(git rev-parse --show-toplevel)"
  while IFS= read -r -d '' lockfile; do
    found=1
    check_lockfile "$lockfile" || failed=1
  done < <(git ls-files -z -- ':(glob)**/Cargo.lock')
  if [[ "$found" -eq 0 ]]; then
    echo "error: no tracked Cargo.lock files found" >&2
    return 1
... (8 lines truncated)
</file>

<file path="tasks/scripts/codex_security_range_test.py">
SCRIPT = Path(__file__).resolve().parent / "codex_security_range.py"
⋮----
def _git(repo: Path, *args: str) -> str
⋮----
def _commit(repo: Path, name: str) -> None
⋮----
def _publish_main(repo: Path) -> None
⋮----
def _run(repo: Path, *args: str) -> subprocess.CompletedProcess[str]
⋮----
@pytest.fixture
def repo(tmp_path: Path) -> Path
⋮----
def test_parses_strict_stable_and_prerelease_tags() -> None
⋮----
def test_selects_the_newest_stable_strictly_before_the_candidate_train() -> None
⋮----
tags = ["v0.1.9", "v0.1.10", "v0.2.0-pre.1", "v0.2.0", "vm-runtime", "0.1.11"]
⋮----
def test_resolves_a_cumulative_prerelease_range_from_git_history(repo: Path) -> None
⋮----
result = ranges.resolve_range(repo=repo, candidate="v0.1.1-pre.2")
⋮----
def test_rejects_a_candidate_that_is_not_a_prerelease_tag(repo: Path) -> None
⋮----
def test_rejects_a_prerelease_that_is_not_on_main(repo: Path) -> None
⋮----
def test_requires_explicit_approval_before_a_full_bootstrap_scan(repo: Path) -> None
⋮----
approved = ranges.resolve_range(
... (15 lines truncated)
</file>

<file path="tasks/scripts/codex_security_range.py">
class ReleaseRangeError(Exception)
⋮----
def _git(repo: Path, cmd: list[str]) -> str
⋮----
def _resolve_commit(repo: Path, ref: str) -> str
⋮----
def _is_ancestor(repo: Path, ancestor: str, descendant: str) -> bool
⋮----
result = subprocess.run(
⋮----
def parse_stable_tag(tag: str) -> tuple[int, int, int] | None
⋮----
def parse_prerelease_tag(tag: str) -> tuple[int, int, int, int] | None
⋮----
older = [
⋮----
parsed_candidate = parse_prerelease_tag(candidate)
⋮----
candidate_version = parsed_candidate[:3]
train = f"v{_format_semver(candidate_version)}"
⋮----
candidate_sha = _resolve_commit(repo, candidate)
main_sha = _resolve_commit(repo, main_ref)
⋮----
resolved = {
⋮----
merged_tags = [
stable_tag = stable or select_previous_stable(merged_tags, candidate_version)
⋮----
stable_version = parse_stable_tag(stable_tag)
... (18 lines truncated)
</file>

<file path="tasks/scripts/container-engine.sh">
if [[ -n "${_CONTAINER_ENGINE_LOADED:-}" ]]; then
  return 0
fi
_CONTAINER_ENGINE_LOADED=1
_ce_lower() {
  printf '%s' "$1" | tr '[:upper:]' '[:lower:]'
}
_ce_error() {
  echo "Error: $*" >&2
  exit 1
}
_ce_validate_engine_value() {
  local name=$1
  local value=$2
  case "${value}" in
    docker|podman)
      ;;
    *)
      _ce_error "${name}=${value} is invalid; expected docker or podman"
      ;;
  esac
}
_ce_docker_is_podman_shim() {
  command -v docker >/dev/null 2>&1 && docker --version 2>/dev/null | grep -qi podman
}
_ce_require_engine_available() {
  local engine=$1
  case "${engine}" in
    docker)
      if ! command -v docker >/dev/null 2>&1; then
... (321 lines truncated)
</file>

<file path="tasks/scripts/docker-build-ci.sh">
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${SCRIPT_DIR}/container-engine.sh"
OUTPUT_ARGS=(--load)
if [[ "${DOCKER_PUSH:-}" == "1" ]]; then
  OUTPUT_ARGS=(--push)
elif [[ "${DOCKER_PLATFORM:-}" == *","* ]]; then
  OUTPUT_ARGS=(--push)
fi
SECRET_ARGS=()
if [[ -n "${MISE_GITHUB_TOKEN:-}" ]]; then
  SECRET_ARGS=(--secret id=MISE_GITHUB_TOKEN,env=MISE_GITHUB_TOKEN)
elif [[ -n "${GITHUB_TOKEN:-}" ]]; then
  SECRET_ARGS=(--secret id=MISE_GITHUB_TOKEN,env=GITHUB_TOKEN)
fi
exec ce_build \
  ${DOCKER_BUILDER:+--builder ${DOCKER_BUILDER}} \
  ${DOCKER_PLATFORM:+--platform ${DOCKER_PLATFORM}} \
  ${SECRET_ARGS[@]+"${SECRET_ARGS[@]}"} \
  -f deploy/docker/Dockerfile.ci \
  -t "openshell/ci:${IMAGE_TAG:-dev}" \
  --provenance=false \
  "$@" \
  ${OUTPUT_ARGS[@]+"${OUTPUT_ARGS[@]}"} \
  .
</file>

<file path="tasks/scripts/docker-build-image.sh">
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${SCRIPT_DIR}/container-engine.sh"
normalize_arch() {
	case "$1" in
		x86_64|amd64) echo "amd64" ;;
		aarch64|arm64) echo "arm64" ;;
		*) echo "$1" ;;
	esac
}
prebuilt_arches() {
	if [[ -n "${DOCKER_PLATFORM:-}" ]]; then
		local raw_platforms=${DOCKER_PLATFORM//[[:space:]]/}
		local platform
		IFS=',' read -r -a platforms <<< "${raw_platforms}"
		for platform in "${platforms[@]}"; do
			case "${platform}" in
				linux/amd64) echo "amd64" ;;
				linux/arm64) echo "arm64" ;;
				*)
					echo "Error: unsupported DOCKER_PLATFORM '${platform}'" >&2
					echo "Supported platforms: linux/amd64, linux/arm64" >&2
					exit 1
					;;
			esac
		done
		return
	fi
	normalize_arch "$(ce_info_arch)"
}
... (153 lines truncated)
</file>

<file path="tasks/scripts/docker-publish-multiarch.sh">
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${SCRIPT_DIR}/container-engine.sh"
REGISTRY=${DOCKER_REGISTRY:?Set DOCKER_REGISTRY to push multi-arch images (e.g. ghcr.io/myorg)}
IMAGE_TAG=${IMAGE_TAG:-dev}
PLATFORMS=${DOCKER_PLATFORMS:-linux/amd64,linux/arm64}
TAG_LATEST=${TAG_LATEST:-false}
EXTRA_DOCKER_TAGS_RAW=${EXTRA_DOCKER_TAGS:-}
EXTRA_TAGS=()
if [[ -n "${EXTRA_DOCKER_TAGS_RAW}" ]]; then
  EXTRA_DOCKER_TAGS_RAW=${EXTRA_DOCKER_TAGS_RAW//,/ }
  for tag in ${EXTRA_DOCKER_TAGS_RAW}; do
    [[ -n "${tag}" ]] && EXTRA_TAGS+=("${tag}")
  done
fi
_publish_multiarch_docker() {
  BUILDER_NAME=${DOCKER_BUILDER:-multiarch}
  if ce buildx inspect "${BUILDER_NAME}" >/dev/null 2>&1; then
    echo "Using existing buildx builder: ${BUILDER_NAME}"
    ce buildx use "${BUILDER_NAME}"
  else
    echo "Creating multi-platform buildx builder: ${BUILDER_NAME}..."
    ce buildx create --name "${BUILDER_NAME}" --use --bootstrap
  fi
  export DOCKER_BUILDER="${BUILDER_NAME}"
  export DOCKER_PLATFORM="${PLATFORMS}"
  export DOCKER_PUSH=1
  export IMAGE_REGISTRY="${REGISTRY}"
  echo "Building multi-arch gateway image..."
  tasks/scripts/docker-build-image.sh gateway
... (86 lines truncated)
</file>

<file path="tasks/scripts/e2e-build-workload.sh">
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
source "${ROOT}/tasks/scripts/container-engine.sh"
ce_build --load --file "${ROOT}/e2e/python/Dockerfile.workload" \
  --build-arg "PYTHON_VERSION=$(cat "${ROOT}/.python-version")" \
  --tag openshell/e2e-python:dev \
  "${ROOT}/e2e/python"
</file>

<file path="tasks/scripts/e2e-gpu-build-images.sh">
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT="$(cd "${SCRIPT_DIR}/../.." && pwd)"
source "${SCRIPT_DIR}/container-engine.sh"
IMAGES_ROOT="${ROOT}/e2e/gpu/images"
BUILD_DIR="${IMAGES_ROOT}/.build"
BASE_IMAGE="${OPENSHELL_SANDBOX_BASE_IMAGE:-nvcr.io/nvidia/base/ubuntu:24.04}"
CUDA_BUILD_IMAGE="${CUDA_BUILD_IMAGE:-nvcr.io/nvidia/cuda:12.8.1-base-ubuntu22.04}"
CUDA_SAMPLES_REPO="${CUDA_SAMPLES_REPO:-https://github.com/NVIDIA/cuda-samples}"
CUDA_SAMPLES_REF="${CUDA_SAMPLES_REF:-v12.8}"
SUPPORTED_IMAGES=(smoke-pass smoke-fail cuda-basic)
shell_quote() {
  local value=$1
  printf "'%s'" "${value//\'/\'\\\'\'}"
}
write_env_var() {
  local name=$1
  local value=$2
  printf 'export %s=%s\n' "${name}" "$(shell_quote "${value}")"
}
yaml_quote() {
  local value=$1
  value=${value//\\/\\\\}
  value=${value//\"/\\\"}
  value=${value//$'\n'/\\n}
  value=${value//$'\r'/\\r}
  value=${value//$'\t'/\\t}
  printf '"%s"' "${value}"
}
if command -v sha256sum >/dev/null 2>&1; then
... (214 lines truncated)
</file>

<file path="tasks/scripts/gateway-docker.sh">
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
source "${ROOT}/tasks/scripts/gateway-toml.sh"
source "${ROOT}/tasks/scripts/gateway-pull-policy.sh"
PORT="${OPENSHELL_SERVER_PORT:-18080}"
GATEWAY_NAME="${OPENSHELL_DOCKER_GATEWAY_NAME:-docker-dev}"
STATE_DIR="${OPENSHELL_DOCKER_GATEWAY_STATE_DIR:-${ROOT}/.cache/gateway-docker}"
SANDBOX_NAMESPACE="${OPENSHELL_SANDBOX_NAMESPACE:-docker-dev}"
SANDBOX_IMAGE="${OPENSHELL_SANDBOX_IMAGE:-nvcr.io/nvidia/base/ubuntu:24.04}"
SUPERVISOR_IMAGE="${OPENSHELL_SUPERVISOR_IMAGE:-openshell/supervisor:dev}"
SANDBOX_RUNTIME_IMAGE="${OPENSHELL_SANDBOX_RUNTIME_IMAGE:-openshell/sandbox:dev}"
SANDBOX_IMAGE_PULL_POLICY="$(normalize_image_pull_policy "${OPENSHELL_SANDBOX_IMAGE_PULL_POLICY:-if_not_present}")"
LOG_LEVEL="${OPENSHELL_LOG_LEVEL:-info}"
GATEWAY_BIN="${ROOT}/target/debug/openshell-gateway"
port_is_in_use() {
  local port=$1
  if command -v lsof >/dev/null 2>&1; then
    lsof -nP -iTCP:"${port}" -sTCP:LISTEN >/dev/null 2>&1
    return $?
  fi
  if command -v nc >/dev/null 2>&1; then
    nc -z 127.0.0.1 "${port}" >/dev/null 2>&1
    return $?
  fi
  (echo >/dev/tcp/127.0.0.1/"${port}") >/dev/null 2>&1
}
ensure_docker_runtime_image() {
  local image=$1
  local configured_image=$2
  local build_target=$3
... (154 lines truncated)
</file>

<file path="tasks/scripts/gateway-podman.sh">
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
source "${ROOT}/tasks/scripts/gateway-toml.sh"
source "${ROOT}/tasks/scripts/gateway-pull-policy.sh"
PORT="${OPENSHELL_SERVER_PORT:-18080}"
GATEWAY_NAME="${OPENSHELL_PODMAN_GATEWAY_NAME:-podman-dev}"
STATE_DIR="${OPENSHELL_PODMAN_GATEWAY_STATE_DIR:-${OPENSHELL_GATEWAY_STATE_DIR:-${ROOT}/.cache/gateway-podman}}"
SANDBOX_NAMESPACE="${OPENSHELL_SANDBOX_NAMESPACE:-podman-dev}"
SANDBOX_IMAGE="${OPENSHELL_SANDBOX_IMAGE:-nvcr.io/nvidia/base/ubuntu:24.04}"
SANDBOX_IMAGE_PULL_POLICY="$(normalize_image_pull_policy "${OPENSHELL_SANDBOX_IMAGE_PULL_POLICY:-if_not_present}")"
GRPC_ENDPOINT="${OPENSHELL_GRPC_ENDPOINT:-}"
LOG_LEVEL="${OPENSHELL_LOG_LEVEL:-info}"
PRIMARY_BIND_IP="${OPENSHELL_BIND_ADDRESS:-127.0.0.1}"
CLI_ENDPOINT_HOST="127.0.0.1"
GATEWAY_BIN="${ROOT}/target/debug/openshell-gateway"
command_available() {
  command -v "$1" >/dev/null 2>&1
}
require_mise() {
  if ! command_available mise; then
    echo "ERROR: mise is required to build local gateway artifacts" >&2
    exit 1
  fi
}
podman_available() {
  command_available podman && podman info >/dev/null 2>&1
}
require_podman_service() {
  if ! command_available podman; then
    echo "ERROR: podman is not installed or not in PATH" >&2
... (194 lines truncated)
</file>

<file path="tasks/scripts/gateway-pull-policy.sh">
normalize_image_pull_policy() {
  local value
  value="$(printf '%s' "${1:-}" | LC_ALL=C tr '[:upper:]' '[:lower:]')"
  case "${value}" in
    always)
      printf '%s\n' "always"
      ;;
    if_not_present|ifnotpresent|missing)
      printf '%s\n' "if_not_present"
      ;;
    never)
      printf '%s\n' "never"
      ;;
    newer)
      printf '%s\n' "newer"
      ;;
    *)
      printf 'unsupported image pull policy: %s\n' "${1:-}" >&2
      return 2
      ;;
  esac
}
</file>

<file path="tasks/scripts/gateway-toml.sh">
toml_escape() {
  local value=$1
  value=${value//\\/\\\\}
  value=${value//\"/\\\"}
  value=${value//$'\n'/\\n}
  value=${value//$'\r'/\\r}
  value=${value//$'\t'/\\t}
  printf '%s' "${value}"
}
</file>

<file path="tasks/scripts/gateway-vm.sh">
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
source "${ROOT}/tasks/scripts/gateway-toml.sh"
PORT="${OPENSHELL_SERVER_PORT:-18081}"
GATEWAY_NAME="${OPENSHELL_VM_GATEWAY_NAME:-vm-dev}"
STATE_DIR="${OPENSHELL_VM_GATEWAY_STATE_DIR:-${ROOT}/.cache/gateway-vm}"
SANDBOX_NAMESPACE="${OPENSHELL_SANDBOX_NAMESPACE:-vm-dev}"
SANDBOX_IMAGE="${OPENSHELL_SANDBOX_IMAGE:-nvcr.io/nvidia/base/ubuntu:24.04}"
VM_BOOTSTRAP_IMAGE="${OPENSHELL_VM_BOOTSTRAP_IMAGE:-}"
SANDBOX_IMAGE_PULL_POLICY="${OPENSHELL_SANDBOX_IMAGE_PULL_POLICY:-if_not_present}"
LOG_LEVEL="${OPENSHELL_LOG_LEVEL:-info}"
GATEWAY_BIN="${ROOT}/target/debug/openshell-gateway"
DRIVER_DIR_DEFAULT="${ROOT}/target/debug"
DRIVER_DIR="${OPENSHELL_DRIVER_DIR:-${DRIVER_DIR_DEFAULT}}"
COMPRESSED_DIR_DEFAULT="${ROOT}/target/vm-runtime-compressed"
COMPRESSED_DIR="${OPENSHELL_VM_RUNTIME_COMPRESSED_DIR:-${COMPRESSED_DIR_DEFAULT}}"
VM_HOST_GATEWAY_DEFAULT="${OPENSHELL_VM_HOST_GATEWAY:-host.containers.internal}"
GRPC_ENDPOINT="${OPENSHELL_GRPC_ENDPOINT:-http://${VM_HOST_GATEWAY_DEFAULT}:${PORT}}"
normalize_arch() {
  case "$1" in
    x86_64|amd64) echo "amd64" ;;
    aarch64|arm64) echo "arm64" ;;
    *) echo "$1" ;;
  esac
}
normalize_bool() {
  local val
  val="$(printf '%s' "$1" | tr '[:upper:]' '[:lower:]')"
  case "${val}" in
    1|true|yes|on) echo "true" ;;
... (303 lines truncated)
</file>

<file path="tasks/scripts/gateway.sh">
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
source "${ROOT}/tasks/scripts/gateway-pull-policy.sh"
GATEWAY_BIN="${OPENSHELL_GATEWAY_BIN:-${ROOT}/target/debug/openshell-gateway}"
usage() {
  cat <<'EOF'
Usage: mise run gateway [-- --driver DRIVER]
Start a local OpenShell gateway with the detected compute driver.
Driver detection order:
  kubernetes -> podman -> docker
Options:
  --driver DRIVER  Override detection. Accepted values:
                   kubernetes, podman, docker, vm, microvm
  -h, --help       Show this help.
Environment:
  OPENSHELL_COMPUTE_DRIVER       Driver override used by openshell-gateway.
  OPENSHELL_GATEWAY_NAME  Gateway name for delegated or Kubernetes runs.
  OPENSHELL_BIND_ADDRESS  Gateway listener address. Defaults to 127.0.0.1,
                          or ::1 for Podman Machine on macOS.
  OPENSHELL_SERVER_PORT   Gateway port. Defaults to 8080 for Kubernetes,
                          18080 for Podman/Docker, and 18081 for VM.
Docker, Podman, and VM runs delegate to their gateway:<driver> setup scripts.
EOF
}
normalize_driver() {
  local driver
  driver="$(printf '%s' "$1" | tr '[:upper:]' '[:lower:]')"
  case "${driver}" in
    kubernetes|k8s) echo "kubernetes" ;;
    podman) echo "podman" ;;
... (216 lines truncated)
</file>

<file path="tasks/scripts/generate_python_proto.py">
PROTO_FILES = [
⋮----
LINE_REWRITES = {
⋮----
def main() -> None
⋮----
file_path = Path(path)
text = file_path.read_text()
text = text.replace("from . from . import", "from . import")
⋮----
text = re.sub(pattern, replacement, text, flags=re.MULTILINE)
</file>

<file path="tasks/scripts/generate-qualification-summary.sh">
set -euo pipefail
die() {
  echo "generate-qualification-summary: $*" >&2
  exit 1
}
require_env() {
  local name
  for name in "$@"; do
    if [[ -z "${!name:-}" ]]; then
      die "required environment variable ${name} is not set"
    fi
  done
}
[[ $
output=$1
current_profile_passed=true
require_env \
  RELEASE_TAG SOURCE_SHA IS_PRERELEASE GITHUB_RUN_ID GITHUB_RUN_ATTEMPT \
  GITHUB_SERVER_URL GITHUB_REPOSITORY SECURITY_RESULT CONFORMANCE_RESULT \
  FEATURE_INTEGRATION_RESULT DOCKER_E2E_RESULT VM_E2E_RESULT
for result in \
  "${SECURITY_RESULT}" \
  "${CONFORMANCE_RESULT}" \
  "${FEATURE_INTEGRATION_RESULT}" \
  "${DOCKER_E2E_RESULT}" \
  "${VM_E2E_RESULT}"; do
  if [[ "${result}" != "success" ]]; then
    current_profile_passed=false
    break
  fi
... (47 lines truncated)
</file>

<file path="tasks/scripts/helm-k3s-local.sh">
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT="$(cd "${SCRIPT_DIR}/../.." && pwd)"
_branch="$(git -C "${ROOT}" rev-parse --abbrev-ref HEAD 2>/dev/null)" || _branch=""
_suffix="$(printf '%s' "${_branch##*/}" | tr '[:upper:]' '[:lower:]' | tr -cs 'a-z0-9' '-' | sed 's/-*$//')"
CLUSTER_NAME="${HELM_K3S_CLUSTER_NAME:-openshell-dev${_suffix:+-${_suffix}}}"
# k3d caps cluster names at 32 chars; validated in cmd_create so the operator
# gets an actionable hint instead of a deep-stack k3d validation error.
K3D_CLUSTER_NAME_MAX=32
# Host port forwarded to port 80 via the k3d load balancer.
# Used by Envoy Gateway's LoadBalancer service (values-gateway.yaml).
HOST_LB_PORT="${HELM_K3S_LB_HOST_PORT:-8080}"
# Preload the default sandbox image so the first sandbox create does
# not pay the full registry pull cost inside the cluster.
DEFAULT_SANDBOX_PRELOAD_IMAGE="nvcr.io/nvidia/base/ubuntu:24.04"
PRELOAD_SANDBOX_IMAGE="${HELM_K3S_PRELOAD_SANDBOX_IMAGE-${DEFAULT_SANDBOX_PRELOAD_IMAGE}}"
AGENT_SANDBOX_VERSION="${AGENT_SANDBOX_VERSION:-v1.0.3}"
OBSERVABILITY_NAMESPACE="observability"
COLLECTOR_IMAGE="${HELM_K3S_COLLECTOR_IMAGE:-mcr.microsoft.com/dotnet/aspire-dashboard:latest}"
COLLECTOR_HEALTH_TIMEOUT="${HELM_K3S_COLLECTOR_HEALTH_TIMEOUT:-120}"
GATEWAY_NAMESPACE="openshell"
GATEWAY_HOST_PORT="${HELM_K3S_GATEWAY_HOST_PORT:-8090}"
GATEWAY_NAME="${HELM_K3S_GATEWAY_NAME:-${CLUSTER_NAME}}"
FORWARD_PIDS=()
default_kubeconfig="${ROOT}/kubeconfig"
if [[ -n "${HELM_K3S_KUBECONFIG:-}" ]]; then
  KUBECONFIG_TARGET="${HELM_K3S_KUBECONFIG}"
elif [[ -n "${KUBECONFIG:-}" ]]; then
  if [[ "${KUBECONFIG}" != *:* ]]; then
    KUBECONFIG_TARGET="${KUBECONFIG}"
... (444 lines truncated)
</file>

<file path="tasks/scripts/keycloak-k8s-setup.sh">
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT="$(cd "${SCRIPT_DIR}/../.." && pwd)"
NAMESPACE="keycloak"
GATEWAY_NAMESPACE="${OPENSHELL_NAMESPACE:-openshell}"
KEYCLOAK_IMAGE="${KEYCLOAK_IMAGE:-quay.io/keycloak/keycloak:24.0}"
ADMIN_USER="${KEYCLOAK_ADMIN_USER:-admin}"
ADMIN_PASSWORD="${KEYCLOAK_ADMIN_PASSWORD:-admin}"
SETUP_PORT="${KEYCLOAK_SETUP_PORT:-9090}"
REALM_FILE="${ROOT}/scripts/keycloak-realm.json"
HEALTH_TIMEOUT="${KEYCLOAK_HEALTH_TIMEOUT:-120}"
SVC_HOSTNAME="keycloak.${NAMESPACE}.svc.cluster.local"
TLS_DIR="$(mktemp -d)"
trap 'rm -rf "${TLS_DIR}"' EXIT
if [[ ! -f "${REALM_FILE}" ]]; then
    echo "error: realm file not found: ${REALM_FILE}" >&2
    exit 1
fi
echo "Creating namespace '${NAMESPACE}'..."
kubectl create namespace "${NAMESPACE}" --dry-run=client -o yaml | kubectl apply -f -
echo "Applying realm ConfigMap..."
kubectl -n "${NAMESPACE}" create configmap openshell-realm \
    --from-file=realm.json="${REALM_FILE}" \
    --dry-run=client -o yaml | kubectl apply -f -
echo "Generating a development TLS certificate for '${SVC_HOSTNAME}'..."
openssl req -x509 -newkey rsa:2048 -nodes \
    -keyout "${TLS_DIR}/ca.key" \
    -out "${TLS_DIR}/ca.crt" \
    -days 30 \
    -subj "/CN=OpenShell development Keycloak CA" \
... (143 lines truncated)
</file>

<file path="tasks/scripts/package-deb-install.sh">
set -euo pipefail
repo_root="$(cd "$(dirname "$0")/../.." && pwd)"
cd "$repo_root"
VERSION="${OPENSHELL_DEB_VERSION:-0.0.0-local}"
OUTPUT_DIR="${OPENSHELL_OUTPUT_DIR:-artifacts}"
ARCH="${OPENSHELL_DEB_ARCH:-$(dpkg --print-architecture 2>/dev/null || uname -m)}"
GATEWAY_NAME="openshell"
GATEWAY_ENDPOINT="https://127.0.0.1:17670"
remove_existing_gateway_registration() {
	local config_home="${XDG_CONFIG_HOME:-${HOME}/.config}"
	local openshell_config_dir="${config_home}/openshell"
	local gateway_dir="${openshell_config_dir}/gateways/${GATEWAY_NAME}"
	local active_gateway_path="${openshell_config_dir}/active_gateway"
	if [ ! -f "${gateway_dir}/metadata.json" ]; then
		return
	fi
	echo "==> Removing existing ${GATEWAY_NAME} gateway registration"
	rm -f \
		"${gateway_dir}/metadata.json" \
		"${gateway_dir}/edge_token" \
		"${gateway_dir}/cf_token" \
		"${gateway_dir}/oidc_token.json"
	if [ -f "$active_gateway_path" ] && [ "$(cat "$active_gateway_path")" = "$GATEWAY_NAME" ]; then
		rm -f "$active_gateway_path"
	fi
}
echo "==> Building release binaries"
cargo build --release \
	-p openshell-cli \
	-p openshell-gateway \
... (29 lines truncated)
</file>

<file path="tasks/scripts/package-deb.sh">
set -euo pipefail
APP_NAME="openshell"
usage() {
	cat <<'EOF'
Build the openshell Debian package.
Required environment:
  OPENSHELL_CLI_BINARY        Path to openshell
  OPENSHELL_GATEWAY_BINARY    Path to openshell-gateway
  OPENSHELL_PROVER_BINARY     Path to openshell-prover
  OPENSHELL_DRIVER_VM_BINARY  Path to openshell-driver-vm
  OPENSHELL_DEB_VERSION       Debian package version
Optional environment:
  OPENSHELL_DEB_ARCH          Debian architecture (amd64 or arm64; defaults to host arch)
  OPENSHELL_OUTPUT_DIR        Output directory (default: artifacts)
EOF
}
require_env() {
	local name="$1"
	if [ -z "${!name:-}" ]; then
		echo "error: ${name} is required" >&2
		usage >&2
		exit 2
	fi
}
stage_binary() {
	local src="$1"
	local dst="$2"
	if [ ! -x "$src" ]; then
		echo "error: binary is missing or not executable: ${src}" >&2
		exit 1
... (78 lines truncated)
</file>

<file path="tasks/scripts/release.py">
SEMVER_TAG_RE = re.compile(r"^v?(?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+)$")
PRERELEASE_TAG_RE = re.compile(
⋮----
@dataclass(frozen=True)
class Versions
⋮----
python: str
cargo: str
npm: str
docker: str
deb: str
snap: str
rpm_version: str
rpm_release: str
git_tag: str
git_sha: str
git_distance: int
⋮----
HOMEBREW_TARGET = "aarch64-apple-darwin"
HOMEBREW_CLI_ASSET = f"openshell-{HOMEBREW_TARGET}.tar.gz"
HOMEBREW_GATEWAY_ASSET = f"openshell-gateway-{HOMEBREW_TARGET}.tar.gz"
HOMEBREW_DRIVER_VM_ASSET = f"openshell-driver-vm-{HOMEBREW_TARGET}.tar.gz"
HOMEBREW_PROVER_ASSET = f"openshell-prover-{HOMEBREW_TARGET}.tar.gz"
GITHUB_RELEASE_DOWNLOADS = "https://github.com/NVIDIA/OpenShell/releases/download"
LOCAL_GATEWAY_PORT = 17670
_SHA256_RE = re.compile(r"^[0-9a-fA-F]{64}$")
_RELEASE_TAG_RE = re.compile(r"^[A-Za-z0-9._-]+$")
⋮----
def _repo_root() -> Path
⋮----
... (119 lines truncated)
</file>

<file path="tasks/scripts/run-git-bash.ps1">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

param(
    [Parameter(Mandatory = $true, Position = 0)]
    [string]$Script,
    [Parameter(ValueFromRemainingArguments = $true)]
    [string[]]$Arguments
)

$ErrorActionPreference = "Stop"

$gitCommand = Get-Command git.exe -ErrorAction Stop
$gitRoot = Split-Path -Parent $gitCommand.Source
$bash = $null
# Git can expose cmd/git.exe, mingw64/bin/git.exe, or clangarm64/bin/git.exe.
for ($level = 0; $level -lt 4 -and $gitRoot; $level++) {
    $candidate = Join-Path $gitRoot 'bin\bash.exe'
    if (Test-Path -LiteralPath $candidate -PathType Leaf) {
        $bash = $candidate
        break
    }
    $gitRoot = Split-Path -Parent $gitRoot
}
if (-not $bash) {
    throw "Git for Windows bash.exe was not found beside $($gitCommand.Source)"
}

$repoRoot = (& git rev-parse --show-toplevel).Trim()
if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($repoRoot)) {
... (61 lines truncated)
</file>

<file path="tasks/scripts/sandbox.sh">
set -euo pipefail
SANDBOX_NAME="dev"
read -r -a CMD <<< "${usage_command:-claude}"
if ! openshell status >/dev/null 2>&1; then
  echo "No reachable OpenShell gateway." >&2
  echo "Start one in another shell with: mise run gateway:docker" >&2
  echo "Or register/select an existing gateway with: openshell gateway add <endpoint>" >&2
  exit 2
fi
need_create=1
if openshell sandbox get "${SANDBOX_NAME}" >/dev/null 2>&1; then
  need_create=0
fi
ensure_anthropic_provider() {
  if [[ -z "${ANTHROPIC_API_KEY:-}" ]]; then
    return
  fi
  if openshell provider get anthropic >/dev/null 2>&1; then
    return
  fi
  echo "Registering anthropic provider..."
  openshell provider create \
    --name anthropic \
    --type claude-code \
    --credential "ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY}"
}
ensure_anthropic_provider
PROVIDER_ARGS=()
if openshell provider get anthropic >/dev/null 2>&1; then
  PROVIDER_ARGS+=(--provider anthropic)
... (9 lines truncated)
</file>

<file path="tasks/scripts/setup-zig-cc-wrapper.sh">
set -euo pipefail
usage() {
  echo "Usage: setup-zig-cc-wrapper.sh <cargo-target> <zig-target> <wrapper-dir>" >&2
}
if [[ $
  usage
  exit 2
fi
cargo_target=$1
zig_target=$2
wrapper_dir=$3
bare_cargo_target=$cargo_target
if [[ $bare_cargo_target =~ ^(.+)\.[0-9]+\.[0-9]+$ ]]; then
  bare_cargo_target=${BASH_REMATCH[1]}
fi
zig_cc_target=${zig_target/-unknown-linux-/-linux-}
if [[ -n ${ZIG:-} ]]; then
  zig=$ZIG
elif command -v mise >/dev/null 2>&1; then
  zig=$(mise which zig)
else
  zig=$(command -v zig)
fi
mkdir -p "$wrapper_dir"
for tool in cc c++; do
  cat >"$wrapper_dir/$tool" <<EOF
set -euo pipefail
args=()
skip_next=0
for arg in "\$@"; do
... (89 lines truncated)
</file>

<file path="tasks/scripts/snap-gateway-wrapper.sh">
set -eu
CANONICAL_CONFIG_FILE="${SNAP_COMMON}/gateway.toml"
export OPENSHELL_DB_URL="${OPENSHELL_DB_URL:-sqlite:${SNAP_COMMON}/gateway.db?mode=rwc}"
export OPENSHELL_LOCAL_TLS_DIR="${OPENSHELL_LOCAL_TLS_DIR:-${SNAP_COMMON}/tls}"
cli_config=""
config_seen=false
expect_config_path=false
options_done=false
for argument in "$@"; do
    if [ "$options_done" = true ]; then
        continue
    fi
    if [ "$expect_config_path" = true ]; then
        case "$argument" in
            -*)
                echo "openshell-gateway: --config requires a nonempty path" >&2
                exit 2
                ;;
        esac
        if [ "$config_seen" = true ]; then
            echo "openshell-gateway: duplicate --config option" >&2
            exit 2
        fi
        cli_config=$argument
        config_seen=true
        expect_config_path=false
        continue
    fi
    case "$argument" in
        --)
... (36 lines truncated)
</file>

<file path="tasks/scripts/stage-prebuilt-binaries.sh">
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT="$(cd "${SCRIPT_DIR}/../.." && pwd)"
source "${SCRIPT_DIR}/build-env.sh"
usage() {
  echo "Usage: stage-prebuilt-binaries.sh <gateway|sandbox|supervisor|supervisor-output|all>" >&2
}
normalize_arch() {
  case "$1" in
    x86_64|amd64) echo "amd64" ;;
    aarch64|arm64) echo "arm64" ;;
    *) echo "$1" ;;
  esac
}
target_triple() {
  local libc=${2:-gnu}
  local suffix
  case "$libc" in
    musl) suffix=musl ;;
    gnu) suffix=gnu ;;
    *)
      echo "unsupported libc: $libc" >&2
      exit 1
      ;;
  esac
  case "$1" in
    amd64) echo "x86_64-unknown-linux-${suffix}" ;;
    arm64) echo "aarch64-unknown-linux-${suffix}" ;;
    *)
      echo "unsupported architecture: $1" >&2
... (211 lines truncated)
</file>

<file path="tasks/scripts/sync_docs_website_test.py">
def read_yaml(path: Path) -> dict
⋮----
def read_workflow(name: str) -> dict
⋮----
path = Path(__file__).resolve().parents[2] / ".github" / "workflows" / name
⋮----
def test_release_workflows_sync_and_publish_docs_once() -> None
⋮----
dev = read_workflow("release-dev.yml")
tag = read_workflow("release-tag.yml")
dev_job = dev["jobs"]["publish-fern-docs"]
tag_job = tag["jobs"]["publish-fern-docs"]
⋮----
workflow_path = (
workflow_text = workflow_path.read_text(encoding="utf-8")
⋮----
def test_sync_workflow_serializes_sync_and_publish() -> None
⋮----
workflow = read_workflow("sync-docs.yml")
triggers = workflow["on"]
publish_input = triggers["workflow_call"]["inputs"]["publish"]
⋮----
publish_workflow = read_workflow("publish-docs-website.yml")
⋮----
steps = workflow["jobs"]["sync"]["steps"]
step_names = [step["name"] for step in steps]
⋮----
publish_step = next(step for step in steps if step["name"] == "Publish Fern docs")
⋮----
update_step = next(step for step in steps if step["name"] == "Update docs snapshot")
... (137 lines truncated)
</file>

<file path="tasks/scripts/sync_docs_website.py">
SLUG_RE = re.compile(r"^[A-Za-z0-9._-]+$")
DISPLAY_VERSION_RE = re.compile(r"\bv?(\d+\.\d+\.\d+(?:[.-]?[A-Za-z0-9]+)*)\b")
VERSION_AVAILABILITIES = {"beta", "deprecated", "ga", "stable"}
SNAPSHOT_METADATA_FILE = ".docs-snapshots.yml"
YamlMapping = dict[str, object]
⋮----
@dataclass
class VersionEntry
⋮----
slug: str
display_name: str
path: str
availability: str | None = None
announcement: YamlMapping | None = None
⋮----
def parse_args() -> argparse.Namespace
⋮----
parser = argparse.ArgumentParser(
⋮----
def clean_input(value: str | None) -> str
⋮----
def resolve_slug(channel: str, version_slug: str) -> str
⋮----
def resolve_availability(override: str) -> str | None
⋮----
availability = override
⋮----
supported = ", ".join(sorted(VERSION_AVAILABILITIES))
⋮----
def parse_release_version(value: str) -> Version
... (167 lines truncated)
</file>

<file path="tasks/scripts/test-build-env.sh">
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${SCRIPT_DIR}/build-env.sh"
pass() { echo "PASS: $1"; }
fail() {
  echo "FAIL: $1" >&2
  exit 1
}
if ! declare -F ensure_build_nofile_limit >/dev/null; then
  fail "ensure_build_nofile_limit not defined after sourcing build-env.sh"
fi
pass "ensure_build_nofile_limit is defined"
os="$(uname -s)"
if [ "${os}" != "Darwin" ]; then
  (
    ulimit -Sn 256 2>/dev/null || true
    before="$(ulimit -n)"
    ensure_build_nofile_limit >/dev/null
    after="$(ulimit -n)"
    [ "${before}" = "${after}" ] || fail "limit changed on non-Darwin host (${before} -> ${after})"
  )
  pass "no-op on non-Darwin host (${os})"
  echo "All build-env tests passed."
  exit 0
fi
if ! command -v cargo-zigbuild >/dev/null 2>&1; then
  (
    ulimit -Sn 256 2>/dev/null || true
    before="$(ulimit -n)"
    ensure_build_nofile_limit >/dev/null
... (39 lines truncated)
</file>

<file path="tasks/scripts/test-e2e-image-overrides.sh">
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
source "${ROOT}/e2e/support/gateway-common.sh"
assert_resolves() {
  local description=$1
  local expected=$2
  shift 2
  local actual
  actual="$(e2e_resolve_image_reference "$@")"
  if [ "${actual}" != "${expected}" ]; then
    echo "FAIL: ${description}: expected '${expected}', got '${actual}'" >&2
    exit 1
  fi
}
assert_resolves "repository inherits tag" \
  "registry.example/gateway:test" \
  "registry.example/gateway" test
assert_resolves "repository trims trailing slash" \
  "registry.example/gateway:test" \
  "registry.example/gateway/" test
assert_resolves "tagged reference is unchanged" \
  "registry.example/gateway:branch" \
  "registry.example/gateway:branch" test
assert_resolves "digest reference is unchanged" \
  "registry.example/gateway@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" \
  "registry.example/gateway@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" test
assert_resolves "registry port inherits tag" \
  "localhost:5000/openshell/gateway:test" \
  "localhost:5000/openshell/gateway" test
if e2e_image_reference_is_complete "registry.example/gateway:branch" \
... (67 lines truncated)
</file>

<file path="tasks/scripts/test-gateway-config.sh">
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
WORK="$(mktemp -d)"
UV="$(mise which uv)"
trap 'rm -rf "${WORK}"' EXIT
source "${ROOT}/tasks/scripts/gateway-toml.sh"
raw=$'quote" slash\\ newline\ncarriage\rtab\t'
printf 'value = "' > "${WORK}/escaped.toml"
toml_escape "${raw}" >> "${WORK}/escaped.toml"
printf '"\n' >> "${WORK}/escaped.toml"
printf '%s\n' 'import sys, tomllib' 'from pathlib import Path' 'assert tomllib.loads(Path(sys.argv[1]).read_text())["value"] == sys.argv[2]' > "${WORK}/check_escape.py"
"${UV}" run --no-project python "${WORK}/check_escape.py" "${WORK}/escaped.toml" "${raw}"
mkdir -p "${WORK}/bin"
ln -s /usr/bin/true "${WORK}/bin/mise"
ln -s /usr/bin/false "${WORK}/bin/lsof"
printf '%s\n' '#!/usr/bin/env bash' 'config=""' 'while [ "$#" -gt 0 ]; do' '  if [ "$1" = "--config" ]; then config="$2"; shift 2; else shift; fi' 'done' 'if [ -n "${config}" ]; then cp "${config}" "${CAPTURED_CONFIG}"; fi' > "${WORK}/bin/gateway"
chmod +x "${WORK}/bin/gateway"
CAPTURED_CONFIG="${WORK}/generated.toml"
CAPTURED_CONFIG="${WORK}/generated.toml" PATH="${WORK}/bin:${PATH}" KUBERNETES_SERVICE_HOST=fixture OPENSHELL_GATEWAY_BIN="${WORK}/bin/gateway" OPENSHELL_GATEWAY_STATE_DIR="${WORK}/state" OPENSHELL_SANDBOX_IMAGE_PULL_POLICY=IfNotPresent OPENSHELL_GRPC_ENDPOINT=https://callback.example.test:9443 bash "${ROOT}/tasks/scripts/gateway.sh"
printf '%s\n' 'import sys, tomllib' 'from pathlib import Path' 'config = tomllib.loads(Path(sys.argv[1]).read_text())' 'gateway = config["openshell"]["gateway"]' 'driver = config["openshell"]["drivers"]["kubernetes"]' 'assert config["openshell"]["version"] == 2' 'assert gateway["compute_driver"] == "kubernetes"' 'assert "compute_drivers" not in gateway' 'assert driver["image_pull_policy"] == "if_not_present"' 'assert driver["grpc_endpoint"] == "https://callback.example.test:9443"' > "${WORK}/check_generated.py"
"${UV}" run --no-project python "${WORK}/check_generated.py" "${CAPTURED_CONFIG}"
echo "gateway generated-TOML tests passed"
</file>

<file path="tasks/scripts/test-gateway-pull-policy.sh">
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
source "${ROOT}/tasks/scripts/gateway-pull-policy.sh"
assert_policy() {
  local input=$1
  local expected=$2
  local actual
  actual="$(normalize_image_pull_policy "${input}")"
  if [[ "${actual}" != "${expected}" ]]; then
    printf 'expected %q -> %q, got %q\n' "${input}" "${expected}" "${actual}" >&2
    exit 1
  fi
}
for input in always Always ALWAYS; do
  assert_policy "${input}" always
done
for input in if_not_present IfNotPresent ifnotpresent IFNOTPRESENT missing MISSING; do
  assert_policy "${input}" if_not_present
done
for input in never Never NEVER; do
  assert_policy "${input}" never
done
for input in newer Newer NEWER; do
  assert_policy "${input}" newer
done
if normalize_image_pull_policy sometimes >/dev/null 2>&1; then
  echo "unsupported policy unexpectedly succeeded" >&2
  exit 1
fi
for script in gateway.sh gateway-docker.sh gateway-podman.sh; do
... (28 lines truncated)
</file>

<file path="tasks/scripts/test-install-sh.sh">
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
tmpdir="$(mktemp -d)"
trap 'rm -rf "$tmpdir"' EXIT
out="${tmpdir}/out"
err="${tmpdir}/err"
export OPENSHELL_INSTALL_SH_TEST=1
. "${ROOT}/install.sh"
assert_glibc_preflight_passes() {
  local name=$1
  local ldd_output=$2
  if ! (export OPENSHELL_TEST_GETCONF_UNAVAILABLE=1 OPENSHELL_TEST_LDD_OUTPUT="$ldd_output"; require_linux_package_glibc) >"$out" 2>"$err"; then
    echo "FAIL: ${name}" >&2
    cat "$err" >&2 || true
    exit 1
  fi
}
assert_glibc_preflight_fails() {
  local name=$1
  local expected=$2
  local setup=$3
  if ("$setup"; require_linux_package_glibc) >"$out" 2>"$err"; then
    echo "FAIL: ${name}: expected failure" >&2
    exit 1
  fi
  if ! grep -Fq "$expected" "$err"; then
    echo "FAIL: ${name}: missing expected message" >&2
    echo "Expected: ${expected}" >&2
    echo "Actual:" >&2
    cat "$err" >&2 || true
... (611 lines truncated)
</file>

<file path="tasks/scripts/test-packaging-assets.sh">
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
assert_contains() {
  local file=$1
  local expected=$2
  if ! grep -Fq -- "$expected" "$file"; then
    echo "FAIL: ${file} is missing expected text:" >&2
    echo "  ${expected}" >&2
    exit 1
  fi
}
assert_not_contains() {
  local file=$1
  local unexpected=$2
  if grep -Fq -- "$unexpected" "$file"; then
    echo "FAIL: ${file} contains stale text:" >&2
    echo "  ${unexpected}" >&2
    exit 1
  fi
}
assert_file_exists() {
  local file=$1
  if [[ ! -f "$file" ]]; then
    echo "ERROR: ${file} not found" >&2
    exit 1
  fi
}
service="${ROOT}/deploy/deb/openshell-gateway.service"
control="${ROOT}/deploy/deb/control.in"
spec="${ROOT}/openshell.spec"
... (139 lines truncated)
</file>

<file path="tasks/scripts/test-qualification-summary.sh">
set -euo pipefail
SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
GENERATOR="${SCRIPT_DIR}/generate-qualification-summary.sh"
TEST_DIR=$(mktemp -d)
trap 'rm -rf "${TEST_DIR}"' EXIT
export RELEASE_TAG=v0.1.0-pre.8
export SOURCE_SHA=0123456789abcdef0123456789abcdef01234567
export IS_PRERELEASE=true
export GITHUB_REPOSITORY=NVIDIA/OpenShell
export GITHUB_SERVER_URL=https://github.com
export GITHUB_RUN_ID=1234
export GITHUB_RUN_ATTEMPT=2
export SECURITY_RESULT=failure
export CONFORMANCE_RESULT=success
export FEATURE_INTEGRATION_RESULT=success
export DOCKER_E2E_RESULT=success
export VM_E2E_RESULT=success
current_profile_passed=$("${GENERATOR}" "${TEST_DIR}/qualification-summary.json")
[[ "${current_profile_passed}" == "false" ]]
jq -e '
  .schema_version == 1
  and .tag == "v0.1.0-pre.8"
  and .source_sha == "0123456789abcdef0123456789abcdef01234567"
  and .is_prerelease == true
  and .current_profile_passed == false
  and .profile.rfc_0014_complete == false
  and .suites.security == "failure"
  and .run.id == "1234"
  and .run.attempt == "2"
' "${TEST_DIR}/qualification-summary.json" >/dev/null
... (6 lines truncated)
</file>

<file path="tasks/scripts/test-snap-gateway-wrapper.sh">
set -euo pipefail
wrapper_input=${1:?Usage: test-snap-gateway-wrapper.sh <wrapper>}
wrapper_dir=$(cd "$(dirname "$wrapper_input")" && pwd)
wrapper="${wrapper_dir}/$(basename "$wrapper_input")"
work=$(mktemp -d "${TMPDIR:-/tmp}/openshell snap wrapper.XXXXXX")
trap 'rm -rf "$work"' EXIT
snap="$work/snap"
common="$work/common"
log="$work/calls"
expected="$work/expected"
mkdir -p "$snap/bin" "$common"
cat >"$snap/bin/openshell-gateway" <<'EOF'
printf '%s\n' "$*" >>"$FAKE_GATEWAY_LOG"
if [ "${1:-}" = generate-certs ]; then
  exit 0
fi
printf 'env:%s|%s|%s\n' \
  "${OPENSHELL_GATEWAY_CONFIG:-}" \
  "${OPENSHELL_DB_URL:-}" \
  "${OPENSHELL_DISABLE_TLS:-}" >>"$FAKE_GATEWAY_LOG"
if [ "${1:-}" = config ] && [ "${2:-}" = preflight ]; then
  if [ "${FAKE_PREFLIGHT_FAIL:-}" = 1 ]; then
    exit 42
  fi
  if [ "${FAKE_REJECT_UNPAIRED_RATE:-}" = 1 ]; then
    case " $* " in
      *" --grpc-rate-limit-requests "*)
        case " $* " in
          *" --grpc-rate-limit-window-seconds "*) ;;
          *) exit 43 ;;
... (170 lines truncated)
</file>

<file path="tasks/scripts/test-snap-install-hook.sh">
set -euo pipefail
hook_input=${1:?Usage: test-snap-install-hook.sh <install-hook>}
hook_dir=$(cd "$(dirname "$hook_input")" && pwd)
hook="${hook_dir}/$(basename "$hook_input")"
work=$(mktemp -d "${TMPDIR:-/tmp}/openshell snap install hook.XXXXXX")
trap 'rm -rf "$work"' EXIT
expected="${work}/expected.toml"
cat >"$expected" <<'EOF'
[openshell]
version = 2
[openshell.gateway]
EOF
legacy="${work}/legacy.toml"
cat >"$legacy" <<'EOF'
[openshell]
version = 2
[openshell.gateway]
[openshell.gateway.auth]
allow_unauthenticated_users = true
EOF
common="${work}/fresh"
SNAP_COMMON="$common" "$hook"
cmp -s "$expected" "$common/gateway.toml"
if [[ -z $(find "$common/gateway.toml" -perm 600) ]]; then
  echo "FAIL: install hook config must be mode 0600" >&2
  exit 1
fi
printf '\noperator setting = true\n' >>"$common/gateway.toml"
cp "$common/gateway.toml" "${work}/operator-before"
SNAP_COMMON="$common" "$hook"
... (87 lines truncated)
</file>

<file path="tasks/scripts/trivy-config-report.jq">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

# Inputs are raw, repository-relative Trivy config reports. Consolidation is
# presentation only: the gate continues comparing unmodified reports per profile.
if length == 0 or any(.[];
  .SchemaVersion != 2
  or (.ArtifactName | type) != "string"
  or (.ArtifactType | type) != "string"
  or (.TrivyProfile | type) != "string"
  or (.Results != null and (.Results | type) != "array")
) then error("invalid Trivy configuration reports") else . end
| .[0] as $template
| [
    .[] as $report
    | $report.Results[]?
    | (.Misconfigurations[]?.TrivyProfile) = $report.TrivyProfile
  ] as $results
| $template
| .ArtifactName = "deployment configuration (all profiles)"
| del(.TrivyProfile)
| .Results = (
    $results
    | group_by([.Target, .Class, .Type])
    | map(
        . as $targets
        | .[0]
        | .Misconfigurations = (
            [$targets[] | .Misconfigurations[]?]
            | group_by([
... (19 lines truncated)
</file>

<file path="tasks/scripts/trivy-scan-test.sh">
set -euo pipefail
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
SCANNER="${REPO_ROOT}/tasks/scripts/trivy-scan.sh"
TMP_DIR="$(mktemp -d)"
trap 'rm -rf "${TMP_DIR}"' EXIT
export GITHUB_OUTPUT="${TMP_DIR}/github-output"
export GITHUB_STEP_SUMMARY="${TMP_DIR}/github-summary"
make_case() {
  BASE="${TMP_DIR}/$1/base"
  HEAD="${TMP_DIR}/$1/head"
  mkdir -p "${BASE}" "${HEAD}"
}
write_report() {
  local path=$1 count=$2 profile
  profile="$(basename "${path}" .json)"
  jq -n --argjson count "${count}" --arg profile "${profile}" '
    {
      SchemaVersion: 2,
      ArtifactName: "deploy",
      ArtifactType: "filesystem",
      TrivyProfile: $profile,
      Results: (if $count == 0 then [] else [{
        Target: "deploy/helm/openshell/templates/clusterrole.yaml",
        Class: "config",
        Type: "kubernetes",
        MisconfSummary: {Successes: 0, Failures: $count, Exceptions: 0},
        Misconfigurations: [
          range(0; $count) | {
            ID: "KSV-0041",
            Title: "Manage secrets",
... (183 lines truncated)
</file>

<file path="tasks/scripts/trivy-scan.sh">
set -euo pipefail
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
SOURCE_ROOT="${TRIVY_SOURCE_ROOT:-${REPO_ROOT}}"
IGNORE_FILE="${TRIVY_IGNORE_FILE:-${REPO_ROOT}/.trivyignore.yaml}"
cd "${SOURCE_ROOT}"
SEVERITY="${TRIVY_SEVERITY:-HIGH,CRITICAL}"
REPORT_DIR="${TRIVY_REPORT_DIR:-reports/trivy}"
IGNORE_UNFIXED="${TRIVY_IGNORE_UNFIXED:-true}"
PLATFORMS="${TRIVY_PLATFORMS:-linux/amd64 linux/arm64}"
PREFLIGHT_OFF=(--helm-set agentSandbox.preflight.enabled=false)
SKIP_DOCKERFILES=(
  --skip-files 'deploy/docker/Dockerfile.ci'
  --skip-files 'deploy/docker/Dockerfile.*-macos'
)
HELM_PROFILES=(
  cert-manager credential-driver-kubernetes-secrets credential-driver-vault
  gateway gateway-tls high-availability openshift-route-cert-manager spire
  tls-disabled workspace-managed workspace-operator
  corporate-proxy-e2e keycloak skaffold
)
validate_ignore_file() {
  [ -f "${IGNORE_FILE}" ] || {
    echo "Error: Trivy ignore file not found: ${IGNORE_FILE}" >&2
    return 2
  }
  command -v yq >/dev/null || {
    echo "Error: yq not on PATH; run inside 'nix develop'" >&2
    return 2
  }
  if ! yq --output-format json '.' "${IGNORE_FILE}" |
... (356 lines truncated)
</file>

<file path="tasks/scripts/typescript-install.ps1">
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

[CmdletBinding()]
param()

Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'

$nodeArchitecture = (& node -p "process.arch").Trim()
if ($LASTEXITCODE -ne 0) {
    throw "Unable to determine the Node.js process architecture (exit code $LASTEXITCODE)."
}
if ($nodeArchitecture -notin @('x64', 'arm64')) {
    throw "Unsupported Windows Node.js architecture '$nodeArchitecture'."
}

$previousCpu = $env:npm_config_cpu
try {
    $env:npm_config_cpu = $nodeArchitecture
    & npm ci
    if ($LASTEXITCODE -ne 0) {
        throw "Unable to install TypeScript SDK dependencies (exit code $LASTEXITCODE)."
    }
}
finally {
    $env:npm_config_cpu = $previousCpu
}

$nativePackages = @(
... (11 lines truncated)
</file>

<file path="tasks/scripts/typescript-proto.ps1">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

[CmdletBinding()]
param()

Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'

$repository = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path
$sdkRoot = Join-Path $repository 'sdk\typescript'
$sourceTemplate = Join-Path $sdkRoot 'buf.gen.yaml'
$buf = (Resolve-Path (Join-Path $sdkRoot 'node_modules\.bin\buf.cmd')).Path
$plugin = (Resolve-Path (Join-Path $sdkRoot 'node_modules\.bin\protoc-gen-es.cmd')).Path
$temporaryRoot = Join-Path ([IO.Path]::GetTempPath()) "openshell-ts-proto-$([guid]::NewGuid().ToString('N'))"
$windowsTemplate = Join-Path $temporaryRoot 'buf.gen.windows.yaml'
$tempPrefix = [IO.Path]::GetFullPath([IO.Path]::GetTempPath()).TrimEnd('\', '/') + [IO.Path]::DirectorySeparatorChar
if (-not [IO.Path]::GetFullPath($temporaryRoot).StartsWith($tempPrefix, [StringComparison]::OrdinalIgnoreCase)) {
    throw 'Protobuf temporary directory escaped the temporary root'
}

New-Item -ItemType Directory -Path $temporaryRoot | Out-Null
try {
    $pluginPath = $plugin.Replace('\', '/')
    $template = [IO.File]::ReadAllText($sourceTemplate).Replace(
        './node_modules/.bin/protoc-gen-es',
        $pluginPath
    )
    [IO.File]::WriteAllText(
        $windowsTemplate,
... (29 lines truncated)
</file>

<file path="tasks/scripts/verify-defaults-without-telemetry.sh">
set -euo pipefail
CRATES=(
  openshell-gateway
  openshell-supervisor
  openshell-driver-vm
)
if ! command -v jq >/dev/null 2>&1; then
  echo "error: 'jq' is required to inspect cargo metadata" >&2
  exit 2
fi
metadata=$(cargo metadata --no-deps --format-version 1)
failed=0
for crate in "${CRATES[@]}"; do
  features=$(jq -c --arg crate "$crate" \
    '.packages[] | select(.name == $crate) | .features' <<<"$metadata")
  if [[ -z $features || $features == "null" ]]; then
    echo "FAIL: crate '$crate' not found in workspace metadata" >&2
    failed=1
    continue
  fi
  if ! jq -e 'has("defaults-without-telemetry")' <<<"$features" >/dev/null; then
    echo "FAIL: $crate defines no 'defaults-without-telemetry' feature" >&2
    failed=1
    continue
  fi
  expected=$(jq -r '(.default // []) - ["telemetry"] | sort | join(",")' <<<"$features")
  actual=$(jq -r '(."defaults-without-telemetry" // []) | sort | join(",")' <<<"$features")
  if [[ $expected != "$actual" ]]; then
    echo "FAIL: $crate 'defaults-without-telemetry' is out of sync with 'default'" >&2
    echo "      default minus telemetry:    [${expected}]" >&2
... (21 lines truncated)
</file>

<file path="tasks/scripts/verify-glibc-symbols.sh">
set -euo pipefail
usage() {
  echo "Usage: verify-glibc-symbols.sh <max-glibc-version> <binary> [binary ...]" >&2
}
version_gt() {
  local left=$1
  local right=$2
  local left_major=${left%%.*}
  local left_minor=${left
  local right_major=${right%%.*}
  local right_minor=${right
  left_minor=${left_minor%%.*}
  right_minor=${right_minor%%.*}
  [[ $left_major =~ ^[0-9]+$ && $left_minor =~ ^[0-9]+$ ]] || return 1
  [[ $right_major =~ ^[0-9]+$ && $right_minor =~ ^[0-9]+$ ]] || return 1
  (( left_major > right_major )) && return 0
  (( left_major < right_major )) && return 1
  (( left_minor > right_minor ))
}
extract_glibc_versions() {
  local binary=$1
  if command -v readelf >/dev/null 2>&1; then
    readelf --version-info "$binary" 2>/dev/null | grep -oE 'GLIBC_[0-9]+\.[0-9]+' || true
  elif command -v objdump >/dev/null 2>&1; then
    objdump -T "$binary" 2>/dev/null | grep -oE 'GLIBC_[0-9]+\.[0-9]+' || true
  fi
}
if [[ $
  usage
  exit 2
... (46 lines truncated)
</file>

<file path="tasks/scripts/verify-image-sbom.sh">
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${SCRIPT_DIR}/container-engine.sh"
usage() {
  echo "Usage: verify-image-sbom.sh <image-ref> [--require-cargo]" >&2
}
IMAGE=${1:-}
REQUIRE_CARGO=${2:-}
if [[ -z "${IMAGE}" || $
  usage
  exit 2
fi
if ! ce_is_docker; then
  echo "Error: SBOM attestations are produced on the Docker/buildx path; ${CONTAINER_ENGINE} has no imagetools equivalent" >&2
  exit 2
fi
echo "==> Inspecting SBOM attestation of ${IMAGE}"
SBOM_JSON="$(ce buildx imagetools inspect "${IMAGE}" --format '{{ json .SBOM }}')"
COUNTS="$(
  jq -r '
    [.. | objects | .SPDX? | select(type == "object")] as $documents
    | [
        ($documents | length),
        ([$documents[] | .. | strings | select(startswith("pkg:cargo/"))] | length)
      ]
    | @tsv
  ' <<<"${SBOM_JSON}"
)"
read -r SPDX_COUNT CARGO_COUNT <<<"${COUNTS}"
if [[ "${SPDX_COUNT}" -eq 0 ]]; then
... (9 lines truncated)
</file>

<file path="tasks/scripts/verify-python-wheel.py">
PROTO_STEMS = ("datamodel", "openshell", "options", "sandbox")
BYTECODE_SUFFIXES = (".pyc", ".pyo")
NATIVE_SUFFIXES = (".dll", ".dylib", ".exe", ".pyd", ".so")
⋮----
def _find_wheel(path: Path) -> Path
⋮----
wheels = sorted(path.glob("*.whl"))
⋮----
def _required_files() -> set[str]
⋮----
files = {
⋮----
def _single_member(names: set[str], suffix: str) -> str
⋮----
matches = [name for name in names if name.endswith(suffix)]
⋮----
def verify_wheel(path: Path, expected_version: str | None = None) -> Path
⋮----
wheel = _find_wheel(path)
⋮----
names = set(archive.namelist())
missing = sorted(_required_files() - names)
⋮----
scripts = sorted(
⋮----
entry_points = [
⋮----
parser = ConfigParser(interpolation=None)
⋮----
bytecode_files = sorted(
... (20 lines truncated)
</file>

<file path="tasks/scripts/verify-static-binary.sh">
set -euo pipefail
usage() {
  echo "Usage: verify-static-binary.sh <binary> [binary ...]" >&2
}
if [[ $
  usage
  exit 2
fi
READELF=""
for candidate in readelf greadelf llvm-readelf; do
  if command -v "$candidate" >/dev/null 2>&1; then
    READELF=$candidate
    break
  fi
done
if [[ -z $READELF ]]; then
  host_os=""
  command -v uname >/dev/null 2>&1 && host_os=$(uname -s 2>/dev/null || true)
  # Skip only on a host positively identified as non-Linux — e.g. a macOS dev
  # cross-building a Linux musl binary via cargo-zigbuild, where mise installs
  # no binutils. Linux (including CI), or any host whose OS cannot be determined,
  # fails closed so a missing inspector never silently passes. Static linkage is
  # still enforced in CI, which runs on Linux.
  if [[ "$host_os" == "Linux" || -z $host_os ]]; then
    echo "error: readelf (or greadelf/llvm-readelf) is required to inspect binary linkage" >&2
    exit 2
  fi
  echo "warning: no readelf/greadelf/llvm-readelf found on ${host_os}; skipping static-linkage verification." >&2
  echo "         install GNU binutils (greadelf) or LLVM (llvm-readelf) to verify locally; CI enforces it on Linux." >&2
  exit 0
... (94 lines truncated)
</file>

<file path="tasks/scripts/verify-telemetry-compiled-out.sh">
set -euo pipefail
MARKERS=(
  "events.telemetry.data.nvidia.com"
  "415437562476676"
)
usage() {
  echo "Usage: verify-telemetry-compiled-out.sh <present|absent> <binary> [binary ...]" >&2
  echo "  present  assert telemetry markers ARE present (positive control for a telemetry-enabled build)" >&2
  echo "  absent   assert telemetry markers are NOT present (telemetry compiled out)" >&2
}
if [[ $
  usage
  exit 2
fi
mode=$1
shift
case "$mode" in
  present | absent) ;;
  *)
    usage
    exit 2
    ;;
esac
if ! command -v strings >/dev/null 2>&1; then
  echo "error: 'strings' (binutils) is required to inspect the binary" >&2
  exit 2
fi
failed=0
for binary in "$@"; do
  if [[ ! -f $binary ]]; then
... (20 lines truncated)
</file>

<file path="tasks/scripts/windows-msvc.ps1">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

# Windows MSVC build wrapper used by the `windows:*` mise tasks.

[CmdletBinding()]
param(
    [Parameter(Mandatory = $true, Position = 0)]
    [ValidateSet("check", "lint", "build", "test", "test-precommit", "test-unsupported", "artifacts", "ci")]
    [string] $Action,

    [Parameter(Position = 1)]
    [ValidateSet("x86_64-pc-windows-msvc", "aarch64-pc-windows-msvc", "native", "all")]
    [string] $Target = "all",

    [string] $LogDir
)

Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"

if (-not [System.Runtime.InteropServices.RuntimeInformation]::IsOSPlatform([System.Runtime.InteropServices.OSPlatform]::Windows)) {
    throw "windows-msvc.ps1 requires a Windows MSVC host."
}

$RepoRoot = (Resolve-Path (Join-Path $PSScriptRoot "..\..")).Path
if (-not $LogDir) {
    $LogDir = $RepoRoot
}
if (-not (Test-Path $LogDir)) {
... (636 lines truncated)
</file>

<file path="tasks/ci.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

# CI, build, and quality tasks

[build]
description = "Build the whole project"
depends = ["build:rust:workspace", "build:docker", "build:python:wheel"]

["build:rust"]
description = "Alias for build:rust:workspace"
depends = ["build:rust:workspace"]
hide = true

["build:rust:workspace"]
description = "Build all Rust crates"
run = "cargo build --workspace"
hide = true

["build:release"]
description = "Alias for build:rust:workspace:release"
depends = ["build:rust:workspace:release"]
hide = true

["build:rust:workspace:release"]
description = "Build all Rust crates in release mode"
run = "cargo build --workspace --release"
hide = true

["build:rust:snap"]
... (52 lines truncated)
</file>

<file path="tasks/docker.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

# Docker image build tasks

["build:docker"]
description = "Build all Docker images"
depends = [
  "build:docker:gateway",
  "build:docker:sandbox",
  "build:docker:supervisor",
]
hide = true

["build:docker:ci"]
description = "Build the CI Docker image"
run = "tasks/scripts/docker-build-ci.sh"
hide = true

["build:docker:prebuilt"]
description = "Build and stage Rust binaries consumed by Docker image builds"
run = "tasks/scripts/stage-prebuilt-binaries.sh all"
hide = true

["build:docker:gateway"]
description = "Build the gateway Docker image"
run = "tasks/scripts/docker-build-image.sh gateway"
hide = true

["build:docker:sandbox"]
... (42 lines truncated)
</file>

<file path="tasks/docs.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

# Documentation build, serve, and check tasks

["docs"]
description = "Validate Fern documentation"
depends = ["docs:build:strict", "docs:nav"]

["docs:deps"]
description = "Resolve Fern CLI for docs tasks"
run = """
FERN_VERSION=$(node -p "require('./fern/fern.config.json').version")
npx --yes "fern-api@${FERN_VERSION}" --version
"""

["docs:build:strict"]
description = "Validate docs config and links"
depends = ["docs:deps"]
run = """
FERN_VERSION=$(node -p "require('./fern/fern.config.json').version")
cd fern
npx --yes "fern-api@${FERN_VERSION}" check
"""

["docs:nav"]
description = "Check that docs page URLs match their file paths"
run = "uv run tasks/scripts/check_docs_nav.py"

["docs:serve"]
... (12 lines truncated)
</file>

<file path="tasks/gateway.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

# Standalone gateway tasks

["build:gateway"]
description = "Build the standalone openshell-gateway binary"
run = "cargo build -p openshell-gateway --bin openshell-gateway"
hide = true

["gateway"]
description = "Run a standalone gateway with the detected compute driver"
run = "bash tasks/scripts/gateway.sh"

["gateway:docker"]
description = "Run a standalone gateway with the bundled Docker compute driver"
run = "bash tasks/scripts/gateway-docker.sh"

["gateway:podman"]
description = "Run a standalone gateway with the bundled Podman compute driver"
run = "bash tasks/scripts/gateway-podman.sh"

["gateway:vm"]
description = "Run a standalone gateway with the bundled VM compute driver"
run = "bash tasks/scripts/gateway-vm.sh"
</file>

<file path="tasks/go.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

# Go SDK development, build, lint, and format tasks

["go:test"]
description = "Run Go SDK unit tests with coverage"
dir = "sdk/go"
run = """
#!/usr/bin/env bash
set -euo pipefail

if [ "$(go env GOOS)" = "windows" ] && [ "$(go env GOARCH)" = "arm64" ]; then
  echo "Go race detection is unsupported on windows/arm64; running without -race."
  go test -coverprofile=coverage.out -coverpkg=./openshell/... ./...
else
  go test -coverprofile=coverage.out -coverpkg=./openshell/... -race ./...
fi
"""
hide = true

["go:test:integration"]
description = "Run Go SDK integration tests"
dir = "sdk/go"
run = "go test -tags=integration -race ./..."
hide = true

["go:lint"]
description = "Run Go SDK linter"
dir = "sdk/go"
... (191 lines truncated)
</file>

<file path="tasks/helm.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

# Helm chart tasks

["helm:docs"]
description = "Generate the OpenShell gateway and workspace Helm chart READMEs"
run = """
  helm-docs --chart-search-root deploy/helm/openshell
  helm-docs --chart-search-root deploy/helm/openshell-workspace
"""

["helm:docs:check"]
description = "Verify the openshell Helm chart README is generated and up to date"
run = """
  set -e
  gateway_tmp="$(mktemp)"
  workspace_tmp="$(mktemp)"
  trap 'rm -f "$gateway_tmp" "$workspace_tmp"' EXIT

  helm-docs --chart-search-root deploy/helm/openshell --dry-run > "$gateway_tmp"
  if ! diff -u deploy/helm/openshell/README.md "$gateway_tmp"; then
    echo "Helm chart README is out of sync. Run: mise run helm:docs" >&2
    exit 1
  fi
  helm-docs --chart-search-root deploy/helm/openshell-workspace --dry-run > "$workspace_tmp"
  if ! diff -u deploy/helm/openshell-workspace/README.md "$workspace_tmp"; then
    echo "Workspace Helm chart README is out of sync. Run: mise run helm:docs" >&2
    exit 1
  fi
... (97 lines truncated)
</file>

<file path="tasks/keycloak.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

# Keycloak dev instance for OIDC testing

[keycloak]
description = "Start a local Keycloak instance for OIDC testing"
run = "scripts/keycloak-dev.sh start"

["keycloak:stop"]
description = "Stop and remove the local Keycloak instance"
run = "scripts/keycloak-dev.sh stop"

["keycloak:status"]
description = "Check if the local Keycloak instance is running"
run = "scripts/keycloak-dev.sh status"

["keycloak:k8s:setup"]
description = "Install TLS-enabled Keycloak in the local k3s cluster and import the openshell realm"
run = "tasks/scripts/keycloak-k8s-setup.sh"

["keycloak:k8s:teardown"]
description = "Remove Keycloak from the local k3s cluster"
run = '''
kubectl delete namespace keycloak --ignore-not-found
kubectl -n "${OPENSHELL_NAMESPACE:-openshell}" delete configmap openshell-keycloak-ca --ignore-not-found
'''
</file>

<file path="tasks/license.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

# License header check and update tasks

["license:check"]
description = "Check that all source files have SPDX license headers"
run = "uv run python scripts/update_license_headers.py --check"
hide = true

["license:update"]
description = "Add or update SPDX license headers on all source files"
run = "uv run python scripts/update_license_headers.py"
hide = true
</file>

<file path="tasks/markdown.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

# Markdown and Mermaid linting tasks

["markdown:deps"]
description = "Install Node deps for markdown/mermaid linting from lockfile"
run = "npm --prefix scripts/lint-mermaid ci --no-audit --no-fund --silent"
hide = true
sources = ["scripts/lint-mermaid/package.json", "scripts/lint-mermaid/package-lock.json"]
outputs = ["scripts/lint-mermaid/node_modules/.package-lock.json"]

["markdown:lint:md"]
description = "Lint Markdown files with markdownlint-cli2"
run = "markdownlint-cli2"
hide = true

["markdown:format"]
description = "Auto-fix Markdown lint issues"
run = "markdownlint-cli2 --fix"

["markdown:lint:mermaid"]
description = "Validate Mermaid diagrams in Markdown/MDX files"
depends = ["markdown:deps"]
run = "node scripts/lint-mermaid/lint-mermaid.mjs ."
hide = true

["markdown:lint"]
description = "Run all Markdown and Mermaid linters"
depends = ["markdown:lint:md", "markdown:lint:mermaid"]
... (1 lines truncated)
</file>

<file path="tasks/notices.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

# Third-party license notice generation tasks
#
# Usage:
#   mise run notices    # regenerate THIRD-PARTY-NOTICES at repo root

[notices]
description = "Regenerate THIRD-PARTY-NOTICES with full license texts"
run = "uv run python scripts/generate_third_party_notices.py"
</file>

<file path="tasks/package.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

# Distribution package tasks

["package:deb"]
description = "Build a Debian package from supplied OpenShell binaries"
run = "tasks/scripts/package-deb.sh"
hide = true

["package:deb:amd64"]
description = "Build an amd64 Debian package from supplied OpenShell binaries"
env = { OPENSHELL_DEB_ARCH = "amd64" }
run = "tasks/scripts/package-deb.sh"
hide = true

["package:deb:arm64"]
description = "Build an arm64 Debian package from supplied OpenShell binaries"
env = { OPENSHELL_DEB_ARCH = "arm64" }
run = "tasks/scripts/package-deb.sh"
hide = true

["package:deb:install"]
description = "Build OpenShell from source and install the deb locally (requires sudo)"
run = "tasks/scripts/package-deb-install.sh"
</file>

<file path="tasks/parity.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

["test:e2e-parity"]
description = "Run deterministic schema-v1/schema-v2 parity harness tests"
run = "bash e2e/parity/test.sh"
run_windows = "powershell -NoProfile -ExecutionPolicy Bypass -File tasks/scripts/run-git-bash.ps1 e2e/parity/test.sh"
hide = true

["e2e:parity:podman"]
description = "Compare frozen schema-v1 and current schema-v2 conformance against Podman and retain a fresh evidence directory (opt-in live test)"
run = "bash e2e/parity/run.sh --driver podman"

["e2e:parity:podman-options"]
description = "Compare paired Podman sandbox option semantics and retain a fresh evidence directory (opt-in live test)"
run = "bash e2e/parity/run.sh --driver podman --scenario podman-options"

["e2e:parity:podman-external-driver"]
description = "Compare paired external Podman lifecycle semantics and retain a fresh evidence directory (opt-in live test)"
run = "bash e2e/parity/run.sh --driver podman --scenario external-driver"

["e2e:parity:gateway-options"]
description = "Compare process-level gateway option behavior across schema v1 and v2 (opt-in live test)"
run = "bash e2e/parity/gateway-options.sh"

["test:e2e-parity:kubernetes-options"]
description = "Run deterministic Kubernetes schema parity harness tests"
run = "bash e2e/parity/kubernetes-options-test.sh"
hide = true

... (4 lines truncated)
</file>

<file path="tasks/python.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

# Python development, build, lint, and format tasks

["python:dev"]
description = "Install the Python SDK in development mode"
depends = ["python:proto"]
env = { SETUPTOOLS_SCM_PRETEND_VERSION_FOR_OPENSHELL = "0.0.0" }
run = "uv sync --group dev"
hide = true

["build:python:wheel"]
description = "Build the pure-Python SDK wheel"
depends = ["python:proto"]
run = """
#!/usr/bin/env bash
set -euo pipefail

WHEEL_OUTPUT_DIR=${WHEEL_OUTPUT_DIR:-target/wheels}
rm -rf "$WHEEL_OUTPUT_DIR"
mkdir -p "$WHEEL_OUTPUT_DIR"

uv build --wheel --out-dir "$WHEEL_OUTPUT_DIR"

VERIFY_ARGS=()
if [ -n "${SETUPTOOLS_SCM_PRETEND_VERSION_FOR_OPENSHELL:-}" ]; then
  VERIFY_ARGS+=(--expected-version "$SETUPTOOLS_SCM_PRETEND_VERSION_FOR_OPENSHELL")
fi
uv run --no-project python tasks/scripts/verify-python-wheel.py "$WHEEL_OUTPUT_DIR" ${VERIFY_ARGS[@]+"${VERIFY_ARGS[@]}"}
... (40 lines truncated)
</file>

<file path="tasks/rust.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

# Rust check, lint, and format tasks

["perf:seccomp"]
description = "Compare native and sandbox-filtered TCP socket performance"
run = "cargo run --release -p openshell-sandbox --features perf-harness --bin openshell-seccomp-perf --"

["rust:check"]
description = "Check all Rust crates for errors"
depends = ["rust:lockfiles:check"]
run = [
  "cargo check --workspace",
  "cargo check -p openshell-sandbox --all-targets --features perf-harness",
]
run_windows = "powershell -NoProfile -ExecutionPolicy Bypass -File tasks/scripts/windows-msvc.ps1 check native"
hide = true

["rust:lockfiles:check"]
description = "Verify all tracked Cargo lockfiles are current"
run = "tasks/scripts/check-cargo-lockfiles.sh"
run_windows = "powershell -NoProfile -ExecutionPolicy Bypass -File tasks/scripts/check-cargo-lockfiles.ps1"
hide = true

["rust:lint"]
description = "Lint Rust code with Clippy (deny warnings)"
depends = ["rust:lockfiles:check"]
run = [
  "cargo clippy --workspace --all-targets -- -D warnings",
... (69 lines truncated)
</file>

<file path="tasks/sandbox.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

# Sandbox tasks

[sandbox]
description = "Create or reconnect to the dev sandbox using the active gateway"
raw = true
usage = """
arg "[command]" var=#true help="Command to run in the sandbox (default: claude)"
"""
run = "bash tasks/scripts/sandbox.sh"
</file>

<file path="tasks/sbom.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

# SBOM generation, license resolution, and CSV export tasks
#
# Usage:
#   mise run sbom          # generate SBOMs, resolve licenses, export CSVs
#   mise run sbom:check    # advisory license check (for CI)

[sbom]
description = "Generate SBOMs, resolve licenses, and export CSVs to deploy/sbom/output/"
depends = ["sbom:csv"]

["sbom:generate"]
description = "Generate CycloneDX SBOMs with Syft"
hide = true
run = """
#!/usr/bin/env bash
set -euo pipefail

OUTPUT_DIR="deploy/sbom/output"
mkdir -p "$OUTPUT_DIR"

VERSION=$(uv run python tasks/scripts/release.py get-version --cargo)

echo "Generating SBOM for workspace (version ${VERSION})..."

syft dir:. \
  --exclude './.github/**' \
  --exclude './.venv/**' \
... (62 lines truncated)
</file>

<file path="tasks/term.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

# TUI tasks

[term]
description = "Launch the OpenShell TUI"
run = "openshell term"
hide = true

["term:dev"]
description = "Launch the OpenShell TUI with hot-reload on file changes"
run = "cargo watch -s 'openshell term'"
hide = true
</file>

<file path="tasks/test.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

# Test tasks (Rust + Python + TypeScript SDK)

[test]
description = "Run all tests (Rust + Python + TypeScript SDK)"
depends = [
  "test:rust",
  "test:python",
  "sdk:ts:test",
  "test:sbom",
  "test:install-sh",
  "test:build-env",
  "test:gateway-pull-policy",
  "test:e2e-image-overrides",
  "test:gateway-config",
  "test:e2e-parity",
  "test:packaging-assets",
  "test:qualification-summary",
  "test:codex-security-release-range",
  "test:docs-website",
  "test:docs-nav",
]

["test:docs-website"]
description = "Test the docs-website sync script"
# --no-project skips installing the OpenShell package; --with supplies the test
# dependencies and the script's runtime dependency, which live outside the project env.
run = "uv run --no-project --with pytest --with pytest-asyncio --with pyyaml pytest tasks/scripts/sync_docs_website_test.py"
... (281 lines truncated)
</file>

<file path="tasks/typescript.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

# TypeScript SDK tasks (sdk/typescript). Codegen runs `buf generate` (buf and
# the connect-es plugin come from the package's own devDependencies); buf
# self-compiles proto/, so no protoc is required.

["sdk:ts:install"]
description = "Install TypeScript SDK dependencies"
dir = "sdk/typescript"
run = "npm ci"
run_windows = "powershell -NoProfile -ExecutionPolicy Bypass -File ../../tasks/scripts/typescript-install.ps1"
hide = true

["sdk:ts:proto"]
description = "Generate TypeScript protobuf stubs for the SDK"
depends = ["sdk:ts:install"]
dir = "sdk/typescript"
run = "npm run gen"
run_windows = "powershell -NoProfile -ExecutionPolicy Bypass -File ../../tasks/scripts/typescript-proto.ps1"

# Lints the repo-level proto module (buf.yaml at the root) against STANDARD.
# buf ships only in the SDK's devDependencies today, so this depends on the
# SDK install and runs buf from there; the target is all of proto/, not just
# the SDK's client-surface subset.
["proto:lint"]
description = "Lint proto/ with buf (repo-level buf.yaml)"
depends = ["sdk:ts:install"]
run = "./sdk/typescript/node_modules/.bin/buf lint"
run_windows = "sdk\\typescript\\node_modules\\.bin\\buf.cmd lint"
... (90 lines truncated)
</file>

<file path="tasks/version.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

# Version management tasks

["version"]
description = "Print git-derived version"
run = "uv run python tasks/scripts/release.py get-version"
hide = true

["version:print"]
description = "Print git-derived version"
run = "uv run python tasks/scripts/release.py get-version"
hide = true
</file>

<file path="tasks/vm.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

# VM driver development tasks
#
# Workflow:
#   mise run vm:setup          # one-time: download pre-built runtime (~30s)
#   mise run vm:supervisor     # build the bundled sandbox supervisor
#   mise run gateway:vm        # start openshell-gateway with the VM driver
#                              # (defined in tasks/gateway.toml)
#
# See tasks/gateway.toml for `gateway:vm`,
# crates/openshell-driver-vm/README.md for the VM driver workflow.

# ═══════════════════════════════════════════════════════════════════════════
# Main Commands
# ═══════════════════════════════════════════════════════════════════════════

["vm:setup"]
description = "One-time setup: download (or build) the VM driver runtime"
run = "tasks/scripts/vm/vm-setup.sh"

["vm:supervisor"]
description = "Build the bundled openshell-sandbox supervisor for openshell-driver-vm"
run = "tasks/scripts/vm/build-supervisor-bundle.sh"

["vm:smoke:orphan-cleanup"]
description = "Smoke test: start gateway+driver, create a sandbox, signal the gateway, assert no orphaned processes survive"
run = "tasks/scripts/vm/smoke-orphan-cleanup.sh"
</file>

<file path="tasks/windows.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

# Windows MSVC validation and build tasks. These intentionally live outside
# the Linux/macOS task definitions so each hosted workflow has an explicit
# platform-native entry point.

["windows:check"]
description = "Check Windows x64 and ARM64 MSVC targets"
run = "echo 'windows:* tasks require a Windows MSVC host' && exit 1"
run_windows = "powershell -NoProfile -ExecutionPolicy Bypass -File tasks/scripts/windows-msvc.ps1 check all"

["windows:check:x64"]
description = "Check Windows x64 MSVC target"
run = "echo 'windows:* tasks require a Windows MSVC host' && exit 1"
run_windows = "powershell -NoProfile -ExecutionPolicy Bypass -File tasks/scripts/windows-msvc.ps1 check x86_64-pc-windows-msvc"

["windows:check:arm64"]
description = "Check Windows ARM64 MSVC target"
run = "echo 'windows:* tasks require a Windows MSVC host' && exit 1"
run_windows = "powershell -NoProfile -ExecutionPolicy Bypass -File tasks/scripts/windows-msvc.ps1 check aarch64-pc-windows-msvc"

["windows:lint:x64"]
description = "Lint Windows x64 MSVC workspace targets with Clippy"
run = "echo 'windows:* tasks require a Windows MSVC host' && exit 1"
run_windows = "powershell -NoProfile -ExecutionPolicy Bypass -File tasks/scripts/windows-msvc.ps1 lint x86_64-pc-windows-msvc"

["windows:lint:arm64"]
description = "Lint Windows ARM64 MSVC workspace targets with Clippy"
run = "echo 'windows:* tasks require a Windows MSVC host' && exit 1"
... (62 lines truncated)
</file>

<file path="telemetry/2026-07-08.md">
# OpenShell Telemetry — June 24 – July 8, 2026

[← All reports](README.md)

First public telemetry update, so there is no prior period to compare against. The **Last 2 weeks** column covers this two-week window; **All-time** is cumulative since telemetry landed on June 1, 2026 (~5 weeks). A large share of all-time activity falls within this two-week window. Numbers are aggregate counts only — see the [Telemetry section](../README.md#telemetry) of the main README for what's collected and how to opt out.

| Metric | Last 2 weeks | All-time |
|---|---:|---:|
| Sandboxes created | 269,220 | 383,224 |
| Sandboxes deleted | 247,727 | 343,216 |
| Sandbox creation failures | 5,345 | 12,822 |
| Actions denied | 2,323,468 | 3,861,935 |
| Network activity events | 29,935,431 | 43,079,862 |

Creation failure rate held around 2% over the last two weeks (~3% all-time).

**Sandbox drivers.** Docker dominates at 208,816, followed by Podman (34,637) and Kubernetes (23,480). VM (1,562), unknown (422), and MXC (303) make up the long tail. All-time we've also seen a handful of apple-container and macos sandboxes.

```mermaid
xychart-beta
    title "Sandboxes Created by Driver (Jun 24 – Jul 8)"
    x-axis ["docker", "podman", "kubernetes", "vm", "unknown", "mxc"]
    y-axis "Sandboxes created" 0 --> 220000
    bar [208816, 34637, 23480, 1562, 422, 303]
```

**Where sandboxes are created.** The United States leads by a wide margin, followed by Israel, Australia, Hong Kong, India, Singapore, South Korea, Germany, Japan, and China.

**Providers.** `custom` profiles lead (~30k), then `openai` (~21k), with nvidia, claude, anthropic, github, gitlab, opencode, codex, and copilot trailing.

... (17 lines truncated)
</file>

<file path="telemetry/2026-07-26.md">
# OpenShell Telemetry — July 13 – July 26, 2026

[← All reports](README.md)

Metrics below cover this two-week window, compared with the prior period (June 24 – July 8, 2026). Numbers are aggregate counts only — see the [Telemetry section](../README.md#telemetry) of the main README for what's collected and how to opt out.

| Metric | This period | Prior period | Change |
|---|---:|---:|---:|
| Sandboxes created | 556,370 | 269,220 | +106.7% |
| Sandboxes deleted | 421,946 | 247,727 | +70.3% |
| Sandbox creation failures | 100,246 | 5,345 | +1,775.5% |
| Actions denied | 3,505,237 | 2,323,468 | +50.9% |
| Network activity events | 34,946,280 | 29,935,431 | +16.7% |

The creation failure rate was ~18% this period (100,246 failures against 556,370 creates), up from ~2% in the prior period. Docker was the most-used driver at 332,238, ahead of Kubernetes (172,834).

**Sandbox drivers.** Docker leads at 332,238, then Kubernetes (172,834) and Podman (47,374). The long tail: VM (3,198), unknown (399), and MXC (327).

```mermaid
xychart-beta
    title "Sandboxes Created by Driver (Jul 13 – Jul 26)"
    x-axis ["docker", "kubernetes", "podman", "vm", "unknown", "mxc"]
    y-axis "Sandboxes created" 0 --> 350000
    bar [332238, 172834, 47374, 3198, 399, 327]
```

**Where sandboxes are created.** The United States leads by a wide margin, followed by Israel, Japan, India, Singapore, Hong Kong, China, Germany, Thailand, and Sweden.

**Providers.** `custom` profiles lead at 42,758, then `openai` (33,074), claude (2,261), nvidia (1,744), github (784), anthropic (660), opencode (624), gitlab (284), codex (38), and copilot (18).

... (17 lines truncated)
</file>

<file path="telemetry/2026-08-10.md">
# OpenShell Telemetry — July 27 – August 10, 2026

[← All reports](README.md)

Metrics below cover this two-week window, compared with the prior period (July 13 – July 26, 2026). Numbers are aggregate counts only — see the [Telemetry section](../README.md#telemetry) of the main README for what's collected and how to opt out.

| Metric | This period | Prior period | Change |
|---|---:|---:|---:|
| Sandboxes created | 556,389 | 556,370 | +0.0% |
| Sandboxes deleted | 457,086 | 421,946 | +8.3% |
| Sandbox creation failures | 66,511 | 100,246 | -33.7% |
| Actions denied | 4,220,436 | 3,505,237 | +20.4% |
| Network activity events | 27,077,441 | 34,946,280 | -22.5% |

The creation failure rate was ~12% this period (66,511 failures against 556,389 creates), down from ~18% in the prior period. Kubernetes (245,144) overtook Docker (239,444) as the most-used sandbox driver.

**Sandbox drivers.** Kubernetes leads at 245,144, just ahead of Docker (239,444), with Podman third at 58,657. The long tail: unknown (6,386), VM (6,267), MXC (461), apple-container (23), and LXD (7).

```mermaid
xychart-beta
    title "Sandboxes Created by Driver (Jul 27 – Aug 10)"
    x-axis ["kubernetes", "docker", "podman", "unknown", "vm", "mxc"]
    y-axis "Sandboxes created" 0 --> 260000
    bar [245144, 239444, 58657, 6386, 6267, 461]
```

**Where sandboxes are created.** The United States again leads by a wide margin, followed by India, Germany, China, Poland, Japan, the United Kingdom, Israel, Hong Kong, and Denmark.

**Providers.** `custom` profiles lead (~61k), then `openai` (~51k), with claude, nvidia, github, anthropic, gitlab, opencode, codex, and copilot trailing.

... (17 lines truncated)
</file>

<file path="telemetry/README.md">
# OpenShell Community Telemetry Reports

OpenShell collects anonymous, aggregate usage telemetry (see the [Telemetry section](../README.md#telemetry) of the main README for what's collected and how to opt out). We publish periodic summaries of the trends here so the community can see how the project is being used.

Numbers are aggregate counts only — no user data, code, prompts, or command contents are collected. Each report covers one two-week period and, where available, compares against the prior period. Reports are listed newest first.

## Reports

| Reporting period | Report |
|---|---|
| July 27 – August 10, 2026 | [View report](2026-08-10.md) |
| July 13 – July 26, 2026 | [View report](2026-07-26.md) |
| June 24 – July 8, 2026 | [View report](2026-07-08.md) |
</file>

<file path=".env.example">
# OpenShell local development environment
# Copy to .env and customise. Mise loads .env automatically.
#
# Use unique gateway names and ports per worktree when running standalone
# gateways with `mise run gateway:docker`.

# ---------- Gateway identity ----------

# Gateway name registered by `mise run gateway:docker`.
#OPENSHELL_DOCKER_GATEWAY_NAME=openshell-c

# Default gateway name used by `openshell` commands in this repo when `--gateway`
# is not provided. Usually matches OPENSHELL_DOCKER_GATEWAY_NAME.
#OPENSHELL_GATEWAY=openshell-c

# ---------- Ports ----------

# Host port where the standalone gateway listens. Must be unique per worktree.
#OPENSHELL_SERVER_PORT=18080
</file>

<file path=".markdownlint-cli2.jsonc">
{
  "globs": [
    "*.md",
    "crates/**/*.md",
    "deploy/**/*.md",
    "docs/**/*.md",
    "docs/**/*.mdx",
    "e2e/**/*.md",
    "examples/**/*.md",
    "rfc/**/*.md"
  ],
  "gitignore": false,
  "ignores": [
    ".agents/**",
    ".claude/**",
    ".opencode/**",
    ".github/**",
    "plans/**",
    "architecture/plans/**",
    "**/node_modules/**",
    "target/**",
    ".pytest_cache/**",
    "THIRD-PARTY-NOTICES/**",
    "CLAUDE.md",
    // Man page sources use pandoc markdown with multiple H1 sections
    // (NAME, SYNOPSIS, DESCRIPTION, etc.) which is standard for man
    // pages but violates MD025.
    "deploy/man/**"
  ],
  "config": {
... (19 lines truncated)
</file>

<file path=".packit.yaml">
upstream_tag_template: "v{version}"
upstream_package_name: openshell
downstream_package_name: openshell
specfile_path: openshell.spec
srpm_build_deps:
  - cargo
  - git-core
actions:
  get-current-version:
    - 'bash -c "if [ -n \"${OPENSHELL_RPM_VERSION:-}\" ]; then echo \"${OPENSHELL_RPM_VERSION}\"; else git describe --tags --match ''v[0-9]*.[0-9]*.[0-9]*'' --abbrev=0 HEAD | sed ''s/^v//''; fi"'
  create-archive:
    - 'bash -c "VERSION=${PACKIT_PROJECT_VERSION} && TMPDIR=$(mktemp -d) && DIR=openshell-${VERSION} && mkdir -p ${TMPDIR}/${DIR} && git ls-files -z | xargs -0 tar cf - | tar xf - -C ${TMPDIR}/${DIR}/ && tar -czf openshell-${VERSION}.tar.gz -C ${TMPDIR} ${DIR} && rm -rf ${TMPDIR}"'
    - 'bash -c "VERSION=${PACKIT_PROJECT_VERSION} && CARGO_HTTP_TIMEOUT=600 CARGO_NET_RETRY=5 cargo vendor --locked --quiet && tar -cJf openshell-${VERSION}-vendor.tar.xz vendor/ && rm -rf vendor/"'
    - 'bash -c "echo openshell-${PACKIT_PROJECT_VERSION}.tar.gz"'
  fix-spec-file:
    - 'bash -c "sed -i -r \"s/^%global openshell_version .*/%global openshell_version ${PACKIT_RPMSPEC_VERSION}/\" openshell.spec"'
    - 'bash -c "RELEASE=${OPENSHELL_RPM_RELEASE:-${PACKIT_RPMSPEC_RELEASE}} && sed -i -r \"s/^Release:(\\s*)\\S+/Release:\\1${RELEASE}%{?dist}/\" openshell.spec"'
    - 'bash -c "if [ -n \"${OPENSHELL_CARGO_VERSION:-}\" ]; then sed -i -r \"s/^%global openshell_cargo_version .*/%global openshell_cargo_version ${OPENSHELL_CARGO_VERSION}/\" openshell.spec; fi"'
jobs:
  - job: copr_build
    trigger: pull_request
    branch: main
    identifier: main-pr
    targets:
      - fedora-all
      - epel-10
  - job: copr_build
    trigger: commit
    branch: main
    owner: "maxamillion"
... (17 lines truncated)
</file>

<file path=".python-version">
3.14.5
</file>

<file path=".trivyignore.yaml">
misconfigurations:
  - id: KSV-0110
    paths:
      - "**/statefulset.yaml"
      - "**/deployment.yaml"
    statement: >-
      An artifact of rendering the chart outside a cluster. The namespace is
      supplied at install time.
  - id: KSV-01010
    paths:
      - "**/gateway-config.yaml"
    statement: >-
      The ConfigMap holds the name of a key in an external Secret, not a
      credential.
  - id: KSV-0125
    paths:
      - "**/statefulset.yaml"
      - "**/deployment.yaml"
    statement: >-
      Images come from ghcr.io/nvidia/openshell, this project's own registry.
  - id: KSV-0056
    paths:
      - "**/role.yaml"
    statement: >-
      The namespace-scoped gateway role can create Services and NetworkPolicy
      resources so the compute driver can connect each sandbox runtime to its
      supervisor while denying direct workload egress.
</file>

<file path="about.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

# cargo-about configuration for generating third-party license notices.
# See https://embarkstudios.github.io/cargo-about/

# Accepted licenses (SPDX expressions). All permissive/weak-copyleft licenses
# found in this workspace's dependency tree.
accepted = [
    "0BSD",
    "Apache-2.0",
    "Apache-2.0 WITH LLVM-exception",
    "BSD-1-Clause",
    "BSD-2-Clause",
    "BSD-3-Clause",
    "BSL-1.0",
    "CC0-1.0",
    "CDLA-Permissive-2.0",
    "ISC",
    "LGPL-2.1-or-later",
    "MIT",
    "MIT-0",
    "OpenSSL",
    "Unicode-3.0",
    "Unlicense",
    "Zlib",
]
</file>

<file path="AGENTS.md">
# Agent Instructions

This file is the primary instruction surface for agents contributing to OpenShell. It is injected into your context on every interaction — keep that in mind when proposing changes to it.

See [CONTRIBUTING.md](CONTRIBUTING.md) for build instructions, task reference, project structure, and the full agent skills table.

## Project Identity

OpenShell is built agent-first. We design systems and use agents to implement them — this is not vibe coding. The product provides safe, sandboxed runtimes for autonomous AI agents, and the project itself is built using the same agent-driven workflows it enables.

## Skills

OpenShell has two skill collections:

- `skills/` contains public, installable skills for using and operating OpenShell. These skills must work outside a source checkout and use installed CLI help plus published documentation as their sources of truth.
- `.agents/skills/` contains internal contributor and maintainer workflows for developing OpenShell. Your repository-aware harness can discover and load them natively.

Do not rely on this file for a full inventory. The detailed public and contributor skill tables are in [CONTRIBUTING.md](CONTRIBUTING.md) (for humans).

## Workflow Chains

These pipelines connect skills into end-to-end workflows. Individual skill files don't describe these relationships.

- **Community inflow:** `triage-issue` → human disposition and roadmap placement → `create-spike` when needed → `build-from-issue`
  - Triage establishes facts and marks technically valid issues `state:validated`. A human signals that the project should pursue the work by applying `state:accepted` or placing the issue on the roadmap. The `agent:*` labels support unattended agents that scan for queued work: a human queues a plan with `agent:plan-requested`, the agent returns `agent:plan-ready`, and a human queues implementation with `agent:implementation-requested`. A direct user request to an agent authorizes the requested phase even when the expected lifecycle or workflow labels are missing or incomplete; the agent warns about the discrepancies and continues without changing the labels.
- **Internal development:** `create-spike` → human disposition and roadmap placement → `build-from-issue`
  - Spike explores feasibility and marks its issue `state:validated` when sufficient evidence exists. A human accepts it with `state:accepted` or roadmap placement, or declines it, and optionally queues it through the `agent:*` workflow or directs an agent to it. A direct request proceeds after warning about missing or incomplete expected labels.
- **Security:** `review-security-issue` → `fix-security-issue`
  - General build agents must not process `topic:security` issues. For unattended processing, a human queues specialized review with `agent:plan-requested`; review produces a severity assessment and remediation plan; a human queues remediation with `agent:implementation-requested`. On direct requests to the specialized skills, missing workflow labels produce a warning rather than blocking the requested phase.
- **Policy iteration:** `openshell-cli` → `generate-sandbox-policy`
... (249 lines truncated)
</file>

<file path="buf.yaml">
version: v2
modules:
  - path: proto
  - path: crates/openshell-server/proto
lint:
  use:
    - STANDARD
  except:
    - DIRECTORY_SAME_PACKAGE
    - PACKAGE_DIRECTORY_MATCH
    - RPC_REQUEST_RESPONSE_UNIQUE
    - RPC_REQUEST_STANDARD_NAME
    - RPC_RESPONSE_STANDARD_NAME
    - SERVICE_SUFFIX
breaking:
  use:
    - FILE
</file>

<file path="Cargo.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

[workspace]
resolver = "2"
members = ["crates/*"]

[workspace.package]
version = "0.0.0"
edition = "2024"
rust-version = "1.94"
license = "Apache-2.0"
repository = "https://github.com/NVIDIA/OpenShell"

[workspace.dependencies]
# Async runtime
tokio = { version = "1.43", features = ["full"] }

# gRPC/Protobuf
tonic = "0.14"
tonic-types = "0.14"
tonic-prost = "0.14"
tonic-prost-build = "0.14"
prost = "0.14"
prost-types = "0.14"
prost-reflect = { version = "0.16.5", features = ["serde"] }

# HTTP server
axum = { version = "0.8", features = ["ws"] }
tower = "0.5"
... (154 lines truncated)
</file>

<file path="CI.md">
# CI

This document describes how OpenShell's continuous integration works for pull requests, with a focus on what contributors need to do to get their PR tested.

For local test commands see [TESTING.md](TESTING.md). For PR conventions see [CONTRIBUTING.md](CONTRIBUTING.md).

## Overview

PR CI that runs on NVIDIA self-hosted runners uses NVIDIA's copy-pr-bot. The bot mirrors trusted PR commits to internal `pull-request/<N>` branches in this repository. The gated workflows trigger on pushes to those branches, not on the original PR.

When a PR is not mirrored automatically, anyone with Write, Maintain, or Admin
access to this repository can admit its current revision with
`/ok to test <SHA>`. This includes external maintainers with repository access.
Manual admission does not change the bot's automatic trust policy for ready PRs.

`Branch Checks` run automatically after copy-pr-bot mirrors the PR. `Required CI Gates` posts PR-head statuses that verify the mirror exists, is current, and ran the expected push-based workflows. E2E suites are opt-in because they are more expensive and publish temporary images.

Merge queue validation is a second integration gate for `main`. After a PR has passed the required PR-head statuses, a maintainer adds it to the merge queue. GitHub creates a temporary merge-group branch that combines the latest `main`, the queued PR, and any earlier queued PRs. The same required `OpenShell / ...` status contexts are then published against the merge-group SHA before GitHub merges it.

Windows PR checks are opt-in: add `test:windows`, then select **Re-run all jobs**
on the current Windows MSVC run. Subsequent mirrored commits run them automatically.
Windows checks are not required for merging and do not run in merge queues.
Main and manual runs also build release binaries, with `continue-on-error: true`
so Windows failures do not fail the workflow.

Three opt-in labels enable the long-running E2E suites:

- `test:e2e` runs the Docker, rootless Podman, Kubernetes, and VM E2E suites
  with both managed and standalone compute drivers in `Branch E2E Checks`
- `test:e2e-gpu` runs GPU E2E in `Branch E2E Checks`
... (422 lines truncated)
</file>

<file path="CLAUDE.md">
@AGENTS.md
</file>

<file path="CODE_OF_CONDUCT.md">
# Code of Conduct

We follow the [CNCF Code of Conduct](https://github.com/cncf/foundation/blob/main/code-of-conduct.md).

Please contact [openshell-maintainers@ai-openshell.org](mailto:openshell-maintainers@ai-openshell.org) or the [CNCF Code of Conduct Committee](mailto:conduct@cncf.io) to report violations of the Code of Conduct.
</file>

<file path="CONTRIBUTING.md">
# Contributing to OpenShell

OpenShell is built agent-first. We use agents to design and implement systems, while humans manage product decisions and the project roadmap.

## The Critical Rule

**You must understand your code.** Using AI agents to write code is not just acceptable, it's how this project works. But you must be able to explain what your changes do and how they interact with the rest of the system. If you can't, don't submit it.

Submitting agent-generated code without understanding it — regardless of how clean it looks — wastes maintainer time and will result in your PR being closed. Repeat offenders will be blocked from the project.

## AI Usage

OpenShell is agent-first, not agent-only. The distinction matters:

- **Do** use agents to explore the codebase, run diagnostics, generate code, and iterate on implementations.
- **Do** use the skills in `.agents/skills/` — they exist to make your agent effective.
- **Do** interrogate your agent until you understand every edge case and interaction in your changes.
- **Don't** submit code you can't explain without your agent open.
- **Don't** use agents as a substitute for understanding the system. Read the RFCs, crate READMEs, and published docs.

## First-Time Contributors

We use a vouch system. This exists because AI makes it trivial to generate plausible-looking but low-quality contributions, and we can no longer trust by default.

1. Open a [Vouch Request](https://github.com/NVIDIA/OpenShell/discussions/new?category=vouch-request) discussion.
2. Describe what you want to change and why.
3. Write in your own words. AI-generated vouch requests will be denied.
4. A maintainer will comment `/vouch` if approved, and the request discussion
   will close automatically.
5. Once vouched, you can submit pull requests.
... (580 lines truncated)
</file>

<file path="DCO">
Developer Certificate of Origin
Version 1.1

Copyright (C) 2004, 2006 The Linux Foundation and its contributors.

Everyone is permitted to copy and distribute verbatim copies of this
license document, but changing it is not allowed.


Developer's Certificate of Origin 1.1

By making a contribution to this project, I certify that:

(a) The contribution was created in whole or in part by me and I
    have the right to submit it under the open source license
    indicated in the file; or

(b) The contribution is based upon previous work that, to the best
    of my knowledge, is covered under an appropriate open source
    license and I have the right under that license to submit that
    work with modifications, whether created in whole or in part
    by me, under the same open source license (unless I am
    permitted to submit under a different license), as indicated
    in the file; or

(c) The contribution was provided directly to me by some other
    person who certified (a), (b) or (c) and I have not modified
    it.

(d) I understand and agree that this project and the contribution
... (5 lines truncated)
</file>

<file path="deny.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

# cargo-deny configuration
# https://embarkstudios.github.io/cargo-deny/

[graph]
all-features = true
no-default-features = false

# -- Advisories (RustSec + NVD) ------------------------------------------------
[advisories]
yanked = "warn"
unmaintained = "workspace"
maximum-db-staleness = "P30D"
ignore = [
    # Pre-existing advisories acknowledged at onboarding. Each should be
    # resolved by upgrading the affected transitive dependency and then
    # removing the ignore entry.
    { id = "RUSTSEC-2026-0190", reason = "anyhow unsoundness in downcast_mut — awaiting upstream fix" },
    { id = "RUSTSEC-2026-0204", reason = "crossbeam-epoch pointer deref — transitive via metrics/quanta" },
    { id = "RUSTSEC-2023-0071", reason = "rsa Marvin attack — transitive via spiffe, no direct exposure" },
    { id = "RUSTSEC-2025-0134", reason = "rustls-pemfile unmaintained — transitive via older kube/hyper" },
]

# -- Licenses ------------------------------------------------------------------
[licenses]
confidence-threshold = 0.8
unused-allowed-license = "allow"

... (43 lines truncated)
</file>

<file path="GOVERNANCE.md">
# OpenShell Project Governance

OpenShell is dedicated to creating safe, private, policy-governed runtimes for autonomous AI agents. This document explains how the project is governed.

## Values

OpenShell and its leadership embrace the following values:

- **Openness:** Communication and decision-making happen in the open and remain discoverable for future reference. As much as possible, discussions and work take place in public forums and repositories.
- **Fairness:** All stakeholders may provide feedback and submit contributions. The project considers contributions on their merits.
- **Community over product or company:** Sustaining and growing the community takes priority over shipping code or advancing one sponsor's organizational goals. Contributors participate as individuals.
- **Vendor neutrality:** No single organization controls project direction or decisions. Maintainer selection, roadmap priorities, and release decisions are based on the interests of the project rather than employer affiliation.
- **Inclusivity:** Different perspectives and skills make OpenShell better. The project provides a welcoming and respectful environment for participation.
- **Participation:** Responsibilities and privileges are earned through sustained participation, demonstrated judgment, and earned community trust.

## Contributor Ladder

OpenShell uses a contributor ladder to provide a path from participation to project leadership. Movement through the ladder reflects increasing trust, responsibility, and project-wide stewardship. Contributions may include code, documentation, design, testing, issue triage, reviews, release work, community support, and other work that advances the project.

### Contributor

A Contributor is anyone who participates constructively in the OpenShell community.

Contributors are responsible for:

- Following the project Code of Conduct and contribution guidelines.
- Taking responsibility for the correctness and provenance of their work, including work created with AI tools or agents.
- Engaging constructively with reviewers, users, and other contributors.

Contributors may:
... (137 lines truncated)
</file>

<file path="install.sh">
set -e
APP_NAME="openshell"
REPO="NVIDIA/OpenShell"
GITHUB_URL="https://github.com/${REPO}"
RELEASE_TAG="${OPENSHELL_VERSION:-}"
RELEASE_ASSET_DIR=""
CHECKSUMS_NAME="openshell-checksums-sha256.txt"
LOCAL_GATEWAY_PORT="17670"
HOMEBREW_TAP="nvidia/openshell"
HOMEBREW_FORMULA_NAME="openshell"
HOMEBREW_CLI_ASSET="openshell-aarch64-apple-darwin.tar.gz"
HOMEBREW_GATEWAY_ASSET="openshell-gateway-aarch64-apple-darwin.tar.gz"
HOMEBREW_DRIVER_VM_ASSET="openshell-driver-vm-aarch64-apple-darwin.tar.gz"
HOMEBREW_PROVER_ASSET="openshell-prover-aarch64-apple-darwin.tar.gz"
BREAKING_RELEASE_VERSION="0.0.37"
LINUX_PACKAGE_GLIBC_MIN_VERSION="2.28"
UPGRADE_NOTICE_ACK="${OPENSHELL_ACK_BREAKING_UPGRADE:-}"
info() {
  printf '%s: %s\n' "$APP_NAME" "$*" >&2
}
warn() {
  printf '%s: warning: %s\n' "$APP_NAME" "$*" >&2
}
error() {
  printf '%s: error: %s\n' "$APP_NAME" "$*" >&2
  exit 1
}
usage() {
  cat <<EOF
install.sh - Install OpenShell
... (1215 lines truncated)
</file>

<file path="LICENSE">
Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.

                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.
... (174 lines truncated)
</file>

<file path="MAINTAINERS.md">
# Maintainers

The current maintainers of OpenShell are listed below.

| Name | GitHub ID | Company/Organization |
| --- | --- | --- |
| Derek Carr | [@derekwaynecarr](https://github.com/derekwaynecarr) | Red Hat |
| Matthew Grossman | [@matthewgrossman](https://github.com/matthewgrossman) | NVIDIA |
| Kris Hicks | [@krishicks](https://github.com/krishicks) | NVIDIA |
| Seth Jennings | [@sjenning](https://github.com/sjenning) | Red Hat |
| Adrien Langou | [@alangou](https://github.com/alangou) | NVIDIA |
| Evan Lezar | [@elezar](https://github.com/elezar) | NVIDIA |
| Jim Meyer | [@purp](https://github.com/purp) | NVIDIA |
| Piotr Mlocek | [@pimlock](https://github.com/pimlock) | NVIDIA |
| Taylor Mutch | [@TaylorMutch](https://github.com/TaylorMutch) | NVIDIA |
| John T. Myers | [@johntmyers](https://github.com/johntmyers) | NVIDIA |
| Drew Newberry | [@drew](https://github.com/drew) | NVIDIA |
| Mrunal Patel | [@mrunalp](https://github.com/mrunalp) | Red Hat |
| Simon Scatton | [@SDAChess](https://github.com/SDAChess) | NVIDIA |
</file>

<file path="mise.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

# OpenShell mise configuration
# See https://mise.jdx.dev/ for documentation
#
# Tasks are defined in tasks/*.toml — run `mise tasks` to list them all.

# NOTE: keep this version in sync with what CI uses in Dockerfile.ci
min_version = { soft = "2026.9.9" }

redactions = ["*_TOKEN", "*_PASSWORD"]

[settings]
experimental = true
python.precompiled_flavor = "install_only_stripped"

lockfile = true
lockfile_platforms = ["linux-x64", "linux-arm64", "macos-arm64", "windows-x64", "windows-arm64"]

[tools]
python = "3.14.5"
rust = "1.95.0"
node = "24.15.0"
kubectl = { version = "1.36.1", version_prefix = "v" }
uv = "0.10.12"
protoc = "29.6"
go = "1.26.7"
"go:github.com/golangci/golangci-lint/v2/cmd/golangci-lint" = "2.12"
"go:google.golang.org/protobuf/cmd/protoc-gen-go" = "1.36.11"
... (51 lines truncated)
</file>

<file path="openshell.spec">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

%global crate openshell
%global openshell_version 0.0.37
%global openshell_cargo_version %{openshell_version}
# Python dist-info metadata intentionally follows the RPM Version. Dev build
# identity is represented by Release for RPM packages.
%global openshell_python_version %{openshell_version}

# Cargo/Rust builds with vendored deps do not produce debugsource listings
# in the format redhat-rpm-config expects (especially on EPEL).
%global debug_package %{nil}

Name:           openshell
Version:        %{openshell_version}
Release:        1.20260518180028805757.podman.toml.gateway.listener.11.g8c0cb7c8%{?dist}
Summary:        Safe, sandboxed runtimes for autonomous AI agents

License:        Apache-2.0
URL:            https://github.com/NVIDIA/OpenShell
Source0: openshell-%{openshell_version}.tar.gz
Source1: openshell-%{openshell_version}-vendor.tar.xz

ExclusiveArch:  x86_64 aarch64

# Cargo metadata generation
BuildRequires:  cargo
BuildRequires:  cargo-rpm-macros >= 25
BuildRequires:  systemd-rpm-macros
... (261 lines truncated)
</file>

<file path="pyproject.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

[build-system]
requires = ["setuptools>=80", "setuptools-scm[simple]>=8"]
build-backend = "setuptools.build_meta"

[project]
name = "openshell"
dynamic = ["version"]
description = "OpenShell is the safe, private runtime for autonomous AI agents. "
license = "Apache-2.0"
readme = "README.md"
authors = [{ name = "NVIDIA Inc." }]
requires-python = ">=3.11"
dependencies = [
    "cloudpickle>=3.0",
    "grpcio>=1.60",
    "googleapis-common-protos>=1.63",
    "httpx>=0.27",
    "protobuf>=4.25",
]
classifiers = [
    "Development Status :: 3 - Alpha",
    "Intended Audience :: Developers",
    "Intended Audience :: Science/Research",
    "Intended Audience :: Information Technology",
    "Programming Language :: Python :: 3",
    "Programming Language :: Python :: 3.11",
    "Programming Language :: Python :: 3.12",
... (95 lines truncated)
</file>

<file path="README.md">
<!-- markdownlint-disable MD033 MD041 -->

<picture>
  <source media="(prefers-color-scheme: dark)" srcset="docs/brand/assets/openshell-banner-dark.png">
  <source media="(prefers-color-scheme: light)" srcset="docs/brand/assets/openshell-banner-light.png">
  <img alt="OpenShell" src="docs/brand/assets/openshell-banner-light.png" width="430">
</picture>

<!-- markdownlint-enable MD033 MD041 -->

[![License](https://img.shields.io/badge/License-Apache_2.0-blue)](https://github.com/NVIDIA/OpenShell/blob/main/LICENSE)
[![PyPI](https://img.shields.io/badge/PyPI-openshell-orange?logo=pypi)](https://pypi.org/project/openshell/)
[![Security Policy](https://img.shields.io/badge/Security-Report%20a%20Vulnerability-red)](SECURITY.md)
[![Documentation](https://img.shields.io/badge/docs-latest-brightgreen)](https://docs.nvidia.com/openshell/latest/index.html)

> [!IMPORTANT]
> **New in OpenShell 0.1.x:** a stable release cadence, new isolation primitives, an expanded extension surface, and new APIs. [Read the 0.1.0 upgrade guide](https://docs.nvidia.com/openshell/latest/upgrade/0-1-0).

OpenShell is the safe, private runtime for fleets of autonomous AI agents. Agents are most useful when they can read files, install packages, call APIs, and use credentials. OpenShell gives them that capability without giving them unrestricted access to your data, secrets, or network. You declare what each agent can touch in a policy, and OpenShell enforces it.

## How It Works

OpenShell governs what agents can do in two ways: it instruments the kernel to enforce policy on every file access, system call, and network connection at runtime, and it uses formal verification to check what a policy change would allow before it is applied.

- **Kernel-level enforcement.** Each agent runs in an isolated sandbox. Kernel controls confine which files it can access and which system calls it can make, and every network connection passes through a policy check before it leaves the sandbox. Agents never see real credentials; OpenShell adds them only to requests bound for approved endpoints.
- **Formally verified policy changes.** Before a policy change is approved, OpenShell uses formal verification to flag risky new access it would grant, such as reaching a new host with credentials or calling a new API method, so those changes wait for human review.

See [Architecture](https://docs.nvidia.com/openshell/latest/about/architecture) for how the gateway, supervisor, and sandbox fit together.

## Quickstart
... (64 lines truncated)
</file>

<file path="rust-toolchain.toml">
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

[toolchain]
channel = "1.95.0"
components = [ "rustfmt", "rust-src", "rust-analyzer" ]
</file>

<file path="SECURITY.md">
# Security

NVIDIA is dedicated to the security and trust of our software products and services, including all source code repositories managed through our organization.

If you need to report a security issue, please use the appropriate contact points outlined below. **Please do not report security vulnerabilities through GitHub.** If a potential security issue is inadvertently reported via a public issue or pull request, NVIDIA maintainers may limit public discussion and redirect the reporter to the appropriate private disclosure channels.

## Reporting Potential Security Vulnerability in an NVIDIA Product

To report a potential security vulnerability in any NVIDIA product:

- Web: [Security Vulnerability Submission Form](https://www.nvidia.com/object/submit-security-vulnerability.html)
- E-Mail: psirt@nvidia.com
  - We encourage you to use the following PGP key for secure email communication: [NVIDIA public PGP Key for communication](https://www.nvidia.com/en-us/security/pgp-key)
  - Please include the following information:
    - Product/Driver name and version/branch that contains the vulnerability
    - Type of vulnerability (code execution, denial of service, buffer overflow, etc.)
    - Instructions to reproduce the vulnerability
    - Proof-of-concept or exploit code
    - Potential impact of the vulnerability, including how an attacker could exploit the vulnerability

While NVIDIA currently does not have a bug bounty program, we do offer acknowledgement when an externally reported security issue is addressed under our coordinated vulnerability disclosure policy. Please visit our [Product Security Incident Response Team (PSIRT)](https://www.nvidia.com/en-us/security/psirt-policies/) policies page for more information.

## NVIDIA Product Security

For all security-related concerns, please visit NVIDIA's Product Security portal at https://www.nvidia.com/en-us/security
</file>

<file path="snapcraft.yaml">
name: openshell
title: OpenShell
adopt-info: openshell
summary: Safe, sandboxed runtimes for autonomous AI agents
description: |
  OpenShell provides safe, sandboxed runtimes for autonomous AI agents.
  It offers a CLI for managing gateways, sandboxes, and providers with
  policy-enforced egress routing, credential proxying, and privacy-aware
  profile-backed model-provider access.
  The OpenShell snap ships a CLI (`openshell`), a terminal UI
  (`openshell.term`), and a managed gateway daemon (`openshell.gateway`).
  **Setup instructions**
    1. Install and start Docker using your preferred package source before
       installing the OpenShell snap. Use a system package or Docker's package
       repository. The Docker snap is not currently compatible with OpenShell.
       Snap Store installations automatically connect the required interfaces.
       If the OpenShell snap was installed before Docker was running, it may
       have hit the systemd start limit when trying to repeatedly start and
       connect to docker. If this is the case, it can be resolved by doing:
         sudo systemctl reset-failed snap.openshell.gateway.service
         sudo snap restart openshell.gateway
    2. Give your user the gateway client certificate and register the gateway.
       The gateway requires mTLS; only users holding this certificate can use
       it, so copy it only for trusted users:
         snap services openshell.gateway
         d=~/snap/openshell/common/.local/state/openshell/tls
         mkdir -p -m 700 "$d" "$d/client"
         sudo install -o "$USER" -m 600 /var/snap/openshell/common/tls/ca.crt "$d/"
         sudo install -o "$USER" -m 600 -t "$d/client" \
           /var/snap/openshell/common/tls/client/tls.crt /var/snap/openshell/common/tls/client/tls.key
... (100 lines truncated)
</file>

<file path="STYLEGUIDE.md">
# STYLEGUIDE

## License Headers

All source files must include SPDX copyright headers.

```bash
# Add/update headers
mise run license:update

# Check headers
mise run license:check
```

## Code Style

- Rust: format with `rustfmt`, lint with Clippy.
- Python: format and lint with `ruff`, type-check with `ty`.

Recommended workflow before opening a PR:

```bash
mise run fmt
mise run lint
mise run ci
```

## CLI Output Style

When printing structured CLI output:
... (25 lines truncated)
</file>

<file path="TESTING.md">
# Testing

## Running Tests

```bash
mise run test          # Rust + Python unit tests
mise run e2e           # End-to-end tests (starts a Docker-backed gateway)
mise run ci            # Everything: lint, compile checks, and tests
```

## Test Layout

```text
crates/*/src/          # Inline #[cfg(test)] modules
crates/*/tests/        # Rust integration tests
python/openshell/      # Python unit tests (*_test.py suffix)
e2e/python/            # Python E2E tests (test_*.py prefix)
e2e/rust/              # Rust CLI E2E tests
```

## Rust Tests

Unit tests live inline with `#[cfg(test)] mod tests` blocks. Integration tests
go in `crates/*/tests/` and are named `*_integration.rs`.

Use `#[tokio::test]` for anything async:

```rust
#[cfg(test)]
mod tests {
... (484 lines truncated)
</file>

<file path="THIRD-PARTY-NOTICES">
THIRD-PARTY SOFTWARE NOTICES AND INFORMATION

This product includes third-party software components. The following
notices and licenses are provided in compliance with the terms of the
respective licenses.

To regenerate: mise run notices

================================================================================
Rust Dependencies (566 packages)
================================================================================

================================================================================
License: 0BSD
--------------------------------------------------------------------------------

Used by:
  - adler2 2.0.1  (https://github.com/oyvindln/adler2)

Copyright (C) Jonas Schievink <jonasschievink@gmail.com>

Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
... (15949 lines truncated)
</file>

</files>
