Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat: lazy websockets for arbitrary harnesses (#5701)

Wolf Mermelstein9eb547a4b51a
diff --git a/.github/actionlint.yaml b/.github/actionlint.yaml
index 0f45ea3d1c..f2014fee24 100644
--- a/.github/actionlint.yaml
+++ b/.github/actionlint.yaml
@@ -10,3 +10,4 @@ self-hosted-runner:
- namespace-profile-linux-tiny-no-cache
- namespace-profile-linux-rust-ci
- namespace-profile-linux-rust-ci;overrides.cache-tag=sccache-ci
+ - nscloud-macos-sequoia-arm64-6x14
diff --git a/.github/workflows/build_agent_daemon_on_tag.yml b/.github/workflows/build_agent_daemon_on_tag.yml
new file mode 100644
index 0000000000..44cd6b73dd
--- /dev/null
+++ b/.github/workflows/build_agent_daemon_on_tag.yml
@@ -0,0 +1,748 @@
+# DO NOT EDIT — regenerate with `cargo x workflows` (from the repository root).
+# Source: tooling/xtask/crates/xtask_workflows/src/workflows/build_agent_daemon_on_tag.rs
+name: Build Agent Daemon on Tag
+'on':
+ push:
+ tags:
+ - v[0-9]*
+ workflow_dispatch:
+ inputs:
+ ref:
+ description: Optional release tag override (v* or refs/tags/v*). Leave empty to build the branch or tag selected for this workflow run.
+ type: string
+jobs:
+ resolve-ref:
+ name: Resolve build ref
+ runs-on: namespace-profile-linux-tiny-no-cache
+ outputs:
+ ref: ${{ steps.resolve.outputs.ref }}
+ steps:
+ - id: resolve
+ name: Resolve ref
+ run: |
+ set -euo pipefail
+
+ # Resolve the git ref for desktop builds from any trigger type:
+ # push (tag) → github.ref
+ # create (tag) → github.event.ref
+ # workflow_dispatch → inputs.ref (release tag) or the selected workflow ref
+
+ case "$EVENT_NAME" in
+ push)
+ echo "ref=$SELECTED_REF" >> "$GITHUB_OUTPUT"
+ ;;
+ create)
+ if [ "$GITHUB_EVENT_REF_TYPE" != "tag" ]; then
+ echo "create event was not a tag; skipping" >&2
+ exit 1
+ fi
+ echo "ref=$GITHUB_EVENT_REF" >> "$GITHUB_OUTPUT"
+ ;;
+ workflow_dispatch)
+ # An empty override means "build the ref selected in GitHub's Run workflow
+ # menu". This allows branch builds while keeping explicit overrides limited
+ # to release tags.
+ if [ -z "$INPUT_REF" ]; then
+ echo "ref=$SELECTED_REF" >> "$GITHUB_OUTPUT"
+ exit 0
+ fi
+ if [[ "$INPUT_REF" =~ ^refs/tags/v[0-9][0-9A-Za-z._-]*$ ]]; then
+ echo "ref=$INPUT_REF" >> "$GITHUB_OUTPUT"
+ exit 0
+ fi
+ if [[ "$INPUT_REF" =~ ^v[0-9][0-9A-Za-z._-]*$ ]]; then
+ echo "ref=refs/tags/$INPUT_REF" >> "$GITHUB_OUTPUT"
+ exit 0
+ fi
+ echo "The ref input only accepts release tags (v*). To build a branch, select it in the Run workflow menu and leave ref empty." >&2
+ exit 1
+ ;;
+ *)
+ echo "Unexpected event: $EVENT_NAME" >&2
+ exit 1
+ ;;
+ esac
+ shell: bash
+ env:
+ EVENT_NAME: ${{ github.event_name }}
+ INPUT_REF: ${{ inputs.ref }}
+ GITHUB_EVENT_REF: ${{ github.event.ref }}
+ GITHUB_EVENT_REF_TYPE: ${{ github.event.ref_type }}
+ SELECTED_REF: ${{ github.ref }}
+ build-daemon-linux-x86-64:
+ needs:
+ - resolve-ref
+ name: Build daemon (linux-x86_64)
+ runs-on: namespace-profile-linux-rust-ci
+ steps:
+ - name: Checkout Repo
+ uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10
+ with:
+ ref: ${{ needs.resolve-ref.outputs.ref }}
+ persist-credentials: 'false'
+ - name: Mount Namespace cache volume
+ uses: namespacelabs/nscloud-cache-action@15799a6b54e5765f85b2aac25b3f0df43ed571c0
+ with:
+ cache: rust
+ path: /nix
+ continue-on-error: true
+ - name: Setup Nix
+ uses: './.github/actions/setup-nix'
+ - name: Setup Nix dev shell
+ uses: './.github/actions/setup-nix-dev-shell'
+ - name: Configure Namespace remote sccache
+ if: (github.event_name != 'pull_request' && github.event_name != 'pull_request_target') || github.event.pull_request.head.repo.full_name == github.repository
+ run: |-
+ set -euo pipefail
+ env_file="$(mktemp "$RUNNER_TEMP/namespace-sccache.XXXXXX")"
+ trap 'rm -f "$env_file"' EXIT
+ if nsc cache sccache setup --cache_name sccache-ci > "$env_file"; then
+ # Register credential values as masked BEFORE exporting: GitHub only
+ # masks `secrets.*`, so without this SCCACHE_WEBDAV_TOKEN — a broad,
+ # ~24h Namespace workspace token (registry + cache write) — printed
+ # verbatim in every subsequent step's env dump. Masking is selective by
+ # key name: masking non-secrets like the endpoint URL or key prefix
+ # would redact those strings everywhere in the logs.
+ while IFS= read -r line; do
+ k="${line%%=*}"
+ v="${line#*=}"
+ [ -n "$v" ] && [ "$k" != "$line" ] || continue
+ case "$k" in
+ *TOKEN*|*SECRET*|*PASSWORD*) echo "::add-mask::$v" ;;
+ esac
+ done < "$env_file"
+ cat "$env_file" >> "$GITHUB_ENV"
+ # Force the next compiler invocation to start a server with the new remote
+ # backend even if a setup hook happened to launch one already.
+ sccache --stop-server >/dev/null 2>&1 || true
+ else
+ echo "::warning::Namespace remote sccache setup failed; using local cache fallback"
+ fi
+ - id: metadata
+ name: Derive artifact metadata
+ run: |
+ set -euo pipefail
+ tag="${RAW_REF#refs/tags/}"
+ if [ -z "$tag" ]; then
+ tag="${GITHUB_REF_NAME:-untagged}"
+ fi
+ safe_tag=$(printf '%s' "$tag" | sed 's#[/\\:*?"<>|]#-#g' | tr -d '\r\n')
+ echo "tag=$tag" >> "$GITHUB_OUTPUT"
+ echo "safe_tag=$safe_tag" >> "$GITHUB_OUTPUT"
+ shell: bash
+ env:
+ RAW_REF: ${{ needs.resolve-ref.outputs.ref }}
+ - name: Build daemon
+ run: |
+ set -euo pipefail
+
+ # Statically linked musl build of the self-hosted coding-agent daemon.
+ #
+ # The musl std that ships with the toolchain links pure-Rust crates on its own,
+ # but aws-lc-sys — rustls' crypto provider, and so the whole reason the daemon
+ # can talk HTTPS and WSS — is C, and needs a compiler that targets musl. zig is
+ # that compiler, which is what cargo-zigbuild wires up; it also makes the
+ # aarch64 build a cross-compile rather than a second runner.
+ #
+ # aws-lc-sys' own cc builder rejects zig, so force its cmake builder instead.
+ # The Lambda builds hit the same wall and take the same way out
+ # (see nix/cloud-storage.nix).
+ export AWS_LC_SYS_CMAKE_BUILDER=1
+
+ # The daemon runs no queries of its own, but crates in its dependency graph
+ # carry sqlx macros; offline mode keeps a release build from wanting a database.
+ export SQLX_OFFLINE=true
+
+ cargo zigbuild --release --package coding_agent_worker --target "$TARGET"
+ shell: bash
+ env:
+ TARGET: x86_64-unknown-linux-musl
+ - name: Package daemon
+ run: |
+ set -euo pipefail
+
+ # Package one built daemon binary as a release asset — and prove it is as
+ # self-contained as its platform allows before it ships. A binary that resolves
+ # a library at startup on the build runner and not on a user's machine is
+ # exactly the failure this whole pipeline exists to prevent, so it is checked
+ # here rather than assumed.
+
+ binary="target/$TARGET/release/macrod"
+ if [ ! -x "$binary" ]; then
+ echo "no daemon binary at $binary" >&2
+ exit 1
+ fi
+
+ case "$TARGET" in
+ *-linux-musl)
+ # Statically linked: nothing may be left to resolve at run time. `ldd`
+ # exits non-zero with "not a dynamic executable" for a static binary, so
+ # a successful ldd that names shared objects is the failure case.
+ if ldd "$binary" 2>/dev/null | grep -q '=>'; then
+ echo "expected a static binary, but $binary still links:" >&2
+ ldd "$binary" >&2
+ exit 1
+ fi
+ ;;
+ *-apple-darwin)
+ # macOS has no static libSystem, so "self-contained" means nothing from
+ # outside the OS: a Homebrew or Nix-store path is one that will not exist
+ # on the machine that downloads this.
+ strays=$(otool -L "$binary" | tail -n +2 | awk '{ print $1 }' \
+ | grep -Ev '^(/usr/lib/|/System/Library/)' || true)
+ if [ -n "$strays" ]; then
+ echo "daemon links libraries that will not exist on a user's Mac:" >&2
+ echo "$strays" >&2
+ exit 1
+ fi
+ ;;
+ *)
+ echo "no self-containment check defined for $TARGET" >&2
+ exit 1
+ ;;
+ esac
+
+ # It has to actually run, too — a binary that links cleanly and dies on its
+ # first instruction still ships broken. `--version` is the cheapest end-to-end
+ # proof, and the caller says whether this runner can execute this slice: the
+ # cross-built ones (aarch64 anywhere, x86_64 on an Apple Silicon runner) cannot.
+ if [ "$SMOKE_RUN" = "1" ]; then
+ "$binary" --version
+ else
+ echo "skipping smoke run: $TARGET does not execute on this runner"
+ fi
+
+ mkdir -p artifacts
+ name="macrod-${SAFE_TAG}-${SLUG}"
+ stage=$(mktemp -d)
+ install -m 755 "$binary" "$stage/macrod"
+ tar -czf "artifacts/${name}.tar.gz" -C "$stage" macrod
+ rm -rf "$stage"
+
+ # coreutils on Linux, BSD/perl on macOS.
+ (
+ cd artifacts
+ if command -v sha256sum >/dev/null 2>&1; then
+ sha256sum "${name}.tar.gz" >"${name}.tar.gz.sha256"
+ else
+ shasum -a 256 "${name}.tar.gz" >"${name}.tar.gz.sha256"
+ fi
+ )
+
+ echo "packaged ${name}.tar.gz"
+ shell: bash
+ env:
+ TARGET: x86_64-unknown-linux-musl
+ SLUG: linux-x86_64
+ SAFE_TAG: ${{ steps.metadata.outputs.safe_tag }}
+ SMOKE_RUN: '1'
+ - name: Upload macrod-linux-x86_64-${{ steps.metadata.outputs.safe_tag }} artifact
+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02
+ with:
+ name: macrod-linux-x86_64-${{ steps.metadata.outputs.safe_tag }}
+ path: artifacts/*
+ if-no-files-found: error
+ retention-days: '30'
+ - name: Teardown Nix
+ if: always()
+ uses: './.github/actions/teardown-nix'
+ build-daemon-linux-aarch64:
+ needs:
+ - resolve-ref
+ name: Build daemon (linux-aarch64)
+ runs-on: namespace-profile-linux-rust-ci
+ steps:
+ - name: Checkout Repo
+ uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10
+ with:
+ ref: ${{ needs.resolve-ref.outputs.ref }}
+ persist-credentials: 'false'
+ - name: Mount Namespace cache volume
+ uses: namespacelabs/nscloud-cache-action@15799a6b54e5765f85b2aac25b3f0df43ed571c0
+ with:
+ cache: rust
+ path: /nix
+ continue-on-error: true
+ - name: Setup Nix
+ uses: './.github/actions/setup-nix'
+ - name: Setup Nix dev shell
+ uses: './.github/actions/setup-nix-dev-shell'
+ - name: Configure Namespace remote sccache
+ if: (github.event_name != 'pull_request' && github.event_name != 'pull_request_target') || github.event.pull_request.head.repo.full_name == github.repository
+ run: |-
+ set -euo pipefail
+ env_file="$(mktemp "$RUNNER_TEMP/namespace-sccache.XXXXXX")"
+ trap 'rm -f "$env_file"' EXIT
+ if nsc cache sccache setup --cache_name sccache-ci > "$env_file"; then
+ # Register credential values as masked BEFORE exporting: GitHub only
+ # masks `secrets.*`, so without this SCCACHE_WEBDAV_TOKEN — a broad,
+ # ~24h Namespace workspace token (registry + cache write) — printed
+ # verbatim in every subsequent step's env dump. Masking is selective by
+ # key name: masking non-secrets like the endpoint URL or key prefix
+ # would redact those strings everywhere in the logs.
+ while IFS= read -r line; do
+ k="${line%%=*}"
+ v="${line#*=}"
+ [ -n "$v" ] && [ "$k" != "$line" ] || continue
+ case "$k" in
+ *TOKEN*|*SECRET*|*PASSWORD*) echo "::add-mask::$v" ;;
+ esac
+ done < "$env_file"
+ cat "$env_file" >> "$GITHUB_ENV"
+ # Force the next compiler invocation to start a server with the new remote
+ # backend even if a setup hook happened to launch one already.
+ sccache --stop-server >/dev/null 2>&1 || true
+ else
+ echo "::warning::Namespace remote sccache setup failed; using local cache fallback"
+ fi
+ - id: metadata
+ name: Derive artifact metadata
+ run: |
+ set -euo pipefail
+ tag="${RAW_REF#refs/tags/}"
+ if [ -z "$tag" ]; then
+ tag="${GITHUB_REF_NAME:-untagged}"
+ fi
+ safe_tag=$(printf '%s' "$tag" | sed 's#[/\\:*?"<>|]#-#g' | tr -d '\r\n')
+ echo "tag=$tag" >> "$GITHUB_OUTPUT"
+ echo "safe_tag=$safe_tag" >> "$GITHUB_OUTPUT"
+ shell: bash
+ env:
+ RAW_REF: ${{ needs.resolve-ref.outputs.ref }}
+ - name: Build daemon
+ run: |
+ set -euo pipefail
+
+ # Statically linked musl build of the self-hosted coding-agent daemon.
+ #
+ # The musl std that ships with the toolchain links pure-Rust crates on its own,
+ # but aws-lc-sys — rustls' crypto provider, and so the whole reason the daemon
+ # can talk HTTPS and WSS — is C, and needs a compiler that targets musl. zig is
+ # that compiler, which is what cargo-zigbuild wires up; it also makes the
+ # aarch64 build a cross-compile rather than a second runner.
+ #
+ # aws-lc-sys' own cc builder rejects zig, so force its cmake builder instead.
+ # The Lambda builds hit the same wall and take the same way out
+ # (see nix/cloud-storage.nix).
+ export AWS_LC_SYS_CMAKE_BUILDER=1
+
+ # The daemon runs no queries of its own, but crates in its dependency graph
+ # carry sqlx macros; offline mode keeps a release build from wanting a database.
+ export SQLX_OFFLINE=true
+
+ cargo zigbuild --release --package coding_agent_worker --target "$TARGET"
+ shell: bash
+ env:
+ TARGET: aarch64-unknown-linux-musl
+ - name: Package daemon
+ run: |
+ set -euo pipefail
+
+ # Package one built daemon binary as a release asset — and prove it is as
+ # self-contained as its platform allows before it ships. A binary that resolves
+ # a library at startup on the build runner and not on a user's machine is
+ # exactly the failure this whole pipeline exists to prevent, so it is checked
+ # here rather than assumed.
+
+ binary="target/$TARGET/release/macrod"
+ if [ ! -x "$binary" ]; then
+ echo "no daemon binary at $binary" >&2
+ exit 1
+ fi
+
+ case "$TARGET" in
+ *-linux-musl)
+ # Statically linked: nothing may be left to resolve at run time. `ldd`
+ # exits non-zero with "not a dynamic executable" for a static binary, so
+ # a successful ldd that names shared objects is the failure case.
+ if ldd "$binary" 2>/dev/null | grep -q '=>'; then
+ echo "expected a static binary, but $binary still links:" >&2
+ ldd "$binary" >&2
+ exit 1
+ fi
+ ;;
+ *-apple-darwin)
+ # macOS has no static libSystem, so "self-contained" means nothing from
+ # outside the OS: a Homebrew or Nix-store path is one that will not exist
+ # on the machine that downloads this.
+ strays=$(otool -L "$binary" | tail -n +2 | awk '{ print $1 }' \
+ | grep -Ev '^(/usr/lib/|/System/Library/)' || true)
+ if [ -n "$strays" ]; then
+ echo "daemon links libraries that will not exist on a user's Mac:" >&2
+ echo "$strays" >&2
+ exit 1
+ fi
+ ;;
+ *)
+ echo "no self-containment check defined for $TARGET" >&2
+ exit 1
+ ;;
+ esac
+
+ # It has to actually run, too — a binary that links cleanly and dies on its
+ # first instruction still ships broken. `--version` is the cheapest end-to-end
+ # proof, and the caller says whether this runner can execute this slice: the
+ # cross-built ones (aarch64 anywhere, x86_64 on an Apple Silicon runner) cannot.
+ if [ "$SMOKE_RUN" = "1" ]; then
+ "$binary" --version
+ else
+ echo "skipping smoke run: $TARGET does not execute on this runner"
+ fi
+
+ mkdir -p artifacts
+ name="macrod-${SAFE_TAG}-${SLUG}"
+ stage=$(mktemp -d)
+ install -m 755 "$binary" "$stage/macrod"
+ tar -czf "artifacts/${name}.tar.gz" -C "$stage" macrod
+ rm -rf "$stage"
+
+ # coreutils on Linux, BSD/perl on macOS.
+ (
+ cd artifacts
+ if command -v sha256sum >/dev/null 2>&1; then
+ sha256sum "${name}.tar.gz" >"${name}.tar.gz.sha256"
+ else
+ shasum -a 256 "${name}.tar.gz" >"${name}.tar.gz.sha256"
+ fi
+ )
+
+ echo "packaged ${name}.tar.gz"
+ shell: bash
+ env:
+ TARGET: aarch64-unknown-linux-musl
+ SLUG: linux-aarch64
+ SAFE_TAG: ${{ steps.metadata.outputs.safe_tag }}
+ SMOKE_RUN: '0'
+ - name: Upload macrod-linux-aarch64-${{ steps.metadata.outputs.safe_tag }} artifact
+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02
+ with:
+ name: macrod-linux-aarch64-${{ steps.metadata.outputs.safe_tag }}
+ path: artifacts/*
+ if-no-files-found: error
+ retention-days: '30'
+ - name: Teardown Nix
+ if: always()
+ uses: './.github/actions/teardown-nix'
+ build-daemon-macos-aarch64:
+ needs:
+ - resolve-ref
+ name: Build daemon (macos-aarch64)
+ runs-on: nscloud-macos-sequoia-arm64-6x14
+ steps:
+ - name: Checkout Repo
+ uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10
+ with:
+ ref: ${{ needs.resolve-ref.outputs.ref }}
+ persist-credentials: 'false'
+ - name: Setup Rust
+ uses: './.github/actions/setup-rust'
+ with:
+ sccache: 'false'
+ rust-cache: 'false'
+ - id: metadata
+ name: Derive artifact metadata
+ run: |
+ set -euo pipefail
+ tag="${RAW_REF#refs/tags/}"
+ if [ -z "$tag" ]; then
+ tag="${GITHUB_REF_NAME:-untagged}"
+ fi
+ safe_tag=$(printf '%s' "$tag" | sed 's#[/\\:*?"<>|]#-#g' | tr -d '\r\n')
+ echo "tag=$tag" >> "$GITHUB_OUTPUT"
+ echo "safe_tag=$safe_tag" >> "$GITHUB_OUTPUT"
+ shell: bash
+ env:
+ RAW_REF: ${{ needs.resolve-ref.outputs.ref }}
+ - name: Build daemon
+ run: |
+ set -euo pipefail
+
+ # macOS build of the self-hosted coding-agent daemon.
+ #
+ # No zig here: the Apple targets link against the SDK the runner already has,
+ # and the arm64 runner cross-compiles the x86_64 slice on its own. All this
+ # step needs is the matching rust-std.
+ #
+ # See build_agent_daemon_linux.sh for why sqlx runs offline.
+ export SQLX_OFFLINE=true
+
+ rustup target add "$TARGET"
+
+ # aws-lc-sys compiles its C through cmake. The GitHub macOS image ships cmake
+ # today, but the build is too far downstream to discover that it stopped.
+ if ! command -v cmake >/dev/null 2>&1; then
+ brew install cmake
+ fi
+
+ cargo build --release --package coding_agent_worker --target "$TARGET"
+ shell: bash
+ env:
+ TARGET: aarch64-apple-darwin
+ - name: Package daemon
+ run: |
+ set -euo pipefail
+
+ # Package one built daemon binary as a release asset — and prove it is as
+ # self-contained as its platform allows before it ships. A binary that resolves
+ # a library at startup on the build runner and not on a user's machine is
+ # exactly the failure this whole pipeline exists to prevent, so it is checked
+ # here rather than assumed.
+
+ binary="target/$TARGET/release/macrod"
+ if [ ! -x "$binary" ]; then
+ echo "no daemon binary at $binary" >&2
+ exit 1
+ fi
+
+ case "$TARGET" in
+ *-linux-musl)
+ # Statically linked: nothing may be left to resolve at run time. `ldd`
+ # exits non-zero with "not a dynamic executable" for a static binary, so
+ # a successful ldd that names shared objects is the failure case.
+ if ldd "$binary" 2>/dev/null | grep -q '=>'; then
+ echo "expected a static binary, but $binary still links:" >&2
+ ldd "$binary" >&2
+ exit 1
+ fi
+ ;;
+ *-apple-darwin)
+ # macOS has no static libSystem, so "self-contained" means nothing from
+ # outside the OS: a Homebrew or Nix-store path is one that will not exist
+ # on the machine that downloads this.
+ strays=$(otool -L "$binary" | tail -n +2 | awk '{ print $1 }' \
+ | grep -Ev '^(/usr/lib/|/System/Library/)' || true)
+ if [ -n "$strays" ]; then
+ echo "daemon links libraries that will not exist on a user's Mac:" >&2
+ echo "$strays" >&2
+ exit 1
+ fi
+ ;;
+ *)
+ echo "no self-containment check defined for $TARGET" >&2
+ exit 1
+ ;;
+ esac
+
+ # It has to actually run, too — a binary that links cleanly and dies on its
+ # first instruction still ships broken. `--version` is the cheapest end-to-end
+ # proof, and the caller says whether this runner can execute this slice: the
+ # cross-built ones (aarch64 anywhere, x86_64 on an Apple Silicon runner) cannot.
+ if [ "$SMOKE_RUN" = "1" ]; then
+ "$binary" --version
+ else
+ echo "skipping smoke run: $TARGET does not execute on this runner"
+ fi
+
+ mkdir -p artifacts
+ name="macrod-${SAFE_TAG}-${SLUG}"
+ stage=$(mktemp -d)
+ install -m 755 "$binary" "$stage/macrod"
+ tar -czf "artifacts/${name}.tar.gz" -C "$stage" macrod
+ rm -rf "$stage"
+
+ # coreutils on Linux, BSD/perl on macOS.
+ (
+ cd artifacts
+ if command -v sha256sum >/dev/null 2>&1; then
+ sha256sum "${name}.tar.gz" >"${name}.tar.gz.sha256"
+ else
+ shasum -a 256 "${name}.tar.gz" >"${name}.tar.gz.sha256"
+ fi
+ )
+
+ echo "packaged ${name}.tar.gz"
+ shell: bash
+ env:
+ TARGET: aarch64-apple-darwin
+ SLUG: macos-aarch64
+ SAFE_TAG: ${{ steps.metadata.outputs.safe_tag }}
+ SMOKE_RUN: '1'
+ - name: Upload macrod-macos-aarch64-${{ steps.metadata.outputs.safe_tag }} artifact
+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02
+ with:
+ name: macrod-macos-aarch64-${{ steps.metadata.outputs.safe_tag }}
+ path: artifacts/*
+ if-no-files-found: error
+ retention-days: '30'
+ build-daemon-macos-x86-64:
+ needs:
+ - resolve-ref
+ name: Build daemon (macos-x86_64)
+ runs-on: nscloud-macos-sequoia-arm64-6x14
+ steps:
+ - name: Checkout Repo
+ uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10
+ with:
+ ref: ${{ needs.resolve-ref.outputs.ref }}
+ persist-credentials: 'false'
+ - name: Setup Rust
+ uses: './.github/actions/setup-rust'
+ with:
+ sccache: 'false'
+ rust-cache: 'false'
+ - id: metadata
+ name: Derive artifact metadata
+ run: |
+ set -euo pipefail
+ tag="${RAW_REF#refs/tags/}"
+ if [ -z "$tag" ]; then
+ tag="${GITHUB_REF_NAME:-untagged}"
+ fi
+ safe_tag=$(printf '%s' "$tag" | sed 's#[/\\:*?"<>|]#-#g' | tr -d '\r\n')
+ echo "tag=$tag" >> "$GITHUB_OUTPUT"
+ echo "safe_tag=$safe_tag" >> "$GITHUB_OUTPUT"
+ shell: bash
+ env:
+ RAW_REF: ${{ needs.resolve-ref.outputs.ref }}
+ - name: Build daemon
+ run: |
+ set -euo pipefail
+
+ # macOS build of the self-hosted coding-agent daemon.
+ #
+ # No zig here: the Apple targets link against the SDK the runner already has,
+ # and the arm64 runner cross-compiles the x86_64 slice on its own. All this
+ # step needs is the matching rust-std.
+ #
+ # See build_agent_daemon_linux.sh for why sqlx runs offline.
+ export SQLX_OFFLINE=true
+
+ rustup target add "$TARGET"
+
+ # aws-lc-sys compiles its C through cmake. The GitHub macOS image ships cmake
+ # today, but the build is too far downstream to discover that it stopped.
+ if ! command -v cmake >/dev/null 2>&1; then
+ brew install cmake
+ fi
+
+ cargo build --release --package coding_agent_worker --target "$TARGET"
+ shell: bash
+ env:
+ TARGET: x86_64-apple-darwin
+ - name: Package daemon
+ run: |
+ set -euo pipefail
+
+ # Package one built daemon binary as a release asset — and prove it is as
+ # self-contained as its platform allows before it ships. A binary that resolves
+ # a library at startup on the build runner and not on a user's machine is
+ # exactly the failure this whole pipeline exists to prevent, so it is checked
+ # here rather than assumed.
+
+ binary="target/$TARGET/release/macrod"
+ if [ ! -x "$binary" ]; then
+ echo "no daemon binary at $binary" >&2
+ exit 1
+ fi
+
+ case "$TARGET" in
+ *-linux-musl)
+ # Statically linked: nothing may be left to resolve at run time. `ldd`
+ # exits non-zero with "not a dynamic executable" for a static binary, so
+ # a successful ldd that names shared objects is the failure case.
+ if ldd "$binary" 2>/dev/null | grep -q '=>'; then
+ echo "expected a static binary, but $binary still links:" >&2
+ ldd "$binary" >&2
+ exit 1
+ fi
+ ;;
+ *-apple-darwin)
+ # macOS has no static libSystem, so "self-contained" means nothing from
+ # outside the OS: a Homebrew or Nix-store path is one that will not exist
+ # on the machine that downloads this.
+ strays=$(otool -L "$binary" | tail -n +2 | awk '{ print $1 }' \
+ | grep -Ev '^(/usr/lib/|/System/Library/)' || true)
+ if [ -n "$strays" ]; then
+ echo "daemon links libraries that will not exist on a user's Mac:" >&2
+ echo "$strays" >&2
+ exit 1
+ fi
+ ;;
+ *)
+ echo "no self-containment check defined for $TARGET" >&2
+ exit 1
+ ;;
+ esac
+
+ # It has to actually run, too — a binary that links cleanly and dies on its
+ # first instruction still ships broken. `--version` is the cheapest end-to-end
+ # proof, and the caller says whether this runner can execute this slice: the
+ # cross-built ones (aarch64 anywhere, x86_64 on an Apple Silicon runner) cannot.
+ if [ "$SMOKE_RUN" = "1" ]; then
+ "$binary" --version
+ else
+ echo "skipping smoke run: $TARGET does not execute on this runner"
+ fi
+
+ mkdir -p artifacts
+ name="macrod-${SAFE_TAG}-${SLUG}"
+ stage=$(mktemp -d)
+ install -m 755 "$binary" "$stage/macrod"
+ tar -czf "artifacts/${name}.tar.gz" -C "$stage" macrod
+ rm -rf "$stage"
+
+ # coreutils on Linux, BSD/perl on macOS.
+ (
+ cd artifacts
+ if command -v sha256sum >/dev/null 2>&1; then
+ sha256sum "${name}.tar.gz" >"${name}.tar.gz.sha256"
+ else
+ shasum -a 256 "${name}.tar.gz" >"${name}.tar.gz.sha256"
+ fi
+ )
+
+ echo "packaged ${name}.tar.gz"
+ shell: bash
+ env:
+ TARGET: x86_64-apple-darwin
+ SLUG: macos-x86_64
+ SAFE_TAG: ${{ steps.metadata.outputs.safe_tag }}
+ SMOKE_RUN: '0'
+ - name: Upload macrod-macos-x86_64-${{ steps.metadata.outputs.safe_tag }} artifact
+ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02
+ with:
+ name: macrod-macos-x86_64-${{ steps.metadata.outputs.safe_tag }}
+ path: artifacts/*
+ if-no-files-found: error
+ retention-days: '30'
+ publish-daemon:
+ needs:
+ - resolve-ref
+ - build-daemon-linux-x86-64
+ - build-daemon-linux-aarch64
+ - build-daemon-macos-aarch64
+ - build-daemon-macos-x86-64
+ name: Upload Release Artifacts
+ runs-on: ubuntu-latest
+ permissions:
+ contents: write
+ steps:
+ - id: metadata
+ name: Derive artifact metadata
+ run: |
+ set -euo pipefail
+ tag="${RAW_REF#refs/tags/}"
+ if [ -z "$tag" ]; then
+ tag="${GITHUB_REF_NAME:-untagged}"
+ fi
+ safe_tag=$(printf '%s' "$tag" | sed 's#[/\\:*?"<>|]#-#g' | tr -d '\r\n')
+ echo "tag=$tag" >> "$GITHUB_OUTPUT"
+ echo "safe_tag=$safe_tag" >> "$GITHUB_OUTPUT"
+ shell: bash
+ env:
+ RAW_REF: ${{ needs.resolve-ref.outputs.ref }}
+ - name: Download Build Artifacts
+ uses: actions/download-artifact@634f93cb2916e3fdff6788551b99b062d0335ce0
+ with:
+ path: release-artifacts
+ merge-multiple: 'true'
+ - name: Upload Release Artifacts
+ if: startsWith(steps.metadata.outputs.tag, 'v')
+ uses: softprops/action-gh-release@3bb12739c298aeb8a4eeaf626c5b8d85266b0e65
+ with:
+ tag_name: ${{ steps.metadata.outputs.tag }}
+ files: release-artifacts/*
+ fail_on_unmatched_files: 'true'
+concurrency:
+ group: agent-daemon-${{ inputs.ref || github.ref_name }}
+ cancel-in-progress: true
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index a5baa287ac..e7b7919d29 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -1286,6 +1286,102 @@
"crates/share_permission_db_utils",
"crates/workspace-hack"
],
+ "coding_agent_worker": [
+ "crates/activity",
+ "crates/agent",
+ "crates/agent_fold",
+ "crates/agent_runtime_protocol",
+ "crates/agent_session",
+ "crates/agent_trigger",
+ "crates/ai_toolset",
+ "crates/ai_usage",
+ "crates/attachment",
+ "crates/authentication_service_client",
+ "crates/bot_id",
+ "crates/bots",
+ "crates/broadcast",
+ "crates/call",
+ "crates/channel_sender",
+ "crates/channels",
+ "crates/coding_agent_worker",
+ "crates/connection",
+ "crates/connection_gateway_client",
+ "crates/connection_gateway_models",
+ "crates/contacts",
+ "crates/cowlike",
+ "crates/crm",
+ "crates/document_sub_type",
+ "crates/documents",
+ "crates/email",
+ "crates/email_utils",
+ "crates/embedding",
+ "crates/entity_access",
+ "crates/entity_access_db_utils",
+ "crates/entity_access_management",
+ "crates/entity_mutation",
+ "crates/filter_ast",
+ "crates/foreign_entity",
+ "crates/frecency",
+ "crates/invite_email",
+ "crates/item_filters",
+ "crates/kafka_util",
+ "crates/last_online_tracker",
+ "crates/lexical_client",
+ "crates/macro_auth",
+ "crates/macro_authorization",
+ "crates/macro_aws_config",
+ "crates/macro_entrypoint",
+ "crates/macro_env",
+ "crates/macro_env_var",
+ "crates/macro_event_broker",
+ "crates/macro_event_topics",
+ "crates/macro_service_urls",
+ "crates/macro_sync_service_jwt",
+ "crates/macro_tower_layers",
+ "crates/macro_user_id",
+ "crates/macro_uuid",
+ "crates/mention_utils",
+ "crates/model",
+ "crates/model-entity",
+ "crates/model-error-response",
+ "crates/model_file_type",
+ "crates/model_notifications",
+ "crates/model_user",
+ "crates/models_ai_projection",
+ "crates/models_bulk_upload",
+ "crates/models_email",
+ "crates/models_entity_access_management",
+ "crates/models_opensearch",
+ "crates/models_pagination",
+ "crates/models_permissions",
+ "crates/models_properties",
+ "crates/models_search",
+ "crates/models_search_cursor",
+ "crates/models_soup",
+ "crates/non_empty",
+ "crates/notification",
+ "crates/opensearch_client",
+ "crates/opensearch_query_builder",
+ "crates/prompt",
+ "crates/properties",
+ "crates/rate_limit",
+ "crates/reminders",
+ "crates/remote_env_var",
+ "crates/s3_key",
+ "crates/secretsmanager_client",
+ "crates/share_permission_db_utils",
+ "crates/sqs_client",
+ "crates/sqs_worker",
+ "crates/sync_service",
+ "crates/sync_service_client",
+ "crates/system_properties",
+ "crates/system_skills",
+ "crates/task_dedup",
+ "crates/unfurl",
+ "crates/webhook",
+ "crates/webhook_signature",
+ "crates/workspace-hack"
+ ],
"comms_db_client": [
"crates/activity",
"crates/agent",
@@ -1995,6 +2091,8 @@
"crates/agent",
"crates/agent_fold",
"crates/agent_runtime_protocol",
+ "crates/agent_session",
+ "crates/agent_trigger",
"crates/ai_tools",
"crates/ai_toolset",
"crates/ai_usage",
@@ -2136,6 +2234,7 @@
"crates/unfurl",
"crates/user_quota",
"crates/webhook",
+ "crates/webhook_signature",
"crates/workspace-hack",
"services/document_storage_service"
],
@@ -6932,11 +7031,14 @@
"crates/agent",
"crates/agent_fold",
"crates/agent_runtime_protocol",
+ "crates/agent_session",
+ "crates/agent_trigger",
"crates/ai_toolset",
"crates/ai_usage",
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bots",
"crates/broadcast",
"crates/call",
"crates/channel_sender",
@@ -7016,6 +7118,11 @@
"crates/task_dedup",
"crates/unfurl",
"crates/webhook",
+ "crates/webhook_signature",
+ "crates/workspace-hack"
+ ],
+ "webhook_signature": [
+ "crates/webhook_signature",
"crates/workspace-hack"
],
"worker-rs-otel": [
diff --git a/.gitignore b/.gitignore
index 68e40ea333..7f0611661d 100644
--- a/.gitignore
+++ b/.gitignore
@@ -35,3 +35,4 @@ infra/local/generated/
.pi/outputs/
.commandcode/
**/.webhook.json
+/artifacts
diff --git a/.sqlx/query-97ce7a26f2d9eb32dc03bddef530bddccb8b87cefe615ad257f10c179245ba0c.json b/.sqlx/query-1b01a7091a13b8088a31b1f4d539a47e43f866d1cc6ff35e2046924f71011039.json
similarity index 75%
rename from .sqlx/query-97ce7a26f2d9eb32dc03bddef530bddccb8b87cefe615ad257f10c179245ba0c.json
rename to .sqlx/query-1b01a7091a13b8088a31b1f4d539a47e43f866d1cc6ff35e2046924f71011039.json
index 3c0198d46e..8135b925e6 100644
--- a/.sqlx/query-97ce7a26f2d9eb32dc03bddef530bddccb8b87cefe615ad257f10c179245ba0c.json
+++ b/.sqlx/query-1b01a7091a13b8088a31b1f4d539a47e43f866d1cc6ff35e2046924f71011039.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n id, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, acp_session_id, status, status_event_name,\n created_at, modified_at,\n (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\"\n FROM agent_session\n WHERE thread_id = $1 AND bot_id = $2\n ORDER BY created_at DESC\n LIMIT 1\n ",
+ "query": "\n SELECT\n id, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, workspace, acp_session_id, status,\n status_event_name, created_at, modified_at,\n (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\"\n FROM agent_session\n WHERE thread_id = $1 AND bot_id = $2\n ORDER BY created_at DESC\n LIMIT 1\n ",
"describe": {
"columns": [
{
@@ -45,31 +45,36 @@
},
{
"ordinal": 8,
- "name": "acp_session_id",
+ "name": "workspace",
"type_info": "Text"
},
{
"ordinal": 9,
- "name": "status",
+ "name": "acp_session_id",
"type_info": "Text"
},
{
"ordinal": 10,
- "name": "status_event_name",
+ "name": "status",
"type_info": "Text"
},
{
"ordinal": 11,
+ "name": "status_event_name",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 12,
"name": "created_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 12,
+ "ordinal": 13,
"name": "modified_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 13,
+ "ordinal": 14,
"name": "thread_channel_id?",
"type_info": "Uuid"
}
@@ -88,6 +93,7 @@
false,
false,
false,
+ true,
false,
true,
false,
@@ -97,5 +103,5 @@
null
]
},
- "hash": "97ce7a26f2d9eb32dc03bddef530bddccb8b87cefe615ad257f10c179245ba0c"
+ "hash": "1b01a7091a13b8088a31b1f4d539a47e43f866d1cc6ff35e2046924f71011039"
}
diff --git a/.sqlx/query-284cbb89903bdbc2a8f42e0b4702f52dddc568e5d49086647bff2bf46d33ed8a.json b/.sqlx/query-1b6a994bc0efcc170efa1e9e9115289830b5bc89bfd64dfdb870a503c34ff07e.json
similarity index 78%
rename from .sqlx/query-284cbb89903bdbc2a8f42e0b4702f52dddc568e5d49086647bff2bf46d33ed8a.json
rename to .sqlx/query-1b6a994bc0efcc170efa1e9e9115289830b5bc89bfd64dfdb870a503c34ff07e.json
index 62c05ada48..dd40fd3057 100644
--- a/.sqlx/query-284cbb89903bdbc2a8f42e0b4702f52dddc568e5d49086647bff2bf46d33ed8a.json
+++ b/.sqlx/query-1b6a994bc0efcc170efa1e9e9115289830b5bc89bfd64dfdb870a503c34ff07e.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n id, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, acp_session_id, status, status_event_name,\n created_at, modified_at,\n (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\"\n FROM agent_session\n WHERE id = $1\n ",
+ "query": "\n SELECT\n id, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, workspace, acp_session_id, status,\n status_event_name, created_at, modified_at,\n (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\"\n FROM agent_session\n WHERE id = $1\n ",
"describe": {
"columns": [
{
@@ -45,31 +45,36 @@
},
{
"ordinal": 8,
- "name": "acp_session_id",
+ "name": "workspace",
"type_info": "Text"
},
{
"ordinal": 9,
- "name": "status",
+ "name": "acp_session_id",
"type_info": "Text"
},
{
"ordinal": 10,
- "name": "status_event_name",
+ "name": "status",
"type_info": "Text"
},
{
"ordinal": 11,
+ "name": "status_event_name",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 12,
"name": "created_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 12,
+ "ordinal": 13,
"name": "modified_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 13,
+ "ordinal": 14,
"name": "thread_channel_id?",
"type_info": "Uuid"
}
@@ -87,6 +92,7 @@
false,
false,
false,
+ true,
false,
true,
false,
@@ -96,5 +102,5 @@
null
]
},
- "hash": "284cbb89903bdbc2a8f42e0b4702f52dddc568e5d49086647bff2bf46d33ed8a"
+ "hash": "1b6a994bc0efcc170efa1e9e9115289830b5bc89bfd64dfdb870a503c34ff07e"
}
diff --git a/.sqlx/query-ec49a0e8b746ec3c00169e46003fdde30d06177a76cdd8f63735758334b614fb.json b/.sqlx/query-4a0dce32f3ee05bc65e3707e9ce5fd4d12fd92d583a422cdf05b29d3d639c5f5.json
similarity index 71%
rename from .sqlx/query-ec49a0e8b746ec3c00169e46003fdde30d06177a76cdd8f63735758334b614fb.json
rename to .sqlx/query-4a0dce32f3ee05bc65e3707e9ce5fd4d12fd92d583a422cdf05b29d3d639c5f5.json
index 8d04514539..b22638e3ff 100644
--- a/.sqlx/query-ec49a0e8b746ec3c00169e46003fdde30d06177a76cdd8f63735758334b614fb.json
+++ b/.sqlx/query-4a0dce32f3ee05bc65e3707e9ce5fd4d12fd92d583a422cdf05b29d3d639c5f5.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n INSERT INTO agent_session (\n id, owner_id, thread_id, originating_message_id, bot_id, model,\n harness, repo_url, acp_session_id, status, status_event_name\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)\n RETURNING\n id, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, acp_session_id, status, status_event_name,\n created_at, modified_at,\n (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\"\n ",
+ "query": "\n INSERT INTO agent_session (\n id, owner_id, thread_id, originating_message_id, bot_id, model,\n harness, repo_url, workspace, acp_session_id, status,\n status_event_name\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)\n RETURNING\n id, owner_id, thread_id, originating_message_id, bot_id,\n model, harness, repo_url, workspace, acp_session_id, status,\n status_event_name, created_at, modified_at,\n (SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)\n AS \"thread_channel_id?\"\n ",
"describe": {
"columns": [
{
@@ -45,31 +45,36 @@
},
{
"ordinal": 8,
- "name": "acp_session_id",
+ "name": "workspace",
"type_info": "Text"
},
{
"ordinal": 9,
- "name": "status",
+ "name": "acp_session_id",
"type_info": "Text"
},
{
"ordinal": 10,
- "name": "status_event_name",
+ "name": "status",
"type_info": "Text"
},
{
"ordinal": 11,
+ "name": "status_event_name",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 12,
"name": "created_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 12,
+ "ordinal": 13,
"name": "modified_at",
"type_info": "Timestamptz"
},
{
- "ordinal": 13,
+ "ordinal": 14,
"name": "thread_channel_id?",
"type_info": "Uuid"
}
@@ -86,6 +91,7 @@
"Text",
"Text",
"Text",
+ "Text",
"Text"
]
},
@@ -97,6 +103,7 @@
false,
false,
false,
+ true,
false,
true,
false,
@@ -106,5 +113,5 @@
null
]
},
- "hash": "ec49a0e8b746ec3c00169e46003fdde30d06177a76cdd8f63735758334b614fb"
+ "hash": "4a0dce32f3ee05bc65e3707e9ce5fd4d12fd92d583a422cdf05b29d3d639c5f5"
}
diff --git a/.sqlx/query-0c12508f0a369f8b12d80ea6c8b8ab09f9e95fa463585e5a5d2ba884909abe01.json b/.sqlx/query-8bc90c2fc983342cddf149b9b12c1279d0c8200e3a1c0717e7a196018b4216c9.json
similarity index 73%
rename from .sqlx/query-0c12508f0a369f8b12d80ea6c8b8ab09f9e95fa463585e5a5d2ba884909abe01.json
rename to .sqlx/query-8bc90c2fc983342cddf149b9b12c1279d0c8200e3a1c0717e7a196018b4216c9.json
index 9797ea6233..f15f400335 100644
--- a/.sqlx/query-0c12508f0a369f8b12d80ea6c8b8ab09f9e95fa463585e5a5d2ba884909abe01.json
+++ b/.sqlx/query-8bc90c2fc983342cddf149b9b12c1279d0c8200e3a1c0717e7a196018b4216c9.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n INSERT INTO bots (\n id, kind, owner_user_id, team_id, name, handle, description, avatar_url, created_by\n )\n VALUES ($1, 'owned', $2, $3, $4, $5, $6, $7, $8)\n RETURNING\n id,\n kind,\n owner_user_id,\n team_id,\n name,\n handle,\n description,\n avatar_url,\n created_by,\n created_at,\n updated_at,\n deleted_at,\n has_agent\n ",
+ "query": "\n INSERT INTO bots (\n id, kind, owner_user_id, team_id, name, handle, description, avatar_url,\n created_by, has_agent\n )\n VALUES ($1, 'owned', $2, $3, $4, $5, $6, $7, $8, COALESCE($9, false))\n RETURNING\n id,\n kind,\n owner_user_id,\n team_id,\n name,\n handle,\n description,\n avatar_url,\n created_by,\n created_at,\n updated_at,\n deleted_at,\n has_agent\n ",
"describe": {
"columns": [
{
@@ -78,7 +78,8 @@
"Text",
"Text",
"Text",
- "Text"
+ "Text",
+ "Bool"
]
},
"nullable": [
@@ -97,5 +98,5 @@
false
]
},
- "hash": "0c12508f0a369f8b12d80ea6c8b8ab09f9e95fa463585e5a5d2ba884909abe01"
+ "hash": "8bc90c2fc983342cddf149b9b12c1279d0c8200e3a1c0717e7a196018b4216c9"
}
diff --git a/.sqlx/query-2193ea6a085a6ca908e4f050ff8772232065f9ea07d8c413853fe3f391a2b02f.json b/.sqlx/query-9a40ec0b7b576db4194a6a1c8dab550bce0aa53d0099f9e7e3574be42bd2b8ce.json
similarity index 74%
rename from .sqlx/query-2193ea6a085a6ca908e4f050ff8772232065f9ea07d8c413853fe3f391a2b02f.json
rename to .sqlx/query-9a40ec0b7b576db4194a6a1c8dab550bce0aa53d0099f9e7e3574be42bd2b8ce.json
index 24b6581bfa..280dfc84eb 100644
--- a/.sqlx/query-2193ea6a085a6ca908e4f050ff8772232065f9ea07d8c413853fe3f391a2b02f.json
+++ b/.sqlx/query-9a40ec0b7b576db4194a6a1c8dab550bce0aa53d0099f9e7e3574be42bd2b8ce.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n UPDATE bots\n SET name = COALESCE($2, name),\n handle = COALESCE($3, handle),\n description = COALESCE($4, description),\n avatar_url = COALESCE($5, avatar_url),\n updated_at = now()\n WHERE id = $1\n AND deleted_at IS NULL\n RETURNING\n id,\n kind,\n owner_user_id,\n team_id,\n name,\n handle,\n description,\n avatar_url,\n created_by,\n created_at,\n updated_at,\n deleted_at,\n has_agent\n ",
+ "query": "\n UPDATE bots\n SET name = COALESCE($2, name),\n handle = COALESCE($3, handle),\n description = COALESCE($4, description),\n avatar_url = COALESCE($5, avatar_url),\n has_agent = COALESCE($6, has_agent),\n updated_at = now()\n WHERE id = $1\n AND deleted_at IS NULL\n RETURNING\n id,\n kind,\n owner_user_id,\n team_id,\n name,\n handle,\n description,\n avatar_url,\n created_by,\n created_at,\n updated_at,\n deleted_at,\n has_agent\n ",
"describe": {
"columns": [
{
@@ -75,7 +75,8 @@
"Text",
"Text",
"Text",
- "Text"
+ "Text",
+ "Bool"
]
},
"nullable": [
@@ -94,5 +95,5 @@
false
]
},
- "hash": "2193ea6a085a6ca908e4f050ff8772232065f9ea07d8c413853fe3f391a2b02f"
+ "hash": "9a40ec0b7b576db4194a6a1c8dab550bce0aa53d0099f9e7e3574be42bd2b8ce"
}
diff --git a/.sqlx/query-789032d7c308dd2faedd24387f78362acb64f8f8b530c4bb54512c3aabce57c2.json b/.sqlx/query-ce4b4bb6eb2914d32b6101026bf32b80d9385858668ab7e99b96faecdac27b30.json
similarity index 81%
rename from .sqlx/query-789032d7c308dd2faedd24387f78362acb64f8f8b530c4bb54512c3aabce57c2.json
rename to .sqlx/query-ce4b4bb6eb2914d32b6101026bf32b80d9385858668ab7e99b96faecdac27b30.json
index 4718e57588..1d686d7e3e 100644
--- a/.sqlx/query-789032d7c308dd2faedd24387f78362acb64f8f8b530c4bb54512c3aabce57c2.json
+++ b/.sqlx/query-ce4b4bb6eb2914d32b6101026bf32b80d9385858668ab7e99b96faecdac27b30.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n INSERT INTO webhook (\n id, workspace_id, namespace, name, endpoint_url, signing_secret, headers,\n filters, status, is_valid, created_by_user_id\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, false, $10)\n ON CONFLICT (workspace_id, namespace) WHERE deleted_at IS NULL DO NOTHING\n ",
+ "query": "\n INSERT INTO webhook (\n id, workspace_id, namespace, name, endpoint_url, signing_secret,\n headers, filters, status, is_valid, created_by_user_id\n )\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, false, $10)\n ON CONFLICT (workspace_id, namespace) WHERE deleted_at IS NULL DO NOTHING\n ",
"describe": {
"columns": [],
"parameters": {
@@ -19,5 +19,5 @@
},
"nullable": []
},
- "hash": "789032d7c308dd2faedd24387f78362acb64f8f8b530c4bb54512c3aabce57c2"
+ "hash": "ce4b4bb6eb2914d32b6101026bf32b80d9385858668ab7e99b96faecdac27b30"
}
diff --git a/Cargo.lock b/Cargo.lock
index d879567466..539ec7257b 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -200,6 +200,7 @@ dependencies = [
"agent_session",
"agent_trigger",
"anyhow",
+ "axum",
"base64 0.22.1",
"bot_id",
"channel_sender",
@@ -209,6 +210,7 @@ dependencies = [
"futures",
"kafka_util",
"lexical_client",
+ "macro_authorization",
"macro_env_var",
"macro_event_broker",
"macro_user_id",
@@ -262,6 +264,7 @@ dependencies = [
"macro_event_broker",
"macro_queues",
"macro_service_urls",
+ "macro_user_id",
"macro_uuid",
"notification",
"rdkafka",
@@ -305,6 +308,7 @@ dependencies = [
"agent_runtime_protocol",
"anyhow",
"axum",
+ "bot_id",
"bots",
"chrono",
"clap",
@@ -314,6 +318,7 @@ dependencies = [
"entity_access_db_utils",
"macro_authorization",
"macro_db_migrator",
+ "macro_service_urls",
"macro_user_id",
"macro_uuid",
"mockall",
@@ -327,6 +332,7 @@ dependencies = [
"thiserror 2.0.18",
"tokio",
"tokio-tungstenite 0.28.0",
+ "tower 0.5.3",
"tracing",
"utoipa",
"workspace-hack",
@@ -348,6 +354,7 @@ dependencies = [
"mockall",
"serde",
"serde_json",
+ "strum 0.27.2",
"thiserror 2.0.18",
"tokio",
"tracing",
@@ -3389,6 +3396,43 @@ dependencies = [
"thiserror 2.0.18",
]
+[[package]]
+name = "coding_agent_worker"
+version = "0.1.0"
+dependencies = [
+ "agent-client-protocol",
+ "agent_runtime_protocol",
+ "agent_session",
+ "agent_trigger",
+ "axum",
+ "bot_id",
+ "bots",
+ "channel_sender",
+ "channels",
+ "chrono",
+ "clap",
+ "dashmap",
+ "macro_event_broker",
+ "macro_user_id",
+ "macro_uuid",
+ "reqwest 0.13.4",
+ "rootcause",
+ "serde",
+ "serde_json",
+ "strum 0.27.2",
+ "thiserror 2.0.18",
+ "tokio",
+ "tokio-retry",
+ "tokio-tungstenite 0.28.0",
+ "toml 0.8.23",
+ "tower 0.5.3",
+ "tracing",
+ "tracing-subscriber",
+ "webhook",
+ "webhook_signature",
+ "workspace-hack",
+]
+
[[package]]
name = "color_quant"
version = "1.1.0"
@@ -6936,7 +6980,7 @@ dependencies = [
"smallvec",
"static_assertions",
"target-spec",
- "toml",
+ "toml 0.5.11",
]
[[package]]
@@ -6951,7 +6995,7 @@ dependencies = [
"guppy-workspace-hack",
"semver",
"serde",
- "toml",
+ "toml 0.5.11",
]
[[package]]
@@ -7022,7 +7066,7 @@ dependencies = [
"serde",
"tabular",
"target-spec",
- "toml",
+ "toml 0.5.11",
"toml_edit 0.22.27",
"twox-hash",
]
@@ -14157,6 +14201,15 @@ dependencies = [
"syn 2.0.117",
]
+[[package]]
+name = "serde_spanned"
+version = "0.6.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3"
+dependencies = [
+ "serde",
+]
+
[[package]]
name = "serde_urlencoded"
version = "0.7.1"
@@ -15914,11 +15967,26 @@ dependencies = [
"serde",
]
+[[package]]
+name = "toml"
+version = "0.8.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362"
+dependencies = [
+ "serde",
+ "serde_spanned",
+ "toml_datetime 0.6.11",
+ "toml_edit 0.22.27",
+]
+
[[package]]
name = "toml_datetime"
version = "0.6.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c"
+dependencies = [
+ "serde",
+]
[[package]]
name = "toml_datetime"
@@ -15936,6 +16004,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a"
dependencies = [
"indexmap 2.14.0",
+ "serde",
+ "serde_spanned",
"toml_datetime 0.6.11",
"toml_write",
"winnow 0.7.15",
@@ -17115,6 +17185,8 @@ dependencies = [
name = "webhook"
version = "0.1.0"
dependencies = [
+ "agent_session",
+ "agent_trigger",
"anyhow",
"axum",
"axum-extra",
@@ -17125,8 +17197,6 @@ dependencies = [
"documents",
"entity_access",
"futures",
- "hex",
- "hmac 0.12.1",
"kafka_util",
"macro_authorization",
"macro_db_migrator",
@@ -17142,7 +17212,6 @@ dependencies = [
"rootcause",
"serde",
"serde_json",
- "sha2 0.10.9",
"sqlx",
"sqs_client",
"thiserror 2.0.18",
@@ -17153,6 +17222,17 @@ dependencies = [
"url",
"utoipa",
"uuid",
+ "webhook_signature",
+ "workspace-hack",
+]
+
+[[package]]
+name = "webhook_signature"
+version = "0.1.0"
+dependencies = [
+ "hex",
+ "hmac 0.12.1",
+ "sha2 0.10.9",
"workspace-hack",
]
@@ -17977,7 +18057,7 @@ dependencies = [
"hakari",
"serde",
"serde_json",
- "toml",
+ "toml 0.8.23",
"xtask_graph",
]
diff --git a/Cargo.toml b/Cargo.toml
index 07f69b2f05..8bf0686a66 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -18,6 +18,7 @@ members = [
"crates/client/cache-turso",
"crates/client/cache-wasm",
"crates/client/turso-opfs",
+ "crates/coding_agent_worker",
"crates/complete_graph",
"crates/cowlike",
"crates/crm",
@@ -61,6 +62,7 @@ members = [
"crates/system_skills",
"crates/task_dedup",
"crates/unfurl",
+ "crates/webhook_signature",
"crates/worker-rs-otel",
"crates/workspace-hack",
"services/agent_harness_service",
@@ -281,6 +283,7 @@ tower-http = { version = "0.6.1", features = [
"cors",
"trace",
] }
+toml = "0.8"
tracing = "0.1.44"
tracing-opentelemetry = "0.32.1"
tracing-subscriber = { version = "0.3.22", features = ["env-filter", "json"] }
diff --git a/apps/web/src/features/block-agent/debug/replay/driver.ts b/apps/web/src/features/block-agent/debug/replay/driver.ts
index 4d13d37926..b688a3cbc1 100644
--- a/apps/web/src/features/block-agent/debug/replay/driver.ts
+++ b/apps/web/src/features/block-agent/debug/replay/driver.ts
@@ -80,6 +80,7 @@ function sessionFixture(id: string): AgentSessionResponse {
ownerId: REPLAY_OWNER,
repoUrl: 'https://example.com/replay.git',
status: { kind: 'no_messages' },
+ workspace: '/workspace',
};
}
diff --git a/apps/web/src/features/channel/Bots/BotAgentSection.tsx b/apps/web/src/features/channel/Bots/BotAgentSection.tsx
new file mode 100644
index 0000000000..121677dc0f
--- /dev/null
+++ b/apps/web/src/features/channel/Bots/BotAgentSection.tsx
@@ -0,0 +1,42 @@
+import { ToggleSwitch } from '@ui';
+import { Show } from 'solid-js';
+import { useChatV3AgentsFlag } from '../use-chat-v3-agents-flag';
+import { BotFormSection } from './BotFormSection';
+
+/**
+ * The "Coding agent" toggle. Hidden entirely unless the chat v3 agents flag is
+ * on, so bots stay plain webhook bots for everyone else.
+ */
+export function BotAgentSection(props: {
+ checked: boolean;
+ disabled?: boolean;
+ onChange: (checked: boolean) => void;
+}) {
+ const agentsEnabled = useChatV3AgentsFlag();
+
+ return (
+ <Show when={agentsEnabled()}>
+ <BotFormSection
+ title="Agent"
+ description="Turn this bot into a coding agent instead of a webhook responder."
+ >
+ <div class="flex items-center justify-between gap-4">
+ <div class="min-w-0">
+ <div class="text-sm font-medium text-ink">Agent Harness</div>
+ <p class="mt-0.5 text-xs text-ink-muted">
+ This bot manages an agent harness like Codex or Hermes
+ </p>
+ </div>
+ <ToggleSwitch
+ size="md"
+ checked={props.checked}
+ disabled={props.disabled}
+ onChange={props.onChange}
+ label={<span>Make this bot a coding agent</span>}
+ labelClass="sr-only"
+ />
+ </div>
+ </BotFormSection>
+ </Show>
+ );
+}
diff --git a/apps/web/src/features/channel/Bots/BotCreatePage.tsx b/apps/web/src/features/channel/Bots/BotCreatePage.tsx
index 3bc39f8df8..25b77936d0 100644
--- a/apps/web/src/features/channel/Bots/BotCreatePage.tsx
+++ b/apps/web/src/features/channel/Bots/BotCreatePage.tsx
@@ -16,6 +16,7 @@ import type { Bot } from '@service-storage/generated/schemas/bot';
import { Button, ToggleSwitch } from '@ui';
import { createMemo, createSignal, Show } from 'solid-js';
import { createStore } from 'solid-js/store';
+import { BotAgentSection } from './BotAgentSection';
import { BotCreationResult } from './BotCreationResult';
import { BotFormSection } from './BotFormSection';
import { BotProfileFields } from './BotProfileFields';
@@ -112,6 +113,7 @@ export function BotCreate(props: { channelId?: string; onBack: () => void }) {
description: values.description || undefined,
avatar_url: values.avatarUrl || undefined,
token_label: 'webhook',
+ has_agent: values.hasAgent,
},
{
onSuccess: async ({ bot, bot_token }) => {
@@ -145,6 +147,7 @@ export function BotCreate(props: { channelId?: string; onBack: () => void }) {
handle: values.handle,
description: values.description || undefined,
avatarUrl: values.avatarUrl || undefined,
+ hasAgent: values.hasAgent,
},
{
onSuccess: (bot) => {
@@ -240,6 +243,12 @@ export function BotCreate(props: { channelId?: string; onBack: () => void }) {
/>
</BotFormSection>
+ <BotAgentSection
+ checked={form.hasAgent}
+ disabled={pending()}
+ onChange={(checked) => setForm('hasAgent', checked)}
+ />
+
<BotFormSection
title="Ownership"
description="Bots are personal by default."
diff --git a/apps/web/src/features/channel/Bots/BotDetailPage.tsx b/apps/web/src/features/channel/Bots/BotDetailPage.tsx
index 042089f965..59c5ee8b43 100644
--- a/apps/web/src/features/channel/Bots/BotDetailPage.tsx
+++ b/apps/web/src/features/channel/Bots/BotDetailPage.tsx
@@ -12,6 +12,7 @@ import { useSyncBotChannelsMutation } from '@queries/channel/channel-bots';
import { Button } from '@ui';
import { createEffect, createMemo, createSignal, on, Show } from 'solid-js';
import { createStore } from 'solid-js/store';
+import { BotAgentSection } from './BotAgentSection';
import { BotAvatar } from './BotAvatar';
import { BotDeleteDialog } from './BotDeleteDialog';
import { BotDetailActions } from './BotDetailActions';
@@ -91,7 +92,8 @@ export function BotDetail(props: { botId: string; onBack: () => void }) {
form.name === original.name &&
form.handle === original.handle &&
form.description === original.description &&
- form.avatarUrl === original.avatarUrl;
+ form.avatarUrl === original.avatarUrl &&
+ form.hasAgent === original.hasAgent;
return (
!sameForm || !sameChannelSelection(initialChannelIds(), channelIds())
);
@@ -120,6 +122,7 @@ export function BotDetail(props: { botId: string; onBack: () => void }) {
handle: parsed.data.handle,
description: parsed.data.description ?? '',
avatarUrl: parsed.data.avatarUrl ?? '',
+ hasAgent: parsed.data.hasAgent,
});
const channelResult = await syncChannelsMutation.mutateAsync({
botId: props.botId,
@@ -248,6 +251,12 @@ export function BotDetail(props: { botId: string; onBack: () => void }) {
/>
</BotFormSection>
+ <BotAgentSection
+ checked={form.hasAgent}
+ disabled={saving()}
+ onChange={(checked) => setForm('hasAgent', checked)}
+ />
+
<BotFormSection
title="Channels"
description="Choose every channel this bot can post to."
diff --git a/apps/web/src/features/channel/Bots/botForm.ts b/apps/web/src/features/channel/Bots/botForm.ts
index c2d6a9b615..d75cf035c9 100644
--- a/apps/web/src/features/channel/Bots/botForm.ts
+++ b/apps/web/src/features/channel/Bots/botForm.ts
@@ -11,6 +11,7 @@ const botFormSchema = z.object({
.regex(/^[a-z0-9_-]+$/, "Use lowercase letters, numbers, '-' or '_' only."),
description: z.string().trim().max(500),
avatarUrl: z.string().trim(),
+ hasAgent: z.boolean(),
});
export type BotFormValues = z.infer<typeof botFormSchema>;
@@ -21,6 +22,7 @@ export const EMPTY_BOT_FORM: BotFormValues = {
handle: '',
description: '',
avatarUrl: '',
+ hasAgent: false,
};
export function botToFormValues(bot: Bot): BotFormValues {
@@ -29,6 +31,7 @@ export function botToFormValues(bot: Bot): BotFormValues {
handle: bot.handle,
description: bot.description ?? '',
avatarUrl: bot.avatar_url ?? '',
+ hasAgent: bot.has_agent,
};
}
diff --git a/apps/web/src/features/channel/Bots/tests/bot-form.test.ts b/apps/web/src/features/channel/Bots/tests/bot-form.test.ts
index fbc213925d..f81e16e8fc 100644
--- a/apps/web/src/features/channel/Bots/tests/bot-form.test.ts
+++ b/apps/web/src/features/channel/Bots/tests/bot-form.test.ts
@@ -13,6 +13,7 @@ describe('bot form', () => {
handle: ' release-bot ',
description: ' Posts releases ',
avatarUrl: ' https://example.com/avatar.png ',
+ hasAgent: true,
});
expect(result).toEqual({
@@ -22,6 +23,7 @@ describe('bot form', () => {
handle: 'release-bot',
description: 'Posts releases',
avatarUrl: 'https://example.com/avatar.png',
+ hasAgent: true,
},
});
});
@@ -32,6 +34,7 @@ describe('bot form', () => {
handle: 'Invalid Handle',
description: '',
avatarUrl: '',
+ hasAgent: false,
});
expect(result.success).toBe(false);
diff --git a/apps/web/src/lib/queries/bots/bots.ts b/apps/web/src/lib/queries/bots/bots.ts
index a8836471c9..8a34d16e41 100644
--- a/apps/web/src/lib/queries/bots/bots.ts
+++ b/apps/web/src/lib/queries/bots/bots.ts
@@ -10,6 +10,7 @@ type CreateBotParams = {
avatarUrl?: string;
description?: string;
handle: string;
+ hasAgent?: boolean;
name: string;
teamId?: string;
};
@@ -20,7 +21,8 @@ type CreateBotTokenParams = {
expiresAt?: string;
};
-type UpdateBotParams = Omit<CreateBotParams, 'teamId'> & {
+/** PATCH /bots/{bot_id} leaves every omitted field unchanged. */
+type UpdateBotParams = Partial<Omit<CreateBotParams, 'teamId'>> & {
botId: string;
};
@@ -58,6 +60,7 @@ export function useCreateBotMutation() {
avatar_url: vars.avatarUrl,
description: vars.description,
handle: vars.handle,
+ has_agent: vars.hasAgent,
name: vars.name,
team_id: vars.teamId,
})
@@ -77,6 +80,7 @@ export function useUpdateBotMutation() {
avatar_url: vars.avatarUrl,
description: vars.description,
handle: vars.handle,
+ has_agent: vars.hasAgent,
name: vars.name,
})
),
diff --git a/apps/web/src/lib/queries/channel/channel-bots.ts b/apps/web/src/lib/queries/channel/channel-bots.ts
index 5e31beec22..3278f2de27 100644
--- a/apps/web/src/lib/queries/channel/channel-bots.ts
+++ b/apps/web/src/lib/queries/channel/channel-bots.ts
@@ -25,6 +25,7 @@ type SyncBotChannelsParams = {
type CreateChannelScopedBotParams = CreateChannelScopedBotRequest & {
channelId: string;
+ has_agent?: boolean;
};
export function useChannelBotsQuery(channelId: () => string) {
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/client.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/client.ts
index 9b5ee222a4..7152401252 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/client.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/client.ts
@@ -9,8 +9,91 @@ import type {
AgentSessionLogResponse,
AgentSessionResponse,
ControlRequest,
+ CreateAgentSessionRequest,
+ CreateAgentSessionResponse,
} from './schemas';
+/**
+ * Nothing here tells the runtime where to dial: one connection per bot
+carries every session it runs, so a runtime that has already dialed serves
+this session too, and one that has not dials the gateway its own
+configuration names. The triggering mention reaches the session as its
+first prompt through the control endpoint.
+ * @summary Open an agent session served by an external runtime.
+ */
+export type createAgentSessionResponse201 = {
+ data: CreateAgentSessionResponse;
+ status: 201;
+};
+
+export type createAgentSessionResponse401 = {
+ data: string;
+ status: 401;
+};
+
+export type createAgentSessionResponse403 = {
+ data: string;
+ status: 403;
+};
+
+export type createAgentSessionResponse404 = {
+ data: string;
+ status: 404;
+};
+
+export type createAgentSessionResponse422 = {
+ data: string;
+ status: 422;
+};
+
+export type createAgentSessionResponse500 = {
+ data: string;
+ status: 500;
+};
+
+export type createAgentSessionResponseSuccess =
+ createAgentSessionResponse201 & {
+ headers: Headers;
+ };
+export type createAgentSessionResponseError = (
+ | createAgentSessionResponse401
+ | createAgentSessionResponse403
+ | createAgentSessionResponse404
+ | createAgentSessionResponse422
+ | createAgentSessionResponse500
+) & {
+ headers: Headers;
+};
+
+export type createAgentSessionResponse =
+ | createAgentSessionResponseSuccess
+ | createAgentSessionResponseError;
+
+export const getCreateAgentSessionUrl = () => {
+ return `/agent-sessions`;
+};
+
+export const createAgentSession = async (
+ createAgentSessionRequest: CreateAgentSessionRequest,
+ options?: RequestInit
+): Promise<createAgentSessionResponse> => {
+ const res = await fetch(getCreateAgentSessionUrl(), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(createAgentSessionRequest),
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: createAgentSessionResponse['data'] = body ? JSON.parse(body) : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as createAgentSessionResponse;
+};
+
/**
* @summary Get an agent session by id.
*/
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionResponse.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionResponse.ts
index 44d1289c70..6b4cbf6d66 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionResponse.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionResponse.ts
@@ -6,12 +6,15 @@
*/
import type { AgentSessionResponseAcpSessionId } from './agentSessionResponseAcpSessionId';
import type { AgentSessionResponseOriginatingMessageId } from './agentSessionResponseOriginatingMessageId';
+import type { AgentSessionResponseRepoUrl } from './agentSessionResponseRepoUrl';
import type { AgentSessionResponseThreadChannelId } from './agentSessionResponseThreadChannelId';
import type { AgentSessionResponseThreadId } from './agentSessionResponseThreadId';
import type { SessionStatusDto } from './sessionStatusDto';
/**
* Response body describing an agent session.
+
+Clients deserialize this, so both derives are used.
*/
export interface AgentSessionResponse {
/** The ACP session id, if one exists. */
@@ -32,8 +35,8 @@ export interface AgentSessionResponse {
originatingMessageId?: AgentSessionResponseOriginatingMessageId;
/** The user who created and owns the session. */
ownerId: string;
- /** The repository the session works with. */
- repoUrl: string;
+ /** The repository the session works with, when one was stated. */
+ repoUrl?: AgentSessionResponseRepoUrl;
/** The session's status. */
status: SessionStatusDto;
/** The channel `thread_id` lives in, when the session was spawned from a
@@ -41,4 +44,6 @@ thread. */
threadChannelId?: AgentSessionResponseThreadChannelId;
/** The root message of the thread the session was created from, if any. */
threadId?: AgentSessionResponseThreadId;
+ /** The directory the session's harness runs in on its runtime. */
+ workspace: string;
}
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionResponseRepoUrl.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionResponseRepoUrl.ts
new file mode 100644
index 0000000000..447a808365
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionResponseRepoUrl.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The repository the session works with, when one was stated.
+ */
+export type AgentSessionResponseRepoUrl = string | null;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/controlRequest.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/controlRequest.ts
index b26ec3a7fd..9aa8f464b5 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/controlRequest.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/controlRequest.ts
@@ -13,5 +13,7 @@ A wrapper around the operation rather than the bare enum so that fields
which are about the request rather than the operation have somewhere to go.
The acting user is deliberately not one of them: it comes from the caller's
credentials, so that a caller cannot attribute an operation to someone else.
+
+Clients serialize this, so both derives are used.
*/
export type ControlRequest = AgentAction;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequest.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequest.ts
new file mode 100644
index 0000000000..4ad8448d83
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequest.ts
@@ -0,0 +1,36 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { CreateAgentSessionRequestBotId } from './createAgentSessionRequestBotId';
+import type { CreateAgentSessionRequestOwner } from './createAgentSessionRequestOwner';
+import type { CreateAgentSessionRequestRepoUrl } from './createAgentSessionRequestRepoUrl';
+import type { CreateAgentSessionRequestThread } from './createAgentSessionRequestThread';
+
+/**
+ * Request body for `POST /agent-sessions`.
+
+Clients serialize this, so both derives are used.
+ */
+export interface CreateAgentSessionRequest {
+ /** Bot the session runs for. Bot callers may omit it (their own identity
+is used) and must not name another bot; user callers must supply a
+bot they own. */
+ botId?: CreateAgentSessionRequestBotId;
+ /** The user who owns the session. Ignored for user callers, who always
+own their own sessions; required for bot callers without verified
+acting-user claims.
+
+For bot callers this is a claim, not a verified fact: it is scoped to
+the bot's own sessions, but the named user owns the session on the
+bot's say-so. */
+ owner?: CreateAgentSessionRequestOwner;
+ /** Repository nominally checked out at `workspace`. Informational and
+optional: having it cloned there is the runtime operator's job. */
+ repoUrl?: CreateAgentSessionRequestRepoUrl;
+ thread?: CreateAgentSessionRequestThread;
+ /** Absolute directory the bot's harness runs in on its runtime. */
+ workspace: string;
+}
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestBotId.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestBotId.ts
new file mode 100644
index 0000000000..82cd4355c3
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestBotId.ts
@@ -0,0 +1,13 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Bot the session runs for. Bot callers may omit it (their own identity
+is used) and must not name another bot; user callers must supply a
+bot they own.
+ */
+export type CreateAgentSessionRequestBotId = string | null;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestOwner.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestOwner.ts
new file mode 100644
index 0000000000..87040125c8
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestOwner.ts
@@ -0,0 +1,17 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The user who owns the session. Ignored for user callers, who always
+own their own sessions; required for bot callers without verified
+acting-user claims.
+
+For bot callers this is a claim, not a verified fact: it is scoped to
+the bot's own sessions, but the named user owns the session on the
+bot's say-so.
+ */
+export type CreateAgentSessionRequestOwner = string | null;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestRepoUrl.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestRepoUrl.ts
new file mode 100644
index 0000000000..fbbb32ae7b
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestRepoUrl.ts
@@ -0,0 +1,12 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Repository nominally checked out at `workspace`. Informational and
+optional: having it cloned there is the runtime operator's job.
+ */
+export type CreateAgentSessionRequestRepoUrl = string | null;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestThread.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestThread.ts
new file mode 100644
index 0000000000..94f96f4316
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestThread.ts
@@ -0,0 +1,9 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { CreateSessionThread } from './createSessionThread';
+
+export type CreateAgentSessionRequestThread = null | CreateSessionThread;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionResponse.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionResponse.ts
new file mode 100644
index 0000000000..893e62d094
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionResponse.ts
@@ -0,0 +1,17 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { AgentSessionResponse } from './agentSessionResponse';
+
+/**
+ * Response body for `POST /agent-sessions`.
+
+Clients deserialize this, so both derives are used.
+ */
+export interface CreateAgentSessionResponse {
+ /** The created session. */
+ session: AgentSessionResponse;
+}
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createSessionThread.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createSessionThread.ts
new file mode 100644
index 0000000000..3c6528efff
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createSessionThread.ts
@@ -0,0 +1,24 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { CreateSessionThreadThreadId } from './createSessionThreadThreadId';
+
+/**
+ * The triggering mention on a create request.
+
+Clients serialize this, so both derives are used.
+ */
+export interface CreateSessionThread {
+ /** Channel the mentioning message was posted in. */
+ channelId: string;
+ /** The mention's text, quoted in the session's announcement. */
+ content?: string;
+ /** The mentioning message. */
+ messageId: string;
+ /** Thread the session belongs to; defaults to the message itself, which
+is how a top-level mention roots its own thread. */
+ threadId?: CreateSessionThreadThreadId;
+}
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createSessionThreadThreadId.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createSessionThreadThreadId.ts
new file mode 100644
index 0000000000..ddf46d2b0b
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createSessionThreadThreadId.ts
@@ -0,0 +1,12 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Thread the session belongs to; defaults to the message itself, which
+is how a top-level mention roots its own thread.
+ */
+export type CreateSessionThreadThreadId = string | null;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts
index 9d3524adbd..92853cbf6b 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts
@@ -25,11 +25,20 @@ export * from './agentSessionLogResponse';
export * from './agentSessionResponse';
export * from './agentSessionResponseAcpSessionId';
export * from './agentSessionResponseOriginatingMessageId';
+export * from './agentSessionResponseRepoUrl';
export * from './agentSessionResponseThreadChannelId';
export * from './agentSessionResponseThreadId';
export * from './agentSetModelAction';
export * from './botId';
export * from './controlRequest';
+export * from './createAgentSessionRequest';
+export * from './createAgentSessionRequestBotId';
+export * from './createAgentSessionRequestOwner';
+export * from './createAgentSessionRequestRepoUrl';
+export * from './createAgentSessionRequestThread';
+export * from './createAgentSessionResponse';
+export * from './createSessionThread';
+export * from './createSessionThreadThreadId';
export * from './logDirectionDto';
export * from './logFrameDto';
export * from './logFrameDtoContent';
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/openapi.json b/apps/web/src/lib/service-clients/service-agent-harness/openapi.json
index 17a21507d3..421f1f521a 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/openapi.json
+++ b/apps/web/src/lib/service-clients/service-agent-harness/openapi.json
@@ -10,6 +10,86 @@
"version": "0.1.0"
},
"paths": {
+ "/agent-sessions": {
+ "post": {
+ "tags": ["agent-sessions"],
+ "summary": "Open an agent session served by an external runtime.",
+ "description": "Nothing here tells the runtime where to dial: one connection per bot\ncarries every session it runs, so a runtime that has already dialed serves\nthis session too, and one that has not dials the gateway its own\nconfiguration names. The triggering mention reaches the session as its\nfirst prompt through the control endpoint.",
+ "operationId": "create_agent_session",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CreateAgentSessionRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "201": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CreateAgentSessionResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "422": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/agent-sessions/{session_id}": {
"get": {
"tags": ["agent-sessions"],
@@ -383,14 +463,14 @@
},
"AgentSessionResponse": {
"type": "object",
- "description": "Response body describing an agent session.",
+ "description": "Response body describing an agent session.\n\nClients deserialize this, so both derives are used.",
"required": [
"id",
"ownerId",
"botId",
"model",
"harness",
- "repoUrl",
+ "workspace",
"status",
"createdAt",
"modifiedAt"
@@ -438,8 +518,8 @@
"description": "The user who created and owns the session."
},
"repoUrl": {
- "type": "string",
- "description": "The repository the session works with."
+ "type": ["string", "null"],
+ "description": "The repository the session works with, when one was stated."
},
"status": {
"$ref": "#/components/schemas/SessionStatusDto",
@@ -454,6 +534,10 @@
"type": ["string", "null"],
"format": "uuid",
"description": "The root message of the thread the session was created from, if any."
+ },
+ "workspace": {
+ "type": "string",
+ "description": "The directory the session's harness runs in on its runtime."
}
}
},
@@ -478,7 +562,79 @@
"description": "The operation to perform."
}
],
- "description": "Request body for a control operation on a live session.\n\nA wrapper around the operation rather than the bare enum so that fields\nwhich are about the request rather than the operation have somewhere to go.\nThe acting user is deliberately not one of them: it comes from the caller's\ncredentials, so that a caller cannot attribute an operation to someone else."
+ "description": "Request body for a control operation on a live session.\n\nA wrapper around the operation rather than the bare enum so that fields\nwhich are about the request rather than the operation have somewhere to go.\nThe acting user is deliberately not one of them: it comes from the caller's\ncredentials, so that a caller cannot attribute an operation to someone else.\n\nClients serialize this, so both derives are used."
+ },
+ "CreateAgentSessionRequest": {
+ "type": "object",
+ "description": "Request body for `POST /agent-sessions`.\n\nClients serialize this, so both derives are used.",
+ "required": ["workspace"],
+ "properties": {
+ "botId": {
+ "type": ["string", "null"],
+ "format": "uuid",
+ "description": "Bot the session runs for. Bot callers may omit it (their own identity\nis used) and must not name another bot; user callers must supply a\nbot they own."
+ },
+ "owner": {
+ "type": ["string", "null"],
+ "description": "The user who owns the session. Ignored for user callers, who always\nown their own sessions; required for bot callers without verified\nacting-user claims.\n\nFor bot callers this is a claim, not a verified fact: it is scoped to\nthe bot's own sessions, but the named user owns the session on the\nbot's say-so."
+ },
+ "repoUrl": {
+ "type": ["string", "null"],
+ "description": "Repository nominally checked out at `workspace`. Informational and\noptional: having it cloned there is the runtime operator's job."
+ },
+ "thread": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/CreateSessionThread",
+ "description": "The thread whose mention triggered the session, when one did.\nLinkage only - the mention's text is delivered by the runtime as the\nfirst prompt through the control endpoint, never through here."
+ }
+ ]
+ },
+ "workspace": {
+ "type": "string",
+ "description": "Absolute directory the bot's harness runs in on its runtime."
+ }
+ }
+ },
+ "CreateAgentSessionResponse": {
+ "type": "object",
+ "description": "Response body for `POST /agent-sessions`.\n\nClients deserialize this, so both derives are used.",
+ "required": ["session"],
+ "properties": {
+ "session": {
+ "$ref": "#/components/schemas/AgentSessionResponse",
+ "description": "The created session."
+ }
+ }
+ },
+ "CreateSessionThread": {
+ "type": "object",
+ "description": "The triggering mention on a create request.\n\nClients serialize this, so both derives are used.",
+ "required": ["channelId", "messageId"],
+ "properties": {
+ "channelId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Channel the mentioning message was posted in."
+ },
+ "content": {
+ "type": "string",
+ "description": "The mention's text, quoted in the session's announcement."
+ },
+ "messageId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "The mentioning message."
+ },
+ "threadId": {
+ "type": ["string", "null"],
+ "format": "uuid",
+ "description": "Thread the session belongs to; defaults to the message itself, which\nis how a top-level mention roots its own thread."
+ }
+ }
},
"LogDirectionDto": {
"type": "string",
diff --git a/apps/web/src/lib/service-clients/service-storage/client.ts b/apps/web/src/lib/service-clients/service-storage/client.ts
index d60607bfa0..eee016856c 100644
--- a/apps/web/src/lib/service-clients/service-storage/client.ts
+++ b/apps/web/src/lib/service-clients/service-storage/client.ts
@@ -290,6 +290,8 @@ type CreateBotRequest = {
handle: string;
description?: string;
avatar_url?: string;
+ /** Whether mentioning this bot opens a coding-agent session. Defaults to false. */
+ has_agent?: boolean;
};
type PatchBotRequest = {
@@ -297,6 +299,8 @@ type PatchBotRequest = {
handle?: string;
description?: string;
avatar_url?: string;
+ /** Whether mentioning this bot opens a coding-agent session. Omit to leave unchanged. */
+ has_agent?: boolean;
};
type CreateBotTokenRequest = {
@@ -680,7 +684,11 @@ export const storageServiceClient = {
},
async createChannelScopedBot(
- args: WithChannelId & CreateChannelScopedBotRequest
+ args: WithChannelId &
+ CreateChannelScopedBotRequest & {
+ /** Whether mentioning this bot opens a coding-agent session. Defaults to false. */
+ has_agent?: boolean;
+ }
) {
const { channel_id, ...request } = args;
return (
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/bot.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/bot.ts
index 5e716bf445..ee94d8e2e6 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/bot.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/bot.ts
@@ -14,6 +14,8 @@ import type { BotOwnerProperty } from './botOwnerProperty';
/**
* Bot row.
+
+Clients deserialize this, so both derives are used.
*/
export interface Bot {
/** Optional avatar URL. */
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createBotRequest.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createBotRequest.ts
new file mode 100644
index 0000000000..32ee2c33c8
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createBotRequest.ts
@@ -0,0 +1,28 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { CreateBotRequestAvatarUrl } from './createBotRequestAvatarUrl';
+import type { CreateBotRequestDescription } from './createBotRequestDescription';
+import type { CreateBotRequestHasAgent } from './createBotRequestHasAgent';
+import type { CreateBotRequestTeamId } from './createBotRequestTeamId';
+
+/**
+ * Request to create a bot.
+ */
+export interface CreateBotRequest {
+ /** Optional avatar URL. */
+ avatar_url?: CreateBotRequestAvatarUrl;
+ /** Optional description. */
+ description?: CreateBotRequestDescription;
+ /** Stable handle. */
+ handle: string;
+ /** Whether mentioning this bot opens a sandboxed coding-agent session. Defaults to false. */
+ has_agent?: CreateBotRequestHasAgent;
+ /** Display name. */
+ name: string;
+ /** Team owner. The caller must be a team administrator or owner. Omit for a user-owned bot. */
+ team_id?: CreateBotRequestTeamId;
+}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createBotRequestAvatarUrl.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createBotRequestAvatarUrl.ts
new file mode 100644
index 0000000000..487f4b4b4e
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createBotRequestAvatarUrl.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Optional avatar URL.
+ */
+export type CreateBotRequestAvatarUrl = string | null;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createBotRequestDescription.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createBotRequestDescription.ts
new file mode 100644
index 0000000000..e627645210
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createBotRequestDescription.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Optional description.
+ */
+export type CreateBotRequestDescription = string | null;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createBotRequestHasAgent.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createBotRequestHasAgent.ts
new file mode 100644
index 0000000000..f6eecdf88f
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createBotRequestHasAgent.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Whether mentioning this bot opens a sandboxed coding-agent session. Defaults to false.
+ */
+export type CreateBotRequestHasAgent = boolean | null;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createBotRequestTeamId.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createBotRequestTeamId.ts
new file mode 100644
index 0000000000..ea02b1e141
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createBotRequestTeamId.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Team owner. The caller must be a team administrator or owner. Omit for a user-owned bot.
+ */
+export type CreateBotRequestTeamId = string | null;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createChannelScopedBotRequest.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createChannelScopedBotRequest.ts
index 1376ae490c..11cc38841f 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createChannelScopedBotRequest.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createChannelScopedBotRequest.ts
@@ -6,6 +6,7 @@
*/
import type { CreateChannelScopedBotRequestAvatarUrl } from './createChannelScopedBotRequestAvatarUrl';
import type { CreateChannelScopedBotRequestDescription } from './createChannelScopedBotRequestDescription';
+import type { CreateChannelScopedBotRequestHasAgent } from './createChannelScopedBotRequestHasAgent';
import type { CreateChannelScopedBotRequestTeamId } from './createChannelScopedBotRequestTeamId';
import type { CreateChannelScopedBotRequestTokenExpiresAt } from './createChannelScopedBotRequestTokenExpiresAt';
import type { CreateChannelScopedBotRequestTokenLabel } from './createChannelScopedBotRequestTokenLabel';
@@ -20,6 +21,8 @@ export interface CreateChannelScopedBotRequest {
description?: CreateChannelScopedBotRequestDescription;
/** Stable handle. */
handle: string;
+ /** Whether mentioning this bot opens a sandboxed coding-agent session. Defaults to false. */
+ has_agent?: CreateChannelScopedBotRequestHasAgent;
/** Display name. */
name: string;
/** Team owner. The caller must be a team administrator or owner. Omit for a user-owned bot. */
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createChannelScopedBotRequestHasAgent.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createChannelScopedBotRequestHasAgent.ts
new file mode 100644
index 0000000000..fa8e1f8c93
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createChannelScopedBotRequestHasAgent.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Whether mentioning this bot opens a sandboxed coding-agent session. Defaults to false.
+ */
+export type CreateChannelScopedBotRequestHasAgent = boolean | null;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createWebhookRequest.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createWebhookRequest.ts
index bbddaec471..78f17805e0 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createWebhookRequest.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createWebhookRequest.ts
@@ -11,6 +11,8 @@ import type { WebhookScope } from './webhookScope';
/**
* Request to create a webhook.
+
+Clients serialize this, so both derives are used.
*/
export interface CreateWebhookRequest {
/** Endpoint URL. HTTPS is required outside local environments. */
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createWebhookResponse.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createWebhookResponse.ts
index 2e3441ca30..a6f6422fcf 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/createWebhookResponse.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/createWebhookResponse.ts
@@ -13,6 +13,8 @@ import type { WebhookStatus } from './webhookStatus';
/**
* Webhook returned after creation, including its signing secret.
+
+Clients deserialize this, so both derives are used.
*/
export interface CreateWebhookResponse {
/** Creation timestamp. */
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
index e87c990a4a..f6e4de2cad 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
@@ -290,6 +290,11 @@ export * from './copyDocumentQueryParamsVersionId';
export * from './copyDocumentRequest';
export * from './copyDocumentRequestVersionId';
export * from './copyDocumentResponse';
+export * from './createBotRequest';
+export * from './createBotRequestAvatarUrl';
+export * from './createBotRequestDescription';
+export * from './createBotRequestHasAgent';
+export * from './createBotRequestTeamId';
export * from './createBulkDocumentResponse';
export * from './createBulkDocumentResponseData';
export * from './createBulkDocumentResponseDataDocumentMetadata';
@@ -301,6 +306,7 @@ export * from './createChannelResponse';
export * from './createChannelScopedBotRequest';
export * from './createChannelScopedBotRequestAvatarUrl';
export * from './createChannelScopedBotRequestDescription';
+export * from './createChannelScopedBotRequestHasAgent';
export * from './createChannelScopedBotRequestTeamId';
export * from './createChannelScopedBotRequestTokenExpiresAt';
export * from './createChannelScopedBotRequestTokenLabel';
@@ -766,6 +772,12 @@ export * from './paramsLimit';
export * from './paramsSortDirection';
export * from './paramsSortMethod';
export * from './participantRole';
+export * from './patchBotRequest';
+export * from './patchBotRequestAvatarUrl';
+export * from './patchBotRequestDescription';
+export * from './patchBotRequestHandle';
+export * from './patchBotRequestHasAgent';
+export * from './patchBotRequestName';
export * from './patchChannelRequest';
export * from './patchChannelRequestAutoJoinTeam';
export * from './patchChannelRequestChannelName';
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/listWebhooksResponse.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/listWebhooksResponse.ts
index c3d5139057..3c515cfdf7 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/listWebhooksResponse.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/listWebhooksResponse.ts
@@ -8,6 +8,8 @@ import type { Webhook } from './webhook';
/**
* Webhooks visible to the caller across their personal and team workspaces.
+
+Clients deserialize this, so both derives are used.
*/
export interface ListWebhooksResponse {
/** The caller's webhooks, newest first. Signing secrets are omitted. */
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/patchBotRequest.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/patchBotRequest.ts
new file mode 100644
index 0000000000..3689147a4d
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/patchBotRequest.ts
@@ -0,0 +1,27 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { PatchBotRequestAvatarUrl } from './patchBotRequestAvatarUrl';
+import type { PatchBotRequestDescription } from './patchBotRequestDescription';
+import type { PatchBotRequestHandle } from './patchBotRequestHandle';
+import type { PatchBotRequestHasAgent } from './patchBotRequestHasAgent';
+import type { PatchBotRequestName } from './patchBotRequestName';
+
+/**
+ * Request to patch a bot.
+ */
+export interface PatchBotRequest {
+ /** Optional avatar URL. */
+ avatar_url?: PatchBotRequestAvatarUrl;
+ /** Optional description. */
+ description?: PatchBotRequestDescription;
+ /** Stable handle. */
+ handle?: PatchBotRequestHandle;
+ /** Whether mentioning this bot opens a sandboxed coding-agent session. Omit to leave unchanged. */
+ has_agent?: PatchBotRequestHasAgent;
+ /** Display name. */
+ name?: PatchBotRequestName;
+}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/patchBotRequestAvatarUrl.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/patchBotRequestAvatarUrl.ts
new file mode 100644
index 0000000000..764dcd4eb9
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/patchBotRequestAvatarUrl.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Optional avatar URL.
+ */
+export type PatchBotRequestAvatarUrl = string | null;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/patchBotRequestDescription.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/patchBotRequestDescription.ts
new file mode 100644
index 0000000000..0252df2660
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/patchBotRequestDescription.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Optional description.
+ */
+export type PatchBotRequestDescription = string | null;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/patchBotRequestHandle.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/patchBotRequestHandle.ts
new file mode 100644
index 0000000000..891724944a
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/patchBotRequestHandle.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Stable handle.
+ */
+export type PatchBotRequestHandle = string | null;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/patchBotRequestHasAgent.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/patchBotRequestHasAgent.ts
new file mode 100644
index 0000000000..d477d004fd
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/patchBotRequestHasAgent.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Whether mentioning this bot opens a sandboxed coding-agent session. Omit to leave unchanged.
+ */
+export type PatchBotRequestHasAgent = boolean | null;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/patchBotRequestName.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/patchBotRequestName.ts
new file mode 100644
index 0000000000..777545cec9
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/patchBotRequestName.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Display name.
+ */
+export type PatchBotRequestName = string | null;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/webhook.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/webhook.ts
index 6e041cf479..8de76df83b 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/webhook.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/webhook.ts
@@ -13,6 +13,8 @@ import type { WebhookStatus } from './webhookStatus';
/**
* Webhook row returned by application APIs.
+
+Clients deserialize this, so both derives are used.
*/
export interface Webhook {
/** Creation timestamp. */
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/webhookScope.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/webhookScope.ts
index 4d7870a94d..4a3ad69f3b 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/webhookScope.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/webhookScope.ts
@@ -7,6 +7,8 @@
/**
* Scope that owns a newly-created webhook.
+
+Clients serialize this, so both derives are used.
*/
export type WebhookScope = (typeof WebhookScope)[keyof typeof WebhookScope];
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
index 0637e0b6d1..869dc523c8 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts
@@ -713,7 +713,7 @@ export const getSelfBotResponse = zod
.optional(),
updated_at: zod.iso.datetime({}).describe('Update timestamp.'),
})
- .describe('Bot row.');
+ .describe('Bot row.\n\nClients deserialize this, so both derives are used.');
/**
* @summary Handler for `GET /bots/{bot_id}/channels`.
@@ -2287,6 +2287,12 @@ export const createChannelScopedBotBody = zod
avatar_url: zod.string().nullish().describe('Optional avatar URL.'),
description: zod.string().nullish().describe('Optional description.'),
handle: zod.string().describe('Stable handle.'),
+ has_agent: zod
+ .boolean()
+ .nullish()
+ .describe(
+ 'Whether mentioning this bot opens a sandboxed coding-agent session. Defaults to false.'
+ ),
name: zod.string().describe('Display name.'),
team_id: zod
.uuid()
@@ -27006,14 +27012,16 @@ export const listWebhooksResponse = zod
updated_at: zod.iso.datetime({}).describe('Update timestamp.'),
workspace_id: zod.string().describe('Owning workspace id.'),
})
- .describe('Webhook row returned by application APIs.')
+ .describe(
+ 'Webhook row returned by application APIs.\n\nClients deserialize this, so both derives are used.'
+ )
)
.describe(
"The caller's webhooks, newest first. Signing secrets are omitted."
),
})
.describe(
- 'Webhooks visible to the caller across their personal and team workspaces.'
+ 'Webhooks visible to the caller across their personal and team workspaces.\n\nClients deserialize this, so both derives are used.'
);
/**
@@ -27052,9 +27060,13 @@ export const createWebhookBody = zod
),
scope: zod
.enum(['user', 'team'])
- .describe('Scope that owns a newly-created webhook.'),
+ .describe(
+ 'Scope that owns a newly-created webhook.\n\nClients serialize this, so both derives are used.'
+ ),
})
- .describe('Request to create a webhook.');
+ .describe(
+ 'Request to create a webhook.\n\nClients serialize this, so both derives are used.'
+ );
/**
* @summary Get a webhook.
@@ -27110,7 +27122,9 @@ export const getWebhookResponse = zod
updated_at: zod.iso.datetime({}).describe('Update timestamp.'),
workspace_id: zod.string().describe('Owning workspace id.'),
})
- .describe('Webhook row returned by application APIs.');
+ .describe(
+ 'Webhook row returned by application APIs.\n\nClients deserialize this, so both derives are used.'
+ );
/**
* @summary Delete a webhook.
@@ -27218,7 +27232,9 @@ export const patchWebhookResponse = zod
updated_at: zod.iso.datetime({}).describe('Update timestamp.'),
workspace_id: zod.string().describe('Owning workspace id.'),
})
- .describe('Webhook row returned by application APIs.');
+ .describe(
+ 'Webhook row returned by application APIs.\n\nClients deserialize this, so both derives are used.'
+ );
/**
* @summary Validate a webhook endpoint.
diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.json
index 84b69e314e..3b615d3ef3 100644
--- a/apps/web/src/lib/service-clients/service-storage/openapi.json
+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json
@@ -12614,7 +12614,7 @@
},
"Bot": {
"type": "object",
- "description": "Bot row.",
+ "description": "Bot row.\n\nClients deserialize this, so both derives are used.",
"required": [
"id",
"kind",
@@ -14844,6 +14844,38 @@
}
}
},
+ "CreateBotRequest": {
+ "type": "object",
+ "description": "Request to create a bot.",
+ "required": ["name", "handle"],
+ "properties": {
+ "avatar_url": {
+ "type": ["string", "null"],
+ "description": "Optional avatar URL."
+ },
+ "description": {
+ "type": ["string", "null"],
+ "description": "Optional description."
+ },
+ "handle": {
+ "type": "string",
+ "description": "Stable handle."
+ },
+ "has_agent": {
+ "type": ["boolean", "null"],
+ "description": "Whether mentioning this bot opens a sandboxed coding-agent session. Defaults to false."
+ },
+ "name": {
+ "type": "string",
+ "description": "Display name."
+ },
+ "team_id": {
+ "type": ["string", "null"],
+ "format": "uuid",
+ "description": "Team owner. The caller must be a team administrator or owner. Omit for a user-owned bot."
+ }
+ }
+ },
"CreateBulkDocumentResponse": {
"type": "object",
"required": ["error", "data"],
@@ -14954,6 +14986,10 @@
"type": "string",
"description": "Stable handle."
},
+ "has_agent": {
+ "type": ["boolean", "null"],
+ "description": "Whether mentioning this bot opens a sandboxed coding-agent session. Defaults to false."
+ },
"name": {
"type": "string",
"description": "Display name."
@@ -15607,7 +15643,7 @@
},
"CreateWebhookRequest": {
"type": "object",
- "description": "Request to create a webhook.",
+ "description": "Request to create a webhook.\n\nClients serialize this, so both derives are used.",
"required": ["scope", "namespace", "name", "endpoint_url", "filters"],
"properties": {
"endpoint_url": {
@@ -15645,7 +15681,7 @@
},
"CreateWebhookResponse": {
"type": "object",
- "description": "Webhook returned after creation, including its signing secret.",
+ "description": "Webhook returned after creation, including its signing secret.\n\nClients deserialize this, so both derives are used.",
"required": [
"id",
"workspace_id",
@@ -19725,7 +19761,7 @@
},
"ListWebhooksResponse": {
"type": "object",
- "description": "Webhooks visible to the caller across their personal and team workspaces.",
+ "description": "Webhooks visible to the caller across their personal and team workspaces.\n\nClients deserialize this, so both derives are used.",
"required": ["webhooks"],
"properties": {
"webhooks": {
@@ -19939,6 +19975,32 @@
"description": "The role a user has within a channel.",
"enum": ["owner", "admin", "member"]
},
+ "PatchBotRequest": {
+ "type": "object",
+ "description": "Request to patch a bot.",
+ "properties": {
+ "avatar_url": {
+ "type": ["string", "null"],
+ "description": "Optional avatar URL."
+ },
+ "description": {
+ "type": ["string", "null"],
+ "description": "Optional description."
+ },
+ "handle": {
+ "type": ["string", "null"],
+ "description": "Stable handle."
+ },
+ "has_agent": {
+ "type": ["boolean", "null"],
+ "description": "Whether mentioning this bot opens a sandboxed coding-agent session. Omit to leave unchanged."
+ },
+ "name": {
+ "type": ["string", "null"],
+ "description": "Display name."
+ }
+ }
+ },
"PatchChannelRequest": {
"type": "object",
"description": "Request to patch a channel.",
@@ -24282,7 +24344,7 @@
},
"Webhook": {
"type": "object",
- "description": "Webhook row returned by application APIs.",
+ "description": "Webhook row returned by application APIs.\n\nClients deserialize this, so both derives are used.",
"required": [
"id",
"workspace_id",
@@ -24392,7 +24454,7 @@
},
"WebhookScope": {
"type": "string",
- "description": "Scope that owns a newly-created webhook.",
+ "description": "Scope that owns a newly-created webhook.\n\nClients serialize this, so both derives are used.",
"enum": ["user", "team"]
},
"WebhookStatus": {
diff --git a/crates/agent_harness/Cargo.toml b/crates/agent_harness/Cargo.toml
index 64a8e1cc23..93d71e3c3c 100644
--- a/crates/agent_harness/Cargo.toml
+++ b/crates/agent_harness/Cargo.toml
@@ -10,6 +10,7 @@ agent_runtime_protocol = { path = "../agent_runtime_protocol" }
agent_session = { path = "../agent_session" }
agent_trigger = { path = "../agent_trigger" }
anyhow = { workspace = true }
+axum = { workspace = true, features = ["ws"] }
base64 = { workspace = true }
bot_id = { path = "../bot_id" }
channel_sender = { path = "../channel_sender" }
@@ -21,6 +22,7 @@ futures = { workspace = true }
kafka_util = { path = "../kafka_util" }
macro_env_var = { path = "../macro_env_var" }
macro_event_broker = { path = "../macro_event_broker", features = ["outbound"] }
+macro_authorization = { path = "../macro_authorization", features = ["axum"] }
macro_user_id = { path = "../macro_user_id" }
macro_uuid = { path = "../macro_uuid" }
reqwest = { workspace = true }
diff --git a/crates/agent_harness/src/domain/model.rs b/crates/agent_harness/src/domain/model.rs
index 8ee40420d0..606bea6084 100644
--- a/crates/agent_harness/src/domain/model.rs
+++ b/crates/agent_harness/src/domain/model.rs
@@ -23,6 +23,12 @@ pub struct MentionOrigin {
}
/// Open a new session for a mention.
+///
+/// Only for managed sessions - the ones whose sandbox this deployment
+/// provisions. External sessions are opened through
+/// [`agent_session::domain::ports::ExternalSessionOpener`] instead: they
+/// need no provisioning, no announcement, and no first prompt, so they are
+/// a plain create rather than a harness command.
#[derive(Debug, Clone)]
pub struct OpenSession {
/// The bot that was mentioned.
@@ -31,6 +37,16 @@ pub struct OpenSession {
pub origin: MentionOrigin,
}
+/// Whether this deployment provisions a sandbox for `bot`'s sessions.
+///
+/// Only the dedicated Macro coder bot is managed; every other agent bot hosts
+/// its own runtime and dials the gateway. This becomes a bot attribute the
+/// day managed bots stop being a closed set of one.
+#[must_use]
+pub fn is_managed_bot(bot: BotId) -> bool {
+ bot == bot_id::MACRO_CODER_BOT_ID
+}
+
/// Where a prompt came from, when it came from somewhere the session should
/// answer back into.
#[derive(Debug, Clone)]
@@ -93,8 +109,10 @@ impl DeliverAction {
}
}
- /// A control request under a caller-visible id. Names no origin: whoever
- /// called the endpoint is looking at the session already.
+ /// A control request under a caller-visible id. Names no origin: control
+ /// is "deliver this to the session", and announcing a prompt into its
+ /// channel is the trigger pipeline's job, keyed on what it observed
+ /// rather than anything a caller claims.
pub fn control(id: AgentActionId, event: ControlEvent) -> Self {
Self {
id,
@@ -105,11 +123,33 @@ impl DeliverAction {
}
}
+/// Announce a prompt an external runtime delivers itself.
+///
+/// For a mention in an external session's thread, the trigger pipeline fans
+/// out twice: the bot's runtime gets the webhook and sends the prompt through
+/// the control endpoint, and this posts the magic-chip message the replies
+/// render into. Split that way because each side is the only one that can
+/// do its half honestly: only the runtime can reach its harness, and only
+/// the observed trigger event can vouch for the channel context.
+#[derive(Debug, Clone)]
+pub struct AnnouncePrompt {
+ /// The bot the trigger named; must match the session row before posting.
+ pub bot_id: BotId,
+ /// Where the mention was posted.
+ pub origin: AnnounceOrigin,
+ /// The mention's text, quoted in the announcement.
+ pub content: String,
+ /// Who mentioned the bot.
+ pub sender: MacroUserIdStr<'static>,
+}
+
/// Facts required to announce one prompt into its originating context.
#[derive(Debug, Clone)]
pub struct SessionAnnouncement {
/// Agent session represented by the announcement.
pub session_id: AgentSessionId,
+ /// The bot the session runs for; the announcement posts as it.
+ pub bot_id: BotId,
/// Channel containing the mention that opened the session.
pub origin_channel_id: Uuid,
/// Thread where the announcement should be posted.
diff --git a/crates/agent_harness/src/domain/ports.rs b/crates/agent_harness/src/domain/ports.rs
index 53bab4a620..fa1355640d 100644
--- a/crates/agent_harness/src/domain/ports.rs
+++ b/crates/agent_harness/src/domain/ports.rs
@@ -1,7 +1,9 @@
//! Outbound capabilities required by the harness domain.
+use agent_session::domain::connection::RuntimeAttachment;
use agent_session::domain::model::AgentSessionId;
use agent_session::domain::ports::AgentConnector;
+use bot_id::BotId;
use super::error::Result;
use super::model::{SessionAnnouncement, SpawnContainer};
@@ -18,10 +20,35 @@ pub trait SessionAnnouncer: Send + Sync + 'static {
) -> impl Future<Output = Result<()>> + Send;
}
+/// Where a session finds its bot's live runtime connection.
+///
+/// A self-hosted runtime dials once and carries every session its bot is
+/// serving, so binding a session to a connection happens when work arrives for
+/// it rather than when the runtime dials. That is what keeps a reconnect cheap:
+/// sessions nobody is prompting are never restored at all, and the one being
+/// prompted restores itself on the way to being prompted.
+/// Only binding: taking a dialed-in socket into the registry is the inbound
+/// adapter's business, and the type it hands over is not the type a session
+/// talks through.
+pub trait RuntimeConnections: Send + Sync + 'static {
+ /// Transport one session on a shared connection talks through.
+ type Connector: AgentConnector;
+
+ /// Bind `session` onto `bot`'s connection, or `None` if it has none.
+ ///
+ /// Rebinding replaces, so this is for a session with no live actor - one
+ /// that has just been prompted after a reconnect, or for the first time.
+ fn bind(
+ &self,
+ bot: BotId,
+ session: AgentSessionId,
+ ) -> impl Future<Output = Option<RuntimeAttachment<Self::Connector>>> + Send;
+}
+
/// Provisions the container transports agent sessions run through.
pub trait ContainerManager: Send + Sync + 'static {
/// Transport returned by this provider.
- type Transport: AgentConnector + Clone;
+ type Transport: AgentConnector;
/// Boot a new container for a session that has never had one.
fn spawn(
diff --git a/crates/agent_harness/src/domain/ports/test.rs b/crates/agent_harness/src/domain/ports/test.rs
index ee5eb7f7df..127bb42356 100644
--- a/crates/agent_harness/src/domain/ports/test.rs
+++ b/crates/agent_harness/src/domain/ports/test.rs
@@ -6,6 +6,7 @@ use agent_client_protocol::schema::v1::{
use agent_fold::domain::service::FoldedMessageService;
use agent_runtime_protocol::domain::action::{AgentAction, AgentActionId};
use agent_session::PROTOCOL_VERSION;
+use agent_session::domain::connection::RuntimeAttachment;
use agent_session::domain::error::AgentSessionError;
use agent_session::domain::model::{AgentSessionId, CreateAgentSessionParams, Message};
use agent_session::domain::ports::{AgentSessionLogRepo, NoOpRealtime};
@@ -31,7 +32,8 @@ fn params(id: AgentSessionId) -> CreateAgentSessionParams {
originating_message_id: None,
model: "claude".to_owned(),
harness: "opencode".to_owned(),
- repo_url: "https://github.com/macro/macro".to_owned(),
+ repo_url: Some("https://github.com/macro/macro".to_owned()),
+ workspace: "/workspace".to_owned(),
}
}
@@ -68,7 +70,7 @@ async fn container_session_runs_and_logs_end_to_end() {
let record = sessions.create_session(params(id)).await.unwrap();
sessions
- .attach_session(id, container.clone())
+ .attach_session(id, RuntimeAttachment::solo(container.clone()))
.await
.unwrap();
assert_eq!(record.id, id);
@@ -144,8 +146,14 @@ async fn attaching_a_second_transport_to_an_active_session_fails() {
let second = ContainerMock::default();
sessions.create_session(params(id)).await.unwrap();
- sessions.attach_session(id, first).await.unwrap();
- let error = sessions.attach_session(id, second).await.unwrap_err();
+ sessions
+ .attach_session(id, RuntimeAttachment::solo(first))
+ .await
+ .unwrap();
+ let error = sessions
+ .attach_session(id, RuntimeAttachment::solo(second))
+ .await
+ .unwrap_err();
assert!(matches!(error, AgentSessionError::AlreadyConnected(found) if found == id));
}
diff --git a/crates/agent_harness/src/domain/service.rs b/crates/agent_harness/src/domain/service.rs
index 969a0ae28f..0be0f43439 100644
--- a/crates/agent_harness/src/domain/service.rs
+++ b/crates/agent_harness/src/domain/service.rs
@@ -4,12 +4,14 @@ mod test;
use std::sync::Arc;
use agent_runtime_protocol::domain::action::{AgentAction, AgentActionId};
+use agent_session::domain::connection::RuntimeAttachment;
use agent_session::domain::error::AgentSessionError;
use agent_session::domain::model::{
- AgentSessionId, AuthorKind, CreateAgentSessionParams, MessageId,
+ AgentSession, AgentSessionId, AuthorKind, CreateAgentSessionParams, MessageId,
};
use agent_session::domain::ports::{AgentSessionNotificationRecipient, ControlEvent};
use agent_session::domain::service::AgentSessionService;
+use bot_id::BotId;
use dashmap::DashMap;
use dashmap::mapref::entry::Entry;
use macro_user_id::user_id::MacroUserIdStr;
@@ -17,10 +19,10 @@ use tokio::sync::{mpsc, oneshot};
use crate::domain::error::{HarnessError, Result};
use crate::domain::model::{
- AnnounceOrigin, DeliverAction, HarnessCommand, OpenSession, SessionAnnouncement,
- SessionDefaults, SpawnContainer,
+ AnnounceOrigin, AnnouncePrompt, DeliverAction, HarnessCommand, OpenSession,
+ SessionAnnouncement, SessionDefaults, SpawnContainer, is_managed_bot,
};
-use crate::domain::ports::{ContainerManager, SessionAnnouncer};
+use crate::domain::ports::{ContainerManager, RuntimeConnections, SessionAnnouncer};
type SessionWorkers = DashMap<AgentSessionId, mpsc::UnboundedSender<QueuedCommand>>;
@@ -29,30 +31,34 @@ struct QueuedCommand {
completed: oneshot::Sender<Result<()>>,
}
-struct AgentHarnessInner<Sessions, Containers, Announcer> {
+struct AgentHarnessInner<Sessions, Containers, Announcer, Runtimes> {
sessions: Sessions,
containers: Containers,
announcer: Announcer,
+ runtimes: Runtimes,
defaults: SessionDefaults,
}
/// Turns trigger commands into running, announced agent sessions.
-pub struct AgentHarnessService<Sessions, Containers, Announcer> {
- inner: Arc<AgentHarnessInner<Sessions, Containers, Announcer>>,
+pub struct AgentHarnessService<Sessions, Containers, Announcer, Runtimes> {
+ inner: Arc<AgentHarnessInner<Sessions, Containers, Announcer, Runtimes>>,
workers: Arc<SessionWorkers>,
}
-impl<Sessions, Containers, Announcer> AgentHarnessService<Sessions, Containers, Announcer>
+impl<Sessions, Containers, Announcer, Runtimes>
+ AgentHarnessService<Sessions, Containers, Announcer, Runtimes>
where
Sessions: AgentSessionService,
Containers: ContainerManager,
Announcer: SessionAnnouncer,
+ Runtimes: RuntimeConnections,
{
/// Build the orchestrator from its ports.
pub fn new(
sessions: Sessions,
containers: Containers,
announcer: Announcer,
+ runtimes: Runtimes,
defaults: SessionDefaults,
) -> Self {
Self {
@@ -60,6 +66,7 @@ where
sessions,
containers,
announcer,
+ runtimes,
defaults,
}),
workers: Arc::new(DashMap::new()),
@@ -116,18 +123,63 @@ where
) {
tokio::spawn(run_session_worker(session_id, self.inner.clone(), receiver));
}
+
+ /// Post the announcement for a prompt an external runtime delivers.
+ ///
+ /// The follow-up-mention half of the external split: the runtime sends
+ /// the prompt through the control endpoint, and the observed trigger
+ /// event lands here to post the magic chip the replies render into.
+ /// Needs only the session row - a chip must post even while the runtime
+ /// is disconnected, anchoring whatever reply eventually comes.
+ #[tracing::instrument(err, skip(self, prompt), fields(%session_id))]
+ pub async fn announce_external_prompt(
+ &self,
+ session_id: AgentSessionId,
+ prompt: AnnouncePrompt,
+ ) -> Result<()> {
+ // Re-read rather than trusted: the row is what vouches that the
+ // trigger's session and bot actually belong together.
+ let session = self.inner.sessions.get_session(session_id).await?;
+ if session.bot_id != prompt.bot_id {
+ tracing::warn!(
+ %session_id,
+ event_bot = %prompt.bot_id,
+ session_bot = %session.bot_id,
+ "dropping an announce whose bot does not own the session"
+ );
+ return Ok(());
+ }
+
+ self.inner
+ .announcer
+ .announce(SessionAnnouncement {
+ session_id,
+ bot_id: session.bot_id,
+ origin_channel_id: prompt.origin.channel_id,
+ origin_thread_id: prompt.origin.thread_id,
+ prompted_message_id: self
+ .inner
+ .sessions
+ .next_prompt_message_id(session_id)
+ .await?,
+ prompted_content: prompt.content,
+ triggered_by: prompt.sender,
+ })
+ .await
+ }
}
/// The harness is what holds a session's live resources, so it is what the
/// control routes notify. Both operations go through the per-session queue, so
/// a teardown cannot land in the middle of an open and a model change cannot
/// overtake the prompt it was meant to follow.
-impl<Sessions, Containers, Announcer> AgentSessionNotificationRecipient
- for AgentHarnessService<Sessions, Containers, Announcer>
+impl<Sessions, Containers, Announcer, Runtimes> AgentSessionNotificationRecipient
+ for AgentHarnessService<Sessions, Containers, Announcer, Runtimes>
where
Sessions: AgentSessionService,
Containers: ContainerManager,
Announcer: SessionAnnouncer,
+ Runtimes: RuntimeConnections,
{
async fn session_deleted(
&self,
@@ -154,6 +206,84 @@ where
}
}
+/// External sessions create the row and announce - the magic-chip message
+/// the session's bot posts into the mention's thread, which is where the
+/// app renders the session's replies. No sandbox (the runtime dials in) and
+/// no first prompt (the runtime sends it through the control endpoint).
+/// The announcement is best-effort: a session a runtime is about to serve
+/// must not die because the courtesy post failed, most plainly when the bot
+/// cannot post in the claimed channel.
+impl<Sessions, Containers, Announcer, Runtimes> agent_session::domain::ports::ExternalSessionOpener
+ for AgentHarnessService<Sessions, Containers, Announcer, Runtimes>
+where
+ Sessions: AgentSessionService,
+ Containers: ContainerManager,
+ Announcer: SessionAnnouncer,
+ Runtimes: RuntimeConnections,
+{
+ async fn open_external_session(
+ &self,
+ request: agent_session::domain::ports::OpenExternalAgentSession,
+ ) -> agent_session::domain::error::Result<AgentSession> {
+ let session = self
+ .inner
+ .sessions
+ .create_session(CreateAgentSessionParams {
+ id: AgentSessionId::new(),
+ owner_id: request.owner.clone(),
+ bot_id: request.bot_id,
+ thread_id: request.thread.as_ref().map(|thread| thread.thread_id),
+ originating_message_id: request.thread.as_ref().map(|thread| thread.message_id),
+ model: self.inner.defaults.model.clone(),
+ harness: self.inner.defaults.harness.clone(),
+ repo_url: request.repo_url,
+ workspace: request.workspace,
+ // The thread linkage is the caller's claim, not an observed
+ // mention; it must not grant the channel anything.
+ })
+ .await?;
+
+ if let Some(thread) = request.thread {
+ let announcement = SessionAnnouncement {
+ session_id: session.id,
+ bot_id: request.bot_id,
+ origin_channel_id: thread.channel_id,
+ origin_thread_id: thread.thread_id,
+ prompted_message_id: MessageId::first(AuthorKind::User),
+ prompted_content: thread.content,
+ triggered_by: request.owner,
+ };
+ if let Err(error) = self.inner.announcer.announce(announcement).await {
+ tracing::warn!(
+ error = ?error,
+ session = %session.id,
+ "external session announcement failed; the session runs unannounced"
+ );
+ }
+ }
+
+ Ok(session)
+ }
+
+ async fn find_thread_session(
+ &self,
+ thread_id: macro_uuid::Uuid,
+ bot_id: BotId,
+ ) -> agent_session::domain::error::Result<Option<AgentSessionId>> {
+ match self
+ .inner
+ .sessions
+ .find_for_channel(Some(thread_id), Some(bot_id))
+ .await?
+ {
+ agent_session::domain::model::ChannelSession::CreatedFromThread(session) => {
+ Ok(Some(session.id))
+ }
+ agent_session::domain::model::ChannelSession::None => Ok(None),
+ }
+ }
+}
+
/// Collapse a harness failure back into the session vocabulary the port speaks.
///
/// A harness error that started life as a session error is unwrapped rather
@@ -165,11 +295,13 @@ fn into_session_error(error: HarnessError) -> AgentSessionError {
}
}
-impl<Sessions, Containers, Announcer> AgentHarnessInner<Sessions, Containers, Announcer>
+impl<Sessions, Containers, Announcer, Runtimes>
+ AgentHarnessInner<Sessions, Containers, Announcer, Runtimes>
where
Sessions: AgentSessionService,
Containers: ContainerManager,
Announcer: SessionAnnouncer,
+ Runtimes: RuntimeConnections,
{
async fn execute(&self, session_id: AgentSessionId, command: HarnessCommand) -> Result<()> {
match command {
@@ -211,13 +343,17 @@ where
originating_message_id: Some(origin.message_id),
model: self.defaults.model.clone(),
harness: self.defaults.harness.clone(),
- repo_url: repo_url.clone(),
+ repo_url: Some(repo_url.clone()),
+ // Managed sandboxes run in the path baked into their image.
+ workspace: agent_session::MANAGED_CONTAINER_WORKSPACE.to_owned(),
+ // This open came from the trigger pipeline seeing the mention.
})
.await?;
self.announcer
.announce(SessionAnnouncement {
session_id,
+ bot_id,
origin_channel_id: origin.channel_id,
origin_thread_id: origin.thread_id,
prompted_message_id: MessageId::first(AuthorKind::User),
@@ -233,7 +369,9 @@ where
repo_url,
})
.await?;
- self.sessions.attach_session(session_id, container).await?;
+ self.sessions
+ .attach_session(session_id, RuntimeAttachment::solo(container))
+ .await?;
self.sessions
.send_action(
session_id,
@@ -269,12 +407,33 @@ where
.await
{
Ok(()) => {}
- // Nothing is attached, so bring the container back and retry the
- // action against the new connection. Same id: the first attempt
- // never reached the wire.
+ // Nothing is attached, so get this session onto a transport and
+ // retry against it. Same id: the first attempt never reached the
+ // wire.
Err(AgentSessionError::Disconnected(_)) => {
- let container = self.containers.resume(session_id).await?;
- self.sessions.attach_session(session_id, container).await?;
+ let session = self.sessions.get_session(session_id).await?;
+ if is_managed_bot(session.bot_id) {
+ let container = self.containers.resume(session_id).await?;
+ self.sessions
+ .attach_session(session_id, RuntimeAttachment::solo(container))
+ .await?;
+ } else {
+ // An external runtime is not ours to start - only its
+ // operator can dial - but a bot whose runtime is already
+ // connected just has not had this session bound to it
+ // yet. That is the ordinary case: sessions bind when they
+ // are prompted, not when the runtime dials, so the first
+ // prompt after a reconnect is what restores the session.
+ let Some(attachment) = self.runtimes.bind(session.bot_id, session_id).await
+ else {
+ // Kept in the session vocabulary so transports report
+ // it as a disconnect, not an internal error.
+ return Err(HarnessError::Session(AgentSessionError::Disconnected(
+ session_id,
+ )));
+ };
+ self.sessions.attach_session(session_id, attachment).await?;
+ }
self.sessions
.send_action(session_id, actor, action, id)
.await?;
@@ -306,8 +465,13 @@ where
return Ok(None);
};
+ // The announcement posts as the session's own bot, which only the
+ // row remembers.
+ let session = self.sessions.get_session(session_id).await?;
+
Ok(Some(SessionAnnouncement {
session_id,
+ bot_id: session.bot_id,
origin_channel_id: origin.channel_id,
origin_thread_id: origin.thread_id,
prompted_message_id: self.sessions.next_prompt_message_id(session_id).await?,
@@ -317,14 +481,15 @@ where
}
}
-async fn run_session_worker<Sessions, Containers, Announcer>(
+async fn run_session_worker<Sessions, Containers, Announcer, Runtimes>(
session_id: AgentSessionId,
- inner: Arc<AgentHarnessInner<Sessions, Containers, Announcer>>,
+ inner: Arc<AgentHarnessInner<Sessions, Containers, Announcer, Runtimes>>,
mut receiver: mpsc::UnboundedReceiver<QueuedCommand>,
) where
Sessions: AgentSessionService,
Containers: ContainerManager,
Announcer: SessionAnnouncer,
+ Runtimes: RuntimeConnections,
{
while let Some(queued) = receiver.recv().await {
let QueuedCommand { command, completed } = queued;
diff --git a/crates/agent_harness/src/domain/service/test.rs b/crates/agent_harness/src/domain/service/test.rs
index ca678e46d4..458b8d032d 100644
--- a/crates/agent_harness/src/domain/service/test.rs
+++ b/crates/agent_harness/src/domain/service/test.rs
@@ -2,6 +2,8 @@
//! with in-memory persistence, mock containers, a fake agent, and a
//! recording announcer. Only the edges are doubles.
+use std::sync::Arc;
+
use agent_client_protocol::RawJsonRpcMessage;
use agent_client_protocol::schema::v1::{
AgentCapabilities, ClientRequest, ContentBlock, InitializeResponse, NewSessionResponse,
@@ -11,7 +13,7 @@ use agent_fold::domain::model::{AuthorKind, MessageId};
use agent_fold::domain::service::FoldedMessageService;
use agent_runtime_protocol::domain::{
action::AgentAction,
- schema::v0::{AcpMessage, ToRuntimeMessage},
+ schema::v0::{AcpMessage, SystemEvent, ToRuntimeMessage, ToServerMessage},
};
use agent_session::PROTOCOL_VERSION;
use agent_session::domain::model::{AgentSessionId, CreateAgentSessionParams, Message};
@@ -32,9 +34,12 @@ use crate::domain::model::{
SpawnContainer,
};
use crate::domain::ports::ContainerManager as _;
+use crate::outbound::runtime_registry::RuntimeRegistry;
use crate::testing::helpers::agent::FakeAgent;
use crate::testing::helpers::announcer::AnnouncerMock;
-use crate::testing::helpers::containers::{ContainerMock, MockContainerManager};
+use crate::testing::helpers::containers::{ContainerMock, ContainerSender, MockContainerManager};
+use agent_session::domain::error::AgentSessionError;
+use agent_session::domain::ports::{ExternalSessionOpener as _, OpenExternalAgentSession};
fn sender() -> MacroUserIdStr<'static> {
MacroUserIdStr::try_from_email("[email protected]").expect("a valid user id")
@@ -67,23 +72,29 @@ fn forward_message(content: &str) -> DeliverAction {
)
}
-fn harness() -> (
- AgentHarnessService<
- AgentSessionServiceImpl<
- InMemoryAgentSessionRepo,
- FoldedMessageService<InMemoryAgentSessionRepo>,
- NoOpRealtime,
- >,
- MockContainerManager,
- AnnouncerMock,
+/// The orchestrator under test, over the session service it really uses.
+type TestHarness = AgentHarnessService<
+ AgentSessionServiceImpl<
+ InMemoryAgentSessionRepo,
+ FoldedMessageService<InMemoryAgentSessionRepo>,
+ NoOpRealtime,
>,
+ MockContainerManager,
+ AnnouncerMock,
+ Arc<RuntimeRegistry<ContainerSender>>,
+>;
+
+fn harness() -> (
+ TestHarness,
InMemoryAgentSessionRepo,
MockContainerManager,
AnnouncerMock,
+ Arc<RuntimeRegistry<ContainerSender>>,
) {
let repo = InMemoryAgentSessionRepo::new();
let containers = MockContainerManager::new();
let announcer = AnnouncerMock::new();
+ let runtimes = RuntimeRegistry::new();
let service = AgentHarnessService::new(
AgentSessionServiceImpl::new(
repo.clone(),
@@ -92,13 +103,14 @@ fn harness() -> (
),
containers.clone(),
announcer.clone(),
+ Arc::clone(&runtimes),
SessionDefaults {
model: "claude".to_owned(),
harness: "opencode".to_owned(),
repo_url: "https://github.com/macro-inc/macro".to_owned(),
},
);
- (service, repo, containers, announcer)
+ (service, repo, containers, announcer, runtimes)
}
/// Play the agent's half of the ACP handshake.
@@ -146,7 +158,9 @@ async fn disconnected_session(
repo: &InMemoryAgentSessionRepo,
containers: &MockContainerManager,
) -> AgentSessionId {
- let OpenSession { bot_id, origin } = open_command();
+ let OpenSession { origin, .. } = open_command();
+ // The coder bot: resume-on-disconnect only exists for managed sessions.
+ let bot_id = bot_id::MACRO_CODER_BOT_ID;
let id = AgentSessionId::new();
agent_session::domain::ports::AgentSessionRepo::create(
repo,
@@ -158,7 +172,8 @@ async fn disconnected_session(
originating_message_id: Some(origin.message_id),
model: "claude".to_owned(),
harness: "opencode".to_owned(),
- repo_url: "https://github.com/macro-inc/macro".to_owned(),
+ repo_url: Some("https://github.com/macro-inc/macro".to_owned()),
+ workspace: "/workspace".to_owned(),
},
)
.await
@@ -178,7 +193,7 @@ async fn disconnected_session(
#[tokio::test]
async fn open_creates_announces_and_delivers_the_mention() {
- let (service, repo, containers, announcer) = harness();
+ let (service, repo, containers, announcer, _runtimes) = harness();
let command = open_command();
let id = AgentSessionId::new();
let origin = command.origin.clone();
@@ -204,7 +219,7 @@ async fn open_creates_announces_and_delivers_the_mention() {
// The row exists, carries the origin, and was announced into it.
let session = repo.get(id).await.expect("the session row exists");
- assert_eq!(session.acp_session_id.as_deref(), Some("acp-test"));
+ assert_eq!(session.acp_session_id, Some(SessionId::new("acp-test")));
assert_eq!(session.originating_message_id, Some(origin.message_id));
assert_eq!(session.thread_id, Some(origin.thread_id));
let announced = announcer.announced();
@@ -226,7 +241,7 @@ async fn open_creates_announces_and_delivers_the_mention() {
#[tokio::test]
async fn open_announces_while_the_container_is_still_booting() {
- let (service, _repo, containers, announcer) = harness();
+ let (service, _repo, containers, announcer, _runtimes) = harness();
let id = AgentSessionId::new();
let open = service.execute(id, HarnessCommand::Open(open_command()));
@@ -261,7 +276,7 @@ async fn open_announces_while_the_container_is_still_booting() {
#[tokio::test]
async fn forward_to_a_live_session_reuses_the_transport() {
- let (service, _repo, containers, announcer) = harness();
+ let (service, _repo, containers, announcer, _runtimes) = harness();
let command = open_command();
let id = AgentSessionId::new();
let open = service.execute(id, HarnessCommand::Open(command));
@@ -307,7 +322,7 @@ async fn forward_to_a_live_session_reuses_the_transport() {
#[tokio::test]
async fn a_delivery_failure_is_not_automatically_resumed() {
- let (service, _repo, containers, _announcer) = harness();
+ let (service, _repo, containers, _announcer, _runtimes) = harness();
let command = open_command();
let id = AgentSessionId::new();
let open = service.execute(id, HarnessCommand::Open(command));
@@ -341,7 +356,7 @@ async fn a_delivery_failure_is_not_automatically_resumed() {
#[tokio::test]
async fn forward_to_a_disconnected_session_resumes_acp_and_delivers_the_prompt() {
- let (service, repo, containers, _announcer) = harness();
+ let (service, repo, containers, _announcer, _runtimes) = harness();
let id = disconnected_session(&repo, &containers).await;
let forward = service.execute(
@@ -392,7 +407,7 @@ async fn forward_to_a_disconnected_session_resumes_acp_and_delivers_the_prompt()
#[tokio::test]
async fn concurrent_forwards_share_one_session_recovery() {
- let (service, repo, containers, announcer) = harness();
+ let (service, repo, containers, announcer, _runtimes) = harness();
let id = disconnected_session(&repo, &containers).await;
let first = service.execute(id, HarnessCommand::Deliver(forward_message("first")));
let second = service.execute(id, HarnessCommand::Deliver(forward_message("second")));
@@ -441,7 +456,7 @@ async fn concurrent_forwards_share_one_session_recovery() {
#[tokio::test]
async fn different_sessions_execute_concurrently() {
- let (service, repo, containers, _announcer) = harness();
+ let (service, repo, containers, _announcer, _runtimes) = harness();
let first_id = disconnected_session(&repo, &containers).await;
let second_id = disconnected_session(&repo, &containers).await;
let first = service.execute(first_id, HarnessCommand::Deliver(forward_message("first")));
@@ -487,7 +502,7 @@ async fn different_sessions_execute_concurrently() {
#[tokio::test]
async fn an_admitted_command_survives_caller_cancellation() {
- let (service, repo, containers, _announcer) = harness();
+ let (service, repo, containers, _announcer, _runtimes) = harness();
let id = disconnected_session(&repo, &containers).await;
let completion = service.execute(
id,
@@ -517,7 +532,7 @@ async fn an_admitted_command_survives_caller_cancellation() {
#[tokio::test]
async fn a_failed_announce_surfaces_and_does_not_start_the_agent() {
- let (service, repo, containers, announcer) = harness();
+ let (service, repo, containers, announcer, _runtimes) = harness();
announcer.fails("comms is down");
let result = service
@@ -540,15 +555,7 @@ fn session_of(containers: &MockContainerManager) -> AgentSessionId {
/// Open a session and complete its handshake, returning its live container.
async fn live_session(
- service: &AgentHarnessService<
- AgentSessionServiceImpl<
- InMemoryAgentSessionRepo,
- FoldedMessageService<InMemoryAgentSessionRepo>,
- NoOpRealtime,
- >,
- MockContainerManager,
- AnnouncerMock,
- >,
+ service: &TestHarness,
containers: &MockContainerManager,
id: AgentSessionId,
) -> ContainerMock {
@@ -573,7 +580,7 @@ async fn live_session(
#[tokio::test]
async fn changing_the_model_persists_it_and_tells_the_running_agent() {
- let (service, repo, containers, _announcer) = harness();
+ let (service, repo, containers, _announcer, _runtimes) = harness();
let id = AgentSessionId::new();
let container = live_session(&service, &containers, id).await;
@@ -606,7 +613,7 @@ async fn changing_the_model_persists_it_and_tells_the_running_agent() {
#[tokio::test]
async fn deleting_a_session_tears_down_its_container_and_removes_it() {
- let (service, repo, containers, _announcer) = harness();
+ let (service, repo, containers, _announcer, _runtimes) = harness();
let id = AgentSessionId::new();
live_session(&service, &containers, id).await;
@@ -624,7 +631,7 @@ async fn deleting_a_session_tears_down_its_container_and_removes_it() {
#[tokio::test]
async fn a_prompt_through_control_reaches_the_agent_without_announcing() {
- let (service, _repo, containers, announcer) = harness();
+ let (service, _repo, containers, announcer, _runtimes) = harness();
let id = AgentSessionId::new();
let container = live_session(&service, &containers, id).await;
let announced_before = announcer.announced().len();
@@ -654,7 +661,7 @@ async fn a_prompt_through_control_reaches_the_agent_without_announcing() {
#[tokio::test]
async fn compact_through_control_reaches_opencode_as_a_slash_command() {
- let (service, _repo, containers, _announcer) = harness();
+ let (service, _repo, containers, _announcer, _runtimes) = harness();
let id = AgentSessionId::new();
let container = live_session(&service, &containers, id).await;
@@ -682,7 +689,7 @@ async fn compact_through_control_reaches_opencode_as_a_slash_command() {
#[tokio::test]
async fn a_prompt_through_control_resumes_a_disconnected_session() {
- let (service, repo, containers, _announcer) = harness();
+ let (service, repo, containers, _announcer, _runtimes) = harness();
let id = disconnected_session(&repo, &containers).await;
let prompted = service.control_event(
@@ -715,3 +722,387 @@ async fn a_prompt_through_control_resumes_a_disconnected_session() {
[vec![ContentBlock::from("wake up")]]
);
}
+
+fn open_external_request(workspace: &str) -> OpenExternalAgentSession {
+ OpenExternalAgentSession {
+ bot_id: BotId::new_from_uuid(macro_uuid::generate_uuid_v7()),
+ workspace: workspace.to_owned(),
+ repo_url: None,
+ owner: sender(),
+ thread: None,
+ }
+}
+
+/// Play the agent's half of the handshake for a session that binds lazily.
+///
+/// The ready event is repeated because it is the connection's, not the
+/// session's: a session binds when it is prompted, and until it has, there is
+/// nobody on the connection to act on being told the runtime is up.
+async fn complete_bound_handshake(runtime: &ContainerMock) {
+ let agent = runtime.agent();
+ while agent.received_requests().is_empty() {
+ runtime.sends_ready();
+ tokio::task::yield_now().await;
+ }
+ agent.completes_initialize(InitializeResponse::new(PROTOCOL_VERSION));
+ agent.wait_for_requests(2).await;
+ agent.opens_session(NewSessionResponse::new("acp-test"));
+}
+
+/// As [`complete_bound_handshake`], for a session the runtime is restoring.
+async fn complete_bound_resume(runtime: &ContainerMock) {
+ let agent = runtime.agent();
+ while agent.received_requests().is_empty() {
+ runtime.sends_ready();
+ tokio::task::yield_now().await;
+ }
+ agent.completes_initialize(
+ InitializeResponse::new(PROTOCOL_VERSION).agent_capabilities(
+ AgentCapabilities::new().session_capabilities(
+ SessionCapabilities::new().resume(SessionResumeCapabilities::new()),
+ ),
+ ),
+ );
+ agent.wait_for_requests(2).await;
+ assert!(matches!(
+ &agent.received_requests()[1],
+ ClientRequest::ResumeSessionRequest(request) if request.session_id.to_string() == "acp-test"
+ ));
+ agent.resumes_session(ResumeSessionResponse::new());
+}
+
+/// Wait until a session has noticed that its transport ended.
+///
+/// Until it has, the session still counts as attached, and an action sent in
+/// that window goes into the dead socket instead of being retried onto a live
+/// one - so anything about reconnecting has to start from here.
+async fn await_disconnect(repo: &InMemoryAgentSessionRepo, id: AgentSessionId) {
+ loop {
+ let log = repo
+ .list_by_session(id)
+ .await
+ .expect("the session log is readable");
+ let disconnected = log.iter().any(|stored| {
+ matches!(
+ &stored.entry.content,
+ Message::ToServer(ToServerMessage::Event {
+ event: SystemEvent::Disconnected
+ })
+ )
+ });
+ if disconnected {
+ return;
+ }
+ tokio::task::yield_now().await;
+ }
+}
+
+/// Prompt a session the way the control endpoint does.
+async fn prompt(
+ service: &TestHarness,
+ id: AgentSessionId,
+ content: &str,
+) -> Result<(), HarnessError> {
+ service
+ .execute(
+ id,
+ HarnessCommand::Deliver(DeliverAction::prompt(content, Some(sender()), None)),
+ )
+ .await
+}
+
+#[tokio::test]
+async fn an_external_open_provisions_nothing_and_prompts_nobody() {
+ let (service, repo, containers, announcer, runtimes) = harness();
+
+ let session = service
+ .open_external_session(open_external_request("/home/operator/code"))
+ .await
+ .expect("an external open needs no runtime yet");
+
+ // The row exists with the stated workspace, but nothing was provisioned,
+ // nothing was announced, and no prompt has gone anywhere: the runtime
+ // delivers the first prompt itself through the control endpoint after
+ // dialing in.
+ assert_eq!(session.workspace, "/home/operator/code");
+ assert_eq!(containers.spawned(), 0);
+ assert!(announcer.announced().is_empty());
+
+ // The operator's runtime dials in for the bot. Nothing happens to the
+ // session: no handshake, no ACP session, nothing sent - a session nobody
+ // is prompting costs the runtime nothing.
+ let runtime = ContainerMock::default();
+ runtimes.attach(session.bot_id, runtime.clone());
+ assert!(runtime.agent().received_requests().is_empty());
+ assert!(
+ repo.get(session.id)
+ .await
+ .expect("the session row exists")
+ .acp_session_id
+ .is_none()
+ );
+
+ // The runtime forwards the mention through control: that is what binds the
+ // session to the connection, handshakes, and lands the prompt.
+ let prompted = service.control_event(
+ session.id,
+ ControlEvent {
+ action: AgentAction::prompt("@claude fix the failing test"),
+ actor: Some(sender()),
+ },
+ );
+ let (result, ()) = tokio::join!(prompted, complete_bound_handshake(&runtime));
+ result.expect("the first prompt binds the session and reaches the runtime");
+ assert_eq!(
+ prompts(&runtime.agent()),
+ [vec![ContentBlock::from("@claude fix the failing test")]]
+ );
+ // Prompt delivery is ordered behind the `session/new` response, so the
+ // negotiated ACP session id has been persisted by now.
+ let row = repo.get(session.id).await.expect("the session row exists");
+ assert_eq!(row.acp_session_id, Some(SessionId::new("acp-test")));
+}
+
+#[tokio::test]
+async fn a_bound_session_stays_on_its_connection_until_it_drops() {
+ let (service, _repo, _containers, _announcer, runtimes) = harness();
+ let session = service
+ .open_external_session(open_external_request("/srv/agent"))
+ .await
+ .expect("open");
+
+ let first = ContainerMock::default();
+ runtimes.attach(session.bot_id, first.clone());
+ let (result, ()) = tokio::join!(
+ prompt(&service, session.id, "fix the failing test"),
+ complete_bound_handshake(&first)
+ );
+ result.expect("the first prompt binds the session");
+
+ // Already bound: a second prompt goes straight down the same connection,
+ // with no second handshake to drive.
+ prompt(&service, session.id, "and now the docs")
+ .await
+ .expect("a bound session needs no rebinding");
+ assert_eq!(
+ prompts(&first.agent()),
+ ["fix the failing test", "and now the docs"]
+ .map(|text| vec![ContentBlock::from(text)])
+ .to_vec()
+ );
+}
+
+#[tokio::test]
+async fn a_prompt_after_a_redial_restores_the_session_on_the_new_connection() {
+ let (service, repo, containers, _announcer, runtimes) = harness();
+ let session = service
+ .open_external_session(open_external_request("/srv/agent"))
+ .await
+ .expect("open");
+
+ let first = ContainerMock::default();
+ runtimes.attach(session.bot_id, first.clone());
+ let (result, ()) = tokio::join!(
+ prompt(&service, session.id, "fix the failing test"),
+ complete_bound_handshake(&first)
+ );
+ result.expect("the first prompt binds the session");
+
+ // The socket dies and the operator's runtime redials. The session is not
+ // touched by the redial itself - the next prompt is what restores it, on
+ // the ACP session id the row remembers.
+ first.disconnects();
+ await_disconnect(&repo, session.id).await;
+ let second = ContainerMock::default();
+ runtimes.attach(session.bot_id, second.clone());
+ assert!(second.agent().received_requests().is_empty());
+
+ let (result, ()) = tokio::join!(
+ prompt(&service, session.id, "carry on"),
+ complete_bound_resume(&second)
+ );
+ result.expect("a prompt after a reconnect restores the session on the way through");
+ assert_eq!(
+ prompts(&second.agent()),
+ [vec![ContentBlock::from("carry on")]]
+ );
+ // Still an operator-hosted session: reconnecting never provisions.
+ assert_eq!(containers.spawned(), 0);
+ assert_eq!(containers.resumed(), 0);
+}
+
+#[tokio::test]
+async fn a_managed_session_resumes_its_sandbox_rather_than_a_dialed_in_runtime() {
+ let (service, repo, containers, _announcer, runtimes) = harness();
+ let id = disconnected_session(&repo, &containers).await;
+ let session = repo.get(id).await.expect("the session row exists");
+
+ // A runtime dialed in claiming to serve the managed bot. Its sandbox is
+ // this deployment's to run, so the dial must not be what the session is
+ // restored onto.
+ let dialed_in = ContainerMock::default();
+ runtimes.attach(session.bot_id, dialed_in.clone());
+
+ let prompted = service.control_event(
+ id,
+ ControlEvent {
+ action: AgentAction::prompt("wake up"),
+ actor: Some(sender()),
+ },
+ );
+ let drive_resume = async {
+ loop {
+ if containers.resumed() == 1 {
+ break;
+ }
+ tokio::task::yield_now().await;
+ }
+ let resumed = containers
+ .container(id)
+ .expect("the resumed container is findable");
+ complete_resume(&resumed).await;
+ resumed.agent().wait_for_requests(3).await;
+ resumed
+ };
+ let (result, resumed) = tokio::join!(prompted, drive_resume);
+ result.expect("a managed session resumes its own sandbox");
+
+ assert_eq!(
+ prompts(&resumed.agent()),
+ [vec![ContentBlock::from("wake up")]]
+ );
+ assert!(
+ dialed_in.agent().received_requests().is_empty(),
+ "the dialed-in runtime is never consulted for a managed session"
+ );
+}
+
+#[tokio::test]
+async fn a_disconnected_external_session_never_gets_a_sandbox() {
+ let (service, _repo, containers, _announcer, _runtimes) = harness();
+ let session = service
+ .open_external_session(open_external_request("/srv/agent"))
+ .await
+ .expect("open");
+
+ // No runtime ever dialed in, so a follow-up prompt has nowhere to go -
+ // and must NOT fall into the managed resume path and boot a sandbox for
+ // an operator-hosted bot.
+ let error = service
+ .execute(session.id, HarnessCommand::Deliver(forward_message("more")))
+ .await
+ .expect_err("nothing is attached");
+
+ assert!(
+ matches!(
+ error,
+ HarnessError::Session(AgentSessionError::Disconnected(id)) if id == session.id,
+ ),
+ "got {error:?}"
+ );
+ assert_eq!(containers.spawned(), 0);
+ assert_eq!(containers.resumed(), 0);
+}
+
+#[tokio::test]
+async fn an_external_open_with_a_mention_announces_as_the_sessions_bot() {
+ let (service, _repo, containers, announcer, _runtimes) = harness();
+ let mut request = open_external_request("/srv/agent");
+ let bot = request.bot_id;
+ request.thread = Some(agent_session::domain::ports::SessionThread {
+ channel_id: macro_uuid::Uuid::from_u128(0xC1),
+ thread_id: macro_uuid::Uuid::from_u128(0xC2),
+ message_id: macro_uuid::Uuid::from_u128(0xC2),
+ content: "@opencode fix the flaky test".to_owned(),
+ });
+
+ service
+ .open_external_session(request)
+ .await
+ .expect("open with a mention");
+
+ // The magic-chip announcement lands in the mention's thread, posted as
+ // the session's own bot - still with nothing provisioned.
+ assert_eq!(containers.spawned(), 0);
+ let announced = announcer.announced();
+ assert_eq!(announced.len(), 1);
+ assert_eq!(announced[0].bot_id, bot);
+ assert_eq!(
+ announced[0].origin_channel_id,
+ macro_uuid::Uuid::from_u128(0xC1)
+ );
+ assert_eq!(
+ announced[0].prompted_content,
+ "@opencode fix the flaky test"
+ );
+}
+
+#[tokio::test]
+async fn an_external_prompt_announce_posts_into_the_observed_origin() {
+ let (service, _repo, containers, announcer, _runtimes) = harness();
+ let request = open_external_request("/srv/agent");
+ let bot = request.bot_id;
+ let session = service
+ .open_external_session(request)
+ .await
+ .expect("open without a mention");
+
+ // No runtime ever attached: the chip must still post, anchoring
+ // whatever reply arrives once the runtime comes back.
+ service
+ .announce_external_prompt(
+ session.id,
+ crate::domain::model::AnnouncePrompt {
+ bot_id: bot,
+ origin: AnnounceOrigin {
+ channel_id: macro_uuid::Uuid::from_u128(0xAA),
+ thread_id: macro_uuid::Uuid::from_u128(0xAB),
+ },
+ content: "follow-up from the channel".to_owned(),
+ sender: sender(),
+ },
+ )
+ .await
+ .expect("the observed prompt announces");
+
+ assert_eq!(containers.spawned(), 0);
+ let announced = announcer.announced();
+ assert_eq!(announced.len(), 1, "threadless open posts no chip");
+ assert_eq!(announced[0].bot_id, bot);
+ assert_eq!(
+ announced[0].origin_channel_id,
+ macro_uuid::Uuid::from_u128(0xAA)
+ );
+ assert_eq!(
+ announced[0].origin_thread_id,
+ macro_uuid::Uuid::from_u128(0xAB)
+ );
+ assert_eq!(announced[0].prompted_content, "follow-up from the channel");
+}
+
+#[tokio::test]
+async fn an_announce_whose_bot_does_not_own_the_session_is_dropped() {
+ let (service, _repo, _containers, announcer, _runtimes) = harness();
+ let session = service
+ .open_external_session(open_external_request("/srv/agent"))
+ .await
+ .expect("open without a mention");
+
+ service
+ .announce_external_prompt(
+ session.id,
+ crate::domain::model::AnnouncePrompt {
+ bot_id: BotId::new_from_uuid(macro_uuid::generate_uuid_v7()),
+ origin: AnnounceOrigin {
+ channel_id: macro_uuid::Uuid::from_u128(0xAA),
+ thread_id: macro_uuid::Uuid::from_u128(0xAB),
+ },
+ content: "not yours".to_owned(),
+ sender: sender(),
+ },
+ )
+ .await
+ .expect("a foreign announce is dropped, not an error");
+
+ assert_eq!(announcer.announced().len(), 0);
+}
diff --git a/crates/agent_harness/src/inbound/kafka.rs b/crates/agent_harness/src/inbound/kafka.rs
index f9d79624bc..05e348230d 100644
--- a/crates/agent_harness/src/inbound/kafka.rs
+++ b/crates/agent_harness/src/inbound/kafka.rs
@@ -14,17 +14,28 @@ use bot_id::BotId;
use macro_user_id::email::ReadEmailParts;
use crate::domain::model::{
- AnnounceOrigin, DeliverAction, HarnessCommand, MentionOrigin, OpenSession,
+ AnnounceOrigin, AnnouncePrompt, DeliverAction, HarnessCommand, MentionOrigin, OpenSession,
+ is_managed_bot,
};
#[cfg(test)]
mod test;
-/// Why an event yielded no command. Only for logging - none of these are
+/// What one trigger event asks this deployment to do.
+#[derive(Debug, Clone)]
+pub enum RoutedTrigger {
+ /// Run a harness command for the managed bot's session.
+ Command(AgentSessionId, HarnessCommand),
+ /// Post the chip for a prompt an external bot's runtime delivers itself.
+ Announce(AgentSessionId, AnnouncePrompt),
+}
+
+/// Why an event yielded no work. Only for logging - none of these are
/// errors, and the consumer commits the offset either way.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Skipped {
- /// The event belongs to a different bot's deployment.
+ /// The event is another deployment's to act on: an open for a bot whose
+ /// runtime opens its own sessions, or managed traffic that is not ours.
ForeignBot,
/// The sender is not a user, so there is nobody to own the session.
NotFromUser,
@@ -36,12 +47,18 @@ pub enum Skipped {
NotMacroStaff,
}
-/// Route one trigger event: a command for `our_bot`, or a reason it was
+/// Route one trigger event: work for this deployment, or a reason it was
/// skipped.
-pub fn agent_trigger_to_harness_command(
+///
+/// Opens are only ours when the mentioned bot is `our_bot` - external bots'
+/// runtimes open their own sessions over the API. Events for sessions that
+/// already exist always carry work: a prompt to deliver when the session is
+/// managed here, or just its announcement when the bot's own runtime
+/// delivers the prompt.
+pub fn route_agent_trigger(
event: AgentTriggerTopicEvent,
our_bot: BotId,
-) -> Result<(AgentSessionId, HarnessCommand), Skipped> {
+) -> Result<RoutedTrigger, Skipped> {
match event {
AgentTriggerTopicEvent::New(NewAgentSessionEvent::TopLevelMentioned(mentioned)) => {
// TODO: remove
@@ -64,7 +81,7 @@ pub fn agent_trigger_to_harness_command(
.as_user()
.cloned()
.ok_or(Skipped::NotFromUser)?;
- Ok((
+ Ok(RoutedTrigger::Command(
AgentSessionId::new(),
HarnessCommand::Open(OpenSession {
bot_id: mentioned.bot_id,
@@ -87,19 +104,39 @@ pub fn agent_trigger_to_harness_command(
message,
},
)) => {
- if bot_id != our_bot {
- return Err(Skipped::ForeignBot);
+ let origin = AnnounceOrigin {
+ channel_id: message.channel_id,
+ thread_id: message.thread_id.unwrap_or(message.message_id),
+ };
+ if is_managed_bot(bot_id) {
+ // A managed session's prompt is delivered (and announced)
+ // by the deployment that manages it; anyone else stays out
+ // of the way entirely.
+ if bot_id != our_bot {
+ return Err(Skipped::ForeignBot);
+ }
+ return Ok(RoutedTrigger::Command(
+ session_id,
+ HarnessCommand::Deliver(DeliverAction::prompt(
+ message.content,
+ message.sender.as_user().cloned(),
+ Some(origin),
+ )),
+ ));
}
- Ok((
+ let sender = message
+ .sender
+ .as_user()
+ .cloned()
+ .ok_or(Skipped::NotFromUser)?;
+ Ok(RoutedTrigger::Announce(
session_id,
- HarnessCommand::Deliver(DeliverAction::prompt(
- message.content,
- message.sender.as_user().cloned(),
- Some(AnnounceOrigin {
- channel_id: message.channel_id,
- thread_id: message.thread_id.unwrap_or(message.message_id),
- }),
- )),
+ AnnouncePrompt {
+ bot_id,
+ origin,
+ content: message.content,
+ sender,
+ },
))
}
_ => Err(Skipped::Unrecognized),
diff --git a/crates/agent_harness/src/inbound/kafka/test.rs b/crates/agent_harness/src/inbound/kafka/test.rs
index df5749886f..e1cace084b 100644
--- a/crates/agent_harness/src/inbound/kafka/test.rs
+++ b/crates/agent_harness/src/inbound/kafka/test.rs
@@ -4,6 +4,7 @@ use agent_trigger::domain::broker_events::{
AgentBotMentionedEvent, AgentTriggerTopicEvent, ChannelEventMetadata,
ExistingAgentSessionEvent, NewAgentSessionEvent,
};
+use bot_id::MACRO_CODER_BOT_ID;
use channel_sender::ChannelSender;
use channels::domain::broker_events::ChannelMessagePostedMetadata;
use channels::domain::models::ChannelType;
@@ -52,13 +53,13 @@ fn channel_message(bot: BotId) -> AgentTriggerTopicEvent {
#[test]
fn a_mention_for_our_bot_opens_a_session() {
- let (_, command) = agent_trigger_to_harness_command(
+ let routed = route_agent_trigger(
mentioned(BotId::TEST_A, ChannelSender::new_from_user(user())),
BotId::TEST_A,
)
- .expect("a mention for our bot should yield a command");
+ .expect("a mention for our bot should yield work");
- let HarnessCommand::Open(open) = command else {
+ let RoutedTrigger::Command(_, HarnessCommand::Open(open)) = routed else {
panic!("a new-session event should open");
};
assert_eq!(open.bot_id, BotId::TEST_A);
@@ -81,8 +82,8 @@ fn a_threaded_mention_answers_into_its_thread() {
},
));
- let (_, HarnessCommand::Open(open)) = agent_trigger_to_harness_command(event, BotId::TEST_A)
- .expect("the mention should yield a command")
+ let RoutedTrigger::Command(_, HarnessCommand::Open(open)) =
+ route_agent_trigger(event, BotId::TEST_A).expect("the mention should yield work")
else {
panic!("a new-session event should open");
};
@@ -90,18 +91,21 @@ fn a_threaded_mention_answers_into_its_thread() {
}
#[test]
-fn a_foreign_bots_event_is_skipped() {
+fn a_foreign_bots_open_is_skipped() {
assert_eq!(
- agent_trigger_to_harness_command(
+ route_agent_trigger(
mentioned(BotId::TEST_A, ChannelSender::new_from_user(user())),
BotId::TEST_B,
)
.unwrap_err(),
Skipped::ForeignBot
);
+}
+
+#[test]
+fn another_deployments_managed_traffic_is_skipped() {
assert_eq!(
- agent_trigger_to_harness_command(channel_message(BotId::TEST_A), BotId::TEST_B)
- .unwrap_err(),
+ route_agent_trigger(channel_message(MACRO_CODER_BOT_ID), BotId::TEST_B).unwrap_err(),
Skipped::ForeignBot
);
}
@@ -109,7 +113,7 @@ fn a_foreign_bots_event_is_skipped() {
#[test]
fn a_bot_authored_mention_is_skipped() {
assert_eq!(
- agent_trigger_to_harness_command(
+ route_agent_trigger(
mentioned(BotId::TEST_A, ChannelSender::new_from_bot(BotId::TEST_B)),
BotId::TEST_A,
)
@@ -123,7 +127,7 @@ fn a_non_staff_mention_is_skipped() {
let user = MacroUserIdStr::try_from_email("[email protected]").expect("a valid user id");
assert_eq!(
- agent_trigger_to_harness_command(
+ route_agent_trigger(
mentioned(BotId::TEST_A, ChannelSender::new_from_user(user)),
BotId::TEST_A,
)
@@ -133,13 +137,12 @@ fn a_non_staff_mention_is_skipped() {
}
#[test]
-fn a_channel_message_forwards_to_its_session() {
- let (session_id, command) =
- agent_trigger_to_harness_command(channel_message(BotId::TEST_A), BotId::TEST_A)
- .expect("a channel event for our bot should yield a command");
+fn a_managed_channel_message_forwards_to_its_session() {
+ let routed = route_agent_trigger(channel_message(MACRO_CODER_BOT_ID), MACRO_CODER_BOT_ID)
+ .expect("a channel event for our bot should yield work");
- let HarnessCommand::Deliver(deliver) = command else {
- panic!("an existing-session event should deliver");
+ let RoutedTrigger::Command(session_id, HarnessCommand::Deliver(deliver)) = routed else {
+ panic!("a managed existing-session event should deliver");
};
assert_eq!(session_id, AgentSessionId::TEST_A);
assert_eq!(deliver.actor, Some(user()));
@@ -154,3 +157,36 @@ fn a_channel_message_forwards_to_its_session() {
assert_eq!(announce.channel_id, Uuid::from_u128(1));
assert_eq!(announce.thread_id, Uuid::from_u128(2));
}
+
+#[test]
+fn an_external_channel_message_announces_only() {
+ // The external bot's own runtime delivers the prompt; this deployment
+ // only posts the chip, whichever bot it manages itself.
+ let routed = route_agent_trigger(channel_message(BotId::TEST_A), MACRO_CODER_BOT_ID)
+ .expect("an external existing-session event should yield work");
+
+ let RoutedTrigger::Announce(session_id, prompt) = routed else {
+ panic!("an external existing-session event should announce");
+ };
+ assert_eq!(session_id, AgentSessionId::TEST_A);
+ assert_eq!(prompt.bot_id, BotId::TEST_A);
+ assert_eq!(prompt.sender, user());
+ assert_eq!(prompt.content, "@claude fix the tests");
+ assert_eq!(prompt.origin.channel_id, Uuid::from_u128(1));
+ assert_eq!(prompt.origin.thread_id, Uuid::from_u128(2));
+}
+
+#[test]
+fn a_bot_authored_external_channel_message_is_skipped() {
+ let event = AgentTriggerTopicEvent::Existing(ExistingAgentSessionEvent::Channel(
+ ChannelEventMetadata {
+ bot_id: BotId::TEST_A,
+ session_id: AgentSessionId::TEST_A,
+ message: message(ChannelSender::new_from_bot(BotId::TEST_B)),
+ },
+ ));
+ assert_eq!(
+ route_agent_trigger(event, MACRO_CODER_BOT_ID).unwrap_err(),
+ Skipped::NotFromUser
+ );
+}
diff --git a/crates/agent_harness/src/inbound/mod.rs b/crates/agent_harness/src/inbound/mod.rs
index 627f9da984..856caaa13c 100644
--- a/crates/agent_harness/src/inbound/mod.rs
+++ b/crates/agent_harness/src/inbound/mod.rs
@@ -4,3 +4,4 @@
//! is addressed to us, hand one value inward. No policy lives here.
pub mod kafka;
+pub mod runtime_gateway;
diff --git a/crates/agent_harness/src/inbound/runtime_gateway.rs b/crates/agent_harness/src/inbound/runtime_gateway.rs
new file mode 100644
index 0000000000..8fe0e704c5
--- /dev/null
+++ b/crates/agent_harness/src/inbound/runtime_gateway.rs
@@ -0,0 +1,127 @@
+//! The runtime gateway: where external runtimes dial in to serve a bot.
+//!
+//! `GET /runtime/ws`, authenticated with the standard bot credential headers
+//! (`x-macro-bot-token`, `x-macro-bot-scope`) - a WebSocket upgrade is an
+//! ordinary HTTP request, and every runtime dialing in is a real client that
+//! can set headers.
+//!
+//! One connection per bot, not per session. ACP initializes per connection and
+//! carries a `sessionId` on every session-scoped method, so one socket and one
+//! harness process serve every session that bot is running. Which sessions
+//! those are is not something the dial declares: the runtime dials once, and
+//! sessions are bound to the connection as work arrives for them. A session
+//! nobody is prompting costs nothing, and one prompted after a reconnect
+//! restores itself on the way to being prompted.
+//!
+//! Everything checkable is checked before the upgrade, so a bad dial fails with
+//! an HTTP status rather than a dropped socket.
+
+use std::sync::Arc;
+
+use agent_runtime_protocol::domain::schema::v0::{ToRuntimeMessage, ToServerMessage};
+use agent_runtime_protocol::outbound::websocket::connect_socket;
+use agent_session::domain::ports::BotDirectory;
+use axum::Router;
+use axum::extract::ws::WebSocketUpgrade;
+use axum::extract::{FromRef, State};
+use axum::http::StatusCode;
+use axum::response::{IntoResponse, Response};
+use axum::routing::get;
+use macro_authorization::{
+ BotOnly, MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState,
+};
+
+use crate::outbound::runtime_registry::RuntimeRegistry;
+
+#[cfg(test)]
+mod test;
+
+/// The sending half of an accepted dial, shared by every session on it.
+pub type GatewaySender = tokio::sync::mpsc::UnboundedSender<ToRuntimeMessage>;
+
+/// State for the runtime gateway route.
+pub struct RuntimeGatewayState<Bots, Auth> {
+ runtimes: Arc<RuntimeRegistry<GatewaySender>>,
+ bots: Arc<Bots>,
+ authorization_state: MacroAuthorizationState<Auth>,
+}
+
+impl<Bots, Auth> RuntimeGatewayState<Bots, Auth> {
+ /// Create gateway state.
+ pub fn new(
+ runtimes: Arc<RuntimeRegistry<GatewaySender>>,
+ bots: Arc<Bots>,
+ authorization_state: MacroAuthorizationState<Auth>,
+ ) -> Self {
+ Self {
+ runtimes,
+ bots,
+ authorization_state,
+ }
+ }
+}
+
+// Manual Clone impl: everything is behind an Arc.
+impl<Bots, Auth> Clone for RuntimeGatewayState<Bots, Auth> {
+ fn clone(&self) -> Self {
+ Self {
+ runtimes: Arc::clone(&self.runtimes),
+ bots: Arc::clone(&self.bots),
+ authorization_state: self.authorization_state.clone(),
+ }
+ }
+}
+
+impl<Bots, Auth> FromRef<RuntimeGatewayState<Bots, Auth>> for MacroAuthorizationState<Auth> {
+ fn from_ref(state: &RuntimeGatewayState<Bots, Auth>) -> Self {
+ state.authorization_state.clone()
+ }
+}
+
+/// Build the router serving `GET /ws`. Mount it under `/runtime`.
+pub fn runtime_gateway_router<Bots, Auth, S>(state: RuntimeGatewayState<Bots, Auth>) -> Router<S>
+where
+ Bots: BotDirectory,
+ Auth: MacroAuthorizationService,
+ S: Clone + Send + Sync + 'static,
+{
+ Router::new()
+ .route("/ws", get(dial_handler::<Bots, Auth>))
+ .with_state(state)
+}
+
+/// Authenticate a dial and take the socket as this bot's connection.
+async fn dial_handler<Bots, Auth>(
+ State(state): State<RuntimeGatewayState<Bots, Auth>>,
+ caller: MacroAuthorizationExtractor<Auth, BotOnly>,
+ ws: WebSocketUpgrade,
+) -> Response
+where
+ Bots: BotDirectory,
+ Auth: MacroAuthorizationService,
+{
+ let bot = caller.authorization.bot_id;
+
+ // Read rather than trusted from whenever the bot was set up: a bot whose
+ // agent-hood was revoked, or that turned out managed, must not dial in.
+ match state.bots.bot_facts(bot).await {
+ Ok(Some(facts)) if facts.has_agent && !facts.is_managed => {}
+ Ok(_) => {
+ return (StatusCode::FORBIDDEN, "not a dialable agent bot").into_response();
+ }
+ Err(error) => {
+ tracing::error!(error = ?error, %bot, "gateway bot lookup failed");
+ return (StatusCode::INTERNAL_SERVER_ERROR, "bot lookup failed").into_response();
+ }
+ }
+
+ let runtimes = Arc::clone(&state.runtimes);
+ ws.on_upgrade(move |socket| async move {
+ let transport = connect_socket::<ToRuntimeMessage, ToServerMessage>(socket);
+ // Last dial wins. A runtime that redials has lost its old socket
+ // whether or not this side has noticed, so displacing is the only
+ // answer that lets it recover.
+ runtimes.attach(bot, transport);
+ tracing::info!(%bot, "a runtime dialed in");
+ })
+}
diff --git a/crates/agent_harness/src/inbound/runtime_gateway/test.rs b/crates/agent_harness/src/inbound/runtime_gateway/test.rs
new file mode 100644
index 0000000000..e251eff943
--- /dev/null
+++ b/crates/agent_harness/src/inbound/runtime_gateway/test.rs
@@ -0,0 +1,205 @@
+//! What the dial route decides, end to end over a real socket: who may take
+//! over a bot's connection, and what a refusal looks like to the runtime.
+//!
+//! A refusal has to be an HTTP status rather than a closed socket, so every
+//! rejection case asserts the status the upgrade failed with and that nothing
+//! reached the registry.
+
+use super::*;
+use agent_session::domain::error::AgentSessionError;
+use agent_session::domain::ports::BotFacts;
+use bot_id::BotId;
+use macro_authorization::{
+ BOT_SCOPE_HEADER, BOT_TOKEN_HEADER, BotActingUserClaims, BotAuthentication, BotAuthorizer,
+ BotScope, InternalAuthConfig, JwtValidator, MacroAuthorizationError,
+ MacroAuthorizationServiceImpl, ValidatedIdentity,
+};
+use macro_user_id::user_id::MacroUserIdStr;
+use rootcause::Report;
+use tokio_tungstenite::tungstenite;
+
+const BOT_TOKEN: &str = "mbot_self_test";
+
+#[derive(Clone, Default)]
+struct FakeJwtValidator;
+
+impl JwtValidator for FakeJwtValidator {
+ fn validate(&self, jwt: &str) -> Result<ValidatedIdentity, Report<MacroAuthorizationError>> {
+ Ok(ValidatedIdentity {
+ user_id: jwt.to_string(),
+ fusion_user_id: "fusion-user".to_string(),
+ organization_id: None,
+ permissions: None,
+ })
+ }
+}
+
+/// Authorizes exactly one token, as [`BotId::TEST_A`].
+#[derive(Clone)]
+struct SelfBotAuthorizer;
+
+impl BotAuthorizer for SelfBotAuthorizer {
+ async fn authorize_bot(
+ &self,
+ bot_token: &str,
+ bot_scope: BotScope,
+ _acting_user: Option<BotActingUserClaims>,
+ ) -> Result<BotAuthentication, Report<MacroAuthorizationError>> {
+ if bot_token != BOT_TOKEN {
+ return Err(Report::new(MacroAuthorizationError::InvalidCredentials));
+ }
+ Ok(BotAuthentication {
+ bot_id: BotId::TEST_A,
+ token_id: macro_uuid::generate_uuid_v7(),
+ bot_scope,
+ team_id: None,
+ acting_user: None,
+ })
+ }
+}
+
+/// Answers every lookup the same way.
+enum FactsDirectory {
+ Known(BotFacts),
+ Unreadable,
+}
+
+impl BotDirectory for FactsDirectory {
+ async fn bot_facts(
+ &self,
+ _bot: BotId,
+ ) -> agent_session::domain::error::Result<Option<BotFacts>> {
+ match self {
+ Self::Known(facts) => Ok(Some(facts.clone())),
+ Self::Unreadable => Err(AgentSessionError::Unknown(anyhow::anyhow!(
+ "the bots table is unreachable"
+ ))),
+ }
+ }
+}
+
+/// A bot whose runtime its operator hosts: the only kind that may dial.
+fn external_facts() -> BotFacts {
+ BotFacts {
+ has_agent: true,
+ is_managed: false,
+ owner_user_id: Some(MacroUserIdStr::try_from_email("[email protected]").unwrap()),
+ }
+}
+
+/// Serve the gateway on a loopback port, returning the registry it feeds and
+/// the `ws://` base to dial.
+async fn serve(directory: FactsDirectory) -> (Arc<RuntimeRegistry<GatewaySender>>, String) {
+ let runtimes = RuntimeRegistry::new();
+ let authorization = MacroAuthorizationServiceImpl::new(
+ FakeJwtValidator,
+ InternalAuthConfig {
+ api_key: "test-internal-key".to_string(),
+ default_user_id: None,
+ },
+ SelfBotAuthorizer,
+ );
+ let app: Router = Router::new().nest(
+ "/runtime",
+ runtime_gateway_router(RuntimeGatewayState::new(
+ Arc::clone(&runtimes),
+ Arc::new(directory),
+ MacroAuthorizationState::new(Arc::new(authorization)),
+ )),
+ );
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let address = listener.local_addr().unwrap();
+ tokio::spawn(async move { axum::serve(listener, app).await });
+ (runtimes, format!("ws://{address}"))
+}
+
+fn dial_request(base: &str, token: Option<&str>) -> tungstenite::handshake::client::Request {
+ use tungstenite::client::IntoClientRequest as _;
+ let mut request = format!("{base}/runtime/ws").into_client_request().unwrap();
+ if let Some(token) = token {
+ let headers = request.headers_mut();
+ headers.insert(BOT_TOKEN_HEADER, token.parse().unwrap());
+ headers.insert(BOT_SCOPE_HEADER, "user".parse().unwrap());
+ }
+ request
+}
+
+/// Dial expecting rejection; return the HTTP status the upgrade failed with.
+async fn rejected(request: tungstenite::handshake::client::Request) -> StatusCode {
+ match tokio_tungstenite::connect_async(request).await {
+ Err(tungstenite::Error::Http(response)) => response.status(),
+ other => panic!("expected an upgrade rejection, got {other:?}"),
+ }
+}
+
+#[tokio::test]
+async fn a_valid_dial_becomes_the_bots_connection() {
+ let (runtimes, base) = serve(FactsDirectory::Known(external_facts())).await;
+
+ let (_socket, _) = tokio_tungstenite::connect_async(dial_request(&base, Some(BOT_TOKEN)))
+ .await
+ .expect("the dial is valid");
+
+ // The registry is populated after the upgrade completes, so the assertion
+ // is a wait rather than a read.
+ while !runtimes.is_connected(BotId::TEST_A) {
+ tokio::task::yield_now().await;
+ }
+}
+
+#[tokio::test]
+async fn a_bad_token_is_unauthorized() {
+ let (runtimes, base) = serve(FactsDirectory::Known(external_facts())).await;
+
+ let status = rejected(dial_request(&base, Some("mbot_wrong"))).await;
+
+ assert_eq!(status, StatusCode::UNAUTHORIZED);
+ assert!(!runtimes.is_connected(BotId::TEST_A));
+}
+
+#[tokio::test]
+async fn a_missing_token_is_rejected() {
+ let (runtimes, base) = serve(FactsDirectory::Known(external_facts())).await;
+
+ let status = rejected(dial_request(&base, None)).await;
+
+ // No credentials at all: the extractor rejects before anything runs.
+ assert_eq!(status, StatusCode::UNAUTHORIZED);
+ assert!(!runtimes.is_connected(BotId::TEST_A));
+}
+
+#[tokio::test]
+async fn a_managed_bot_may_not_dial() {
+ let mut facts = external_facts();
+ facts.is_managed = true;
+ let (runtimes, base) = serve(FactsDirectory::Known(facts)).await;
+
+ let status = rejected(dial_request(&base, Some(BOT_TOKEN))).await;
+
+ assert_eq!(status, StatusCode::FORBIDDEN);
+ assert!(!runtimes.is_connected(BotId::TEST_A));
+}
+
+#[tokio::test]
+async fn revoked_agenthood_may_not_dial() {
+ let mut facts = external_facts();
+ facts.has_agent = false;
+ let (runtimes, base) = serve(FactsDirectory::Known(facts)).await;
+
+ let status = rejected(dial_request(&base, Some(BOT_TOKEN))).await;
+
+ assert_eq!(status, StatusCode::FORBIDDEN);
+ assert!(!runtimes.is_connected(BotId::TEST_A));
+}
+
+#[tokio::test]
+async fn an_unreadable_bot_lookup_fails_the_dial() {
+ let (runtimes, base) = serve(FactsDirectory::Unreadable).await;
+
+ let status = rejected(dial_request(&base, Some(BOT_TOKEN))).await;
+
+ // A lookup that failed is not a lookup that said no: the runtime is told
+ // to come back rather than that it is unwelcome.
+ assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
+ assert!(!runtimes.is_connected(BotId::TEST_A));
+}
diff --git a/crates/agent_harness/src/outbound/channel_announcer.rs b/crates/agent_harness/src/outbound/channel_announcer.rs
index 8fd887816c..43c82a29cd 100644
--- a/crates/agent_harness/src/outbound/channel_announcer.rs
+++ b/crates/agent_harness/src/outbound/channel_announcer.rs
@@ -16,7 +16,6 @@ mod test;
use std::sync::Arc;
-use bot_id::BotId;
use channel_sender::ChannelSender;
use channels::domain::models::{PostMessageNotificationPolicy, PostMessageRequest};
use channels::domain::ports::ChannelService;
@@ -36,22 +35,18 @@ fn announcement_chip(announcement: &SessionAnnouncement) -> AgentAnnouncementChi
}
}
-/// Posts session announcements as `bot_id` through a [`ChannelService`].
+/// Posts session announcements as their session's bot through a
+/// [`ChannelService`].
pub struct ChannelAnnouncer<Channels> {
channels: Arc<Channels>,
- bot_id: BotId,
lexical: LexicalClient,
}
impl<Channels> ChannelAnnouncer<Channels> {
- /// Announce as `bot_id`, posting through `channels`, with content
- /// composed by `lexical`.
- pub fn new(channels: Arc<Channels>, bot_id: BotId, lexical: LexicalClient) -> Self {
- Self {
- channels,
- bot_id,
- lexical,
- }
+ /// Post through `channels`, with content composed by `lexical`. The
+ /// sender is per-announcement: whichever bot the session runs for.
+ pub fn new(channels: Arc<Channels>, lexical: LexicalClient) -> Self {
+ Self { channels, lexical }
}
}
@@ -69,7 +64,7 @@ where
self.channels
.post_message(
- ChannelSender::new_from_bot(self.bot_id),
+ ChannelSender::new_from_bot(announcement.bot_id),
announcement.origin_channel_id,
PostMessageRequest {
content,
diff --git a/crates/agent_harness/src/outbound/channel_announcer/test.rs b/crates/agent_harness/src/outbound/channel_announcer/test.rs
index d6c3bbb44b..7ef95c2b68 100644
--- a/crates/agent_harness/src/outbound/channel_announcer/test.rs
+++ b/crates/agent_harness/src/outbound/channel_announcer/test.rs
@@ -2,10 +2,12 @@ use macro_user_id::user_id::MacroUserIdStr;
use macro_uuid::Uuid;
use super::*;
+use bot_id::BotId;
#[test]
fn chip_carries_the_announcement_identity() {
let announcement = SessionAnnouncement {
+ bot_id: BotId::TEST_A,
session_id: agent_session::domain::model::AgentSessionId::TEST_A,
origin_channel_id: Uuid::from_u128(1),
origin_thread_id: Uuid::from_u128(2),
diff --git a/crates/agent_harness/src/outbound/daytona/manager.rs b/crates/agent_harness/src/outbound/daytona/manager.rs
index c41ba860ca..a44b0d44a4 100644
--- a/crates/agent_harness/src/outbound/daytona/manager.rs
+++ b/crates/agent_harness/src/outbound/daytona/manager.rs
@@ -2,7 +2,7 @@ use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
-use agent_runtime_protocol::domain::ports::{Transport, TransportError};
+use agent_runtime_protocol::domain::ports::Transport;
use agent_runtime_protocol::domain::schema::v0::{ToRuntimeMessage, ToServerMessage};
use agent_session::domain::model::AgentSessionId;
use futures::{StreamExt as _, stream};
@@ -150,11 +150,11 @@ impl DaytonaContainerManager {
id: id.clone(),
client: self.client.clone(),
managed: self.managed.clone(),
- wire: Arc::new(SidecarTransport::connect_observed(socket, move || {
+ wire: SidecarTransport::connect_observed(socket, move || {
managed
.containers
.record_activity(&observed, Instant::now());
- })),
+ }),
})
}
@@ -413,12 +413,11 @@ async fn stop_managed(
}
/// One Daytona sandbox and the live protocol connection to its sidecar.
-#[derive(Clone)]
pub struct DaytonaContainer {
id: DaytonaSandboxId,
client: DaytonaClient,
managed: Arc<DaytonaContainerManagerState>,
- wire: Arc<SidecarTransport>,
+ wire: SidecarTransport,
}
impl DaytonaContainer {
@@ -439,12 +438,14 @@ impl DaytonaContainer {
}
impl Transport<ToRuntimeMessage, ToServerMessage> for DaytonaContainer {
- async fn send(&self, message: ToRuntimeMessage) -> std::result::Result<(), TransportError> {
- self.wire.send(message).await
- }
-
- async fn recv(&self) -> std::result::Result<Option<ToServerMessage>, TransportError> {
- self.wire.recv().await
+ type Sender = crate::outbound::sidecar::SidecarSender;
+ type Receiver = tokio::sync::mpsc::UnboundedReceiver<ToServerMessage>;
+
+ /// The sandbox itself is not carried into the halves: nothing reattaches
+ /// to a container object once its session has it, and ending a sandbox
+ /// goes through the manager by session id.
+ fn split(self) -> (Self::Sender, Self::Receiver) {
+ self.wire.split()
}
}
diff --git a/crates/agent_harness/src/outbound/mod.rs b/crates/agent_harness/src/outbound/mod.rs
index c2d67f2e62..faba70fdcb 100644
--- a/crates/agent_harness/src/outbound/mod.rs
+++ b/crates/agent_harness/src/outbound/mod.rs
@@ -6,4 +6,5 @@ pub mod daytona;
pub(crate) mod managed_containers;
pub mod namespace;
pub(crate) mod provision;
+pub mod runtime_registry;
pub mod sidecar;
diff --git a/crates/agent_harness/src/outbound/namespace/manager.rs b/crates/agent_harness/src/outbound/namespace/manager.rs
index 3ddb1b27d5..e8097798ac 100644
--- a/crates/agent_harness/src/outbound/namespace/manager.rs
+++ b/crates/agent_harness/src/outbound/namespace/manager.rs
@@ -1,6 +1,6 @@
use std::sync::Arc;
-use agent_runtime_protocol::domain::ports::{Transport, TransportError};
+use agent_runtime_protocol::domain::ports::Transport;
use agent_runtime_protocol::domain::schema::v0::{ToRuntimeMessage, ToServerMessage};
use agent_session::domain::model::AgentSessionId;
@@ -73,7 +73,7 @@ impl NamespaceContainerManager {
Ok(NamespaceContainer {
instance: Arc::new(instance),
client: self.client.clone(),
- wire: Arc::new(SidecarTransport::connect(socket)),
+ wire: SidecarTransport::connect(socket),
})
}
}
@@ -129,11 +129,10 @@ impl ContainerManager for NamespaceContainerManager {
}
/// One Namespace instance and its live sidecar transport.
-#[derive(Clone)]
pub struct NamespaceContainer {
instance: Arc<Instance>,
client: NamespaceClient,
- wire: Arc<SidecarTransport>,
+ wire: SidecarTransport,
}
impl NamespaceContainer {
@@ -154,12 +153,14 @@ impl NamespaceContainer {
}
impl Transport<ToRuntimeMessage, ToServerMessage> for NamespaceContainer {
- async fn send(&self, message: ToRuntimeMessage) -> std::result::Result<(), TransportError> {
- self.wire.send(message).await
- }
-
- async fn recv(&self) -> std::result::Result<Option<ToServerMessage>, TransportError> {
- self.wire.recv().await
+ type Sender = crate::outbound::sidecar::SidecarSender;
+ type Receiver = tokio::sync::mpsc::UnboundedReceiver<ToServerMessage>;
+
+ /// The sandbox itself is not carried into the halves: nothing reattaches
+ /// to a container object once its session has it, and ending a sandbox
+ /// goes through the manager by session id.
+ fn split(self) -> (Self::Sender, Self::Receiver) {
+ self.wire.split()
}
}
diff --git a/crates/agent_harness/src/outbound/runtime_registry.rs b/crates/agent_harness/src/outbound/runtime_registry.rs
new file mode 100644
index 0000000000..ca70f83673
--- /dev/null
+++ b/crates/agent_harness/src/outbound/runtime_registry.rs
@@ -0,0 +1,91 @@
+//! The live runtime connections, one per bot that has dialed in.
+//!
+//! Held here rather than in the domain because a connection is liveness: it
+//! exists while a socket does, so it is never persisted and never survives a
+//! restart. What is durable is each session's `acp_session_id`, which is how a
+//! session re-establishes itself on whatever process dials in next.
+//!
+//! One entry per bot. A bot's runtime dials once and carries every session that
+//! bot serves, so this is what makes many ACP sessions share one harness
+//! process.
+
+use std::sync::Arc;
+
+use agent_runtime_protocol::domain::ports::{Transport, TransportSender};
+use agent_runtime_protocol::domain::schema::v0::{ToRuntimeMessage, ToServerMessage};
+use agent_session::domain::connection::{RuntimeAttachment, RuntimeConnection, SessionChannel};
+use agent_session::domain::model::AgentSessionId;
+use bot_id::BotId;
+use dashmap::DashMap;
+
+use crate::domain::ports::RuntimeConnections;
+
+#[cfg(test)]
+mod test;
+
+/// Every bot's live runtime connection.
+pub struct RuntimeRegistry<Sender> {
+ connections: DashMap<BotId, Arc<RuntimeConnection<Sender>>>,
+}
+
+impl<Sender> Default for RuntimeRegistry<Sender> {
+ fn default() -> Self {
+ Self {
+ connections: DashMap::new(),
+ }
+ }
+}
+
+impl<Sender> RuntimeRegistry<Sender>
+where
+ Sender: TransportSender<ToRuntimeMessage>,
+{
+ /// An empty registry.
+ #[must_use]
+ pub fn new() -> Arc<Self> {
+ Arc::new(Self::default())
+ }
+
+ /// Whether a bot currently has a runtime connected.
+ #[must_use]
+ pub fn is_connected(&self, bot: BotId) -> bool {
+ self.connections.contains_key(&bot)
+ }
+}
+
+impl<Sender> RuntimeRegistry<Sender>
+where
+ Sender: TransportSender<ToRuntimeMessage>,
+{
+ /// Take over as `bot`'s connection, displacing whatever it had.
+ ///
+ /// Last dial wins: a runtime that redials has necessarily lost its old
+ /// socket, and the sessions it was carrying rebind as they are next used.
+ pub fn attach<Carrier>(self: &Arc<Self>, bot: BotId, carrier: Carrier)
+ where
+ Carrier: Transport<ToRuntimeMessage, ToServerMessage, Sender = Sender>,
+ {
+ let connection = RuntimeConnection::connect(carrier);
+
+ if let Some(displaced) = self.connections.insert(bot, connection) {
+ displaced.evict();
+ tracing::info!(%bot, "a redialed runtime replaced this bot's connection");
+ }
+ }
+}
+
+impl<Sender> RuntimeConnections for Arc<RuntimeRegistry<Sender>>
+where
+ Sender: TransportSender<ToRuntimeMessage>,
+{
+ type Connector = SessionChannel<Sender>;
+
+ async fn bind(
+ &self,
+ bot: BotId,
+ session: AgentSessionId,
+ ) -> Option<RuntimeAttachment<SessionChannel<Sender>>> {
+ let connection = self.connections.get(&bot).map(|entry| Arc::clone(&entry))?;
+ Some(connection.bind(session).await)
+ }
+}
diff --git a/crates/agent_harness/src/outbound/runtime_registry/test.rs b/crates/agent_harness/src/outbound/runtime_registry/test.rs
new file mode 100644
index 0000000000..cca2f3d8b9
--- /dev/null
+++ b/crates/agent_harness/src/outbound/runtime_registry/test.rs
@@ -0,0 +1,81 @@
+//! Binding rules of the registry: what a session finds when it looks for its
+//! bot's runtime, and what a redial does to whatever was there.
+
+use super::*;
+use crate::testing::helpers::containers::{ContainerMock, ContainerSender};
+
+#[tokio::test]
+async fn a_bot_with_no_runtime_has_nothing_to_bind_to() {
+ let registry = RuntimeRegistry::<ContainerSender>::new();
+
+ assert!(!registry.is_connected(BotId::TEST_A));
+ assert!(
+ registry
+ .bind(BotId::TEST_A, AgentSessionId::TEST_A)
+ .await
+ .is_none()
+ );
+}
+
+#[tokio::test]
+async fn a_session_binds_onto_its_bots_connection() {
+ let registry = RuntimeRegistry::new();
+ registry.attach(BotId::TEST_A, ContainerMock::default());
+
+ assert!(registry.is_connected(BotId::TEST_A));
+ assert!(
+ registry
+ .bind(BotId::TEST_A, AgentSessionId::TEST_A)
+ .await
+ .is_some()
+ );
+ // A connection belongs to one bot only.
+ assert!(
+ registry
+ .bind(BotId::TEST_B, AgentSessionId::TEST_A)
+ .await
+ .is_none()
+ );
+}
+
+#[tokio::test]
+async fn a_redial_displaces_the_previous_connection() {
+ let registry = RuntimeRegistry::new();
+ registry.attach(BotId::TEST_A, ContainerMock::default());
+ registry
+ .bind(BotId::TEST_A, AgentSessionId::TEST_A)
+ .await
+ .expect("the first dial is bindable");
+
+ registry.attach(BotId::TEST_A, ContainerMock::default());
+
+ // Displacing leaves the bot connected, and the session that was riding on
+ // the old connection binds again onto the new one - which is how a
+ // reconnect restores it.
+ assert!(registry.is_connected(BotId::TEST_A));
+ assert!(
+ registry
+ .bind(BotId::TEST_A, AgentSessionId::TEST_A)
+ .await
+ .is_some()
+ );
+}
+
+#[tokio::test]
+async fn one_connection_carries_many_sessions() {
+ let registry = RuntimeRegistry::new();
+ registry.attach(BotId::TEST_A, ContainerMock::default());
+
+ assert!(
+ registry
+ .bind(BotId::TEST_A, AgentSessionId::TEST_A)
+ .await
+ .is_some()
+ );
+ assert!(
+ registry
+ .bind(BotId::TEST_A, AgentSessionId::TEST_B)
+ .await
+ .is_some()
+ );
+}
diff --git a/crates/agent_harness/src/outbound/sidecar.rs b/crates/agent_harness/src/outbound/sidecar.rs
index 4d7f008891..c450c0c4a3 100644
--- a/crates/agent_harness/src/outbound/sidecar.rs
+++ b/crates/agent_harness/src/outbound/sidecar.rs
@@ -8,13 +8,12 @@
//! originates the one [`SystemEvent`] the domain acts on.
use agent_client_protocol::RawJsonRpcMessage;
-use agent_runtime_protocol::domain::ports::{Transport, TransportError};
+use agent_runtime_protocol::domain::ports::{Transport, TransportError, TransportSender};
use agent_runtime_protocol::domain::schema::v0::{
AcpMessage, SystemEvent, ToRuntimeMessage, ToServerMessage,
};
use futures::{SinkExt, StreamExt};
use tokio::io::{AsyncRead, AsyncWrite};
-use tokio::sync::Mutex as AsyncMutex;
use tokio::sync::{mpsc, oneshot};
use tokio_tungstenite::WebSocketStream;
use tokio_tungstenite::tungstenite::Message;
@@ -28,7 +27,12 @@ mod test;
/// through an `Arc`, which is what makes them cloneable.
pub struct SidecarTransport {
outbound: mpsc::UnboundedSender<Outbound>,
- inbound: AsyncMutex<mpsc::UnboundedReceiver<ToServerMessage>>,
+ inbound: mpsc::UnboundedReceiver<ToServerMessage>,
+}
+
+/// The sidecar's sending half.
+pub struct SidecarSender {
+ outbound: mpsc::UnboundedSender<Outbound>,
}
struct Outbound {
@@ -72,12 +76,26 @@ impl SidecarTransport {
Self {
outbound: outbound_tx,
- inbound: AsyncMutex::new(inbound_rx),
+ inbound: inbound_rx,
}
}
}
impl Transport<ToRuntimeMessage, ToServerMessage> for SidecarTransport {
+ type Sender = SidecarSender;
+ type Receiver = mpsc::UnboundedReceiver<ToServerMessage>;
+
+ fn split(self) -> (Self::Sender, Self::Receiver) {
+ (
+ SidecarSender {
+ outbound: self.outbound,
+ },
+ self.inbound,
+ )
+ }
+}
+
+impl TransportSender<ToRuntimeMessage> for SidecarSender {
async fn send(&self, message: ToRuntimeMessage) -> Result<(), TransportError> {
// A message this transport has no way to deliver is dropped rather than
// failed: the sidecar carries ACP and nothing else, and refusing would
@@ -95,10 +113,6 @@ impl Transport<ToRuntimeMessage, ToServerMessage> for SidecarTransport {
.await
.map_err(|_| TransportError::Client("the sidecar connection is closed".to_owned()))?
}
-
- async fn recv(&self) -> Result<Option<ToServerMessage>, TransportError> {
- Ok(self.inbound.lock().await.recv().await)
- }
}
/// Relay frames until either side closes.
diff --git a/crates/agent_harness/src/outbound/sidecar/test.rs b/crates/agent_harness/src/outbound/sidecar/test.rs
index e50c69f496..519ea9190d 100644
--- a/crates/agent_harness/src/outbound/sidecar/test.rs
+++ b/crates/agent_harness/src/outbound/sidecar/test.rs
@@ -18,13 +18,13 @@ fn frame() -> RawJsonRpcMessage {
/// Stand in for the sidecar: accept one WebSocket and hand back the transport
/// under test alongside the sidecar's end of it.
-async fn transport() -> (SidecarTransport, WebSocketStream<TcpStream>) {
+type Halves = (SidecarSender, mpsc::UnboundedReceiver<ToServerMessage>);
+
+async fn transport() -> (Halves, WebSocketStream<TcpStream>) {
observed_transport(|| {}).await
}
-async fn observed_transport<Observer>(
- observer: Observer,
-) -> (SidecarTransport, WebSocketStream<TcpStream>)
+async fn observed_transport<Observer>(observer: Observer) -> (Halves, WebSocketStream<TcpStream>)
where
Observer: Fn() + Send + 'static,
{
@@ -48,14 +48,14 @@ where
let sidecar = server.await.expect("the accept task should not panic");
(
- SidecarTransport::connect_observed(client, observer),
+ SidecarTransport::connect_observed(client, observer).split(),
sidecar,
)
}
#[tokio::test]
async fn reports_acp_ready_before_anything_else() {
- let (transport, mut sidecar) = transport().await;
+ let ((_outbound, mut inbound), mut sidecar) = transport().await;
// The agent speaks immediately, so this also proves ordering: the frame was
// on the wire before the first `recv`, and `AcpReady` still comes first.
@@ -65,11 +65,7 @@ async fn reports_acp_ready_before_anything_else() {
.await
.expect("the sidecar should be able to send");
- let first = transport
- .recv()
- .await
- .expect("receiving should succeed")
- .expect("the stream should be open");
+ let first = inbound.recv().await.expect("the stream should be open");
assert!(matches!(
first,
ToServerMessage::Event {
@@ -80,8 +76,8 @@ async fn reports_acp_ready_before_anything_else() {
#[tokio::test]
async fn wraps_frames_from_the_agent() {
- let (transport, mut sidecar) = transport().await;
- let _ready = transport.recv().await;
+ let ((_outbound, mut inbound), mut sidecar) = transport().await;
+ let _ready = inbound.recv().await;
let json = serde_json::to_string(&frame()).expect("the fixture should serialize");
sidecar
@@ -89,11 +85,7 @@ async fn wraps_frames_from_the_agent() {
.await
.expect("the sidecar should be able to send");
- let message = transport
- .recv()
- .await
- .expect("receiving should succeed")
- .expect("the stream should be open");
+ let message = inbound.recv().await.expect("the stream should be open");
let ToServerMessage::Acp(AcpMessage(received)) = message else {
panic!("an agent frame should arrive as an acp message");
};
@@ -107,11 +99,11 @@ async fn wraps_frames_from_the_agent() {
async fn observes_valid_inbound_acp_frames() {
let observed = Arc::new(AtomicUsize::new(0));
let incremented = observed.clone();
- let (transport, mut sidecar) = observed_transport(move || {
+ let ((_outbound, mut inbound), mut sidecar) = observed_transport(move || {
incremented.fetch_add(1, Ordering::Relaxed);
})
.await;
- let _ready = transport.recv().await;
+ let _ready = inbound.recv().await;
sidecar
.send(Message::Text("not json at all".into()))
@@ -122,16 +114,16 @@ async fn observes_valid_inbound_acp_frames() {
.send(Message::Text(json.into()))
.await
.expect("the sidecar should be able to send");
- let _frame = transport.recv().await;
+ let _frame = inbound.recv().await;
assert_eq!(observed.load(Ordering::Relaxed), 1);
}
#[tokio::test]
async fn unwraps_frames_to_the_agent_without_a_newline() {
- let (transport, mut sidecar) = transport().await;
+ let ((outbound, _inbound), mut sidecar) = transport().await;
- transport
+ outbound
.send(ToRuntimeMessage::Acp(AcpMessage(frame())))
.await
.expect("sending should succeed");
@@ -155,8 +147,8 @@ async fn unwraps_frames_to_the_agent_without_a_newline() {
#[tokio::test]
async fn survives_a_frame_it_cannot_parse() {
- let (transport, mut sidecar) = transport().await;
- let _ready = transport.recv().await;
+ let ((_outbound, mut inbound), mut sidecar) = transport().await;
+ let _ready = inbound.recv().await;
sidecar
.send(Message::Text("not json at all".into()))
@@ -168,38 +160,31 @@ async fn survives_a_frame_it_cannot_parse() {
.await
.expect("the sidecar should be able to send");
- let message = transport
+ let message = inbound
.recv()
.await
- .expect("receiving should succeed")
.expect("one bad frame should not close the stream");
assert!(matches!(message, ToServerMessage::Acp(_)));
}
#[tokio::test]
async fn ends_when_the_sidecar_goes_away() {
- let (transport, sidecar) = transport().await;
- let _ready = transport.recv().await;
+ let ((_outbound, mut inbound), sidecar) = transport().await;
+ let _ready = inbound.recv().await;
drop(sidecar);
- assert!(
- transport
- .recv()
- .await
- .expect("a closed connection is not an error")
- .is_none()
- );
+ assert!(inbound.recv().await.is_none());
}
#[tokio::test]
async fn sending_fails_after_the_sidecar_goes_away() {
- let (transport, sidecar) = transport().await;
- let _ready = transport.recv().await;
+ let ((outbound, mut inbound), sidecar) = transport().await;
+ let _ready = inbound.recv().await;
drop(sidecar);
- let _closed = transport.recv().await;
+ let _closed = inbound.recv().await;
- let error = transport
+ let error = outbound
.send(ToRuntimeMessage::Acp(AcpMessage(frame())))
.await
.expect_err("a closed socket cannot accept a frame");
diff --git a/crates/agent_harness/src/testing/helpers/containers.rs b/crates/agent_harness/src/testing/helpers/containers.rs
index fe98c9cf8b..96ac4a24dc 100644
--- a/crates/agent_harness/src/testing/helpers/containers.rs
+++ b/crates/agent_harness/src/testing/helpers/containers.rs
@@ -5,7 +5,9 @@ use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use agent_client_protocol::RawJsonRpcMessage;
-use agent_runtime_protocol::domain::ports::{Transport, TransportError};
+use agent_runtime_protocol::domain::ports::{
+ Transport, TransportError, TransportReceiver, TransportSender,
+};
use agent_runtime_protocol::domain::schema::v0::{
AcpMessage, SystemEvent, ToRuntimeMessage, ToServerMessage,
};
@@ -111,7 +113,38 @@ impl ContainerMock {
}
}
+/// A [`ContainerMock`]'s sending half. Shares the mock's recorded state, so a
+/// test still observes sends through the mock it kept.
+pub struct ContainerSender {
+ agent: FakeAgent,
+ outbound: Arc<Mutex<Vec<ToRuntimeMessage>>>,
+ send_budget: Arc<Mutex<Option<usize>>>,
+}
+
+/// A [`ContainerMock`]'s receiving half.
+pub struct ContainerReceiver {
+ inbound: Arc<tokio::sync::Mutex<Inbound>>,
+}
+
impl Transport<ToRuntimeMessage, ToServerMessage> for ContainerMock {
+ type Sender = ContainerSender;
+ type Receiver = ContainerReceiver;
+
+ fn split(self) -> (Self::Sender, Self::Receiver) {
+ (
+ ContainerSender {
+ agent: self.agent,
+ outbound: self.outbound,
+ send_budget: self.send_budget,
+ },
+ ContainerReceiver {
+ inbound: self.inbound,
+ },
+ )
+ }
+}
+
+impl TransportSender<ToRuntimeMessage> for ContainerSender {
async fn send(&self, message: ToRuntimeMessage) -> Result<(), TransportError> {
if let Some(budget) = self
.send_budget
@@ -138,8 +171,10 @@ impl Transport<ToRuntimeMessage, ToServerMessage> for ContainerMock {
Ok(())
}
+}
- async fn recv(&self) -> Result<Option<ToServerMessage>, TransportError> {
+impl TransportReceiver<ToServerMessage> for ContainerReceiver {
+ async fn recv(&mut self) -> Result<Option<ToServerMessage>, TransportError> {
let mut inbound = self.inbound.lock().await;
let Inbound { events, frames } = &mut *inbound;
diff --git a/crates/agent_runtime_protocol/src/domain/channel.rs b/crates/agent_runtime_protocol/src/domain/channel.rs
index d5f5d0b46d..3737b49cd9 100644
--- a/crates/agent_runtime_protocol/src/domain/channel.rs
+++ b/crates/agent_runtime_protocol/src/domain/channel.rs
@@ -1,10 +1,8 @@
//! A typed duplex channel over the logical protocol stream.
-use std::sync::Arc;
-
use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender};
-use super::ports::Transport;
+use super::ports::{Transport, TransportReceiver, TransportSender};
/// One typed endpoint of a duplex channel: sends `Tx` messages, receives
/// `Rx` messages.
@@ -51,18 +49,17 @@ impl<Tx, Rx> Channel<Tx, Rx> {
/// Bridge a physical [`Transport`] into a [`Channel`] endpoint.
///
-/// Spawns two independent tasks - one draining outgoing messages into
-/// `transport.send`, one looping on `transport.recv` - until either side
-/// closes or a transport operation fails. They run as separate tasks rather
-/// than arms of one `select!` specifically so that a `recv` future already
-/// mid-flight is always polled to completion instead of being raced against,
-/// and possibly cancelled by, an outgoing send becoming ready.
+/// Spawns two independent tasks, one per half - which is what taking the
+/// carrier apart is for. They run as separate tasks rather than arms of one
+/// `select!` specifically so that a `recv` already mid-flight is always polled
+/// to completion instead of being raced against, and possibly cancelled by, an
+/// outgoing send becoming ready.
///
/// Not exposed outside this crate: outbound adapters adapt to [`Channel`],
/// they don't hand pumps to callers.
-pub(crate) fn pump<T, Tx, Rx>(transport: Arc<T>) -> Channel<Tx, Rx>
+pub(crate) fn pump<T, Tx, Rx>(transport: T) -> Channel<Tx, Rx>
where
- T: Transport<Tx, Rx> + Send + Sync + 'static,
+ T: Transport<Tx, Rx>,
Tx: Send + 'static,
Rx: Send + 'static,
{
@@ -71,18 +68,18 @@ where
tx: worker_tx,
rx: mut worker_rx,
} = worker;
+ let (sender, mut receiver) = transport.split();
- let send_transport = Arc::clone(&transport);
tokio::spawn(async move {
while let Some(outgoing) = worker_rx.recv().await {
- if send_transport.send(outgoing).await.is_err() {
+ if sender.send(outgoing).await.is_err() {
break;
}
}
});
tokio::spawn(async move {
- while let Ok(Some(incoming)) = transport.recv().await {
+ while let Ok(Some(incoming)) = receiver.recv().await {
if worker_tx.send(incoming).is_err() {
break;
}
@@ -91,3 +88,20 @@ where
caller
}
+
+/// A [`Channel`] is already a carrier taken apart, so it is one directly -
+/// no adapter, and nothing to lock. This is what a caller holding a `Channel`
+/// (an accepted WebSocket routed by hand, a test double) hands to anything
+/// wanting the port.
+impl<Tx, Rx> Transport<Tx, Rx> for Channel<Tx, Rx>
+where
+ Tx: Send + Sync + 'static,
+ Rx: Send + 'static,
+{
+ type Sender = UnboundedSender<Tx>;
+ type Receiver = UnboundedReceiver<Rx>;
+
+ fn split(self) -> (Self::Sender, Self::Receiver) {
+ (self.tx, self.rx)
+ }
+}
diff --git a/crates/agent_runtime_protocol/src/domain/ports.rs b/crates/agent_runtime_protocol/src/domain/ports.rs
index 0243c1db09..380d8c7a14 100644
--- a/crates/agent_runtime_protocol/src/domain/ports.rs
+++ b/crates/agent_runtime_protocol/src/domain/ports.rs
@@ -11,18 +11,64 @@ pub enum TransportError {
Client(String),
}
-/// A physical carrier for one logical connection: sends `Tx` messages,
-/// receives `Rx` messages.
+/// The sending half of a physical carrier.
///
-/// This is the port outbound adapters (a plain WebSocket, an in-memory test
-/// double, or any other physical carrier) implement. [`crate::domain::channel::pump`]
-/// bridges any [`Transport`] into a [`crate::domain::channel::Channel`].
-pub trait Transport<Tx, Rx> {
+/// Shared rather than owned: many callers may send on one carrier, which is
+/// what lets a connection carry several sessions.
+pub trait TransportSender<Tx>: Send + Sync + 'static {
/// Send one logical message to the counterpart.
fn send(&self, message: Tx) -> impl Future<Output = Result<(), TransportError>> + Send;
+}
+/// The receiving half of a physical carrier.
+pub trait TransportReceiver<Rx>: Send + Sync + 'static {
/// Receive the next logical message from the counterpart.
///
/// Returns `Ok(None)` once the counterpart has closed the connection.
- fn recv(&self) -> impl Future<Output = Result<Option<Rx>, TransportError>> + Send;
+ fn recv(&mut self) -> impl Future<Output = Result<Option<Rx>, TransportError>> + Send;
+}
+
+/// A physical carrier for one logical connection: sends `Tx` messages,
+/// receives `Rx` messages.
+///
+/// This is the port outbound adapters (a plain WebSocket, an in-memory test
+/// double, or any other physical carrier) implement. A carrier exists only to
+/// be taken apart: [`crate::domain::channel::pump`] bridges one into a
+/// [`crate::domain::channel::Channel`], and a connection holding one keeps the
+/// sender to share and hands the receiver to whichever task reads it.
+pub trait Transport<Tx, Rx> {
+ /// This carrier's sending half.
+ type Sender: TransportSender<Tx>;
+ /// This carrier's receiving half.
+ type Receiver: TransportReceiver<Rx>;
+
+ /// Take the carrier apart into the half that is shared and the half that
+ /// is owned.
+ fn split(self) -> (Self::Sender, Self::Receiver);
+}
+
+/// An unbounded sender is already a sending half: a closed counterpart is the
+/// only way it fails.
+#[cfg(feature = "transport")]
+impl<Tx: Send + Sync + 'static> TransportSender<Tx> for tokio::sync::mpsc::UnboundedSender<Tx> {
+ async fn send(&self, message: Tx) -> Result<(), TransportError> {
+ tokio::sync::mpsc::UnboundedSender::send(self, message)
+ .map_err(|_| TransportError::Client("the connection is closed".to_owned()))
+ }
+}
+
+/// A bounded receiver is already a receiving half, and an exclusive one.
+#[cfg(feature = "transport")]
+impl<Rx: Send + 'static> TransportReceiver<Rx> for tokio::sync::mpsc::Receiver<Rx> {
+ async fn recv(&mut self) -> Result<Option<Rx>, TransportError> {
+ Ok(tokio::sync::mpsc::Receiver::recv(self).await)
+ }
+}
+
+/// An unbounded receiver is already a receiving half, and an exclusive one.
+#[cfg(feature = "transport")]
+impl<Rx: Send + 'static> TransportReceiver<Rx> for tokio::sync::mpsc::UnboundedReceiver<Rx> {
+ async fn recv(&mut self) -> Result<Option<Rx>, TransportError> {
+ Ok(tokio::sync::mpsc::UnboundedReceiver::recv(self).await)
+ }
}
diff --git a/crates/agent_runtime_protocol/src/outbound/websocket/mod.rs b/crates/agent_runtime_protocol/src/outbound/websocket/mod.rs
index 708b3d5c1d..d38fe33c30 100644
--- a/crates/agent_runtime_protocol/src/outbound/websocket/mod.rs
+++ b/crates/agent_runtime_protocol/src/outbound/websocket/mod.rs
@@ -32,7 +32,7 @@ use tokio_tungstenite::WebSocketStream;
use tokio_tungstenite::tungstenite::Message as TungsteniteMessage;
use crate::domain::channel::{Channel, pump};
-use crate::domain::ports::{Transport, TransportError};
+use crate::domain::ports::{Transport, TransportError, TransportSender};
#[cfg(test)]
mod test;
@@ -138,13 +138,21 @@ async fn run_pump<Rx, Socket, Frame, Error>(
/// [`crate::testing::fake_wire::FakeTransport`].
pub(crate) struct WebSocketWire<Rx> {
outgoing: mpsc::UnboundedSender<String>,
- incoming: AsyncMutex<mpsc::UnboundedReceiver<Rx>>,
+ incoming: mpsc::UnboundedReceiver<Rx>,
}
-impl<Tx, Rx> Transport<Tx, Rx> for WebSocketWire<Rx>
+/// The sending half: serializes and hands the text to the pump's write half.
+///
+/// Not parameterized by the message type: the wire carries JSON text, so any
+/// serializable message can go out on it, and which one does is the caller's
+/// business rather than this half's.
+pub(crate) struct WebSocketSender {
+ outgoing: mpsc::UnboundedSender<String>,
+}
+
+impl<Tx> TransportSender<Tx> for WebSocketSender
where
Tx: Serialize + Send + Sync + 'static,
- Rx: Send + 'static,
{
async fn send(&self, message: Tx) -> Result<(), TransportError> {
let payload = serde_json::to_string(&message)
@@ -153,9 +161,23 @@ where
.send(payload)
.map_err(|_| TransportError::Client("WebSocket connection closed".to_owned()))
}
+}
+
+impl<Tx, Rx> Transport<Tx, Rx> for WebSocketWire<Rx>
+where
+ Tx: Serialize + Send + Sync + 'static,
+ Rx: Send + 'static,
+{
+ type Sender = WebSocketSender;
+ type Receiver = mpsc::UnboundedReceiver<Rx>;
- async fn recv(&self) -> Result<Option<Rx>, TransportError> {
- Ok(self.incoming.lock().await.recv().await)
+ fn split(self) -> (Self::Sender, Self::Receiver) {
+ (
+ WebSocketSender {
+ outgoing: self.outgoing,
+ },
+ self.incoming,
+ )
}
}
@@ -167,10 +189,7 @@ where
Tx: Serialize + Send + Sync + 'static,
Rx: Send + 'static,
{
- pump(Arc::new(WebSocketWire {
- outgoing,
- incoming: AsyncMutex::new(incoming),
- }))
+ pump(WebSocketWire { outgoing, incoming })
}
/// An axum WebSocket acceptor and its stream of accepted runtime connections.
@@ -268,7 +287,7 @@ where
WebSocketWire {
outgoing: outgoing_tx,
- incoming: AsyncMutex::new(incoming_rx),
+ incoming: incoming_rx,
}
}
@@ -279,5 +298,5 @@ where
Rx: DeserializeOwned + Send + Sync + 'static,
S: AsyncRead + AsyncWrite + Unpin + Send + 'static,
{
- pump(Arc::new(client_wire::<Rx, S>(stream)))
+ pump(client_wire::<Rx, S>(stream))
}
diff --git a/crates/agent_runtime_protocol/src/outbound/websocket/test.rs b/crates/agent_runtime_protocol/src/outbound/websocket/test.rs
index f30d570cbe..39ffb3872c 100644
--- a/crates/agent_runtime_protocol/src/outbound/websocket/test.rs
+++ b/crates/agent_runtime_protocol/src/outbound/websocket/test.rs
@@ -25,10 +25,12 @@ async fn sent_payload_is_exactly_the_serialized_envelope_with_no_rpc_wrapper() {
let (outgoing_tx, mut outgoing_rx) = mpsc::unbounded_channel::<String>();
let wire: WebSocketWire<()> = WebSocketWire {
outgoing: outgoing_tx,
- incoming: AsyncMutex::new(mpsc::unbounded_channel().1),
+ incoming: mpsc::unbounded_channel().1,
};
+ let (sender, _receiver) = Transport::<ToRuntimeMessage, ()>::split(wire);
- Transport::<ToRuntimeMessage, ()>::send(&wire, acp_to_runtime())
+ sender
+ .send(acp_to_runtime())
.await
.expect("send should succeed");
diff --git a/crates/agent_runtime_protocol/src/testing/fake_wire.rs b/crates/agent_runtime_protocol/src/testing/fake_wire.rs
index 33bab4cc3f..6aa1cf0427 100644
--- a/crates/agent_runtime_protocol/src/testing/fake_wire.rs
+++ b/crates/agent_runtime_protocol/src/testing/fake_wire.rs
@@ -5,7 +5,7 @@ use std::sync::{Arc, Mutex};
use futures::StreamExt;
use futures::channel::mpsc;
-use crate::domain::ports::{Transport, TransportError};
+use crate::domain::ports::{Transport, TransportError, TransportReceiver, TransportSender};
#[cfg(test)]
mod test;
@@ -18,10 +18,22 @@ mod test;
pub struct FakeTransport<Tx, Rx> {
fail_next_recv: Arc<Mutex<Option<String>>>,
fail_next_send: Arc<Mutex<Option<String>>>,
- incoming: Arc<tokio::sync::Mutex<mpsc::UnboundedReceiver<Rx>>>,
+ incoming: mpsc::UnboundedReceiver<Rx>,
sent: mpsc::UnboundedSender<Tx>,
}
+/// A [`FakeTransport`]'s sending half.
+pub struct FakeSender<Tx> {
+ fail_next_send: Arc<Mutex<Option<String>>>,
+ sent: mpsc::UnboundedSender<Tx>,
+}
+
+/// A [`FakeTransport`]'s receiving half.
+pub struct FakeReceiver<Rx> {
+ fail_next_recv: Arc<Mutex<Option<String>>>,
+ incoming: mpsc::UnboundedReceiver<Rx>,
+}
+
/// Observes and controls a [`FakeTransport`] from outside the transport port.
pub struct FakeTransportProbe<Tx, Rx> {
fail_next_recv: Arc<Mutex<Option<String>>>,
@@ -42,7 +54,7 @@ impl<Tx, Rx> FakeTransport<Tx, Rx> {
Self {
fail_next_recv: Arc::clone(&fail_next_recv),
fail_next_send: Arc::clone(&fail_next_send),
- incoming: Arc::new(tokio::sync::Mutex::new(incoming_rx)),
+ incoming: incoming_rx,
sent: sent_tx,
},
FakeTransportProbe {
@@ -57,9 +69,27 @@ impl<Tx, Rx> FakeTransport<Tx, Rx> {
impl<Tx, Rx> Transport<Tx, Rx> for FakeTransport<Tx, Rx>
where
- Tx: Send + 'static,
+ Tx: Send + Sync + 'static,
Rx: Send + 'static,
{
+ type Sender = FakeSender<Tx>;
+ type Receiver = FakeReceiver<Rx>;
+
+ fn split(self) -> (Self::Sender, Self::Receiver) {
+ (
+ FakeSender {
+ fail_next_send: self.fail_next_send,
+ sent: self.sent,
+ },
+ FakeReceiver {
+ fail_next_recv: self.fail_next_recv,
+ incoming: self.incoming,
+ },
+ )
+ }
+}
+
+impl<Tx: Send + Sync + 'static> TransportSender<Tx> for FakeSender<Tx> {
async fn send(&self, message: Tx) -> Result<(), TransportError> {
let _ = self.sent.unbounded_send(message);
if let Some(reason) = self
@@ -72,8 +102,10 @@ where
}
Ok(())
}
+}
- async fn recv(&self) -> Result<Option<Rx>, TransportError> {
+impl<Rx: Send + 'static> TransportReceiver<Rx> for FakeReceiver<Rx> {
+ async fn recv(&mut self) -> Result<Option<Rx>, TransportError> {
if let Some(reason) = self
.fail_next_recv
.lock()
@@ -82,8 +114,7 @@ where
{
return Err(TransportError::Client(reason));
}
- let mut incoming = self.incoming.lock().await;
- Ok(incoming.next().await)
+ Ok(self.incoming.next().await)
}
}
diff --git a/crates/agent_runtime_protocol/src/testing/fake_wire/test.rs b/crates/agent_runtime_protocol/src/testing/fake_wire/test.rs
index 36f57278a0..a26fe25a3c 100644
--- a/crates/agent_runtime_protocol/src/testing/fake_wire/test.rs
+++ b/crates/agent_runtime_protocol/src/testing/fake_wire/test.rs
@@ -5,7 +5,8 @@ use super::*;
#[tokio::test]
async fn send_is_recorded_and_succeeds_by_default() {
let (transport, mut probe): (FakeTransport<String, String>, _) = FakeTransport::new();
- transport.send("system_event".to_owned()).await.unwrap();
+ let (sender, _receiver) = transport.split();
+ sender.send("system_event".to_owned()).await.unwrap();
let message = timeout(Duration::from_secs(1), probe.next_send())
.await
@@ -17,9 +18,10 @@ async fn send_is_recorded_and_succeeds_by_default() {
async fn fail_next_send_fails_exactly_one_send() {
let (transport, mut probe): (FakeTransport<String, String>, _) = FakeTransport::new();
probe.fail_next_send("socket closed");
+ let (sender, _receiver) = transport.split();
- assert!(transport.send("system_event".to_owned()).await.is_err());
- assert!(transport.send("system_event".to_owned()).await.is_ok());
+ assert!(sender.send("system_event".to_owned()).await.is_err());
+ assert!(sender.send("system_event".to_owned()).await.is_ok());
}
#[tokio::test]
@@ -27,10 +29,11 @@ async fn fail_next_recv_fails_exactly_one_recv() {
let (transport, mut probe): (FakeTransport<String, String>, _) = FakeTransport::new();
probe.fail_next_recv("no such connection");
probe.push_incoming("system_event".to_owned());
+ let (_sender, mut receiver) = transport.split();
- assert!(transport.recv().await.is_err());
+ assert!(receiver.recv().await.is_err());
assert_eq!(
- transport.recv().await.unwrap(),
+ receiver.recv().await.unwrap(),
Some("system_event".to_owned())
);
}
@@ -40,8 +43,9 @@ async fn push_incoming_is_delivered_by_recv() {
let (transport, mut probe): (FakeTransport<String, String>, _) = FakeTransport::new();
probe.push_incoming("system_event".to_owned());
+ let (_sender, mut receiver) = transport.split();
- let delivered = timeout(Duration::from_secs(1), transport.recv())
+ let delivered = timeout(Duration::from_secs(1), receiver.recv())
.await
.expect("recv should return promptly")
.expect("recv should not fail");
diff --git a/crates/agent_runtime_protocol/src/testing/wire_conformance.rs b/crates/agent_runtime_protocol/src/testing/wire_conformance.rs
index 390712a5dc..79293f3887 100644
--- a/crates/agent_runtime_protocol/src/testing/wire_conformance.rs
+++ b/crates/agent_runtime_protocol/src/testing/wire_conformance.rs
@@ -27,9 +27,9 @@ use crate::testing::fake_wire::FakeTransport;
/// on this protocol is a tagged enum or struct, so it is always an object in
/// practice; there is no other reason to prefer an object here now that the
/// wire carries the bare envelope with no outer framing.
-async fn asserts_runtime_to_server_delivery<T, F, Fut>(transport: Arc<T>, receive_from_transport: F)
+async fn asserts_runtime_to_server_delivery<T, F, Fut>(transport: T, receive_from_transport: F)
where
- T: Transport<Value, Value> + Send + Sync + 'static,
+ T: Transport<Value, Value>,
F: FnOnce() -> Fut,
Fut: Future<Output = Value>,
{
@@ -46,11 +46,7 @@ where
#[tokio::test]
async fn fake_transport_delivers_runtime_to_server_messages() {
let (transport, mut probe) = FakeTransport::new();
- asserts_runtime_to_server_delivery(
- Arc::new(transport),
- || async move { probe.next_send().await },
- )
- .await;
+ asserts_runtime_to_server_delivery(transport, || async move { probe.next_send().await }).await;
}
#[tokio::test(flavor = "multi_thread")]
@@ -70,7 +66,7 @@ async fn websocket_transport_delivers_runtime_to_server_messages() {
.expect("runtime should connect");
let wire = client_wire::<Value, _>(stream);
- asserts_runtime_to_server_delivery(Arc::new(wire), || async {
+ asserts_runtime_to_server_delivery(wire, || async {
let mut channel = timeout(Duration::from_secs(1), transport.accept())
.await
.expect("server accept should not hang")
diff --git a/crates/agent_session/Cargo.toml b/crates/agent_session/Cargo.toml
index 564ae81b72..7e77c9c717 100644
--- a/crates/agent_session/Cargo.toml
+++ b/crates/agent_session/Cargo.toml
@@ -29,6 +29,7 @@ clap = { workspace = true }
macro_authorization = { path = "../macro_authorization", default-features = false, features = [
"axum",
] }
+macro_service_urls = { path = "../macro_service_urls" }
macro_user_id = { path = "../macro_user_id", features = ["sqlx"] }
utoipa = { workspace = true }
rootcause = { workspace = true }
@@ -45,9 +46,11 @@ workspace-hack = { version = "0.1", path = "../workspace-hack" }
[dev-dependencies]
agent-client-protocol = { workspace = true }
+bot_id = { path = "../bot_id", features = ["test-utils"] }
non_empty = { path = "../non_empty" }
agent_fold = { path = "../agent_fold", features = ["test-utils"] }
axum = { workspace = true, features = ["ws"] }
macro_db_migrator = { path = "../macro_db_migrator" }
tokio = { workspace = true, features = ["fs", "io-std", "io-util", "macros", "net", "rt-multi-thread", "time"] }
tokio-tungstenite = { workspace = true }
+tower = { workspace = true, features = ["util"] }
diff --git a/crates/agent_session/src/bin/seed_jsonl.rs b/crates/agent_session/src/bin/seed_jsonl.rs
index ce07c76900..9ce6d0d664 100644
--- a/crates/agent_session/src/bin/seed_jsonl.rs
+++ b/crates/agent_session/src/bin/seed_jsonl.rs
@@ -81,6 +81,10 @@ struct Args {
/// Repository the session is nominally working in.
#[arg(long, default_value = "https://github.com/macro/cloud-storage")]
repo_url: String,
+
+ /// Directory the session's harness nominally ran in.
+ #[arg(long, default_value = "/workspace")]
+ workspace: String,
}
/// Why seeding failed.
@@ -242,7 +246,8 @@ async fn seed(args: &Args) -> Result<(), SeedError> {
originating_message_id: None,
model: args.model.clone(),
harness: args.harness.clone(),
- repo_url: args.repo_url.clone(),
+ repo_url: Some(args.repo_url.clone()),
+ workspace: args.workspace.clone(),
},
)
.await
diff --git a/crates/agent_session/src/domain/connection/mod.rs b/crates/agent_session/src/domain/connection/mod.rs
new file mode 100644
index 0000000000..2d8e578564
--- /dev/null
+++ b/crates/agent_session/src/domain/connection/mod.rs
@@ -0,0 +1,455 @@
+//! One runtime connection, shared by every session it carries.
+//!
+//! ACP initializes per connection rather than per session, and a `sessionId`
+//! on every session-scoped method is what lets one connection carry many. So
+//! the transport belongs here rather than to any one session: this owns the
+//! socket, decides which session each inbound frame belongs to, and holds the
+//! handshake result for sessions that bind long after it completed.
+//!
+//! Sessions still see a [`Transport`]. [`RuntimeConnection::bind`] hands each
+//! one a [`SessionChannel`] - sends go out on the shared socket tagged with
+//! their owner, receives read only that session's frames - so the actor and
+//! machine above are unchanged by sharing.
+//!
+//! Routing is the part that has to be exact. Every inbound frame is logged to
+//! a session's transcript, which is that session's durable history, so a
+//! misrouted frame is not a delivery bug but a corrupted record. Three things
+//! decide an owner: a response matches the session whose request it answers, a
+//! session-scoped request or notification matches the session holding that ACP
+//! session id, and system events belong to the connection itself.
+
+use std::collections::HashMap;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{Arc, OnceLock};
+
+use agent_client_protocol::RawJsonRpcMessage;
+use agent_client_protocol::schema::v1::{RequestId, Response, SessionId};
+use agent_runtime_protocol::domain::ports::{
+ Transport, TransportError, TransportReceiver, TransportSender,
+};
+use agent_runtime_protocol::domain::schema::v0::{
+ AcpMessage, SystemEvent, ToRuntimeMessage, ToServerMessage,
+};
+use dashmap::DashMap;
+use tokio::sync::{Mutex, mpsc, watch};
+
+use crate::domain::model::AgentSessionId;
+use crate::domain::session::HandshakeStatus;
+
+#[cfg(test)]
+mod test;
+
+/// Inbound frames buffered per session before the router applies backpressure.
+///
+/// Bounded rather than lossy on purpose: a dropped frame is a hole in a
+/// session's transcript, so a session that cannot keep up slows the router
+/// instead of losing history.
+const SESSION_INBOUND_BUFFER: usize = 1028;
+
+/// What the router decided to do with one inbound frame.
+///
+/// Named so the routing rules can be tested without a socket, a session, or
+/// an actor.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub(crate) enum Routed {
+ /// Deliver to exactly one session.
+ Session(AgentSessionId),
+ /// The whole connection's business: a system event, or its end.
+ Connection,
+ /// Nothing owns it. Kept as its own answer rather than folded into
+ /// `Connection` so it can be counted and logged as the anomaly it is.
+ Orphan,
+}
+
+/// Which session each in-flight request and live ACP session belongs to.
+///
+/// Separate from the connection so the rules can be exercised directly.
+#[derive(Debug, Default)]
+pub(crate) struct Routes {
+ requests: HashMap<RequestId, AgentSessionId>,
+ acp_sessions: HashMap<SessionId, AgentSessionId>,
+}
+
+impl Routes {
+ /// Remember that `session` is awaiting an answer to `request`.
+ pub(crate) fn expect_response(&mut self, request: RequestId, session: AgentSessionId) {
+ self.requests.insert(request, session);
+ }
+
+ /// Remember that `acp_session` is `session`'s session on the agent.
+ pub(crate) fn bind_acp_session(&mut self, acp_session: SessionId, session: AgentSessionId) {
+ self.acp_sessions.insert(acp_session, session);
+ }
+
+ /// Forget everything about a session that is over.
+ pub(crate) fn forget(&mut self, session: AgentSessionId) {
+ self.requests.retain(|_, owner| *owner != session);
+ self.acp_sessions.retain(|_, owner| *owner != session);
+ }
+
+ /// Who owns this frame.
+ ///
+ /// A response is claimed by whoever is waiting for it, and the
+ /// expectation is consumed - a second answer to one request has no owner.
+ /// Anything carrying a `sessionId` belongs to that ACP session's owner.
+ pub(crate) fn route(&mut self, message: &ToServerMessage) -> Routed {
+ let ToServerMessage::Acp(AcpMessage(frame)) = message else {
+ return Routed::Connection;
+ };
+
+ if let Some(id) = frame.response_id() {
+ return match self.requests.remove(id) {
+ Some(session) => Routed::Session(session),
+ None => Routed::Orphan,
+ };
+ }
+
+ match acp_session_of(frame).and_then(|acp| self.acp_sessions.get(&acp)) {
+ Some(session) => Routed::Session(*session),
+ None => Routed::Orphan,
+ }
+ }
+}
+
+/// The ACP session a frame names, when it names one.
+///
+/// Read out of the raw params rather than by deserializing each request type:
+/// every session-scoped method carries `sessionId` at the top level, and the
+/// router only needs that one field.
+fn acp_session_of(frame: &RawJsonRpcMessage) -> Option<SessionId> {
+ let params = match frame {
+ RawJsonRpcMessage::Request(request) => request.params.clone()?,
+ RawJsonRpcMessage::Notification(notification) => notification.params.clone()?,
+ RawJsonRpcMessage::Response(_) => return None,
+ };
+ let session_id = params.into_value().get("sessionId")?.as_str()?.to_owned();
+ Some(SessionId::from(session_id))
+}
+
+/// A transport for one session, plus the handshake gate it shares with every
+/// other session on the same connection.
+///
+/// Attaching needs both: the transport to carry the session's traffic, and the
+/// gate so exactly one session per connection runs `initialize` and the rest
+/// are told its result.
+pub struct RuntimeAttachment<Connector> {
+ pub(crate) connector: Connector,
+ pub(crate) handshake: watch::Sender<HandshakeStatus>,
+}
+
+impl<Connector> RuntimeAttachment<Connector> {
+ /// A transport carrying exactly one session, so its handshake is its own.
+ ///
+ /// What a managed sandbox gets: one container, one session, nothing to
+ /// share the connection with.
+ pub fn solo(connector: Connector) -> Self {
+ let (handshake, _) = watch::channel(HandshakeStatus::Pending);
+ Self {
+ connector,
+ handshake,
+ }
+ }
+}
+
+/// Every session this connection carries, and where to reach it.
+type Bound = DashMap<AgentSessionId, mpsc::Sender<ToServerMessage>>;
+
+/// One runtime connection and the sessions riding on it.
+///
+/// Holds the carrier's sending half only: the receiving half belongs to the
+/// router task, which is the sole reader of a connection by definition.
+pub struct RuntimeConnection<Sender> {
+ outbound: Sender,
+ handshake: watch::Sender<HandshakeStatus>,
+ /// Whether the runtime has reported its agent ready.
+ ///
+ /// Remembered rather than only relayed, because it arrives once and the
+ /// sessions that need it mostly do not exist yet: a runtime dials, says
+ /// ready, and only then does someone mention the bot. A session binding
+ /// afterwards has to be able to learn it happened.
+ runtime_ready: AtomicBool,
+ bound: Bound,
+ routes: Mutex<Routes>,
+ router: OnceLock<tokio::task::AbortHandle>,
+}
+
+impl<Sender> RuntimeConnection<Sender>
+where
+ Sender: TransportSender<ToRuntimeMessage>,
+{
+ /// Take a dialed-in runtime's carrier apart and start serving it.
+ ///
+ /// The receiving half goes straight into the router task and is never
+ /// stored, which is what makes "one reader" a fact about the code rather
+ /// than a convention.
+ pub fn connect<Carrier>(carrier: Carrier) -> Arc<Self>
+ where
+ Carrier: Transport<ToRuntimeMessage, ToServerMessage, Sender = Sender>,
+ {
+ let (outbound, inbound) = carrier.split();
+ let (handshake, _) = watch::channel(HandshakeStatus::Pending);
+ let connection = Arc::new(Self {
+ outbound,
+ handshake,
+ runtime_ready: AtomicBool::new(false),
+ bound: DashMap::new(),
+ routes: Mutex::new(Routes::default()),
+ router: OnceLock::new(),
+ });
+ let router = tokio::spawn(Arc::clone(&connection).route_inbound(inbound));
+ let _ = connection.router.set(router.abort_handle());
+ connection
+ }
+
+ /// Stop serving this connection: it has been displaced by a newer dial.
+ pub fn evict(&self) {
+ self.bound.clear();
+ if let Some(router) = self.router.get() {
+ router.abort();
+ }
+ }
+
+ /// The gate every session on this connection shares.
+ pub fn handshake(&self) -> watch::Sender<HandshakeStatus> {
+ self.handshake.clone()
+ }
+
+ /// Give `session` its own view of this connection.
+ ///
+ /// Rebinding replaces: the newest view receives this session's frames, and
+ /// whatever the displaced one was still waiting for is forgotten. That is
+ /// what makes a session whose actor died recoverable - it binds again and
+ /// the stale queue goes with it - and it is why a caller that already has a
+ /// live actor must not call this.
+ pub async fn bind(
+ self: &Arc<Self>,
+ session: AgentSessionId,
+ ) -> RuntimeAttachment<SessionChannel<Sender>> {
+ let (inbound, frames) = mpsc::channel(SESSION_INBOUND_BUFFER);
+ if self.bound.insert(session, inbound).is_some() {
+ self.routes.lock().await.forget(session);
+ }
+ // A runtime that reported ready before anyone was here to hear it
+ // said so exactly once. Whoever binds first inherits the job.
+ if self.claim_handshake() {
+ let _ = inbound_of(&self.bound, session)
+ .send(ToServerMessage::Event {
+ event: SystemEvent::AcpReady,
+ })
+ .await;
+ }
+
+ RuntimeAttachment {
+ connector: SessionChannel {
+ connection: Arc::clone(self),
+ session,
+ frames,
+ },
+ handshake: self.handshake.clone(),
+ }
+ }
+
+ /// Send on behalf of `session`, recording what it expects back.
+ async fn send_for(
+ &self,
+ session: AgentSessionId,
+ message: ToRuntimeMessage,
+ ) -> std::result::Result<(), TransportError> {
+ // Recorded before the send: the answer can arrive the instant the
+ // frame lands, and a response nobody claims is an orphan.
+ if let ToRuntimeMessage::Acp(AcpMessage(frame)) = &message {
+ let mut routes = self.routes.lock().await;
+ if let RawJsonRpcMessage::Request(request) = frame {
+ routes.expect_response(request.id.clone(), session);
+ }
+ // A request naming an ACP session is also where that session's
+ // ownership is established. It has to be, for the ones that
+ // matter: `session/resume` and `session/load` name the session
+ // going out and their answers do not echo it back, so the
+ // outbound frame is the only place it is ever stated.
+ if let Some(acp) = acp_session_of(frame) {
+ routes.bind_acp_session(acp, session);
+ }
+ }
+ self.outbound.send(message).await
+ }
+
+ /// Pump the shared transport, handing each frame to its session.
+ ///
+ /// Ends when the transport does, closing every session's queue - which
+ /// each session's actor reads as its connection ending.
+ async fn route_inbound(self: Arc<Self>, mut inbound: impl TransportReceiver<ToServerMessage>) {
+ loop {
+ let message = match inbound.recv().await {
+ Ok(Some(message)) => message,
+ Ok(None) => break,
+ Err(error) => {
+ tracing::error!(error = ?error, "runtime connection transport failed");
+ break;
+ }
+ };
+
+ // A session's opening response is where its ACP session id first
+ // appears, and every later frame for it routes on that id.
+ let routed = self.routes.lock().await.route(&message);
+ if let Routed::Session(session) = routed
+ && let ToServerMessage::Acp(AcpMessage(frame)) = &message
+ && let Some(acp) = opened_acp_session(frame)
+ {
+ self.routes.lock().await.bind_acp_session(acp, session);
+ }
+
+ match routed {
+ Routed::Session(session) => self.deliver(session, message).await,
+ Routed::Connection => self.on_connection_message(message).await,
+ Routed::Orphan => {
+ tracing::warn!(
+ frame = ?message,
+ "dropping a runtime frame no session on this connection owns"
+ );
+ }
+ }
+ }
+ self.bound.clear();
+ }
+
+ async fn deliver(&self, session: AgentSessionId, message: ToServerMessage) {
+ let Some(inbound) = self.bound.get(&session).map(|entry| entry.clone()) else {
+ tracing::warn!(%session, "a frame arrived for a session that has gone");
+ return;
+ };
+ if inbound.send(message).await.is_err() {
+ self.bound.remove(&session);
+ }
+ }
+
+ /// A connection-level message: readiness goes to one session, everything
+ /// else to all of them.
+ ///
+ /// Readiness is a job, not news. Handing it to every session would have
+ /// each of them send its own `initialize` on a connection that takes
+ /// exactly one, so it goes to whichever session claims the handshake -
+ /// and if none is bound yet, it waits in `runtime_ready` for one to be.
+ async fn on_connection_message(&self, message: ToServerMessage) {
+ if !matches!(
+ message,
+ ToServerMessage::Event {
+ event: SystemEvent::AcpReady
+ }
+ ) {
+ self.broadcast(message).await;
+ return;
+ }
+
+ self.runtime_ready.store(true, Ordering::Release);
+ let waiting = self
+ .bound
+ .iter()
+ .next()
+ .map(|entry| (*entry.key(), entry.value().clone()));
+ match waiting {
+ Some((session, inbound)) if self.claim_handshake() => {
+ if inbound.send(message).await.is_err() {
+ self.bound.remove(&session);
+ }
+ }
+ _ => tracing::debug!("the runtime is ready; the next session to bind will initialize"),
+ }
+ }
+
+ /// Take the handshake if it is going spare, once the runtime can serve it.
+ ///
+ /// The move from `Pending` to `InFlight` is the claim itself, so two
+ /// sessions binding at once cannot both decide they are the one.
+ fn claim_handshake(&self) -> bool {
+ if !self.runtime_ready.load(Ordering::Acquire) {
+ return false;
+ }
+ let mut claimed = false;
+ self.handshake.send_if_modified(|status| {
+ if matches!(status, HandshakeStatus::Pending) {
+ *status = HandshakeStatus::InFlight;
+ claimed = true;
+ }
+ claimed
+ });
+ claimed
+ }
+
+ /// Hand a connection-level message to every session on it.
+ async fn broadcast(&self, message: ToServerMessage) {
+ let targets: Vec<_> = self
+ .bound
+ .iter()
+ .map(|entry| (*entry.key(), entry.value().clone()))
+ .collect();
+ for (session, inbound) in targets {
+ if inbound.send(message.clone()).await.is_err() {
+ self.bound.remove(&session);
+ }
+ }
+ }
+}
+
+/// A bound session's queue. Only called just after inserting it.
+fn inbound_of(bound: &Bound, session: AgentSessionId) -> mpsc::Sender<ToServerMessage> {
+ bound
+ .get(&session)
+ .map(|entry| entry.clone())
+ .expect("the session was just bound")
+}
+
+/// The ACP session id an opening response announces, when it is one.
+fn opened_acp_session(frame: &RawJsonRpcMessage) -> Option<SessionId> {
+ let RawJsonRpcMessage::Response(Response::Result { result, .. }) = frame else {
+ return None;
+ };
+ let session_id = result.get("sessionId")?.as_str()?.to_owned();
+ Some(SessionId::from(session_id))
+}
+
+/// One session's view of a shared connection.
+///
+/// A [`Transport`] like any other, so the actor above cannot tell whether it
+/// has a socket to itself.
+pub struct SessionChannel<Sender> {
+ connection: Arc<RuntimeConnection<Sender>>,
+ session: AgentSessionId,
+ frames: mpsc::Receiver<ToServerMessage>,
+}
+
+/// One session's sending half: the shared carrier, plus whose traffic this is.
+///
+/// Every send goes out tagged with its session, which is how a response coming
+/// back is attributed to the session that asked for it.
+pub struct SessionSender<Sender> {
+ connection: Arc<RuntimeConnection<Sender>>,
+ session: AgentSessionId,
+}
+
+impl<Sender> Transport<ToRuntimeMessage, ToServerMessage> for SessionChannel<Sender>
+where
+ Sender: TransportSender<ToRuntimeMessage>,
+{
+ type Sender = SessionSender<Sender>;
+ type Receiver = mpsc::Receiver<ToServerMessage>;
+
+ fn split(self) -> (Self::Sender, Self::Receiver) {
+ (
+ SessionSender {
+ connection: self.connection,
+ session: self.session,
+ },
+ self.frames,
+ )
+ }
+}
+
+impl<Sender> TransportSender<ToRuntimeMessage> for SessionSender<Sender>
+where
+ Sender: TransportSender<ToRuntimeMessage>,
+{
+ async fn send(&self, message: ToRuntimeMessage) -> std::result::Result<(), TransportError> {
+ self.connection.send_for(self.session, message).await
+ }
+}
diff --git a/crates/agent_session/src/domain/connection/test.rs b/crates/agent_session/src/domain/connection/test.rs
new file mode 100644
index 0000000000..47fb9a645a
--- /dev/null
+++ b/crates/agent_session/src/domain/connection/test.rs
@@ -0,0 +1,318 @@
+//! The routing rules, exercised without a socket or an actor.
+//!
+//! Attribution is the whole point: every frame is logged to a session's
+//! transcript, so "which session owns this" is a correctness question about
+//! that session's durable history.
+
+use super::*;
+use agent_runtime_protocol::domain::schema::v0::SystemEvent;
+
+const OTHER: AgentSessionId = AgentSessionId::TEST_B;
+
+fn request(id: &str, method: &str, params: serde_json::Value) -> ToServerMessage {
+ ToServerMessage::Acp(AcpMessage(
+ RawJsonRpcMessage::request(method.to_owned(), params, RequestId::Str(id.to_owned()))
+ .expect("a serializable request"),
+ ))
+}
+
+fn notification(method: &str, params: serde_json::Value) -> ToServerMessage {
+ ToServerMessage::Acp(AcpMessage(
+ RawJsonRpcMessage::notification(method.to_owned(), params)
+ .expect("a serializable notification"),
+ ))
+}
+
+fn response(id: &str, result: serde_json::Value) -> ToServerMessage {
+ ToServerMessage::Acp(AcpMessage(RawJsonRpcMessage::response(
+ RequestId::Str(id.to_owned()),
+ Ok(result),
+ )))
+}
+
+fn ready() -> ToServerMessage {
+ ToServerMessage::Event {
+ event: SystemEvent::AcpReady,
+ }
+}
+
+#[test]
+fn a_response_goes_to_whoever_asked() {
+ let mut routes = Routes::default();
+ routes.expect_response(RequestId::Str("mine".to_owned()), AgentSessionId::TEST_A);
+ routes.expect_response(RequestId::Str("theirs".to_owned()), OTHER);
+
+ assert_eq!(
+ routes.route(&response("theirs", serde_json::json!({}))),
+ Routed::Session(OTHER)
+ );
+ assert_eq!(
+ routes.route(&response("mine", serde_json::json!({}))),
+ Routed::Session(AgentSessionId::TEST_A)
+ );
+}
+
+#[test]
+fn a_second_answer_to_one_request_belongs_to_nobody() {
+ let mut routes = Routes::default();
+ routes.expect_response(RequestId::Str("once".to_owned()), AgentSessionId::TEST_A);
+
+ routes.route(&response("once", serde_json::json!({})));
+
+ // Delivering a duplicate would write the same entry into the transcript
+ // twice, which is worse than dropping it loudly.
+ assert_eq!(
+ routes.route(&response("once", serde_json::json!({}))),
+ Routed::Orphan
+ );
+}
+
+#[test]
+fn session_scoped_traffic_routes_on_its_acp_session() {
+ let mut routes = Routes::default();
+ routes.bind_acp_session("acp-mine".into(), AgentSessionId::TEST_A);
+ routes.bind_acp_session("acp-theirs".into(), OTHER);
+
+ let update = notification(
+ "session/update",
+ serde_json::json!({ "sessionId": "acp-theirs", "update": {} }),
+ );
+ let permission = request(
+ "agent:1",
+ "session/request_permission",
+ serde_json::json!({ "sessionId": "acp-mine", "options": [] }),
+ );
+
+ assert_eq!(routes.route(&update), Routed::Session(OTHER));
+ assert_eq!(
+ routes.route(&permission),
+ Routed::Session(AgentSessionId::TEST_A)
+ );
+}
+
+#[test]
+fn traffic_for_an_unknown_session_is_an_orphan() {
+ let mut routes = Routes::default();
+ routes.bind_acp_session("acp-mine".into(), AgentSessionId::TEST_A);
+
+ let stray = notification(
+ "session/update",
+ serde_json::json!({ "sessionId": "acp-nobody", "update": {} }),
+ );
+
+ assert_eq!(routes.route(&stray), Routed::Orphan);
+}
+
+#[test]
+fn a_frame_naming_no_session_is_an_orphan() {
+ let mut routes = Routes::default();
+
+ let anonymous = notification("something/agentwide", serde_json::json!({}));
+
+ assert_eq!(routes.route(&anonymous), Routed::Orphan);
+}
+
+#[test]
+fn system_events_belong_to_the_connection() {
+ let mut routes = Routes::default();
+
+ // Every session needs to see the runtime come up; only one acts on it.
+ assert_eq!(routes.route(&ready()), Routed::Connection);
+}
+
+#[test]
+fn a_finished_session_stops_owning_anything() {
+ let mut routes = Routes::default();
+ routes.expect_response(RequestId::Str("pending".to_owned()), AgentSessionId::TEST_A);
+ routes.bind_acp_session("acp-mine".into(), AgentSessionId::TEST_A);
+ routes.expect_response(RequestId::Str("survives".to_owned()), OTHER);
+
+ routes.forget(AgentSessionId::TEST_A);
+
+ assert_eq!(
+ routes.route(&response("pending", serde_json::json!({}))),
+ Routed::Orphan
+ );
+ assert_eq!(
+ routes.route(&notification(
+ "session/update",
+ serde_json::json!({ "sessionId": "acp-mine" })
+ )),
+ Routed::Orphan
+ );
+ assert_eq!(
+ routes.route(&response("survives", serde_json::json!({}))),
+ Routed::Session(OTHER),
+ "another session's expectations are its own"
+ );
+}
+
+#[test]
+fn an_opening_response_announces_the_acp_session_it_created() {
+ let ToServerMessage::Acp(AcpMessage(frame)) =
+ response("open", serde_json::json!({ "sessionId": "acp-new" }))
+ else {
+ unreachable!("built as an acp frame")
+ };
+
+ assert_eq!(
+ opened_acp_session(&frame).map(|id| id.to_string()),
+ Some("acp-new".to_owned())
+ );
+}
+
+/// A double for the shared socket that records nothing and never answers.
+#[derive(Default)]
+struct SilentSocket;
+
+/// Its sending half: accepts everything, remembers nothing.
+#[derive(Clone, Default)]
+struct SilentSender;
+
+/// Its receiving half: a socket that is open and simply never speaks.
+struct SilentReceiver;
+
+impl Transport<ToRuntimeMessage, ToServerMessage> for SilentSocket {
+ type Sender = SilentSender;
+ type Receiver = SilentReceiver;
+
+ fn split(self) -> (Self::Sender, Self::Receiver) {
+ (SilentSender, SilentReceiver)
+ }
+}
+
+impl TransportSender<ToRuntimeMessage> for SilentSender {
+ async fn send(&self, _message: ToRuntimeMessage) -> Result<(), TransportError> {
+ Ok(())
+ }
+}
+
+impl TransportReceiver<ToServerMessage> for SilentReceiver {
+ async fn recv(&mut self) -> Result<Option<ToServerMessage>, TransportError> {
+ std::future::pending().await
+ }
+}
+
+#[tokio::test]
+async fn a_session_binding_after_the_runtime_reported_ready_is_told_so() {
+ let connection = RuntimeConnection::connect(SilentSocket);
+ // The runtime dials and reports ready with nothing bound yet - the
+ // ordinary case, since a session only binds once somebody mentions the
+ // bot, which is usually later.
+ connection
+ .on_connection_message(ToServerMessage::Event {
+ event: SystemEvent::AcpReady,
+ })
+ .await;
+
+ let attachment = connection.bind(AgentSessionId::TEST_A).await;
+
+ // Handed the readiness it missed, so it can run the handshake rather than
+ // booting forever with its prompt queued behind a signal already spent.
+ let (_outbound, mut inbound) = attachment.connector.split();
+ let first = inbound.recv().await.expect("a frame");
+ assert!(matches!(
+ first,
+ ToServerMessage::Event {
+ event: SystemEvent::AcpReady
+ }
+ ));
+}
+
+#[tokio::test]
+async fn evicting_ends_the_sessions_a_displaced_connection_was_carrying() {
+ let connection = RuntimeConnection::connect(SilentSocket);
+ let attachment = connection.bind(AgentSessionId::TEST_A).await;
+ let (_outbound, mut inbound) = attachment.connector.split();
+
+ // `SilentSocket` never closes, which is the case eviction exists for: a
+ // displaced runtime whose socket is still perfectly healthy. Nothing else
+ // would ever end this connection.
+ connection.evict();
+
+ assert!(
+ inbound.recv().await.is_none(),
+ "the displaced session's queue should be closed at once"
+ );
+}
+
+#[tokio::test]
+async fn only_one_session_is_asked_to_run_the_handshake() {
+ let connection = RuntimeConnection::connect(SilentSocket);
+ connection
+ .on_connection_message(ToServerMessage::Event {
+ event: SystemEvent::AcpReady,
+ })
+ .await;
+
+ let first = connection.bind(AgentSessionId::TEST_A).await;
+ let second = connection.bind(OTHER).await;
+
+ let (_first_outbound, mut first_inbound) = first.connector.split();
+ let (_second_outbound, mut second_inbound) = second.connector.split();
+ assert!(first_inbound.recv().await.is_some());
+ // A connection takes exactly one `initialize`, so the second session waits
+ // for the first one's answer instead of sending its own.
+ assert!(
+ tokio::time::timeout(std::time::Duration::from_millis(50), second_inbound.recv())
+ .await
+ .is_err()
+ );
+}
+
+#[tokio::test]
+async fn a_session_bound_before_ready_still_runs_the_handshake() {
+ let connection = RuntimeConnection::connect(SilentSocket);
+
+ let attachment = connection.bind(AgentSessionId::TEST_A).await;
+ connection
+ .on_connection_message(ToServerMessage::Event {
+ event: SystemEvent::AcpReady,
+ })
+ .await;
+
+ let (_outbound, mut inbound) = attachment.connector.split();
+ let first = inbound.recv().await.expect("a frame");
+ assert!(matches!(
+ first,
+ ToServerMessage::Event {
+ event: SystemEvent::AcpReady
+ }
+ ));
+}
+
+fn resume_request(acp_session: &str) -> ToRuntimeMessage {
+ ToRuntimeMessage::Acp(AcpMessage(
+ RawJsonRpcMessage::request(
+ "session/resume".to_owned(),
+ serde_json::json!({ "sessionId": acp_session, "cwd": "/workspace" }),
+ RequestId::Str("agent_session:resume".to_owned()),
+ )
+ .expect("a serializable request"),
+ ))
+}
+
+#[tokio::test]
+async fn a_resumed_session_owns_the_updates_that_follow() {
+ let connection = RuntimeConnection::connect(SilentSocket);
+ let attachment = connection.bind(AgentSessionId::TEST_A).await;
+
+ // Resuming is the reconnect path: the request names the ACP session and
+ // the answer does not echo it, so this send is the only chance to learn
+ // whose it is. Miss it and every later update for that session is an
+ // orphan - the session goes silent on exactly the path that restores it.
+ let (outbound, _inbound) = attachment.connector.split();
+ outbound
+ .send(resume_request("acp-42"))
+ .await
+ .expect("the send is accepted");
+
+ let update = notification(
+ "session/update",
+ serde_json::json!({ "sessionId": "acp-42", "update": {} }),
+ );
+ assert_eq!(
+ connection.routes.lock().await.route(&update),
+ Routed::Session(AgentSessionId::TEST_A)
+ );
+}
diff --git a/crates/agent_session/src/domain/error.rs b/crates/agent_session/src/domain/error.rs
index c734201424..2bb2c347d4 100644
--- a/crates/agent_session/src/domain/error.rs
+++ b/crates/agent_session/src/domain/error.rs
@@ -12,6 +12,10 @@ pub enum AgentSessionError {
Handshake(String),
#[error("agent session {0} is no longer connected")]
Disconnected(AgentSessionId),
+ #[error("this bot already has a session for this thread")]
+ ThreadSessionExists,
+ #[error("the session owner is not a known user")]
+ UnknownOwner,
#[error(
"agent session {0} cannot be restored because the agent supports neither session/resume nor session/load"
)]
diff --git a/crates/agent_session/src/domain/mod.rs b/crates/agent_session/src/domain/mod.rs
index 980e332309..94cfda322d 100644
--- a/crates/agent_session/src/domain/mod.rs
+++ b/crates/agent_session/src/domain/mod.rs
@@ -1,3 +1,4 @@
+pub mod connection;
pub mod error;
pub mod model;
pub mod ports;
diff --git a/crates/agent_session/src/domain/model.rs b/crates/agent_session/src/domain/model.rs
index c1634d6e2d..5cc07d7646 100644
--- a/crates/agent_session/src/domain/model.rs
+++ b/crates/agent_session/src/domain/model.rs
@@ -1,3 +1,4 @@
+use agent_client_protocol::schema::v1::SessionId;
use agent_runtime_protocol::domain::schema::v0::SystemEvent;
use bots::domain::models::BotId;
use chrono::{DateTime, Utc};
@@ -42,8 +43,10 @@ pub struct CreateAgentSessionParams {
pub model: String,
/// Harness slug.
pub harness: String,
- /// Repository the agent works with.
- pub repo_url: String,
+ /// Repository the agent works with, when one was stated.
+ pub repo_url: Option<String>,
+ /// Absolute directory the harness runs in on its runtime.
+ pub workspace: String,
}
/// A running or historical agent coding session.
@@ -67,10 +70,15 @@ pub struct AgentSession {
pub model: String,
/// harness slug - TODO: probably a better type here
pub harness: String,
- /// repo we are working with
- pub repo_url: String,
+ /// repo we are working with, when one was stated
+ pub repo_url: Option<String>,
+ /// Directory the harness runs in, snapshotted at creation. The session
+ /// actor sends it as the working directory of `session/new`, and resume
+ /// and load re-enter it - the directory the session actually ran in,
+ /// not whatever the runtime is configured with today.
+ pub workspace: String,
/// ACP session if we have one
- pub acp_session_id: Option<String>,
+ pub acp_session_id: Option<SessionId>,
pub status: SessionStatus,
pub created_at: DateTime<Utc>,
pub modified_at: DateTime<Utc>,
diff --git a/crates/agent_session/src/domain/ports.rs b/crates/agent_session/src/domain/ports.rs
index bff2af8f64..783d249773 100644
--- a/crates/agent_session/src/domain/ports.rs
+++ b/crates/agent_session/src/domain/ports.rs
@@ -19,6 +19,82 @@ impl<T> AgentConnector for T where
{
}
+/// The facts about a bot that gate opening sessions for it.
+#[derive(Debug, Clone)]
+pub struct BotFacts {
+ /// Whether mentioning the bot runs a coding agent.
+ pub has_agent: bool,
+ /// Whether this deployment provisions the bot's runtime itself. Managed
+ /// bots' sessions are opened by the trigger pipeline, never over HTTP,
+ /// and nothing may dial in for them.
+ pub is_managed: bool,
+ /// The user who owns the bot, when it is user-owned.
+ pub owner_user_id: Option<MacroUserIdStr<'static>>,
+}
+
+/// Read-only lookup of the bots sessions may be opened for.
+pub trait BotDirectory: Send + Sync + 'static {
+ /// Fetch a bot's facts; `None` when no such bot exists.
+ fn bot_facts(&self, bot: BotId) -> impl Future<Output = Result<Option<BotFacts>>> + Send;
+}
+
+/// The mention that triggered a session, when one did.
+///
+/// Routes follow-up mentions in the thread to this session and feeds the
+/// announcement - the magic-chip message the session's bot posts back into
+/// the thread. The mention's text is quoted there for display only; the
+/// runtime still delivers it as the first prompt through the session
+/// control endpoint. Because all of this is claimed by the caller rather
+/// than observed by the trigger pipeline, it never grants the thread's
+/// channel any access to the session, and the announcement stands only
+/// where the bot can already post.
+#[derive(Debug, Clone)]
+pub struct SessionThread {
+ /// Channel the mentioning message was posted in.
+ pub channel_id: Uuid,
+ /// Thread the session belongs to.
+ pub thread_id: Uuid,
+ /// The mentioning message itself.
+ pub message_id: Uuid,
+ /// The mention's text, quoted in the announcement.
+ pub content: String,
+}
+
+/// Everything needed to open a session served by an external runtime.
+#[derive(Debug, Clone)]
+pub struct OpenExternalAgentSession {
+ /// The bot the session runs for.
+ pub bot_id: BotId,
+ /// Absolute directory the bot's harness runs in on its runtime.
+ pub workspace: String,
+ /// Repository nominally checked out at `workspace`, when stated.
+ pub repo_url: Option<String>,
+ /// The user who owns the session.
+ pub owner: MacroUserIdStr<'static>,
+ /// The thread whose mention triggered the session, when one did.
+ pub thread: Option<SessionThread>,
+}
+
+/// Opens externally-served sessions: rows whose runtime is hosted by the
+/// bot's operator and dials in on its own schedule. Implemented by the
+/// harness, which owns the session-opening semantics.
+pub trait ExternalSessionOpener: Send + Sync + 'static {
+ /// Open a session and return the persisted row.
+ fn open_external_session(
+ &self,
+ request: OpenExternalAgentSession,
+ ) -> impl Future<Output = Result<AgentSession>> + Send;
+
+ /// The session a thread's mentions already route to, if one exists.
+ /// What a caller whose open conflicted needs to recover: redeliveries
+ /// resume serving the existing session instead of being dropped.
+ fn find_thread_session(
+ &self,
+ thread_id: Uuid,
+ bot_id: BotId,
+ ) -> impl Future<Output = Result<Option<AgentSessionId>>> + Send;
+}
+
/// `Send + Sync + 'static` with `Send` futures because callers drive sessions
/// from spawned tasks - a Kafka consumer hands each message to its own task,
/// and a repo whose futures are not `Send` cannot be used there.
diff --git a/crates/agent_session/src/domain/service.rs b/crates/agent_session/src/domain/service.rs
index 4259160174..a072264eab 100644
--- a/crates/agent_session/src/domain/service.rs
+++ b/crates/agent_session/src/domain/service.rs
@@ -37,10 +37,13 @@ use macro_user_id::user_id::MacroUserIdStr;
use macro_uuid::Uuid;
use tokio::sync::{mpsc, oneshot};
+use bots::domain::models::BotId;
+
+use super::connection::RuntimeAttachment;
use super::error::{AgentSessionError, Result};
use super::model::{
- AgentSession, AgentSessionId, AgentSessionLog, AuthorKind, CreateAgentSessionParams,
- LogAppended, MessageId, SessionLog, StoredAgentSessionLog,
+ AgentSession, AgentSessionId, AgentSessionLog, AuthorKind, ChannelSession,
+ CreateAgentSessionParams, LogAppended, Message, MessageId, SessionLog, StoredAgentSessionLog,
};
use super::ports::{
AgentConnector, AgentSessionLogRepo, AgentSessionLogWriter, AgentSessionRealtime,
@@ -77,13 +80,17 @@ pub trait AgentSessionService: Send + Sync + 'static {
fn close_session(&self, id: AgentSessionId) -> impl Future<Output = Result<()>> + Send;
/// Attach a new transport to an existing persisted session.
+ ///
+ /// The attachment carries the connection's handshake gate as well as the
+ /// transport, because whether this session runs `initialize` depends on
+ /// whether another session on the same connection already did.
fn attach_session<Connector>(
&self,
id: AgentSessionId,
- connector: Connector,
+ attachment: RuntimeAttachment<Connector>,
) -> impl Future<Output = Result<()>> + Send
where
- Connector: AgentConnector + Clone;
+ Connector: AgentConnector;
/// Deliver an action through the session's active transport, under the
/// action id it will carry onto the wire.
@@ -95,6 +102,13 @@ pub trait AgentSessionService: Send + Sync + 'static {
action_id: AgentActionId,
) -> impl Future<Output = Result<()>> + Send;
+ /// The session an incoming channel context routes to, if any.
+ fn find_for_channel(
+ &self,
+ thread_id: Option<Uuid>,
+ bot_id: Option<BotId>,
+ ) -> impl Future<Output = Result<ChannelSession>> + Send;
+
/// The user-message id the next prompt appended to this session will fold to.
fn next_prompt_message_id(
&self,
@@ -145,12 +159,13 @@ impl<R, Folds, Rt> AgentSessionServiceImpl<R, Folds, Rt> {
&self,
id: AgentSessionId,
acp_session_id: Option<SessionId>,
- connector: Connector,
+ workspace: String,
+ attachment: RuntimeAttachment<Connector>,
) -> Result<()>
where
R: AgentSessionRepo + AgentSessionLogRepo + Clone,
Rt: AgentSessionRealtime + Clone + Send + Sync + 'static,
- Connector: AgentConnector + Clone,
+ Connector: AgentConnector,
{
let (commands, command_rx) = mpsc::channel(COMMAND_BUFFER);
@@ -167,7 +182,15 @@ impl<R, Folds, Rt> AgentSessionServiceImpl<R, Folds, Rt> {
// which costs an attach nothing until the session actually says
// something.
let logs = LiveSessionLogWriter::new(self.repo.clone(), self.realtime.clone());
- let actor = SessionActor::new(id, acp_session_id, connector, logs, command_rx);
+ let actor = SessionActor::new(
+ id,
+ acp_session_id,
+ workspace,
+ attachment.connector,
+ logs,
+ command_rx,
+ attachment.handshake,
+ );
tokio::spawn(run_session(actor, Arc::downgrade(&self.active), commands));
Ok(())
}
@@ -225,6 +248,14 @@ where
self.repo.get(id).await
}
+ async fn find_for_channel(
+ &self,
+ thread_id: Option<Uuid>,
+ bot_id: Option<BotId>,
+ ) -> Result<ChannelSession> {
+ self.repo.find_for_channel(thread_id, bot_id).await
+ }
+
async fn delete_session(&self, id: AgentSessionId) -> Result<()> {
self.repo.delete(id).await
}
@@ -240,16 +271,17 @@ where
async fn attach_session<Connector>(
&self,
id: AgentSessionId,
- connector: Connector,
+ attachment: RuntimeAttachment<Connector>,
) -> Result<()>
where
- Connector: AgentConnector + Clone,
+ Connector: AgentConnector,
{
let session = self.repo.get(id).await?;
self.register_transport(
session.id,
- session.acp_session_id.map(Into::into),
- connector,
+ session.acp_session_id,
+ session.workspace,
+ attachment,
)
}
@@ -324,6 +356,21 @@ where
async fn append(&mut self, log: AgentSessionLog) -> Result<()> {
let session = log.agent_session_id;
+ // The wire tap: every frame of every session, both directions,
+ // crosses here exactly once. Enable with RUST_LOG=agent_session=trace.
+ if tracing::enabled!(tracing::Level::TRACE) {
+ let (direction, frame) = match &log.content {
+ Message::ToServer(message) => ("to_server", serde_json::to_string(message)),
+ Message::ToRuntime(message) => ("to_runtime", serde_json::to_string(message)),
+ };
+ tracing::trace!(
+ %session,
+ direction,
+ frame = frame.as_deref().unwrap_or("<unserializable>"),
+ "acp frame"
+ );
+ }
+
// Durable first: projections are rebuildable, but a frame omitted from
// session history is not.
let stored = AgentSessionLogRepo::create(&self.repo, log.clone()).await?;
@@ -475,7 +522,7 @@ async fn run_session<Connector, Logs>(
active: std::sync::Weak<ActiveSessions>,
commands: mpsc::Sender<SessionCommand>,
) where
- Connector: AgentConnector + Clone,
+ Connector: AgentConnector,
Logs: AgentSessionLogWriter + AgentSessionRepo,
{
while actor.step().await == Stepped::Continue {}
diff --git a/crates/agent_session/src/domain/session/actors.rs b/crates/agent_session/src/domain/session/actors.rs
index b26cd47cb6..41e49d5c46 100644
--- a/crates/agent_session/src/domain/session/actors.rs
+++ b/crates/agent_session/src/domain/session/actors.rs
@@ -17,19 +17,17 @@ use std::collections::VecDeque;
use agent_client_protocol::schema::v1::SessionId;
use agent_runtime_protocol::domain::action::{AgentAction, AgentActionId};
-use agent_runtime_protocol::domain::ports::TransportError;
use agent_runtime_protocol::domain::schema::v0::{SystemEvent, ToRuntimeMessage, ToServerMessage};
use macro_user_id::user_id::MacroUserIdStr;
-use tokio::sync::{mpsc, oneshot};
+use tokio::sync::{mpsc, oneshot, watch};
use crate::domain::error::Result;
use crate::domain::model::{AgentSessionId, AgentSessionLog, Message};
-use crate::domain::ports::{AgentConnector, AgentSessionLogWriter, AgentSessionRepo};
+use agent_runtime_protocol::domain::ports::{TransportReceiver, TransportSender};
-use super::{CloseReason, Effect, Input, SessionMachine};
+use crate::domain::ports::{AgentConnector, AgentSessionLogWriter, AgentSessionRepo};
-/// Buffered inbound messages between the receive pump and the actor select.
-const INBOUND_BUFFER: usize = 1028;
+use super::{CloseReason, Effect, HandshakeStatus, Input, SessionMachine};
/// A caller's request to deliver one action, and the wire back to them.
pub(crate) struct SessionCommand {
@@ -50,53 +48,54 @@ pub(crate) enum Stepped {
/// One session connection's imperative shell: pulls one input, runs the
/// machine, and executes the effects - nothing else.
-pub(crate) struct SessionActor<Connector, Logs> {
+pub(crate) struct SessionActor<Connector: AgentConnector, Logs> {
machine: SessionMachine<oneshot::Sender<Result<()>>>,
- connector: Connector,
+ /// The carrier's halves. Sending is shared with whoever else is on the
+ /// same connection; receiving is this actor's alone, which is why it can
+ /// be read with `&mut` and needs no lock.
+ outbound: Connector::Sender,
+ inbound: Connector::Receiver,
logs: Logs,
commands: mpsc::Receiver<SessionCommand>,
- inbound: mpsc::Receiver<std::result::Result<Option<ToServerMessage>, TransportError>>,
- /// The task owning the in-flight physical receive; aborted when this
- /// actor drops.
- pump: tokio::task::JoinHandle<()>,
+ /// This connection's handshake gate: published to when this session runs
+ /// the handshake, watched for when another session runs it.
+ handshake: watch::Sender<HandshakeStatus>,
+ handshake_seen: watch::Receiver<HandshakeStatus>,
}
impl<Connector, Logs> SessionActor<Connector, Logs>
where
- Connector: AgentConnector + Clone,
+ Connector: AgentConnector,
Logs: AgentSessionLogWriter + AgentSessionRepo,
{
pub(crate) fn new(
id: AgentSessionId,
acp_session_id: Option<SessionId>,
+ workspace: String,
connector: Connector,
logs: Logs,
commands: mpsc::Receiver<SessionCommand>,
+ handshake: watch::Sender<HandshakeStatus>,
) -> Self {
- // Keep one physical receive alive independently of the actor select.
- // Some transports are not cancellation-safe.
- let (inbound_tx, inbound) = mpsc::channel(INBOUND_BUFFER);
- let receiver = connector.clone();
- let pump = tokio::spawn(async move {
- loop {
- let inbound = receiver.recv().await;
- let finished = matches!(inbound, Ok(None) | Err(_));
- if inbound_tx.send(inbound).await.is_err() || finished {
- break;
- }
- }
- });
+ // Marked unseen so the first wait reports the *current* state rather
+ // than only later changes: a session binding after the handshake
+ // finished would otherwise wait for an announcement already made.
+ let mut handshake_seen = handshake.subscribe();
+ handshake_seen.mark_changed();
+
+ let (outbound, inbound) = connector.split();
Self {
- machine: acp_session_id.map_or_else(
- || SessionMachine::new(id),
- |session_id| SessionMachine::resume(id, session_id),
- ),
- connector,
+ outbound,
+ inbound,
+ handshake_seen,
+ handshake,
+ machine: match acp_session_id {
+ None => SessionMachine::new(id, workspace),
+ Some(session_id) => SessionMachine::resume(id, session_id, workspace),
+ },
logs,
commands,
- inbound,
- pump,
}
}
@@ -124,7 +123,15 @@ where
// The service dropped every handle; nobody can reach us.
None => Input::Closed(CloseReason::Abandoned),
},
- inbound = self.inbound.recv() => match inbound.unwrap_or(Ok(None)) {
+ // A handshake somebody else ran. The machine ignores it unless it
+ // is still booting, which is what makes the session that ran the
+ // handshake ignore its own result coming back.
+ Ok(()) = self.handshake_seen.changed() => match *self.handshake_seen.borrow_and_update() {
+ HandshakeStatus::Ready(restore) => Input::Ready { restore },
+ // Nothing to act on yet, but the wait must resume.
+ HandshakeStatus::Pending | HandshakeStatus::InFlight => return Stepped::Continue,
+ },
+ inbound = self.inbound.recv() => match inbound {
Ok(Some(message)) => Input::Inbound(message),
Ok(None) => Input::Closed(CloseReason::TransportClosed),
Err(error) => {
@@ -183,6 +190,12 @@ where
effects.extend(self.machine.handle(Input::Closed(CloseReason::LogFailed)));
}
}
+ Effect::Initialized { restore } => {
+ // Nothing waits on this today; a failed send would mean
+ // every receiver is gone, which cannot happen while this
+ // actor holds one.
+ let _ = self.handshake.send(HandshakeStatus::Ready(restore));
+ }
Effect::Complete { token, result } => {
let _ = token.send(result);
}
@@ -219,7 +232,7 @@ where
message: ToRuntimeMessage,
) -> Result<()> {
self.log(from, Message::ToRuntime(message.clone())).await?;
- self.connector.send(message).await?;
+ self.outbound.send(message).await?;
Ok(())
}
@@ -243,10 +256,3 @@ where
.await
}
}
-
-/// Abort the receiver pump when the actor goes away, however it goes away.
-impl<Connector, Logs> Drop for SessionActor<Connector, Logs> {
- fn drop(&mut self) {
- self.pump.abort();
- }
-}
diff --git a/crates/agent_session/src/domain/session/mod.rs b/crates/agent_session/src/domain/session/mod.rs
index f2dd80068d..d904e6752f 100644
--- a/crates/agent_session/src/domain/session/mod.rs
+++ b/crates/agent_session/src/domain/session/mod.rs
@@ -11,4 +11,6 @@ mod types;
mod tests;
pub use session::SessionMachine;
-pub use types::{CloseReason, Effect, Input, RuntimeStatus, StopReason};
+pub use types::{
+ CloseReason, Effect, HandshakeStatus, Input, RuntimeStatus, SessionRestoreSupport, StopReason,
+};
diff --git a/crates/agent_session/src/domain/session/session.rs b/crates/agent_session/src/domain/session/session.rs
index 45e6788203..fb556f4fd5 100644
--- a/crates/agent_session/src/domain/session/session.rs
+++ b/crates/agent_session/src/domain/session/session.rs
@@ -15,13 +15,13 @@ use agent_runtime_protocol::domain::schema::v0::{
};
use macro_user_id::user_id::MacroUserIdStr;
+use crate::PROTOCOL_VERSION;
use crate::domain::error::AgentSessionError;
use crate::domain::model::AgentSessionId;
-use crate::{AGENT_WORKING_DIRECTORY, PROTOCOL_VERSION};
use super::types::{
CloseReason, Effect, Input, PendingAction, RuntimeStatus, SessionOpening, SessionPhase,
- StopReason,
+ SessionRestoreSupport, StopReason,
};
const INITIAL_REQUEST_NUM: u64 = 0;
@@ -36,28 +36,35 @@ pub struct SessionMachine<Token> {
/// Held outside the phase so a partial flush strands nothing.
pending: VecDeque<PendingAction<Token>>,
resume_session_id: Option<SessionId>,
+ /// Directory the agent works in, snapshotted on the session row at
+ /// creation; `session/new`, `session/resume`, and `session/load` all
+ /// carry it, so a reconnect re-enters the directory the session
+ /// actually ran in.
+ workspace: String,
}
impl<Token> SessionMachine<Token> {
/// A fresh connection for `id`: booting, nothing queued.
- pub fn new(id: AgentSessionId) -> Self {
+ pub fn new(id: AgentSessionId, workspace: String) -> Self {
Self {
id,
phase: SessionPhase::Booting,
next_request: INITIAL_REQUEST_NUM,
pending: VecDeque::new(),
resume_session_id: None,
+ workspace,
}
}
/// A fresh connection that must restore an existing ACP session.
- pub fn resume(id: AgentSessionId, session_id: SessionId) -> Self {
+ pub fn resume(id: AgentSessionId, session_id: SessionId, workspace: String) -> Self {
Self {
id,
phase: SessionPhase::Booting,
next_request: INITIAL_REQUEST_NUM,
pending: VecDeque::new(),
resume_session_id: Some(session_id),
+ workspace,
}
}
@@ -95,10 +102,24 @@ impl<Token> SessionMachine<Token> {
token,
} => self.on_command(from, action, action_id, token),
Input::Inbound(message) => self.on_inbound(message),
+ Input::Ready { restore } => self.on_connection_ready(restore),
Input::Closed(reason) => self.on_closed(reason),
}
}
+ /// Open on a connection somebody else initialized.
+ ///
+ /// Ignored unless still booting: the machine that ran the handshake is
+ /// told its own result this way too, and a session already opening or
+ /// live has nothing to learn from it.
+ fn on_connection_ready(&mut self, restore: SessionRestoreSupport) -> Vec<Effect<Token>> {
+ let mut effects = Vec::new();
+ if matches!(self.phase, SessionPhase::Booting) {
+ self.begin_opening(restore, &mut effects);
+ }
+ effects
+ }
+
fn on_command(
&mut self,
from: Option<MacroUserIdStr<'static>>,
@@ -232,19 +253,25 @@ impl<Token> SessionMachine<Token> {
}
};
+ let restore = SessionRestoreSupport {
+ resume: response
+ .agent_capabilities
+ .session_capabilities
+ .resume
+ .is_some(),
+ load: response.agent_capabilities.load_session,
+ };
+ // Announced before this session opens: every other session on this
+ // connection needs the same answer, and only this machine was told it.
+ effects.push(Effect::Initialized { restore });
+ self.begin_opening(restore, effects);
+ }
+
+ /// Ask the agent for this session, however it has to be established.
+ fn begin_opening(&mut self, restore: SessionRestoreSupport, effects: &mut Vec<Effect<Token>>) {
let opening = match self.resume_session_id.clone() {
- Some(session_id)
- if response
- .agent_capabilities
- .session_capabilities
- .resume
- .is_some() =>
- {
- self.build_resume_session_request(session_id)
- }
- Some(session_id) if response.agent_capabilities.load_session => {
- self.build_load_session_request(session_id)
- }
+ Some(session_id) if restore.resume => self.build_resume_session_request(session_id),
+ Some(session_id) if restore.load => self.build_load_session_request(session_id),
Some(_) => {
self.resume_unsupported(effects);
return;
@@ -347,7 +374,7 @@ impl<Token> SessionMachine<Token> {
agent_client_protocol::Error,
> {
self.build_session_request(
- ResumeSessionRequest::new(session_id.clone(), AGENT_WORKING_DIRECTORY),
+ ResumeSessionRequest::new(session_id.clone(), self.workspace.clone()),
SessionOpening::Resume(session_id),
)
}
@@ -360,7 +387,7 @@ impl<Token> SessionMachine<Token> {
agent_client_protocol::Error,
> {
self.build_session_request(
- LoadSessionRequest::new(session_id.clone(), AGENT_WORKING_DIRECTORY),
+ LoadSessionRequest::new(session_id.clone(), self.workspace.clone()),
SessionOpening::Load(session_id),
)
}
@@ -383,7 +410,7 @@ impl<Token> SessionMachine<Token> {
agent_client_protocol::Error,
> {
self.build_session_request(
- NewSessionRequest::new(AGENT_WORKING_DIRECTORY),
+ NewSessionRequest::new(self.workspace.clone()),
SessionOpening::New,
)
}
@@ -506,9 +533,11 @@ impl<Token> SessionMachine<Token> {
});
}
- /// Namespaced so a caller's request id can never collide with ours.
+ /// Namespaced so a caller's request id can never collide with ours - and
+ /// carries the session, so sessions sharing one connection cannot collide
+ /// with each other either.
fn next_id(&mut self) -> RequestId {
- let id = RequestId::Str(format!("agent_session:{}", self.next_request));
+ let id = RequestId::Str(format!("agent_session:{}:{}", self.id, self.next_request));
self.next_request += 1;
id
}
diff --git a/crates/agent_session/src/domain/session/tests.rs b/crates/agent_session/src/domain/session/tests.rs
index 66c1943a6b..6995026be5 100644
--- a/crates/agent_session/src/domain/session/tests.rs
+++ b/crates/agent_session/src/domain/session/tests.rs
@@ -18,10 +18,12 @@ use crate::PROTOCOL_VERSION;
use crate::domain::error::AgentSessionError;
use crate::domain::model::AgentSessionId;
-use super::{CloseReason, Effect, Input, RuntimeStatus, SessionMachine, StopReason};
+use super::{
+ CloseReason, Effect, Input, RuntimeStatus, SessionMachine, SessionRestoreSupport, StopReason,
+};
fn machine() -> SessionMachine<u32> {
- SessionMachine::new(AgentSessionId::TEST_A)
+ SessionMachine::new(AgentSessionId::TEST_A, "/workspace".to_owned())
}
fn command(text: &str, token: u32) -> Input<u32> {
@@ -73,7 +75,7 @@ fn begin_opening(machine: &mut SessionMachine<u32>) {
/// The answer to `session/new`, sent after initialization completes.
fn session_opened(session_id: &'static str) -> Input<u32> {
frame(RawJsonRpcMessage::response(
- RequestId::Str("agent_session:1".to_owned()),
+ request_id(1),
Ok(serde_json::to_value(NewSessionResponse::new(session_id))
.expect("a serializable response")),
))
@@ -81,7 +83,7 @@ fn session_opened(session_id: &'static str) -> Input<u32> {
fn session_refused() -> Input<u32> {
frame(RawJsonRpcMessage::response(
- RequestId::Str("agent_session:1".to_owned()),
+ request_id(1),
Err(agent_client_protocol::Error::internal_error()),
))
}
@@ -113,8 +115,10 @@ fn sent_methods(effects: &[Effect<u32>]) -> Vec<String> {
.collect()
}
+/// The machine's own request ids carry the session, so sessions sharing one
+/// connection cannot collide.
fn request_id(n: u64) -> RequestId {
- RequestId::Str(format!("agent_session:{n}"))
+ RequestId::Str(format!("agent_session:{}:{n}", AgentSessionId::TEST_A))
}
#[test]
@@ -225,7 +229,11 @@ fn session_new_success_flushes_the_queue_positionally() {
#[test]
fn reconnect_uses_session_resume_when_the_agent_supports_it() {
- let mut machine = SessionMachine::resume(AgentSessionId::TEST_A, "acp-42".into());
+ let mut machine = SessionMachine::resume(
+ AgentSessionId::TEST_A,
+ "acp-42".into(),
+ "/workspace".to_owned(),
+ );
machine.handle(command("continue", 1));
machine.handle(acp_ready());
let initialized = InitializeResponse::new(PROTOCOL_VERSION).agent_capabilities(
@@ -257,7 +265,11 @@ fn reconnect_uses_session_resume_when_the_agent_supports_it() {
#[test]
fn reconnect_falls_back_to_session_load() {
- let mut machine = SessionMachine::resume(AgentSessionId::TEST_A, "acp-42".into());
+ let mut machine = SessionMachine::resume(
+ AgentSessionId::TEST_A,
+ "acp-42".into(),
+ "/workspace".to_owned(),
+ );
machine.handle(acp_ready());
let initialized = InitializeResponse::new(PROTOCOL_VERSION)
.agent_capabilities(AgentCapabilities::new().load_session(true));
@@ -269,16 +281,24 @@ fn reconnect_falls_back_to_session_load() {
#[test]
fn reconnect_stops_when_the_agent_cannot_restore_sessions() {
- let mut machine = SessionMachine::resume(AgentSessionId::TEST_A, "acp-42".into());
+ let mut machine = SessionMachine::resume(
+ AgentSessionId::TEST_A,
+ "acp-42".into(),
+ "/workspace".to_owned(),
+ );
machine.handle(command("cannot continue", 1));
machine.handle(acp_ready());
let effects = machine.handle(initialized());
+ // The handshake itself succeeded, so its result is still announced: this
+ // session cannot restore itself, but the connection is initialized and a
+ // new session on it would not have to handshake again.
assert!(matches!(
effects[..],
[
Effect::Log { .. },
+ Effect::Initialized { .. },
Effect::Complete {
token: 1,
result: Err(AgentSessionError::ResumeUnsupported(_))
@@ -359,7 +379,7 @@ fn an_unintelligible_session_new_answer_stops() {
begin_opening(&mut machine);
let effects = machine.handle(frame(RawJsonRpcMessage::response(
- RequestId::Str("agent_session:1".to_owned()),
+ request_id(1),
Ok(serde_json::json!({ "not": "a session" })),
)));
@@ -391,7 +411,7 @@ fn a_live_frame_only_logs() {
machine.handle(session_opened("acp-42"));
let effects = machine.handle(frame(RawJsonRpcMessage::response(
- RequestId::Str("agent_session:2".to_owned()),
+ request_id(2),
Ok(serde_json::json!({})),
)));
@@ -659,3 +679,160 @@ fn a_model_change_does_not_disturb_the_queue() {
"both are still queued, in order"
);
}
+
+/// The `cwd` of every sent request with the given method.
+fn sent_cwds(effects: &[Effect<u32>], method: &str) -> Vec<String> {
+ effects
+ .iter()
+ .filter_map(|effect| match effect {
+ Effect::Send {
+ message: ToRuntimeMessage::Acp(AcpMessage(RawJsonRpcMessage::Request(request))),
+ ..
+ } if request.method.as_ref() == method => {
+ let params = request
+ .params
+ .clone()
+ .expect("the request has params")
+ .into_value();
+ Some(params["cwd"].as_str().expect("cwd is a string").to_owned())
+ }
+ _ => None,
+ })
+ .collect()
+}
+
+#[test]
+fn session_new_carries_the_sessions_workspace() {
+ let mut machine = SessionMachine::new(AgentSessionId::TEST_A, "/home/operator/code".to_owned());
+ machine.handle(acp_ready());
+ let effects = machine.handle(initialized());
+
+ // The session/new request works in the row's directory, not a constant.
+ assert_eq!(sent_cwds(&effects, "session/new"), ["/home/operator/code"]);
+}
+
+#[test]
+fn resume_carries_the_sessions_workspace() {
+ let mut machine = SessionMachine::resume(
+ AgentSessionId::TEST_A,
+ "acp-42".into(),
+ "/home/operator/code".to_owned(),
+ );
+ machine.handle(acp_ready());
+ let effects = machine.handle(initialized_with(
+ InitializeResponse::new(PROTOCOL_VERSION).agent_capabilities(
+ AgentCapabilities::new().session_capabilities(
+ SessionCapabilities::new().resume(SessionResumeCapabilities::new()),
+ ),
+ ),
+ ));
+
+ assert_eq!(
+ sent_cwds(&effects, "session/resume"),
+ ["/home/operator/code"]
+ );
+}
+
+#[test]
+fn a_session_on_an_initialized_connection_opens_without_handshaking() {
+ let mut machine = machine();
+ machine.handle(command("fix the flaky test", 1));
+
+ // No `AcpReady`, no `initialize`: another session on this connection
+ // already ran the handshake and this one is told the result.
+ let opening = machine.handle(Input::Ready {
+ restore: SessionRestoreSupport {
+ resume: false,
+ load: false,
+ },
+ });
+
+ assert_eq!(sent_methods(&opening), ["session/new"]);
+ assert_eq!(
+ machine.pending_count(),
+ 1,
+ "the prompt still waits to flush"
+ );
+}
+
+#[test]
+fn a_ready_connection_still_picks_resume_for_a_session_that_has_one() {
+ let mut machine = SessionMachine::resume(
+ AgentSessionId::TEST_A,
+ "acp-42".into(),
+ "/workspace".to_owned(),
+ );
+
+ let opening = machine.handle(Input::Ready {
+ restore: SessionRestoreSupport {
+ resume: true,
+ load: false,
+ },
+ });
+
+ assert_eq!(sent_methods(&opening), ["session/resume"]);
+}
+
+#[test]
+fn a_ready_connection_that_cannot_restore_stops_the_session() {
+ let mut machine: SessionMachine<u32> = SessionMachine::resume(
+ AgentSessionId::TEST_A,
+ "acp-42".into(),
+ "/workspace".to_owned(),
+ );
+
+ let effects = machine.handle(Input::Ready {
+ restore: SessionRestoreSupport {
+ resume: false,
+ load: false,
+ },
+ });
+
+ assert!(matches!(
+ effects[..],
+ [Effect::Stop {
+ reason: StopReason::ResumeUnsupported
+ }]
+ ));
+}
+
+#[test]
+fn the_session_that_ran_the_handshake_ignores_being_told_it_is_ready() {
+ let mut machine = machine();
+ machine.handle(acp_ready());
+ let opened = machine.handle(initialized());
+ assert_eq!(sent_methods(&opened), ["session/new"]);
+
+ // The gate is shared, so the machine that published `Ready` reads it back.
+ // Opening twice would leave the agent with a session nobody tracks.
+ let echo = machine.handle(Input::Ready {
+ restore: SessionRestoreSupport {
+ resume: true,
+ load: true,
+ },
+ });
+
+ assert!(echo.is_empty());
+}
+
+#[test]
+fn the_handshake_result_is_announced_for_the_connection() {
+ let mut machine = machine();
+ machine.handle(acp_ready());
+ let initialized = InitializeResponse::new(PROTOCOL_VERSION)
+ .agent_capabilities(AgentCapabilities::new().load_session(true));
+
+ let effects = machine.handle(initialized_with(initialized));
+
+ let announced = effects.iter().find_map(|effect| match effect {
+ Effect::Initialized { restore } => Some(*restore),
+ _ => None,
+ });
+ assert_eq!(
+ announced,
+ Some(SessionRestoreSupport {
+ resume: false,
+ load: true
+ })
+ );
+}
diff --git a/crates/agent_session/src/domain/session/types.rs b/crates/agent_session/src/domain/session/types.rs
index 0aa08eaadb..3492cc4595 100644
--- a/crates/agent_session/src/domain/session/types.rs
+++ b/crates/agent_session/src/domain/session/types.rs
@@ -44,6 +44,40 @@ pub(super) enum SessionOpening {
Load(SessionId),
}
+/// What the agent said it can do about a session it has seen before, distilled
+/// from the `initialize` response.
+///
+/// Only these two facts decide how a session opens, and one connection's
+/// answer serves every session on it - so this is what gets shared, rather
+/// than the protocol's whole capability set.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct SessionRestoreSupport {
+ /// The agent offers `session/resume`.
+ pub resume: bool,
+ /// The agent offers `session/load`.
+ pub load: bool,
+}
+
+/// Where the sessions on one connection learn that its ACP handshake is done.
+///
+/// Exactly one session runs `initialize` per connection; the rest wait for
+/// its answer here rather than initializing again. Retained rather than
+/// broadcast, because a session can bind long after the handshake finished
+/// and still needs to be told - it reads the current value on subscribe.
+///
+/// The states are a claim as much as a status: exactly one session may run
+/// the handshake, so moving `Pending` to `InFlight` is how a session takes
+/// that job and how every other session knows not to.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum HandshakeStatus {
+ /// Nobody has started initializing this connection.
+ Pending,
+ /// A session is initializing it; the rest wait rather than initialize too.
+ InFlight,
+ /// The connection is initialized and sessions may open.
+ Ready(SessionRestoreSupport),
+}
+
/// Observable phase of a session connection.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RuntimeStatus {
@@ -121,6 +155,14 @@ pub enum Input<Token> {
},
/// The transport produced a message.
Inbound(ToServerMessage),
+ /// Somebody else on this connection completed the ACP handshake, so this
+ /// session may open without initializing anything. Ignored unless the
+ /// machine is still booting - the machine that ran the handshake sees its
+ /// own result come back this way too.
+ Ready {
+ /// What that handshake learned about restoring sessions.
+ restore: SessionRestoreSupport,
+ },
/// The connection is over. Idempotent: a dead machine ignores it.
Closed(CloseReason),
}
@@ -144,6 +186,13 @@ pub enum Effect<Token> {
/// Agent-assigned session identifier.
session_id: SessionId,
},
+ /// This machine ran the connection's `initialize` and learned what the
+ /// agent can do. Emitted so the connection can answer for every session
+ /// that opens after this one, including those that bind hours later.
+ Initialized {
+ /// What the handshake learned about restoring sessions.
+ restore: SessionRestoreSupport,
+ },
/// Resolve a caller's delivery future.
Complete {
/// The token the caller handed in with [`Input::Command`].
diff --git a/crates/agent_session/src/inbound/axum_router.rs b/crates/agent_session/src/inbound/axum_router.rs
index ab254c0d04..b2a3af2152 100644
--- a/crates/agent_session/src/inbound/axum_router.rs
+++ b/crates/agent_session/src/inbound/axum_router.rs
@@ -8,6 +8,10 @@
//! from any channel the session was once rendered in. Handlers only map
//! transport DTOs to domain types and call the [`AgentSessionService`]; they
//! make no authorization or business decisions of their own.
+//!
+//! The one exception is session creation: there is no session yet to resolve
+//! access against, so `create_agent_session_handler` gates on the bot's own
+//! facts - ownership, agent-hood, managedness - through [`BotDirectory`].
use std::sync::Arc;
@@ -29,7 +33,9 @@ use entity_access::domain::ports::EntityAccessService;
use entity_access::inbound::axum_extractors::AgentSessionAccessLevelExtractor;
use macro_authorization::{
MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState, UserOrBot,
+ UserOrBotAuthorization,
};
+use macro_user_id::user_id::MacroUserIdStr;
use macro_uuid::Uuid;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
@@ -38,8 +44,15 @@ use crate::domain::error::AgentSessionError;
use crate::domain::model::{
AgentSession, AgentSessionId, Message, SessionBot, SessionStatus, StoredAgentSessionLog,
};
-use crate::domain::ports::{AgentSessionNotificationRecipient, ControlEvent};
+use crate::domain::ports::{
+ AgentSessionNotificationRecipient, BotDirectory, BotFacts, ControlEvent, ExternalSessionOpener,
+ OpenExternalAgentSession, SessionThread,
+};
use crate::domain::service::AgentSessionService;
+use bots::domain::models::BotId;
+
+#[cfg(test)]
+mod test;
/// Shared state for the agent session router: the agent session service plus
/// the authorization state the request extractors authenticate against.
@@ -258,7 +271,9 @@ impl From<SessionStatusDto> for SessionStatus {
/// which are about the request rather than the operation have somewhere to go.
/// The acting user is deliberately not one of them: it comes from the caller's
/// credentials, so that a caller cannot attribute an operation to someone else.
-#[derive(Debug, Deserialize, ToSchema)]
+///
+/// Clients serialize this, so both derives are used.
+#[derive(Debug, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct ControlRequest {
/// The operation to perform.
@@ -267,7 +282,9 @@ pub struct ControlRequest {
}
/// Response body describing an agent session.
-#[derive(Debug, Serialize, ToSchema)]
+///
+/// Clients deserialize this, so both derives are used.
+#[derive(Debug, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct AgentSessionResponse {
/// The session id.
@@ -287,8 +304,11 @@ pub struct AgentSessionResponse {
pub model: String,
/// Harness slug.
pub harness: String,
- /// The repository the session works with.
- pub repo_url: String,
+ /// The repository the session works with, when one was stated.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub repo_url: Option<String>,
+ /// The directory the session's harness runs in on its runtime.
+ pub workspace: String,
/// The ACP session id, if one exists.
pub acp_session_id: Option<String>,
/// The session's status.
@@ -311,7 +331,8 @@ impl From<AgentSession> for AgentSessionResponse {
model: session.model,
harness: session.harness,
repo_url: session.repo_url,
- acp_session_id: session.acp_session_id,
+ workspace: session.workspace,
+ acp_session_id: session.acp_session_id.map(|id| id.to_string()),
status: session.status.into(),
created_at: session.created_at,
modified_at: session.modified_at,
@@ -572,3 +593,399 @@ pub async fn get_agent_session_log_handler<
entries: log.entries.into_iter().map(Into::into).collect(),
}))
}
+
+/// Shared state for the create route: the opener that owns session-opening
+/// semantics, the bot directory that gates it, and the authorization state the
+/// extractor runs against.
+///
+/// Nothing about the gateway: a runtime dials once per bot, at an address its
+/// own configuration names, so creating a session says nothing about where to
+/// connect.
+pub struct CreateSessionState<Opener, Bots, Auth> {
+ opener: Arc<Opener>,
+ bots: Arc<Bots>,
+ authorization_state: MacroAuthorizationState<Auth>,
+}
+
+impl<Opener, Bots, Auth> CreateSessionState<Opener, Bots, Auth> {
+ /// Create route state.
+ pub fn new(
+ opener: Arc<Opener>,
+ bots: Arc<Bots>,
+ authorization_state: MacroAuthorizationState<Auth>,
+ ) -> Self {
+ Self {
+ opener,
+ bots,
+ authorization_state,
+ }
+ }
+}
+
+// Manual Clone impl so Opener and Bots don't need to be Clone (both are
+// behind Arcs).
+impl<Opener, Bots, Auth> Clone for CreateSessionState<Opener, Bots, Auth> {
+ fn clone(&self) -> Self {
+ Self {
+ opener: Arc::clone(&self.opener),
+ bots: Arc::clone(&self.bots),
+ authorization_state: self.authorization_state.clone(),
+ }
+ }
+}
+
+impl<Opener, Bots, Auth> FromRef<CreateSessionState<Opener, Bots, Auth>>
+ for MacroAuthorizationState<Auth>
+{
+ fn from_ref(state: &CreateSessionState<Opener, Bots, Auth>) -> Self {
+ state.authorization_state.clone()
+ }
+}
+
+/// Build the router serving `POST /agent-sessions`. Mount it under the same
+/// prefix as [`agent_session_read_router`] and [`agent_session_control_router`].
+pub fn agent_session_create_router<Opener, Bots, Auth, S>(
+ state: CreateSessionState<Opener, Bots, Auth>,
+) -> Router<S>
+where
+ Opener: ExternalSessionOpener,
+ Bots: BotDirectory,
+ Auth: MacroAuthorizationService,
+ S: Clone + Send + Sync + 'static,
+{
+ Router::new()
+ .route(
+ "/",
+ post(create_agent_session_handler::<Opener, Bots, Auth>),
+ )
+ .with_state(state)
+}
+
+/// Request body for `POST /agent-sessions`.
+///
+/// Clients serialize this, so both derives are used.
+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct CreateAgentSessionRequest {
+ /// Bot the session runs for. Bot callers may omit it (their own identity
+ /// is used) and must not name another bot; user callers must supply a
+ /// bot they own.
+ pub bot_id: Option<Uuid>,
+ /// Absolute directory the bot's harness runs in on its runtime.
+ pub workspace: String,
+ /// Repository nominally checked out at `workspace`. Informational and
+ /// optional: having it cloned there is the runtime operator's job.
+ pub repo_url: Option<String>,
+ /// The user who owns the session. Ignored for user callers, who always
+ /// own their own sessions; required for bot callers without verified
+ /// acting-user claims.
+ ///
+ /// For bot callers this is a claim, not a verified fact: it is scoped to
+ /// the bot's own sessions, but the named user owns the session on the
+ /// bot's say-so.
+ pub owner: Option<String>,
+ /// The thread whose mention triggered the session, when one did.
+ /// Linkage only - the mention's text is delivered by the runtime as the
+ /// first prompt through the control endpoint, never through here.
+ pub thread: Option<CreateSessionThread>,
+}
+
+/// The triggering mention on a create request.
+///
+/// Clients serialize this, so both derives are used.
+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct CreateSessionThread {
+ /// Channel the mentioning message was posted in.
+ pub channel_id: Uuid,
+ /// Thread the session belongs to; defaults to the message itself, which
+ /// is how a top-level mention roots its own thread.
+ pub thread_id: Option<Uuid>,
+ /// The mentioning message.
+ pub message_id: Uuid,
+ /// The mention's text, quoted in the session's announcement.
+ #[serde(default)]
+ pub content: String,
+}
+
+/// Response body for `POST /agent-sessions`.
+///
+/// Clients deserialize this, so both derives are used.
+#[derive(Debug, Serialize, Deserialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct CreateAgentSessionResponse {
+ /// The created session.
+ pub session: AgentSessionResponse,
+}
+
+/// What the 409 from `POST /agent-sessions` says when a thread already
+/// routes to a session.
+const THREAD_SESSION_EXISTS_MESSAGE: &str = "this bot already has a session for this thread";
+
+/// Body of the 409 answered by `POST /agent-sessions` when the request's
+/// thread already routes to one of this bot's sessions.
+///
+/// Clients deserialize this, so both derives are used.
+#[derive(Debug, Serialize, Deserialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct ThreadSessionExistsResponse {
+ /// Human-readable explanation.
+ pub message: String,
+ /// The session the thread already routes to, when it could be resolved.
+ #[serde(default)]
+ #[schema(value_type = Option<String>)]
+ pub session_id: Option<AgentSessionId>,
+}
+
+/// Transport error for the create route.
+#[derive(Debug)]
+pub enum CreateSessionApiError {
+ /// The request named no usable bot.
+ BotRequired,
+ /// The named bot does not exist.
+ UnknownBot,
+ /// The caller may not open sessions for this bot.
+ NotYourBot,
+ /// The bot is not an agent bot.
+ NotAnAgentBot,
+ /// The bot's sessions are opened by the trigger pipeline, not this route.
+ ManagedBot,
+ /// The caller identified no user to own the session.
+ OwnerRequired,
+ /// The owner is not a parseable user id.
+ UnparseableOwner,
+ /// The workspace is not an acceptable path.
+ InvalidWorkspace(&'static str),
+ /// The thread already routes to a session; carries it for recovery.
+ ThreadSessionExists {
+ /// The existing session, when it could be resolved.
+ session_id: Option<AgentSessionId>,
+ },
+ /// The domain rejected the open.
+ Domain(AgentSessionError),
+}
+
+impl From<AgentSessionError> for CreateSessionApiError {
+ fn from(error: AgentSessionError) -> Self {
+ Self::Domain(error)
+ }
+}
+
+impl IntoResponse for CreateSessionApiError {
+ fn into_response(self) -> Response {
+ let (status, message) = match self {
+ Self::BotRequired => (
+ StatusCode::UNPROCESSABLE_ENTITY,
+ "botId is required for user callers".to_owned(),
+ ),
+ Self::UnknownBot => (StatusCode::NOT_FOUND, "no such bot".to_owned()),
+ Self::NotYourBot => (
+ StatusCode::FORBIDDEN,
+ "you may not open sessions for this bot".to_owned(),
+ ),
+ Self::NotAnAgentBot => (
+ StatusCode::UNPROCESSABLE_ENTITY,
+ "this bot does not run an agent".to_owned(),
+ ),
+ Self::ManagedBot => (
+ StatusCode::UNPROCESSABLE_ENTITY,
+ "this bot's sessions are opened by the trigger pipeline".to_owned(),
+ ),
+ Self::OwnerRequired => (
+ StatusCode::UNPROCESSABLE_ENTITY,
+ "owner is required for bot callers".to_owned(),
+ ),
+ Self::UnparseableOwner => (
+ StatusCode::UNPROCESSABLE_ENTITY,
+ "owner is not a user id".to_owned(),
+ ),
+ Self::InvalidWorkspace(reason) => (StatusCode::UNPROCESSABLE_ENTITY, reason.to_owned()),
+ Self::ThreadSessionExists { session_id } => {
+ let body = ThreadSessionExistsResponse {
+ message: THREAD_SESSION_EXISTS_MESSAGE.to_owned(),
+ session_id,
+ };
+ return (StatusCode::CONFLICT, Json(body)).into_response();
+ }
+ Self::Domain(AgentSessionError::ThreadSessionExists) => (
+ StatusCode::CONFLICT,
+ "this bot already has a session for this thread".to_owned(),
+ ),
+ Self::Domain(AgentSessionError::UnknownOwner) => (
+ StatusCode::UNPROCESSABLE_ENTITY,
+ "owner is not a known user".to_owned(),
+ ),
+ Self::Domain(error) => {
+ tracing::error!(error = ?error, "failed to open an agent session");
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ "failed to open the session".to_owned(),
+ )
+ }
+ };
+ (status, message).into_response()
+ }
+}
+
+/// Reject paths a harness cannot meaningfully run in. Rejection over
+/// normalization: a runtime that sends a relative path is confused about its
+/// own filesystem, and no server-side guess fixes that.
+fn validate_workspace(workspace: &str) -> Result<(), CreateSessionApiError> {
+ if !workspace.starts_with('/') {
+ return Err(CreateSessionApiError::InvalidWorkspace(
+ "workspace must be an absolute path",
+ ));
+ }
+ if workspace.len() > 4096 {
+ return Err(CreateSessionApiError::InvalidWorkspace(
+ "workspace is too long",
+ ));
+ }
+ if workspace.contains('\0') {
+ return Err(CreateSessionApiError::InvalidWorkspace(
+ "workspace must not contain NUL",
+ ));
+ }
+ if workspace.len() > 1 && workspace.ends_with('/') {
+ return Err(CreateSessionApiError::InvalidWorkspace(
+ "workspace must not end with a slash",
+ ));
+ }
+ Ok(())
+}
+
+/// Resolve which bot the session runs for, from the principal and the body.
+fn resolve_bot(
+ caller: &UserOrBotAuthorization,
+ body_bot: Option<Uuid>,
+) -> Result<BotId, CreateSessionApiError> {
+ match caller {
+ UserOrBotAuthorization::Bot(bot) => match body_bot {
+ Some(named) if named != bot.bot_id.as_uuid() => Err(CreateSessionApiError::NotYourBot),
+ _ => Ok(bot.bot_id),
+ },
+ UserOrBotAuthorization::User(_) => body_bot
+ .map(BotId::new_from_uuid)
+ .ok_or(CreateSessionApiError::BotRequired),
+ }
+}
+
+/// Resolve the user who owns the session.
+///
+/// A user caller always owns their own sessions. A bot caller's verified
+/// acting user wins when present; otherwise the body's claimed owner is
+/// accepted (see [`CreateAgentSessionRequest::owner`] for the trust model).
+fn resolve_owner(
+ caller: &UserOrBotAuthorization,
+ claimed: Option<String>,
+) -> Result<MacroUserIdStr<'static>, CreateSessionApiError> {
+ if let Some(user) = caller.acting_user() {
+ return Ok(user.macro_user_id.clone());
+ }
+ let claimed = claimed.ok_or(CreateSessionApiError::OwnerRequired)?;
+ MacroUserIdStr::try_from(claimed).map_err(|_| CreateSessionApiError::UnparseableOwner)
+}
+
+#[utoipa::path(
+ post,
+ path = "/agent-sessions",
+ tag = "agent-sessions",
+ operation_id = "create_agent_session",
+ request_body = CreateAgentSessionRequest,
+ responses(
+ (status = 201, body = CreateAgentSessionResponse),
+ (status = 401, body = String),
+ (status = 403, body = String),
+ (status = 404, body = String),
+ (status = 422, body = String),
+ (status = 500, body = String),
+ )
+)]
+/// Open an agent session served by an external runtime.
+///
+/// Nothing here tells the runtime where to dial: one connection per bot
+/// carries every session it runs, so a runtime that has already dialed serves
+/// this session too, and one that has not dials the gateway its own
+/// configuration names. The triggering mention reaches the session as its
+/// first prompt through the control endpoint.
+#[tracing::instrument(skip_all, err(Debug))]
+pub async fn create_agent_session_handler<
+ Opener: ExternalSessionOpener,
+ Bots: BotDirectory,
+ Auth: MacroAuthorizationService,
+>(
+ State(state): State<CreateSessionState<Opener, Bots, Auth>>,
+ caller: MacroAuthorizationExtractor<Auth, UserOrBot>,
+ Json(request): Json<CreateAgentSessionRequest>,
+) -> Result<(StatusCode, Json<CreateAgentSessionResponse>), CreateSessionApiError> {
+ let bot_id = resolve_bot(&caller.authorization, request.bot_id)?;
+
+ let BotFacts {
+ has_agent,
+ is_managed,
+ owner_user_id,
+ } = state
+ .bots
+ .bot_facts(bot_id)
+ .await?
+ .ok_or(CreateSessionApiError::UnknownBot)?;
+ if !has_agent {
+ return Err(CreateSessionApiError::NotAnAgentBot);
+ }
+ if is_managed {
+ return Err(CreateSessionApiError::ManagedBot);
+ }
+ // A team-owned bot has no owner_user_id, so no user token passes this
+ // check: its sessions are opened with the bot's own token until team
+ // membership is modeled here.
+ if let UserOrBotAuthorization::User(user) = &caller.authorization
+ && owner_user_id.as_ref() != Some(&user.macro_user_id)
+ {
+ return Err(CreateSessionApiError::NotYourBot);
+ }
+
+ validate_workspace(&request.workspace)?;
+ let owner = resolve_owner(&caller.authorization, request.owner)?;
+
+ let thread = request.thread.map(|thread| SessionThread {
+ channel_id: thread.channel_id,
+ thread_id: thread.thread_id.unwrap_or(thread.message_id),
+ message_id: thread.message_id,
+ content: thread.content,
+ });
+ let session = match state
+ .opener
+ .open_external_session(OpenExternalAgentSession {
+ bot_id,
+ workspace: request.workspace,
+ repo_url: request.repo_url,
+ owner,
+ thread: thread.clone(),
+ })
+ .await
+ {
+ Ok(session) => session,
+ // A conflicted open answers with the session the thread already
+ // routes to, so a redelivered trigger can resume serving it
+ // instead of being dropped.
+ Err(AgentSessionError::ThreadSessionExists) => {
+ let session_id = match thread {
+ Some(thread) => state
+ .opener
+ .find_thread_session(thread.thread_id, bot_id)
+ .await
+ .unwrap_or_default(),
+ None => None,
+ };
+ return Err(CreateSessionApiError::ThreadSessionExists { session_id });
+ }
+ Err(error) => return Err(error.into()),
+ };
+
+ Ok((
+ StatusCode::CREATED,
+ Json(CreateAgentSessionResponse {
+ session: session.into(),
+ }),
+ ))
+}
diff --git a/crates/agent_session/src/inbound/axum_router/test.rs b/crates/agent_session/src/inbound/axum_router/test.rs
new file mode 100644
index 0000000000..2bf91c7ea2
--- /dev/null
+++ b/crates/agent_session/src/inbound/axum_router/test.rs
@@ -0,0 +1,360 @@
+use super::*;
+use crate::domain::model::SessionStatus;
+use axum::body::Body;
+use axum::http::{Request, header};
+use chrono::Utc;
+use macro_authorization::{
+ BOT_SCOPE_HEADER, BOT_TOKEN_HEADER, BotActingUserClaims, BotAuthentication, BotAuthorizer,
+ BotScope, InternalAuthConfig, JwtValidator, MacroAuthorizationError,
+ MacroAuthorizationServiceImpl, ValidatedIdentity,
+};
+use rootcause::Report;
+use std::sync::{Arc, Mutex};
+use tower::ServiceExt;
+
+const BOT_TOKEN: &str = "mbot_self_test";
+const OWNER: &str = "macro|[email protected]";
+const STRANGER: &str = "macro|[email protected]";
+
+#[derive(Clone, Default)]
+struct FakeJwtValidator;
+
+impl JwtValidator for FakeJwtValidator {
+ fn validate(&self, jwt: &str) -> Result<ValidatedIdentity, Report<MacroAuthorizationError>> {
+ Ok(ValidatedIdentity {
+ user_id: jwt.to_string(),
+ fusion_user_id: "fusion-user".to_string(),
+ organization_id: None,
+ permissions: None,
+ })
+ }
+}
+
+/// Accepts exactly [`BOT_TOKEN`] as [`BotId::TEST_A`].
+#[derive(Clone)]
+struct SelfBotAuthorizer;
+
+impl BotAuthorizer for SelfBotAuthorizer {
+ async fn authorize_bot(
+ &self,
+ bot_token: &str,
+ bot_scope: BotScope,
+ _acting_user: Option<BotActingUserClaims>,
+ ) -> Result<BotAuthentication, Report<MacroAuthorizationError>> {
+ if bot_token != BOT_TOKEN {
+ return Err(Report::new(MacroAuthorizationError::InvalidCredentials));
+ }
+ Ok(BotAuthentication {
+ bot_id: BotId::TEST_A,
+ token_id: Uuid::new_v4(),
+ bot_scope,
+ team_id: None,
+ acting_user: None,
+ })
+ }
+}
+
+/// Records opens and answers with a canned session row.
+#[derive(Default)]
+struct RecordingOpener {
+ opened: Mutex<Vec<OpenExternalAgentSession>>,
+}
+
+impl ExternalSessionOpener for RecordingOpener {
+ async fn open_external_session(
+ &self,
+ request: OpenExternalAgentSession,
+ ) -> crate::domain::error::Result<AgentSession> {
+ let session = AgentSession {
+ id: AgentSessionId::TEST_A,
+ owner_id: request.owner.clone(),
+ thread_id: request.thread.as_ref().map(|thread| thread.thread_id),
+ thread_channel_id: request.thread.as_ref().map(|thread| thread.channel_id),
+ originating_message_id: request.thread.as_ref().map(|thread| thread.message_id),
+ bot_id: request.bot_id,
+ model: "claude".to_owned(),
+ harness: "opencode".to_owned(),
+ repo_url: request.repo_url.clone(),
+ workspace: request.workspace.clone(),
+ acp_session_id: None,
+ status: SessionStatus::NoMessages,
+ created_at: Utc::now(),
+ modified_at: Utc::now(),
+ };
+ self.opened.lock().unwrap().push(request);
+ Ok(session)
+ }
+
+ async fn find_thread_session(
+ &self,
+ _thread_id: Uuid,
+ _bot_id: BotId,
+ ) -> crate::domain::error::Result<Option<AgentSessionId>> {
+ Ok(None)
+ }
+}
+
+/// Serves one canned bot: [`BotId::TEST_A`], an external agent bot owned by
+/// [`OWNER`]. Every other id is unknown.
+struct OneBotDirectory {
+ facts: BotFacts,
+}
+
+impl OneBotDirectory {
+ fn external_agent() -> Self {
+ Self {
+ facts: BotFacts {
+ has_agent: true,
+ is_managed: false,
+ owner_user_id: Some(MacroUserIdStr::try_from(OWNER.to_owned()).unwrap()),
+ },
+ }
+ }
+
+ fn managed_agent() -> Self {
+ Self {
+ facts: BotFacts {
+ has_agent: true,
+ is_managed: true,
+ owner_user_id: None,
+ },
+ }
+ }
+
+ fn plain_bot() -> Self {
+ Self {
+ facts: BotFacts {
+ has_agent: false,
+ is_managed: false,
+ owner_user_id: Some(MacroUserIdStr::try_from(OWNER.to_owned()).unwrap()),
+ },
+ }
+ }
+}
+
+impl BotDirectory for OneBotDirectory {
+ async fn bot_facts(&self, bot: BotId) -> crate::domain::error::Result<Option<BotFacts>> {
+ Ok((bot == BotId::TEST_A).then(|| self.facts.clone()))
+ }
+}
+
+fn router_for(opener: Arc<RecordingOpener>, bots: OneBotDirectory) -> Router {
+ let service = MacroAuthorizationServiceImpl::new(
+ FakeJwtValidator,
+ InternalAuthConfig {
+ api_key: "test-internal-key".to_string(),
+ default_user_id: None,
+ },
+ SelfBotAuthorizer,
+ );
+ agent_session_create_router(CreateSessionState::new(
+ opener,
+ Arc::new(bots),
+ MacroAuthorizationState::new(Arc::new(service)),
+ ))
+}
+
+fn router(opener: Arc<RecordingOpener>) -> Router {
+ router_for(opener, OneBotDirectory::external_agent())
+}
+
+fn body(bot_id: Option<Uuid>, workspace: &str, owner: Option<&str>) -> String {
+ serde_json::json!({
+ "botId": bot_id,
+ "workspace": workspace,
+ "owner": owner,
+ "thread": {
+ "channelId": "00000000-0000-0000-0000-000000000001",
+ "messageId": "00000000-0000-0000-0000-000000000002",
+ "content": "fix the flaky test",
+ },
+ })
+ .to_string()
+}
+
+fn as_bot(request_body: String) -> Request<Body> {
+ Request::post("/")
+ .header(header::CONTENT_TYPE, "application/json")
+ .header(BOT_TOKEN_HEADER, BOT_TOKEN)
+ .header(BOT_SCOPE_HEADER, "user")
+ .body(Body::from(request_body))
+ .unwrap()
+}
+
+fn as_user(user: &str, request_body: String) -> Request<Body> {
+ Request::post("/")
+ .header(header::CONTENT_TYPE, "application/json")
+ .header(header::AUTHORIZATION, format!("Bearer {user}"))
+ .body(Body::from(request_body))
+ .unwrap()
+}
+
+#[tokio::test]
+async fn a_bot_opens_an_external_session_for_itself() {
+ let opener = Arc::new(RecordingOpener::default());
+ let request = as_bot(body(None, "/home/wolf/code", Some(OWNER)));
+
+ let response = router(opener.clone()).oneshot(request).await.unwrap();
+
+ assert_eq!(response.status(), StatusCode::CREATED);
+ let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let payload: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
+ assert_eq!(payload["session"]["workspace"], "/home/wolf/code");
+
+ let opened = opener.opened.lock().unwrap();
+ assert_eq!(opened.len(), 1);
+ assert_eq!(opened[0].bot_id, BotId::TEST_A);
+ assert_eq!(opened[0].workspace, "/home/wolf/code");
+ // A top-level mention roots its own thread.
+ let thread = opened[0].thread.as_ref().expect("thread linkage was given");
+ assert_eq!(thread.thread_id, thread.message_id);
+ assert_eq!(thread.content, "fix the flaky test");
+}
+
+#[tokio::test]
+async fn a_session_may_have_no_thread_at_all() {
+ let opener = Arc::new(RecordingOpener::default());
+ let request =
+ as_bot(serde_json::json!({ "workspace": "/srv/agent", "owner": OWNER }).to_string());
+
+ let response = router(opener.clone()).oneshot(request).await.unwrap();
+
+ assert_eq!(response.status(), StatusCode::CREATED);
+ assert!(opener.opened.lock().unwrap()[0].thread.is_none());
+}
+
+#[tokio::test]
+async fn the_owner_opens_a_session_for_their_bot() {
+ let opener = Arc::new(RecordingOpener::default());
+ let request = as_user(
+ OWNER,
+ body(Some(BotId::TEST_A.as_uuid()), "/srv/agent", None),
+ );
+
+ let response = router(opener.clone()).oneshot(request).await.unwrap();
+
+ assert_eq!(response.status(), StatusCode::CREATED);
+ // The caller owns their own session; no claimed owner needed.
+ let opened = opener.opened.lock().unwrap();
+ assert_eq!(opened[0].owner.as_ref(), OWNER);
+}
+
+#[tokio::test]
+async fn a_stranger_may_not_open_sessions_for_someone_elses_bot() {
+ let opener = Arc::new(RecordingOpener::default());
+ let request = as_user(
+ STRANGER,
+ body(Some(BotId::TEST_A.as_uuid()), "/srv/agent", None),
+ );
+
+ let response = router(opener.clone()).oneshot(request).await.unwrap();
+
+ assert_eq!(response.status(), StatusCode::FORBIDDEN);
+ assert!(opener.opened.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn a_bot_may_not_name_another_bot() {
+ let opener = Arc::new(RecordingOpener::default());
+ let request = as_bot(body(
+ Some(BotId::TEST_B.as_uuid()),
+ "/srv/agent",
+ Some(OWNER),
+ ));
+
+ let response = router(opener.clone()).oneshot(request).await.unwrap();
+
+ assert_eq!(response.status(), StatusCode::FORBIDDEN);
+ assert!(opener.opened.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn a_user_caller_must_name_a_bot() {
+ let opener = Arc::new(RecordingOpener::default());
+ let request = as_user(OWNER, body(None, "/srv/agent", None));
+
+ let response = router(opener.clone()).oneshot(request).await.unwrap();
+
+ assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
+ assert!(opener.opened.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn a_bot_caller_must_claim_an_owner() {
+ let opener = Arc::new(RecordingOpener::default());
+ let request = as_bot(body(None, "/srv/agent", None));
+
+ let response = router(opener.clone()).oneshot(request).await.unwrap();
+
+ assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
+ assert!(opener.opened.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn a_relative_workspace_is_rejected() {
+ let opener = Arc::new(RecordingOpener::default());
+ let request = as_bot(body(None, "code/agent", Some(OWNER)));
+
+ let response = router(opener.clone()).oneshot(request).await.unwrap();
+
+ assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
+ assert!(opener.opened.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn a_managed_bots_sessions_are_not_openable_here() {
+ let opener = Arc::new(RecordingOpener::default());
+ let request = as_bot(body(None, "/srv/agent", Some(OWNER)));
+
+ let response = router_for(opener.clone(), OneBotDirectory::managed_agent())
+ .oneshot(request)
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
+ assert!(opener.opened.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn a_bot_without_an_agent_is_rejected() {
+ let opener = Arc::new(RecordingOpener::default());
+ let request = as_bot(body(None, "/srv/agent", Some(OWNER)));
+
+ let response = router_for(opener.clone(), OneBotDirectory::plain_bot())
+ .oneshot(request)
+ .await
+ .unwrap();
+
+ assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
+ assert!(opener.opened.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn an_unauthenticated_request_is_rejected() {
+ let opener = Arc::new(RecordingOpener::default());
+ let request = Request::post("/")
+ .header(header::CONTENT_TYPE, "application/json")
+ .body(Body::from(body(None, "/srv/agent", Some(OWNER))))
+ .unwrap();
+
+ let response = router(opener.clone()).oneshot(request).await.unwrap();
+
+ assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
+ assert!(opener.opened.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn an_unknown_bot_is_a_404() {
+ let opener = Arc::new(RecordingOpener::default());
+ let request = as_user(
+ OWNER,
+ body(Some(BotId::TEST_B.as_uuid()), "/srv/agent", None),
+ );
+
+ let response = router(opener.clone()).oneshot(request).await.unwrap();
+
+ assert_eq!(response.status(), StatusCode::NOT_FOUND);
+ assert!(opener.opened.lock().unwrap().is_empty());
+}
diff --git a/crates/agent_session/src/lib.rs b/crates/agent_session/src/lib.rs
index a49c21211f..3ebd6d8256 100644
--- a/crates/agent_session/src/lib.rs
+++ b/crates/agent_session/src/lib.rs
@@ -8,7 +8,7 @@ pub mod outbound;
pub const PROTOCOL_VERSION: ProtocolVersion = ProtocolVersion::V1;
/// Physical directory inside the container where the agent works.
-pub const AGENT_WORKING_DIRECTORY: &str = "/workspace";
+pub const MANAGED_CONTAINER_WORKSPACE: &str = "/workspace";
/// In-memory port implementations for tests.
#[cfg(any(test, feature = "test-utils"))]
diff --git a/crates/agent_session/src/outbound/postgres/mod.rs b/crates/agent_session/src/outbound/postgres/mod.rs
index 621ea28f98..9ccb9b815c 100644
--- a/crates/agent_session/src/outbound/postgres/mod.rs
+++ b/crates/agent_session/src/outbound/postgres/mod.rs
@@ -5,7 +5,7 @@
#[cfg(test)]
mod test;
-use crate::domain::error::Result;
+use crate::domain::error::{AgentSessionError, Result};
use crate::domain::model::{
AgentSession, AgentSessionId, AgentSessionLog, ChannelSession, CreateAgentSessionParams,
Message, SessionBot, SessionStatus, StoredAgentSessionLog,
@@ -96,7 +96,8 @@ struct AgentSessionRow {
bot_id: Uuid,
model: String,
harness: String,
- repo_url: String,
+ repo_url: Option<String>,
+ workspace: String,
acp_session_id: Option<String>,
status: String,
status_event_name: Option<String>,
@@ -120,7 +121,8 @@ impl TryFrom<AgentSessionRow> for AgentSession {
model: row.model,
harness: row.harness,
repo_url: row.repo_url,
- acp_session_id: row.acp_session_id,
+ workspace: row.workspace,
+ acp_session_id: row.acp_session_id.map(Into::into),
status,
created_at: row.created_at,
modified_at: row.modified_at,
@@ -139,6 +141,7 @@ impl AgentSessionRepo for PgAgentSessionRepo {
model,
harness,
repo_url,
+ workspace,
} = params;
// The session row and its access grants land together: a crash between
@@ -156,13 +159,14 @@ impl AgentSessionRepo for PgAgentSessionRepo {
r#"
INSERT INTO agent_session (
id, owner_id, thread_id, originating_message_id, bot_id, model,
- harness, repo_url, acp_session_id, status, status_event_name
+ harness, repo_url, workspace, acp_session_id, status,
+ status_event_name
)
- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)
RETURNING
id, owner_id, thread_id, originating_message_id, bot_id,
- model, harness, repo_url, acp_session_id, status, status_event_name,
- created_at, modified_at,
+ model, harness, repo_url, workspace, acp_session_id, status,
+ status_event_name, created_at, modified_at,
(SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)
AS "thread_channel_id?"
"#,
@@ -174,13 +178,22 @@ impl AgentSessionRepo for PgAgentSessionRepo {
model,
harness,
repo_url,
+ workspace,
None::<String>,
status,
status_event_name,
)
.fetch_one(&mut *transaction)
.await
- .context("failed to create agent session")?;
+ .map_err(
+ |error| match error.as_database_error().and_then(|e| e.constraint()) {
+ Some("agent_session_thread_bot_unique") => AgentSessionError::ThreadSessionExists,
+ Some("agent_session_owner_id_fkey") => AgentSessionError::UnknownOwner,
+ _ => AgentSessionError::Unknown(
+ anyhow::Error::new(error).context("failed to create agent session"),
+ ),
+ },
+ )?;
insert_entity_access_row(
&mut transaction,
@@ -193,11 +206,11 @@ impl AgentSessionRepo for PgAgentSessionRepo {
.await
.context("failed to grant the owner access to the agent session")?;
- // The channel the bot was mentioned in can steer the session: the
+ // The channel the bot was invoked in can steer the session: the
// invocation was public there, so that audience is. Read from the
- // mention rather than taken as a parameter, so a caller cannot claim
- // a channel the mention did not happen in. A directly created
- // session has no mention, and so no inherited audience.
+ // message rather than taken from the caller, so the channel is always
+ // the one the message actually sits in. A session created without a
+ // message - directly, rather than from a channel - is its owner's alone.
let origin_channel_id = match originating_message_id {
Some(message_id) => sqlx::query_scalar!(
"SELECT channel_id FROM comms_messages WHERE id = $1",
@@ -236,8 +249,8 @@ impl AgentSessionRepo for PgAgentSessionRepo {
r#"
SELECT
id, owner_id, thread_id, originating_message_id, bot_id,
- model, harness, repo_url, acp_session_id, status, status_event_name,
- created_at, modified_at,
+ model, harness, repo_url, workspace, acp_session_id, status,
+ status_event_name, created_at, modified_at,
(SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)
AS "thread_channel_id?"
FROM agent_session
@@ -269,8 +282,8 @@ impl AgentSessionRepo for PgAgentSessionRepo {
r#"
SELECT
id, owner_id, thread_id, originating_message_id, bot_id,
- model, harness, repo_url, acp_session_id, status, status_event_name,
- created_at, modified_at,
+ model, harness, repo_url, workspace, acp_session_id, status,
+ status_event_name, created_at, modified_at,
(SELECT channel_id FROM comms_messages WHERE id = agent_session.thread_id)
AS "thread_channel_id?"
FROM agent_session
diff --git a/crates/agent_session/src/outbound/postgres/test.rs b/crates/agent_session/src/outbound/postgres/test.rs
index fdade07443..859d083d4d 100644
--- a/crates/agent_session/src/outbound/postgres/test.rs
+++ b/crates/agent_session/src/outbound/postgres/test.rs
@@ -67,6 +67,7 @@ async fn create_test_bot(pool: &PgPool) -> BotId {
handle: format!("test-agent-{}", macro_uuid::generate_uuid_v7()),
description: None,
avatar_url: None,
+ has_agent: None,
},
)
.await
@@ -87,7 +88,8 @@ fn new_session(
originating_message_id,
model: "claude-sonnet-5".to_string(),
harness: "claude-code".to_string(),
- repo_url: "https://github.com/example/example".to_string(),
+ repo_url: Some("https://github.com/example/example".to_string()),
+ workspace: "/workspace".to_string(),
}
}
@@ -198,7 +200,10 @@ async fn set_acp_session_id_updates_only_the_resume_identity(pool: PgPool) {
.expect("persist ACP session id");
let updated = repo.get(id).await.expect("get updated agent session");
- assert_eq!(updated.acp_session_id.as_deref(), Some("acp-session-1"));
+ assert_eq!(
+ updated.acp_session_id,
+ Some(SessionId::from("acp-session-1"))
+ );
assert!(matches!(
updated.status,
SessionStatus::Event(SystemEvent::AcpReady)
diff --git a/crates/agent_session/src/testing.rs b/crates/agent_session/src/testing.rs
index e8dd6db641..e611eb490e 100644
--- a/crates/agent_session/src/testing.rs
+++ b/crates/agent_session/src/testing.rs
@@ -109,6 +109,7 @@ impl AgentSessionRepo for InMemoryAgentSessionRepo {
model: params.model,
harness: params.harness,
repo_url: params.repo_url,
+ workspace: params.workspace,
acp_session_id: None,
status: SessionStatus::default(),
created_at: now,
@@ -171,7 +172,7 @@ impl AgentSessionRepo for InMemoryAgentSessionRepo {
let session = sessions.get_mut(&id).ok_or_else(|| {
AgentSessionError::Unknown(anyhow::anyhow!("no agent session {}", id.as_uuid()))
})?;
- session.acp_session_id = Some(acp_session_id.to_string());
+ session.acp_session_id = Some(acp_session_id);
session.modified_at = chrono::Utc::now();
Ok(())
}
@@ -243,7 +244,7 @@ impl AgentSessionLogRepo for InMemoryAgentSessionRepo {
.lock()
.expect("in-memory session store is not poisoned")
.get_mut(&session_id)
- && session.acp_session_id.as_deref() == Some(acp_session_id.to_string().as_str())
+ && session.acp_session_id.as_ref() == Some(&acp_session_id)
{
session.model = change.model;
session.modified_at = chrono::Utc::now();
@@ -297,7 +298,8 @@ pub fn test_agent_session(id: AgentSessionId) -> AgentSession {
bot_id: BotId::new_from_uuid(Uuid::from_u128(0xb07)),
model: "claude-sonnet-5".to_string(),
harness: "claude-code".to_string(),
- repo_url: "https://github.com/example/example".to_string(),
+ repo_url: Some("https://github.com/example/example".to_string()),
+ workspace: "/workspace".to_string(),
acp_session_id: None,
status: SessionStatus::NoMessages,
created_at: now,
diff --git a/crates/agent_trigger/Cargo.toml b/crates/agent_trigger/Cargo.toml
index a4201262ab..bf307d89e2 100644
--- a/crates/agent_trigger/Cargo.toml
+++ b/crates/agent_trigger/Cargo.toml
@@ -9,12 +9,17 @@ agent_session = { path = "../agent_session" }
bot_id = { path = "../bot_id" }
channels = { path = "../channels", features = ["ports"] }
chrono = { workspace = true }
-macro_event_broker = { path = "../macro_event_broker", features = ["outbound"] }
+# Only the domain vocabulary (`Event`, `MacroEvent`, `TopicEvent`). Asking for
+# `outbound` here would pull rdkafka — and so librdkafka and openssl — into
+# every consumer of this crate, including the self-hosted daemon, which
+# publishes nothing and has to link statically.
+macro_event_broker = { path = "../macro_event_broker", default-features = false }
macro_event_topics = { path = "../macro_event_topics" }
macro_user_id = { path = "../macro_user_id" }
channel_sender = { path = "../channel_sender" }
macro_uuid = { path = "../macro_uuid" }
serde = { workspace = true }
+strum = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
tracing = { workspace = true }
diff --git a/crates/agent_trigger/src/domain/broker_events.rs b/crates/agent_trigger/src/domain/broker_events.rs
index 2eea88db97..bda3cb1125 100644
--- a/crates/agent_trigger/src/domain/broker_events.rs
+++ b/crates/agent_trigger/src/domain/broker_events.rs
@@ -49,14 +49,25 @@ pub enum ExistingAgentSessionEvent {
}
/// Events publishable to [`MacroAgentSessionsTopic`].
-#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+///
+/// The serde tag and [`AgentTriggerEventName`] spell the same wire names:
+/// subscribers filter on them, so they are API. `event_names_match_the_wire`
+/// holds the two in step.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, strum::EnumDiscriminants)]
#[serde(tag = "event_type", content = "metadata")]
+#[strum_discriminants(
+ name(AgentTriggerEventName),
+ derive(strum::Display, strum::EnumIter, strum::IntoStaticStr),
+ doc = "The wire name of an [`AgentTriggerTopicEvent`], as subscribers filter on it."
+)]
pub enum AgentTriggerTopicEvent {
/// Open a session.
#[serde(rename = "agent_trigger.new")]
+ #[strum_discriminants(strum(serialize = "agent_trigger.new"))]
New(NewAgentSessionEvent),
/// Feed a session that already exists.
#[serde(rename = "agent_trigger.existing")]
+ #[strum_discriminants(strum(serialize = "agent_trigger.existing"))]
Existing(ExistingAgentSessionEvent),
}
diff --git a/crates/agent_trigger/src/domain/broker_events/test.rs b/crates/agent_trigger/src/domain/broker_events/test.rs
index 459a0b85e3..c9e45bda48 100644
--- a/crates/agent_trigger/src/domain/broker_events/test.rs
+++ b/crates/agent_trigger/src/domain/broker_events/test.rs
@@ -62,3 +62,34 @@ fn serializes_an_existing_channel_event() {
json!(AgentSessionId::TEST_A)
);
}
+
+#[test]
+fn event_names_match_the_wire() {
+ use strum::IntoEnumIterator as _;
+
+ // Subscribers filter on these names, so the serde tag is the contract and
+ // `AgentTriggerEventName` must agree with it variant for variant.
+ let wire_names: Vec<String> = [
+ AgentTriggerTopicEvent::New(NewAgentSessionEvent::TopLevelMentioned(
+ AgentBotMentionedEvent {
+ bot_id: BotId::TEST_A,
+ message: message(),
+ },
+ )),
+ AgentTriggerTopicEvent::Existing(ExistingAgentSessionEvent::Channel(
+ ChannelEventMetadata {
+ bot_id: BotId::TEST_A,
+ session_id: AgentSessionId::TEST_A,
+ message: message(),
+ },
+ )),
+ ]
+ .into_iter()
+ .map(|event| serde_json::to_value(event).expect("serialize event")["event_type"].to_string())
+ .collect();
+ let names: Vec<String> = AgentTriggerEventName::iter()
+ .map(|name| serde_json::Value::String(name.to_string()).to_string())
+ .collect();
+
+ assert_eq!(names, wire_names);
+}
diff --git a/crates/agent_trigger/src/domain/service/test.rs b/crates/agent_trigger/src/domain/service/test.rs
index 40b12882c3..808d1bca3b 100644
--- a/crates/agent_trigger/src/domain/service/test.rs
+++ b/crates/agent_trigger/src/domain/service/test.rs
@@ -52,7 +52,8 @@ fn session(id: AgentSessionId, bot_id: BotId) -> AgentSession {
bot_id,
model: "model".to_owned(),
harness: "harness".to_owned(),
- repo_url: "https://example.com/repo".to_owned(),
+ repo_url: Some("https://example.com/repo".to_owned()),
+ workspace: "/workspace".to_owned(),
acp_session_id: None,
status: SessionStatus::NoMessages,
created_at: Utc::now(),
diff --git a/crates/bots/src/domain/models.rs b/crates/bots/src/domain/models.rs
index 5c5f4c5e84..277f0d0f72 100644
--- a/crates/bots/src/domain/models.rs
+++ b/crates/bots/src/domain/models.rs
@@ -100,6 +100,8 @@ pub enum BotOwner {
}
/// Bot row.
+///
+/// Clients deserialize this, so both derives are used.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
pub struct Bot {
@@ -208,6 +210,8 @@ pub struct CreateBotRequest {
pub description: Option<String>,
/// Optional avatar URL.
pub avatar_url: Option<String>,
+ /// Whether mentioning this bot opens a sandboxed coding-agent session. Defaults to false.
+ pub has_agent: Option<bool>,
}
/// Request to patch a bot.
@@ -222,6 +226,8 @@ pub struct PatchBotRequest {
pub description: Option<String>,
/// Optional avatar URL.
pub avatar_url: Option<String>,
+ /// Whether mentioning this bot opens a sandboxed coding-agent session. Omit to leave unchanged.
+ pub has_agent: Option<bool>,
}
/// Request to create a bot token.
@@ -260,6 +266,8 @@ pub struct CreateChannelScopedBotRequest {
pub token_label: Option<String>,
/// Optional token expiration timestamp.
pub token_expires_at: Option<DateTime<Utc>>,
+ /// Whether mentioning this bot opens a sandboxed coding-agent session. Defaults to false.
+ pub has_agent: Option<bool>,
}
/// Response containing a newly minted token.
diff --git a/crates/bots/src/inbound/axum_router/tests.rs b/crates/bots/src/inbound/axum_router/tests.rs
index 134f69e574..e5a3a61307 100644
--- a/crates/bots/src/inbound/axum_router/tests.rs
+++ b/crates/bots/src/inbound/axum_router/tests.rs
@@ -826,6 +826,7 @@ async fn bot_owner_can_list_and_remove_bot_channels_via_bot_routes(
handle: "bot-route-alerts".to_string(),
description: Some("Posts alarm notifications".to_string()),
avatar_url: None,
+ has_agent: None,
},
)
.await?;
@@ -912,6 +913,7 @@ async fn channel_admin_can_add_and_remove_owned_bot_via_http(pool: PgPool) -> an
handle: "datadog-alerts".to_string(),
description: Some("Posts alarm notifications".to_string()),
avatar_url: None,
+ has_agent: None,
},
)
.await?;
@@ -973,3 +975,96 @@ async fn channel_admin_can_add_and_remove_owned_bot_via_http(pool: PgPool) -> an
Ok(())
}
+
+async fn read_bot(response: axum::response::Response) -> Bot {
+ let body = axum::body::to_bytes(response.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ serde_json::from_slice(&body).unwrap()
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn bot_owner_can_create_and_patch_has_agent_via_http(pool: PgPool) -> anyhow::Result<()> {
+ const BOT_OWNER_ID: &str = "macro|[email protected]";
+ insert_user(&pool, BOT_OWNER_ID).await?;
+ let router = real_router(pool, BOT_OWNER_ID);
+
+ let create_agent_request = Request::builder()
+ .method("POST")
+ .uri("/bots")
+ .header("content-type", "application/json")
+ .body(Body::from(
+ serde_json::json!({
+ "name": "Agent Bot",
+ "handle": "agent-bot",
+ "has_agent": true,
+ })
+ .to_string(),
+ ))
+ .unwrap();
+
+ let create_agent_response = router.clone().oneshot(create_agent_request).await.unwrap();
+ assert_eq!(create_agent_response.status(), StatusCode::CREATED);
+ assert!(read_bot(create_agent_response).await.has_agent);
+
+ let create_plain_request = Request::builder()
+ .method("POST")
+ .uri("/bots")
+ .header("content-type", "application/json")
+ .body(Body::from(
+ serde_json::json!({
+ "name": "Plain Bot",
+ "handle": "plain-bot",
+ })
+ .to_string(),
+ ))
+ .unwrap();
+
+ let create_plain_response = router.clone().oneshot(create_plain_request).await.unwrap();
+ assert_eq!(create_plain_response.status(), StatusCode::CREATED);
+ let plain_bot = read_bot(create_plain_response).await;
+ assert!(!plain_bot.has_agent);
+
+ let enable_request = Request::builder()
+ .method("PATCH")
+ .uri(format!("/bots/{}", plain_bot.id))
+ .header("content-type", "application/json")
+ .body(Body::from(
+ serde_json::json!({ "has_agent": true }).to_string(),
+ ))
+ .unwrap();
+
+ let enable_response = router.clone().oneshot(enable_request).await.unwrap();
+ assert_eq!(enable_response.status(), StatusCode::OK);
+ assert!(read_bot(enable_response).await.has_agent);
+
+ let rename_request = Request::builder()
+ .method("PATCH")
+ .uri(format!("/bots/{}", plain_bot.id))
+ .header("content-type", "application/json")
+ .body(Body::from(
+ serde_json::json!({ "name": "Renamed Bot" }).to_string(),
+ ))
+ .unwrap();
+
+ let rename_response = router.clone().oneshot(rename_request).await.unwrap();
+ assert_eq!(rename_response.status(), StatusCode::OK);
+ let renamed_bot = read_bot(rename_response).await;
+ assert_eq!(renamed_bot.name, "Renamed Bot");
+ assert!(renamed_bot.has_agent);
+
+ let disable_request = Request::builder()
+ .method("PATCH")
+ .uri(format!("/bots/{}", plain_bot.id))
+ .header("content-type", "application/json")
+ .body(Body::from(
+ serde_json::json!({ "has_agent": false }).to_string(),
+ ))
+ .unwrap();
+
+ let disable_response = router.oneshot(disable_request).await.unwrap();
+ assert_eq!(disable_response.status(), StatusCode::OK);
+ assert!(!read_bot(disable_response).await.has_agent);
+
+ Ok(())
+}
diff --git a/crates/bots/src/outbound/pg_bots_repo.rs b/crates/bots/src/outbound/pg_bots_repo.rs
index ed238e4962..c349ee6dd5 100644
--- a/crates/bots/src/outbound/pg_bots_repo.rs
+++ b/crates/bots/src/outbound/pg_bots_repo.rs
@@ -207,9 +207,10 @@ impl BotRepo for PgBotsRepo {
BotRow,
r#"
INSERT INTO bots (
- id, kind, owner_user_id, team_id, name, handle, description, avatar_url, created_by
+ id, kind, owner_user_id, team_id, name, handle, description, avatar_url,
+ created_by, has_agent
)
- VALUES ($1, 'owned', $2, $3, $4, $5, $6, $7, $8)
+ VALUES ($1, 'owned', $2, $3, $4, $5, $6, $7, $8, COALESCE($9, false))
RETURNING
id,
kind,
@@ -233,6 +234,7 @@ impl BotRepo for PgBotsRepo {
req.description,
req.avatar_url,
created_by.as_ref(),
+ req.has_agent,
)
.fetch_one(&self.pool)
.await
@@ -262,9 +264,10 @@ impl BotRepo for PgBotsRepo {
BotRow,
r#"
INSERT INTO bots (
- id, kind, owner_user_id, team_id, name, handle, description, avatar_url, created_by
+ id, kind, owner_user_id, team_id, name, handle, description, avatar_url,
+ created_by, has_agent
)
- VALUES ($1, 'owned', $2, $3, $4, $5, $6, $7, $8)
+ VALUES ($1, 'owned', $2, $3, $4, $5, $6, $7, $8, COALESCE($9, false))
RETURNING
id,
kind,
@@ -288,6 +291,7 @@ impl BotRepo for PgBotsRepo {
req.description,
req.avatar_url,
created_by.as_ref(),
+ req.has_agent,
)
.fetch_one(&mut *tx)
.await
@@ -487,6 +491,7 @@ impl BotRepo for PgBotsRepo {
handle = COALESCE($3, handle),
description = COALESCE($4, description),
avatar_url = COALESCE($5, avatar_url),
+ has_agent = COALESCE($6, has_agent),
updated_at = now()
WHERE id = $1
AND deleted_at IS NULL
@@ -510,6 +515,7 @@ impl BotRepo for PgBotsRepo {
req.handle,
req.description,
req.avatar_url,
+ req.has_agent,
)
.fetch_optional(&self.pool)
.await
diff --git a/crates/bots/src/outbound/pg_bots_repo/tests.rs b/crates/bots/src/outbound/pg_bots_repo/tests.rs
index f14a195d7d..75ee032f86 100644
--- a/crates/bots/src/outbound/pg_bots_repo/tests.rs
+++ b/crates/bots/src/outbound/pg_bots_repo/tests.rs
@@ -30,6 +30,7 @@ fn create_req(handle: &str) -> CreateBotRequest {
handle: handle.to_string(),
description: Some("Posts alarm notifications".to_string()),
avatar_url: None,
+ has_agent: None,
}
}
@@ -42,6 +43,7 @@ fn create_channel_scoped_req(handle: &str) -> CreateChannelScopedBotRequest {
avatar_url: None,
token_label: Some("Webhook".to_string()),
token_expires_at: None,
+ has_agent: None,
}
}
@@ -327,6 +329,85 @@ async fn create_user_owned_bot_records_user_owner(pool: PgPool) -> anyhow::Resul
);
assert_eq!(bot.created_by.as_deref(), Some(USER_OWNER));
assert_eq!(bot.handle, "datadog");
+ assert!(!bot.has_agent);
+
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn create_bot_stores_requested_has_agent(pool: PgPool) -> anyhow::Result<()> {
+ let service = service(&pool);
+ let mut request = create_req("agent-bot");
+ request.has_agent = Some(true);
+
+ let bot = service.create_bot(user_id(USER_OWNER), request).await?;
+
+ assert!(bot.has_agent);
+ assert!(
+ service
+ .get_bot(user_id(USER_OWNER), bot.id)
+ .await?
+ .has_agent
+ );
+
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn patch_bot_toggles_has_agent_and_leaves_it_unchanged_when_omitted(
+ pool: PgPool,
+) -> anyhow::Result<()> {
+ let service = service(&pool);
+ let bot = service
+ .create_bot(user_id(USER_OWNER), create_req("agent-toggle"))
+ .await?;
+ assert!(!bot.has_agent);
+
+ let enabled = service
+ .patch_bot(
+ user_id(USER_OWNER),
+ bot.id,
+ PatchBotRequest {
+ name: None,
+ handle: None,
+ description: None,
+ avatar_url: None,
+ has_agent: Some(true),
+ },
+ )
+ .await?;
+ assert!(enabled.has_agent);
+
+ let renamed = service
+ .patch_bot(
+ user_id(USER_OWNER),
+ bot.id,
+ PatchBotRequest {
+ name: Some("Renamed".to_string()),
+ handle: None,
+ description: None,
+ avatar_url: None,
+ has_agent: None,
+ },
+ )
+ .await?;
+ assert_eq!(renamed.name, "Renamed");
+ assert!(renamed.has_agent);
+
+ let disabled = service
+ .patch_bot(
+ user_id(USER_OWNER),
+ bot.id,
+ PatchBotRequest {
+ name: None,
+ handle: None,
+ description: None,
+ avatar_url: None,
+ has_agent: Some(false),
+ },
+ )
+ .await?;
+ assert!(!disabled.has_agent);
Ok(())
}
@@ -523,12 +604,16 @@ async fn create_channel_scoped_bot_creates_bot_participant_and_token(
.create_channel_scoped_bot(
user_id(USER_OWNER),
channel_id,
- create_channel_scoped_req("scoped-alerts"),
+ CreateChannelScopedBotRequest {
+ has_agent: Some(true),
+ ..create_channel_scoped_req("scoped-alerts")
+ },
)
.await?;
assert_eq!(created.bot.kind, BotKind::Owned);
assert_eq!(created.bot.handle, "scoped-alerts");
+ assert!(created.bot.has_agent);
assert_eq!(created.bot.created_by.as_deref(), Some(USER_OWNER));
assert_eq!(created.token.bot_id, created.bot.id);
assert_eq!(created.token.label.as_deref(), Some("Webhook"));
@@ -850,6 +935,7 @@ async fn patch_and_delete_publish_requested_fields_and_team_owner(
handle: None,
description: Some("Replacement description".to_string()),
avatar_url: None,
+ has_agent: None,
};
let patched = service
.patch_bot(user_id(TEAM_ADMIN), bot.id, patch_request)
@@ -942,6 +1028,7 @@ async fn non_lifecycle_and_failed_operations_do_not_publish(pool: PgPool) -> any
handle: None,
description: None,
avatar_url: None,
+ has_agent: None,
},
)
.await;
@@ -993,6 +1080,7 @@ async fn scheduling_failures_do_not_change_successful_mutations(
handle: None,
description: None,
avatar_url: None,
+ has_agent: None,
},
)
.await?;
diff --git a/crates/coding_agent_worker/Cargo.toml b/crates/coding_agent_worker/Cargo.toml
new file mode 100644
index 0000000000..7d2b4c869e
--- /dev/null
+++ b/crates/coding_agent_worker/Cargo.toml
@@ -0,0 +1,50 @@
+[package]
+edition = "2024"
+name = "coding_agent_worker"
+publish = false
+version = "0.1.0"
+
+[[bin]]
+name = "macrod"
+path = "src/main.rs"
+
+[dependencies]
+# Direct crate imports are the whole typegen story: the protocol envelope,
+# the trigger event vocabulary, and the delivery signature all come from the
+# owning crates, compiler-checked.
+agent-client-protocol = { workspace = true }
+agent_runtime_protocol = { path = "../agent_runtime_protocol" }
+agent_session = { path = "../agent_session" }
+agent_trigger = { path = "../agent_trigger" }
+axum = { workspace = true }
+bot_id = { path = "../bot_id" }
+# Only the domain models: the daemon reads `GET /bots/me` and the webhook
+# API's bodies, and wants none of either crate's server-side machinery.
+bots = { path = "../bots", default-features = false }
+clap = { workspace = true }
+dashmap = { workspace = true }
+macro_event_broker = { path = "../macro_event_broker", default-features = false }
+macro_user_id = { path = "../macro_user_id" }
+macro_uuid = { path = "../macro_uuid" }
+reqwest = { workspace = true }
+rootcause = { workspace = true }
+serde = { workspace = true }
+serde_json = { workspace = true }
+strum = { workspace = true }
+thiserror = { workspace = true }
+tokio = { workspace = true, features = ["macros", "process", "rt-multi-thread", "signal", "time"] }
+tokio-retry = { workspace = true }
+tokio-tungstenite = { workspace = true }
+toml = { workspace = true }
+tracing = { workspace = true }
+tracing-subscriber = { workspace = true }
+webhook = { path = "../webhook", default-features = false }
+webhook_signature = { path = "../webhook_signature" }
+workspace-hack = { version = "0.1", path = "../workspace-hack" }
+
+[dev-dependencies]
+bot_id = { path = "../bot_id", features = ["test-utils"] }
+channel_sender = { path = "../channel_sender" }
+channels = { path = "../channels", default-features = false }
+chrono = { workspace = true }
+tower = { workspace = true, features = ["util"] }
diff --git a/crates/coding_agent_worker/config.example.toml b/crates/coding_agent_worker/config.example.toml
new file mode 100644
index 0000000000..a1bd9de681
--- /dev/null
+++ b/crates/coding_agent_worker/config.example.toml
@@ -0,0 +1,35 @@
+# Everything a coding agent daemon needs to serve one bot's sessions.
+
+[macro]
+# Base URL of the agent-harness service. Its ws(s) twin hosts the runtime
+# gateway the daemon dials per session.
+api_url = "http://localhost:50009/agent-harness"
+# Base URL of the storage service (bots + webhook APIs); the daemon
+# registers its own trigger feed there at boot.
+storage_url = "http://localhost:50009/dss"
+# The user who owns the bot; registration acts for them.
+owner_user_id = "macro|[email protected]"
+# The bot's API token.
+bot_token = "mbot_0123456789ab_0123456789abcdef"
+# Optional; `user` unless the bot is team-owned and acts in its team scope.
+bot_scope = "user"
+
+[server]
+# Port `POST /macro-events` is served on.
+port = 8790
+# The URL deliveries reach this daemon at; what the feed registers.
+# Locally, the stack's relay tunnels this to the port above.
+public_url = "http://sdk-webhook-relay:8787/macro-events"
+# Optional override; normally the daemon registers its own feed at boot
+# and keeps the minted secret in a state file next to this config.
+# signing_secret = "whsec_..."
+
+[harness]
+command = "opencode"
+args = ["acp"]
+
+[workspace]
+# Every session this daemon serves runs here.
+path = "/workspace"
+# Informational: having the repo cloned at `path` is the operator's job.
+repo_url = "https://github.com/macro-inc/macro"
diff --git a/crates/coding_agent_worker/justfile b/crates/coding_agent_worker/justfile
new file mode 100644
index 0000000000..854b407c59
--- /dev/null
+++ b/crates/coding_agent_worker/justfile
@@ -0,0 +1,33 @@
+# Run the coding agent daemon.
+#
+# just serve
+# RUST_LOG=coding_agent_worker=trace just serve # tap the ACP wire
+#
+# Reads the repo-root macro.toml by default; override with CONFIG=/path/to.toml.
+
+CONFIG := env("CONFIG", justfile_directory() + "/../../macro.toml")
+
+ROOT := justfile_directory() + "/../.."
+SCRIPTS := ROOT + "/tooling/xtask/crates/xtask_workflows/src/workflows/scripts"
+
+# Serve this bot's agent sessions: webhook receiver, one connection, one harness.
+serve:
+ SQLX_OFFLINE=true cargo run -p coding_agent_worker -- --config {{ CONFIG }}
+
+# Build the release `macrod` the way the tag workflow does, and prove it is as
+# self-contained as it claims. Runs the workflow's own scripts rather than a
+# copy of them, so a green run here means the same steps are green in CI.
+#
+# just build-static # host architecture
+# TARGET=aarch64-unknown-linux-musl just build-static # cross, no smoke run
+#
+# Needs the dev shell: cargo-zigbuild, zig, and cmake all come from it.
+build-static TARGET=(arch() + "-unknown-linux-musl"):
+ cd {{ ROOT }} && TARGET={{ TARGET }} bash {{ SCRIPTS }}/build_agent_daemon_linux.sh
+ cd {{ ROOT }} && TARGET={{ TARGET }} SLUG=local SAFE_TAG=dev \
+ SMOKE_RUN={{ if TARGET == arch() + "-unknown-linux-musl" { "1" } else { "0" } }} \
+ bash {{ SCRIPTS }}/package_agent_daemon.sh
+ @# Both land at the workspace root, which is not where you ran this from.
+ @cd {{ ROOT }} && echo "" \
+ && echo "binary: $(pwd)/target/{{ TARGET }}/release/macrod" \
+ && echo "tarball: $(pwd)/artifacts/macrod-dev-local.tar.gz"
diff --git a/crates/coding_agent_worker/src/config.rs b/crates/coding_agent_worker/src/config.rs
new file mode 100644
index 0000000000..e2a0181317
--- /dev/null
+++ b/crates/coding_agent_worker/src/config.rs
@@ -0,0 +1,144 @@
+//! The daemon's one input: a TOML file describing the bot it serves, the
+//! webhook server it listens on, and the harness it runs per session. See
+//! `config.example.toml` at the crate root.
+
+use serde::Deserialize;
+use std::path::{Path, PathBuf};
+
+#[cfg(test)]
+mod test;
+
+/// Everything the daemon needs, parsed from one TOML file.
+#[derive(Debug, Clone, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct Config {
+ /// The Macro deployment this bot's sessions live in.
+ #[serde(rename = "macro")]
+ pub macro_api: MacroApi,
+ /// The webhook server this daemon listens on.
+ pub server: Server,
+ /// The harness process spawned per session.
+ pub harness: Harness,
+ /// The workspace every session runs against.
+ pub workspace: Workspace,
+}
+
+/// The Macro deployment this bot's sessions live in, and how to act as the
+/// bot there.
+#[derive(Debug, Clone, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct MacroApi {
+ /// Base URL of the agent-harness service, e.g.
+ /// `http://localhost:50009/agent-harness`. Sessions are created and
+ /// prompted here, and its `ws(s)` twin hosts the runtime gateway.
+ pub api_url: String,
+ /// Base URL of the storage service, e.g. `http://localhost:50009/storage`.
+ /// Hosts the bots and webhook APIs the daemon registers itself with.
+ pub storage_url: String,
+ /// The user who owns the bot; webhook registration acts for them.
+ pub owner_user_id: String,
+ /// The bot's API token (`mbot_...`).
+ pub bot_token: String,
+ /// Bot scope requests authorize under; `user` unless the bot is
+ /// team-owned and should act in its team scope.
+ #[serde(default = "default_bot_scope")]
+ pub bot_scope: String,
+}
+
+impl MacroApi {
+ /// The dial-in URL for a session on this deployment's runtime gateway:
+ /// the API base with a websocket scheme.
+ pub fn gateway_url(&self) -> String {
+ let base = self.api_url.trim_end_matches('/');
+ let base = base
+ .replacen("https://", "wss://", 1)
+ .replacen("http://", "ws://", 1);
+ format!("{base}/runtime/ws")
+ }
+}
+
+/// The webhook server this daemon listens on.
+#[derive(Debug, Clone, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct Server {
+ /// Port `POST /macro-events` is served on.
+ pub port: u16,
+ /// The URL webhook deliveries reach this daemon at - what the feed is
+ /// registered with. Locally that is the stack's relay
+ /// (`http://sdk-webhook-relay:8787/macro-events`); in production, a
+ /// public HTTPS endpoint.
+ pub public_url: String,
+ /// Explicit signing secret, overriding boot-time feed registration.
+ /// Normally absent: the daemon registers its own feed and keeps the
+ /// minted secret in a state file next to the config.
+ #[serde(default)]
+ pub signing_secret: Option<String>,
+}
+
+/// The harness process spawned per session. Generic on purpose: any binary
+/// speaking ACP over stdio fits here - opencode, claude, hermes - so a new
+/// harness is a config change, not code.
+#[derive(Debug, Clone, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct Harness {
+ /// The binary to run.
+ pub command: String,
+ /// Arguments, e.g. `["acp"]`.
+ #[serde(default)]
+ pub args: Vec<String>,
+}
+
+/// The workspace every session runs against.
+#[derive(Debug, Clone, Deserialize)]
+#[serde(deny_unknown_fields)]
+pub struct Workspace {
+ /// Absolute directory harnesses run in; sent as each session's
+ /// workspace at creation.
+ pub path: PathBuf,
+ /// Repository nominally checked out at `path`, recorded on each
+ /// session it serves. Informational: having the repo cloned there is
+ /// the operator's job.
+ #[serde(default)]
+ pub repo_url: Option<String>,
+}
+
+fn default_bot_scope() -> String {
+ "user".to_owned()
+}
+
+/// Why a config failed to load.
+#[derive(Debug, thiserror::Error)]
+pub enum ConfigError {
+ /// The file could not be read.
+ #[error("failed to read config at {path}")]
+ Io {
+ /// The path that failed.
+ path: PathBuf,
+ /// What reading it returned.
+ #[source]
+ source: std::io::Error,
+ },
+ /// The file is not a valid daemon config.
+ #[error("invalid config at {path}")]
+ Parse {
+ /// The path that failed.
+ path: PathBuf,
+ /// What parsing it returned.
+ #[source]
+ source: toml::de::Error,
+ },
+}
+
+impl Config {
+ /// Load and parse the config at `path`.
+ pub fn load(path: &Path) -> Result<Self, ConfigError> {
+ let raw = std::fs::read_to_string(path).map_err(|source| ConfigError::Io {
+ path: path.to_owned(),
+ source,
+ })?;
+ toml::from_str(&raw).map_err(|source| ConfigError::Parse {
+ path: path.to_owned(),
+ source,
+ })
+ }
+}
diff --git a/crates/coding_agent_worker/src/config/test.rs b/crates/coding_agent_worker/src/config/test.rs
new file mode 100644
index 0000000000..8f5a5c519c
--- /dev/null
+++ b/crates/coding_agent_worker/src/config/test.rs
@@ -0,0 +1,54 @@
+use super::*;
+
+const EXAMPLE: &str = include_str!("../../config.example.toml");
+
+#[test]
+fn the_example_config_parses() {
+ let config: Config = toml::from_str(EXAMPLE).expect("example config parses");
+ assert_eq!(config.harness.command, "opencode");
+ assert_eq!(config.harness.args, vec!["acp"]);
+ assert_eq!(config.server.port, 8790);
+ assert_eq!(config.macro_api.bot_scope, "user");
+ assert_eq!(config.server.signing_secret, None);
+ assert_eq!(
+ config.server.public_url,
+ "http://sdk-webhook-relay:8787/macro-events"
+ );
+}
+
+#[test]
+fn unknown_fields_are_rejected() {
+ let with_typo = EXAMPLE.replace("repo_url", "repo_uri");
+ assert!(toml::from_str::<Config>(&with_typo).is_err());
+}
+
+#[test]
+fn args_and_scope_default() {
+ let trimmed = EXAMPLE
+ .replace("args = [\"acp\"]\n", "")
+ .replace("bot_scope = \"user\"\n", "");
+ let config: Config = toml::from_str(&trimmed).expect("args and scope are optional");
+ assert!(config.harness.args.is_empty());
+ assert_eq!(config.macro_api.bot_scope, "user");
+}
+
+#[test]
+fn the_gateway_url_is_the_api_base_with_a_websocket_scheme() {
+ let config: Config = toml::from_str(EXAMPLE).expect("example config parses");
+ assert_eq!(
+ config.macro_api.gateway_url(),
+ "ws://localhost:50009/agent-harness/runtime/ws",
+ );
+
+ let secure = MacroApi {
+ api_url: "https://agent-harness.macro.com/".to_owned(),
+ storage_url: "https://cloud-storage.macro.com".to_owned(),
+ owner_user_id: "macro|[email protected]".to_owned(),
+ bot_token: "mbot_x".to_owned(),
+ bot_scope: "user".to_owned(),
+ };
+ assert_eq!(
+ secure.gateway_url(),
+ "wss://agent-harness.macro.com/runtime/ws",
+ );
+}
diff --git a/crates/coding_agent_worker/src/dispatch.rs b/crates/coding_agent_worker/src/dispatch.rs
new file mode 100644
index 0000000000..f3db7726bf
--- /dev/null
+++ b/crates/coding_agent_worker/src/dispatch.rs
@@ -0,0 +1,117 @@
+//! Executes trigger work against the live service: create, dial, prompt.
+
+use agent_session::domain::model::AgentSessionId;
+use agent_session::inbound::axum_router::{CreateAgentSessionRequest, CreateSessionThread};
+
+use crate::config::Workspace;
+use crate::outbound::agent_session::{ApiError, HarnessApi};
+use crate::runtime::Runtime;
+use crate::webhook::{TriggerWork, WorkExecutor};
+
+/// A failure doing an event's work.
+#[derive(Debug, thiserror::Error)]
+pub enum DispatchError {
+ /// The service refused or could not be reached.
+ #[error(transparent)]
+ Api(#[from] ApiError),
+ /// The session's gateway could not be dialed.
+ #[error("failed to dial the runtime gateway")]
+ Dial(#[source] tokio_tungstenite::tungstenite::Error),
+}
+
+/// The daemon's real executor: the API client plus the bridge registry.
+pub struct Dispatcher {
+ api: HarnessApi,
+ runtime: Runtime,
+ workspace: Workspace,
+}
+
+impl Dispatcher {
+ /// Build the executor.
+ pub fn new(api: HarnessApi, runtime: Runtime, workspace: Workspace) -> Self {
+ Self {
+ api,
+ runtime,
+ workspace,
+ }
+ }
+}
+
+impl WorkExecutor for Dispatcher {
+ async fn execute(&self, work: TriggerWork) -> Result<(), DispatchError> {
+ match work {
+ TriggerWork::OpenAndPrompt {
+ sender,
+ channel_id,
+ thread_id,
+ message_id,
+ content,
+ } => {
+ let request = CreateAgentSessionRequest {
+ // The bot is the one whose credentials this daemon holds,
+ // and naming another one is refused anyway.
+ bot_id: None,
+ workspace: self.workspace.path.to_string_lossy().into_owned(),
+ repo_url: self.workspace.repo_url.clone(),
+ owner: Some(sender.as_ref().to_owned()),
+ thread: Some(CreateSessionThread {
+ channel_id,
+ thread_id: Some(thread_id),
+ message_id,
+ content: content.clone(),
+ }),
+ };
+ let created = match self.api.create_session(&request).await {
+ Ok(created) => created,
+ // A redelivered mention: the thread's session exists.
+ // Resume serving it - the first attempt may have died
+ // between create and prompt, and re-prompting a session
+ // that already heard the mention is the cheaper failure.
+ Err(ApiError::ThreadSessionExists {
+ session: Some(session),
+ }) => {
+ tracing::info!(%thread_id, %session, "thread already has a session; resuming it");
+ self.runtime
+ .ensure_connected()
+ .await
+ .map_err(DispatchError::Dial)?;
+ self.api.prompt(session, &sender, &content).await?;
+ return Ok(());
+ }
+ Err(ApiError::ThreadSessionExists { session: None }) => {
+ tracing::warn!(%thread_id, "thread has a session the service could not name; acked");
+ return Ok(());
+ }
+ Err(error) => return Err(error.into()),
+ };
+ let session = AgentSessionId::new_from_uuid(created.session.id);
+ self.runtime
+ .ensure_connected()
+ .await
+ .map_err(DispatchError::Dial)?;
+ // No retry around the prompt: the session actor buffers
+ // actions from the moment the runtime attaches, so the only
+ // uncovered window is the sub-millisecond gap between the
+ // websocket's 101 and the server's `on_upgrade` attach. If
+ // that race ever bites, failing the delivery is the right
+ // answer - webhook redelivery re-runs this arm, and a repeat
+ // create answers 409 with the session id, which the branch
+ // above resumes.
+ self.api.prompt(session, &sender, &content).await?;
+ Ok(())
+ }
+ TriggerWork::PromptExisting {
+ session,
+ sender,
+ content,
+ } => {
+ self.runtime
+ .ensure_connected()
+ .await
+ .map_err(DispatchError::Dial)?;
+ self.api.prompt(session, &sender, &content).await?;
+ Ok(())
+ }
+ }
+ }
+}
diff --git a/crates/coding_agent_worker/src/harness.rs b/crates/coding_agent_worker/src/harness.rs
new file mode 100644
index 0000000000..f5b15391ca
--- /dev/null
+++ b/crates/coding_agent_worker/src/harness.rs
@@ -0,0 +1,49 @@
+//! The harness child process and the bridge between its stdio and the
+//! gateway channel.
+
+use crate::config::Harness;
+use agent_client_protocol::{AcpAgent, AcpAgentConfig, Client, ConnectTo};
+use agent_runtime_protocol::domain::connection::{
+ ConnectionError, RuntimeChannel, RuntimeConnection,
+};
+use agent_runtime_protocol::domain::schema::v0::SystemEvent;
+
+#[cfg(test)]
+mod test;
+
+/// Why the bridge ended.
+#[derive(Debug, thiserror::Error)]
+pub enum BridgeError {
+ /// The service connection closed before the harness could be announced.
+ #[error("the service connection closed before the harness was announced")]
+ Announce(#[source] ConnectionError),
+ /// The harness could not be spawned, or its ACP session ended in failure.
+ #[error("the harness process ended in failure: {0}")]
+ Harness(String),
+}
+
+/// Spawn the harness in ACP mode and pump frames until either side ends.
+pub async fn bridge(harness: &Harness, channel: RuntimeChannel) -> Result<(), BridgeError> {
+ let (runtime, acp) = RuntimeConnection::connect(channel);
+
+ let agent = AcpAgent::new(AcpAgentConfig::new(&harness.command).args(harness.args.clone()))
+ // The wire tap: every ndjson line crossing the child's stdio, plus
+ // its stderr. Enable with RUST_LOG=coding_agent_worker=trace.
+ .with_debug(|line, direction| {
+ tracing::trace!(?direction, line, "acp line");
+ });
+
+ runtime
+ .system_event(SystemEvent::AcpReady)
+ .map_err(BridgeError::Announce)?;
+
+ let outcome = ConnectTo::<Client>::connect_to(agent, acp).await;
+
+ // Best effort: a transport that has already failed cannot carry news of
+ // its own failure, and that is not itself worth failing the worker over.
+ if let Err(error) = runtime.system_event(SystemEvent::Disconnected) {
+ tracing::debug!(error = ?error, "could not announce disconnect");
+ }
+
+ outcome.map_err(|error| BridgeError::Harness(error.to_string()))
+}
diff --git a/crates/coding_agent_worker/src/harness/test.rs b/crates/coding_agent_worker/src/harness/test.rs
new file mode 100644
index 0000000000..42dba96d2d
--- /dev/null
+++ b/crates/coding_agent_worker/src/harness/test.rs
@@ -0,0 +1,68 @@
+use super::*;
+use agent_runtime_protocol::domain::channel::Channel;
+use agent_runtime_protocol::domain::connection::ServerChannel;
+use agent_runtime_protocol::domain::schema::v0::ToServerMessage;
+
+fn harness(command: &str) -> Harness {
+ Harness {
+ command: command.to_owned(),
+ args: Vec::new(),
+ }
+}
+
+/// Drain the system events the service side observed, in order.
+fn events(mut service: ServerChannel) -> Vec<SystemEvent> {
+ let mut seen = Vec::new();
+ while let Ok(message) = service.rx.try_recv() {
+ match message {
+ ToServerMessage::Event { event } => seen.push(event),
+ other => panic!("only system events expected, got {other:?}"),
+ }
+ }
+ seen
+}
+
+#[tokio::test]
+async fn unspawnable_harness_reports_failure() {
+ let (runtime, service) = Channel::duplex();
+
+ let error = bridge(&harness("macro-no-such-harness-binary"), runtime)
+ .await
+ .expect_err("a harness that cannot be spawned must not look like success");
+
+ assert!(matches!(error, BridgeError::Harness(_)), "got {error:?}");
+ // The service is told the transport is done even though the child never
+ // existed, so it is never left waiting on a session that cannot start.
+ assert_eq!(
+ events(service),
+ vec![SystemEvent::AcpReady, SystemEvent::Disconnected],
+ );
+}
+
+#[tokio::test]
+async fn harness_that_exits_immediately_disconnects() {
+ let (runtime, service) = Channel::duplex();
+
+ // `true` spawns cleanly and closes its stdio at once, which is the
+ // shutdown path rather than the spawn-failure path above.
+ let _ = bridge(&harness("true"), runtime).await;
+
+ assert_eq!(
+ events(service),
+ vec![SystemEvent::AcpReady, SystemEvent::Disconnected],
+ );
+}
+
+#[tokio::test]
+async fn dropped_service_channel_does_not_panic_the_bridge() {
+ let (runtime, service) = Channel::duplex();
+ drop(service);
+
+ // Announcing readiness into a closed channel is a failure to announce, not
+ // a harness failure: nothing was ever spawned.
+ let error = bridge(&harness("true"), runtime)
+ .await
+ .expect_err("announcing into a closed channel must fail");
+
+ assert!(matches!(error, BridgeError::Announce(_)), "got {error:?}");
+}
diff --git a/crates/coding_agent_worker/src/main.rs b/crates/coding_agent_worker/src/main.rs
new file mode 100644
index 0000000000..748a119e66
--- /dev/null
+++ b/crates/coding_agent_worker/src/main.rs
@@ -0,0 +1,119 @@
+//! The coding agent daemon: serve a bot's agent sessions from this machine.
+//!
+//! Boots a signed-webhook receiver and waits. Each `agent_trigger.new`
+//! delivery opens a session over the harness service's API, dials its
+//! runtime gateway, spawns the configured harness in ACP mode, bridges its
+//! stdio to the websocket, and forwards the mention as the first prompt;
+//! `agent_trigger.existing` deliveries forward follow-up messages, redialing
+//! first when the bridge is gone.
+
+mod config;
+mod dispatch;
+mod harness;
+mod outbound;
+mod runtime;
+mod webhook;
+
+use clap::Parser;
+use config::Config;
+use rootcause::prelude::ResultExt as _;
+use std::path::PathBuf;
+use std::process::ExitCode;
+
+use crate::dispatch::Dispatcher;
+use crate::outbound::agent_session::HarnessApi;
+use crate::outbound::registration::FeedReconciler;
+use crate::runtime::Runtime;
+use crate::webhook::{WebhookState, webhook_router};
+
+/// Serve a bot's agent sessions: host the webhook receiver, bridge each
+/// triggered session to a harness.
+#[derive(Parser)]
+#[command(name = "macrod", version)]
+struct Args {
+ /// Path to the daemon's TOML config.
+ #[arg(long, default_value = "macro.toml")]
+ config: PathBuf,
+}
+
+#[tokio::main]
+async fn main() -> ExitCode {
+ tracing_subscriber::fmt()
+ .with_env_filter(
+ tracing_subscriber::EnvFilter::try_from_default_env()
+ .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),
+ )
+ .init();
+
+ let args = Args::parse();
+ match run(&args.config).await {
+ Ok(()) => ExitCode::SUCCESS,
+ Err(error) => {
+ tracing::error!(error = ?error, "daemon exited with an error");
+ ExitCode::FAILURE
+ }
+ }
+}
+
+async fn run(config_path: &std::path::Path) -> rootcause::Result<()> {
+ let config = Config::load(config_path)?;
+
+ // The ACP launch config carries command, args, and env but no working
+ // directory, and every session this daemon serves runs in the one
+ // configured workspace - so the daemon's own cwd is the harness's cwd.
+ std::env::set_current_dir(&config.workspace.path).context(format!(
+ "failed to enter the workspace directory {}",
+ config.workspace.path.display()
+ ))?;
+
+ // The feed: make sure one exists, points here, and we hold its secret.
+ // An explicit config secret skips registration entirely (manual setups).
+ let reconciler = FeedReconciler::new(&config.macro_api, &config.server, config_path);
+ let (signing_secret, needs_validation) = match &config.server.signing_secret {
+ Some(secret) => (secret.clone(), None),
+ None => {
+ let feed = reconciler
+ .ensure_feed()
+ .await
+ .context("failed to register this bot's trigger feed")?;
+ let needs_validation = (!feed.is_valid).then_some(feed.webhook_id);
+ (feed.signing_secret, needs_validation)
+ }
+ };
+
+ let api = HarnessApi::new(&config.macro_api);
+ let runtime = Runtime::new(config.macro_api.clone(), config.harness.clone());
+ let app = webhook_router(WebhookState {
+ executor: Dispatcher::new(api, runtime, config.workspace.clone()),
+ signing_secret,
+ });
+
+ let port = config.server.port;
+ let listener = tokio::net::TcpListener::bind(("0.0.0.0", port))
+ .await
+ .context(format!("failed to bind the webhook server to port {port}"))?;
+ tracing::info!(
+ port,
+ api = %config.macro_api.api_url,
+ harness = %config.harness.command,
+ workspace = %config.workspace.path.display(),
+ "daemon listening for agent triggers"
+ );
+
+ // Validation probes the endpoint, so it can only pass once we serve;
+ // request it from the side once the listener is up.
+ if let Some(webhook_id) = needs_validation {
+ tokio::spawn(async move { reconciler.request_validation(&webhook_id).await });
+ }
+
+ axum::serve(listener, app)
+ .with_graceful_shutdown(shutdown_signal())
+ .await
+ .context("the webhook server stopped")?;
+ Ok(())
+}
+
+async fn shutdown_signal() {
+ let _ = tokio::signal::ctrl_c().await;
+ tracing::info!("shutting down");
+}
diff --git a/crates/coding_agent_worker/src/outbound/agent_session.rs b/crates/coding_agent_worker/src/outbound/agent_session.rs
new file mode 100644
index 0000000000..99893e5dc2
--- /dev/null
+++ b/crates/coding_agent_worker/src/outbound/agent_session.rs
@@ -0,0 +1,132 @@
+//! The daemon's client for the agent-harness service: open sessions, drive
+//! them. Both calls act as the bot, and control calls additionally act for
+//! the user whose mention they forward.
+
+use agent_runtime_protocol::domain::action::AgentAction;
+use agent_session::domain::model::AgentSessionId;
+use agent_session::inbound::axum_router::{
+ ControlRequest, CreateAgentSessionRequest, CreateAgentSessionResponse,
+ ThreadSessionExistsResponse,
+};
+use macro_user_id::user_id::MacroUserIdStr;
+use reqwest::StatusCode;
+
+use crate::config::MacroApi;
+
+const BOT_TOKEN_HEADER: &str = "x-macro-bot-token";
+const BOT_SCOPE_HEADER: &str = "x-macro-bot-scope";
+const BOT_ACTING_USER_HEADER: &str = "x-macro-bot-for-macro-user-id";
+
+/// A failure calling the agent-harness service.
+#[derive(Debug, thiserror::Error)]
+pub enum ApiError {
+ /// The request could not be sent or the response not read.
+ #[error(transparent)]
+ Http(#[from] reqwest::Error),
+ /// This bot already has a session for the thread.
+ #[error("this bot already has a session for this thread")]
+ ThreadSessionExists {
+ /// The existing session, when the service could name it.
+ session: Option<AgentSessionId>,
+ },
+ /// The service refused the request.
+ #[error("the service answered {status}: {message}")]
+ Refused {
+ /// The status the service answered with.
+ status: StatusCode,
+ /// The response body, verbatim.
+ message: String,
+ },
+}
+
+/// Client for the agent-harness service, acting as one bot.
+pub struct HarnessApi {
+ http: reqwest::Client,
+ base: String,
+ bot_token: String,
+ bot_scope: String,
+}
+
+impl HarnessApi {
+ /// Build a client from the daemon's config.
+ pub fn new(config: &MacroApi) -> Self {
+ Self {
+ http: reqwest::Client::new(),
+ base: config.api_url.trim_end_matches('/').to_owned(),
+ bot_token: config.bot_token.clone(),
+ bot_scope: config.bot_scope.clone(),
+ }
+ }
+
+ /// Open an external session for this bot.
+ ///
+ /// A thread routes to at most one of a bot's sessions, so a redelivered
+ /// mention lands on [`ApiError::ThreadSessionExists`] carrying the
+ /// session already serving it.
+ pub async fn create_session(
+ &self,
+ request: &CreateAgentSessionRequest,
+ ) -> Result<CreateAgentSessionResponse, ApiError> {
+ let response = self
+ .http
+ .post(format!("{}/agent-sessions", self.base))
+ .header(BOT_TOKEN_HEADER, &self.bot_token)
+ .header(BOT_SCOPE_HEADER, &self.bot_scope)
+ .json(request)
+ .send()
+ .await?;
+ if response.status() == StatusCode::CONFLICT {
+ let session = response
+ .json::<ThreadSessionExistsResponse>()
+ .await
+ .ok()
+ .and_then(|conflict| conflict.session_id);
+ return Err(ApiError::ThreadSessionExists { session });
+ }
+ let response = refuse_errors(response).await?;
+ Ok(response.json().await?)
+ }
+
+ /// Ask a session to do something, acting for the user who asked.
+ ///
+ /// Announcing the result into its channel is not this call's business:
+ /// the harness service posts the chip from the trigger event it observed.
+ pub async fn control(
+ &self,
+ session: AgentSessionId,
+ actor: &MacroUserIdStr<'static>,
+ action: AgentAction,
+ ) -> Result<(), ApiError> {
+ let response = self
+ .http
+ .post(format!("{}/agent-sessions/{session}/control", self.base))
+ .header(BOT_TOKEN_HEADER, &self.bot_token)
+ .header(BOT_SCOPE_HEADER, &self.bot_scope)
+ .header(BOT_ACTING_USER_HEADER, actor.as_ref())
+ .json(&ControlRequest { action })
+ .send()
+ .await?;
+ refuse_errors(response).await?;
+ Ok(())
+ }
+
+ /// Deliver a prompt to a session, acting for the user who sent it.
+ pub async fn prompt(
+ &self,
+ session: AgentSessionId,
+ sender: &MacroUserIdStr<'static>,
+ text: &str,
+ ) -> Result<(), ApiError> {
+ self.control(session, sender, AgentAction::prompt(text))
+ .await
+ }
+}
+
+async fn refuse_errors(response: reqwest::Response) -> Result<reqwest::Response, ApiError> {
+ let status = response.status();
+ if status.is_success() {
+ return Ok(response);
+ }
+ let message = response.text().await.unwrap_or_default();
+ Err(ApiError::Refused { status, message })
+}
diff --git a/crates/coding_agent_worker/src/outbound/link.rs b/crates/coding_agent_worker/src/outbound/link.rs
new file mode 100644
index 0000000000..ef5fb9860b
--- /dev/null
+++ b/crates/coding_agent_worker/src/outbound/link.rs
@@ -0,0 +1,35 @@
+//! The dial-out link to the harness service's runtime gateway.
+
+use agent_runtime_protocol::domain::connection::RuntimeChannel;
+use agent_runtime_protocol::outbound::websocket::connect_runtime;
+use tokio_tungstenite::tungstenite::client::IntoClientRequest;
+
+/// Dial a session's gateway URL - the `gatewayUrl` returned by
+/// `POST /agent-sessions`, taken verbatim - presenting the bot's API token
+/// with the standard bot credential headers. A WebSocket upgrade is an
+/// ordinary HTTP request, so the same headers every other bot call uses
+/// work here too.
+pub async fn dial(
+ gateway_url: &str,
+ bot_token: &str,
+ bot_scope: &str,
+) -> Result<RuntimeChannel, tokio_tungstenite::tungstenite::Error> {
+ let mut request = gateway_url.into_client_request()?;
+ let headers = request.headers_mut();
+ let token = bot_token.parse().map_err(bad_header)?;
+ headers.insert("x-macro-bot-token", token);
+ let scope = bot_scope.parse().map_err(bad_header)?;
+ headers.insert("x-macro-bot-scope", scope);
+ let (stream, _response) = tokio_tungstenite::connect_async(request).await?;
+ Ok(connect_runtime(stream))
+}
+
+fn bad_header(
+ _: tokio_tungstenite::tungstenite::http::header::InvalidHeaderValue,
+) -> tokio_tungstenite::tungstenite::Error {
+ tokio_tungstenite::tungstenite::Error::Url(
+ tokio_tungstenite::tungstenite::error::UrlError::UnableToConnect(
+ "bot credentials are not valid header values".to_owned(),
+ ),
+ )
+}
diff --git a/crates/coding_agent_worker/src/outbound/mod.rs b/crates/coding_agent_worker/src/outbound/mod.rs
new file mode 100644
index 0000000000..b8921c29b9
--- /dev/null
+++ b/crates/coding_agent_worker/src/outbound/mod.rs
@@ -0,0 +1,11 @@
+//! The daemon's adapters to the Macro backend.
+//!
+//! Everything here is a client this daemon calls out with, and every request
+//! and response body is the server's own type imported from the owning crate
+//! rather than a copy declared here. That is the point of the module: a
+//! server-side field rename becomes a compile error on this side instead of a
+//! runtime surprise on someone's laptop.
+
+pub mod agent_session;
+pub mod link;
+pub mod registration;
diff --git a/crates/coding_agent_worker/src/outbound/registration.rs b/crates/coding_agent_worker/src/outbound/registration.rs
new file mode 100644
index 0000000000..16b2ebba3c
--- /dev/null
+++ b/crates/coding_agent_worker/src/outbound/registration.rs
@@ -0,0 +1,292 @@
+//! Boot-time webhook feed reconciliation: make sure this daemon's bot has a
+//! validated trigger feed pointing at this daemon, without any manual step.
+//!
+//! The flow is deliberately the plain webhook API driven as the bot acting
+//! for its owner: who am I (`/bots/me`), do I have a feed (list), is it
+//! mine and current (endpoint match), verify it if unverified, create it if
+//! missing. It leans on no server-side affordance beyond that API: the feed
+//! is an ordinary webhook, scoped to this bot by an `ids` filter and found
+//! again by the namespace this daemon mints for it.
+//!
+//! Secrets are only ever returned at creation, so the daemon persists its
+//! feed's id and secret in a state file next to the config. Losing the file
+//! is recoverable: the stale feed is deleted and recreated.
+
+use std::path::{Path, PathBuf};
+
+use agent_trigger::domain::broker_events::AgentTriggerEventName;
+use bot_id::BotId;
+use bots::domain::models::Bot;
+use rootcause::prelude::ResultExt as _;
+use serde::{Deserialize, Serialize};
+use strum::IntoEnumIterator as _;
+use webhook::domain::models::{
+ CreateWebhookRequest, CreateWebhookResponse, ListWebhooksResponse, Webhook, WebhookFilter,
+ WebhookScope,
+};
+
+use crate::config::{MacroApi, Server};
+
+#[cfg(test)]
+mod test;
+
+const BOT_TOKEN_HEADER: &str = "x-macro-bot-token";
+const BOT_SCOPE_HEADER: &str = "x-macro-bot-scope";
+const BOT_ACTING_USER_HEADER: &str = "x-macro-bot-for-macro-user-id";
+
+/// The namespace a daemon's feed carries: derived from its bot, so the feed
+/// can be found again without the server marking it as that bot's.
+///
+/// Takes the `BotId` rather than its rendering, so no other identifier can be
+/// mistaken for the bot this feed belongs to.
+fn feed_namespace(bot: BotId) -> String {
+ format!("agent-feed-{bot}")
+}
+
+/// Every event a trigger feed carries, straight from the topic's own
+/// vocabulary: a mention that should open a session, and a follow-up message
+/// on a thread that already has one. A name this daemon does not yet handle
+/// is still worth subscribing to - it arrives, is recognised as unsupported,
+/// and is acked - which beats silently never being sent it.
+fn trigger_events() -> Vec<String> {
+ AgentTriggerEventName::iter()
+ .map(|event| event.to_string())
+ .collect()
+}
+
+/// The reconciled feed this daemon serves.
+#[derive(Debug, Clone)]
+pub struct FeedRegistration {
+ /// The webhook row's id.
+ pub webhook_id: String,
+ /// The secret deliveries to this daemon are signed with.
+ pub signing_secret: String,
+ /// Whether the endpoint had already passed validation. When false, the
+ /// caller should request validation once it is serving.
+ pub is_valid: bool,
+}
+
+/// The persisted half of a registration: what only creation reveals.
+#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
+pub(crate) struct FeedState {
+ webhook_id: String,
+ signing_secret: String,
+}
+
+pub(crate) trait FeedStateStore {
+ fn load(&self) -> rootcause::Result<Option<FeedState>>;
+
+ fn save(&self, state: &FeedState) -> rootcause::Result<()>;
+}
+
+pub(crate) struct FileFeedStateStore {
+ path: PathBuf,
+}
+
+impl FileFeedStateStore {
+ fn failure(&self) -> String {
+ format!(
+ "failed to use the feed state file at {}",
+ self.path.display()
+ )
+ }
+}
+
+impl FeedStateStore for FileFeedStateStore {
+ fn load(&self) -> rootcause::Result<Option<FeedState>> {
+ let found = std::fs::read_to_string(&self.path);
+ if let Err(error) = &found
+ && error.kind() == std::io::ErrorKind::NotFound
+ {
+ return Ok(None);
+ }
+ // State we cannot parse is state we do not have: the feed it named
+ // is treated as stale, deleted, and replaced.
+ let raw = found.context(self.failure())?;
+ Ok(serde_json::from_str(&raw).ok())
+ }
+
+ fn save(&self, state: &FeedState) -> rootcause::Result<()> {
+ let raw = serde_json::to_string_pretty(state).expect("a serializable state");
+ std::fs::write(&self.path, raw).context(self.failure())?;
+ // The secret signs deliveries to us; keep it out of other users' reach.
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt as _;
+ let _ = std::fs::set_permissions(&self.path, std::fs::Permissions::from_mode(0o600));
+ }
+ Ok(())
+ }
+}
+
+/// Where the feed state lives: next to the config it belongs to.
+pub fn state_path(config_path: &Path) -> PathBuf {
+ config_path.with_extension("webhook-state.json")
+}
+
+/// The webhook-feed reconciler for one bot on one deployment.
+pub(crate) struct FeedReconciler<S = FileFeedStateStore> {
+ http: reqwest::Client,
+ base: String,
+ macro_api: MacroApi,
+ owner_user_id: String,
+ public_url: String,
+ state_store: S,
+}
+
+impl FeedReconciler<FileFeedStateStore> {
+ /// Build a reconciler from the daemon's config.
+ pub fn new(macro_api: &MacroApi, server: &Server, config_path: &Path) -> Self {
+ Self {
+ http: reqwest::Client::new(),
+ base: macro_api.storage_url.trim_end_matches('/').to_owned(),
+ macro_api: macro_api.clone(),
+ owner_user_id: macro_api.owner_user_id.clone(),
+ public_url: server.public_url.clone(),
+ state_store: FileFeedStateStore {
+ path: state_path(config_path),
+ },
+ }
+ }
+}
+
+impl<S: FeedStateStore> FeedReconciler<S> {
+ fn credentialed(&self, request: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
+ request
+ .header(BOT_TOKEN_HEADER, &self.macro_api.bot_token)
+ .header(BOT_SCOPE_HEADER, &self.macro_api.bot_scope)
+ .header(BOT_ACTING_USER_HEADER, &self.owner_user_id)
+ }
+
+ async fn read<T: serde::de::DeserializeOwned>(
+ &self,
+ what: &'static str,
+ request: reqwest::RequestBuilder,
+ ) -> rootcause::Result<T> {
+ let response = self
+ .credentialed(request)
+ .send()
+ .await
+ .context(format!("could not reach the service to {what}"))?;
+ let status = response.status();
+ if !status.is_success() {
+ let message = response.text().await.unwrap_or_default();
+ rootcause::bail!("the service answered {status} to {what}: {message}");
+ }
+ Ok(response
+ .json()
+ .await
+ .context(format!("could not read the service's answer to {what}"))?)
+ }
+
+ /// Reconcile: return a feed that exists, points at this daemon, and
+ /// whose secret this daemon holds.
+ pub async fn ensure_feed(&self) -> rootcause::Result<FeedRegistration> {
+ let me: Bot = self
+ .read(
+ "identify the bot",
+ self.http.get(format!("{}/bots/me", self.base)),
+ )
+ .await?;
+ let bot = me.id;
+
+ let list: ListWebhooksResponse = self
+ .read(
+ "list webhooks",
+ self.http.get(format!("{}/webhook/webhooks", self.base)),
+ )
+ .await?;
+ let mine: Vec<&Webhook> = list
+ .webhooks
+ .iter()
+ .filter(|row| row.namespace == feed_namespace(bot))
+ .collect();
+
+ // The remembered feed, when it still exists and points here.
+ if let Some(state) = self.state_store.load()?
+ && let Some(row) = mine.iter().find(|row| row.id == state.webhook_id)
+ && row.endpoint_url == self.public_url
+ {
+ return Ok(FeedRegistration {
+ webhook_id: state.webhook_id,
+ signing_secret: state.signing_secret,
+ is_valid: row.is_valid,
+ });
+ }
+
+ // Anything else of ours is a feed whose secret is lost or whose
+ // endpoint moved: delete before recreating, since one bot needs
+ // exactly one feed.
+ for row in mine {
+ tracing::info!(webhook_id = %row.id, "removing this bot's stale trigger feed");
+ let response = self
+ .credentialed(
+ self.http
+ .delete(format!("{}/webhook/webhooks/{}", self.base, row.id)),
+ )
+ .send()
+ .await?;
+ if !response.status().is_success() {
+ tracing::warn!(webhook_id = %row.id, status = %response.status(), "stale feed delete refused");
+ }
+ }
+
+ let created: CreateWebhookResponse = self
+ .read(
+ "create the trigger feed",
+ self.http
+ .post(format!("{}/webhook/webhooks", self.base))
+ .json(&CreateWebhookRequest {
+ scope: WebhookScope::User,
+ namespace: feed_namespace(bot),
+ name: "Agent trigger feed".to_owned(),
+ endpoint_url: self.public_url.clone(),
+ headers: None,
+ // Scoped to this bot: trigger events name the bot they
+ // are for, so without this the feed would receive
+ // every bot's triggers in channels its owner can see.
+ filters: vec![WebhookFilter {
+ events: trigger_events(),
+ ids: Some(vec![bot.to_string()]),
+ }],
+ }),
+ )
+ .await?;
+
+ self.state_store.save(&FeedState {
+ webhook_id: created.id.clone(),
+ signing_secret: created.signing_secret.clone(),
+ })?;
+ tracing::info!(webhook_id = %created.id, %bot, "trigger feed registered");
+
+ Ok(FeedRegistration {
+ webhook_id: created.id,
+ signing_secret: created.signing_secret,
+ is_valid: created.is_valid,
+ })
+ }
+
+ /// Ask the service to validate the feed's endpoint; call once serving.
+ /// Best-effort: a rate-limited or failed validation is retried by a
+ /// later boot, and deliveries to an unvalidated feed simply wait.
+ pub async fn request_validation(&self, webhook_id: &str) {
+ let result = self
+ .credentialed(self.http.post(format!(
+ "{}/webhook/webhooks/{}/validate",
+ self.base, webhook_id
+ )))
+ .send()
+ .await;
+ match result {
+ Ok(response) if response.status().is_success() => {
+ tracing::info!(%webhook_id, "trigger feed validated");
+ }
+ Ok(response) => {
+ tracing::warn!(%webhook_id, status = %response.status(), "feed validation refused");
+ }
+ Err(error) => {
+ tracing::warn!(error = ?error, %webhook_id, "feed validation failed");
+ }
+ }
+ }
+}
diff --git a/crates/coding_agent_worker/src/outbound/registration/test.rs b/crates/coding_agent_worker/src/outbound/registration/test.rs
new file mode 100644
index 0000000000..45cb970968
--- /dev/null
+++ b/crates/coding_agent_worker/src/outbound/registration/test.rs
@@ -0,0 +1,86 @@
+use std::{
+ path::{Path, PathBuf},
+ time::{SystemTime, UNIX_EPOCH},
+};
+
+use super::*;
+
+struct TestFile(PathBuf);
+
+impl TestFile {
+ fn new() -> Self {
+ let nonce = SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .expect("time after epoch")
+ .as_nanos();
+ Self(std::env::temp_dir().join(format!(
+ "coding-agent-worker-feed-state-{}-{nonce}.json",
+ std::process::id()
+ )))
+ }
+
+ fn path(&self) -> &Path {
+ &self.0
+ }
+
+ fn store(&self) -> FileFeedStateStore {
+ FileFeedStateStore {
+ path: self.0.clone(),
+ }
+ }
+}
+
+impl Drop for TestFile {
+ fn drop(&mut self) {
+ let _ = std::fs::remove_file(&self.0);
+ }
+}
+
+#[test]
+fn missing_feed_state_is_absent() {
+ let file = TestFile::new();
+
+ assert_eq!(file.store().load().expect("load state"), None);
+}
+
+#[test]
+fn malformed_feed_state_is_absent() {
+ let file = TestFile::new();
+ std::fs::write(file.path(), "not json").expect("write malformed state");
+
+ assert_eq!(file.store().load().expect("load state"), None);
+}
+
+#[test]
+fn feed_state_round_trips() {
+ let file = TestFile::new();
+ let state = FeedState {
+ webhook_id: "webhook-id".to_owned(),
+ signing_secret: "signing-secret".to_owned(),
+ };
+
+ let store = file.store();
+ store.save(&state).expect("save state");
+
+ assert_eq!(store.load().expect("load state"), Some(state));
+}
+
+#[cfg(unix)]
+#[test]
+fn saved_feed_state_is_private() {
+ use std::os::unix::fs::PermissionsExt as _;
+
+ let file = TestFile::new();
+ let state = FeedState {
+ webhook_id: "webhook-id".to_owned(),
+ signing_secret: "signing-secret".to_owned(),
+ };
+
+ file.store().save(&state).expect("save state");
+
+ let mode = std::fs::metadata(file.path())
+ .expect("state metadata")
+ .permissions()
+ .mode();
+ assert_eq!(mode & 0o777, 0o600);
+}
diff --git a/crates/coding_agent_worker/src/runtime.rs b/crates/coding_agent_worker/src/runtime.rs
new file mode 100644
index 0000000000..3ff1f2ba9f
--- /dev/null
+++ b/crates/coding_agent_worker/src/runtime.rs
@@ -0,0 +1,193 @@
+//! This daemon's one connection to the harness service, and the one harness
+//! process behind it.
+//!
+//! A daemon serves a single bot, and a bot's runtime is a single connection:
+//! ACP initializes per connection and tags every session-scoped message with a
+//! `sessionId`, so one socket and one harness process carry every session this
+//! bot is running. The service decides which sessions those are - it binds a
+//! session when work arrives for it - so nothing here is per-session at all.
+//!
+//! What that buys: a harness starts once per daemon rather than once per
+//! session, so only the first mention after boot pays for a cold agent.
+
+use std::sync::Arc;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::time::Duration;
+
+use agent_runtime_protocol::domain::connection::RuntimeChannel;
+use tokio_retry::RetryIf;
+use tokio_retry::strategy::{ExponentialBackoff, FixedInterval};
+use tokio_tungstenite::tungstenite;
+
+use crate::config::{Harness, MacroApi};
+use crate::harness;
+use crate::outbound::link;
+
+/// A dial races the delivery that asked for it, so it retries quickly and
+/// briefly: a proxy or service mid restart is worth waiting out, a longer
+/// outage is better answered by failing the delivery and being redelivered.
+const DIAL_ATTEMPTS: usize = 3;
+const DIAL_RETRY_DELAY: Duration = Duration::from_millis(500);
+
+/// How many times a dropped connection is rebuilt before the daemon waits for
+/// its next delivery to try again. Bounded because a bridge that fails the
+/// instant it starts - a harness binary that is missing, say - would otherwise
+/// rebuild itself forever. Nobody is waiting on these, so they back off.
+const REBUILD_ATTEMPTS: usize = 4;
+
+/// The daemon's connection to its bot's sessions.
+///
+/// At most one is live. The flag is the claim on it: a delivery that finds it
+/// unset dials, and the task serving the connection clears it on the way out,
+/// so "set" always means "somebody is serving, or about to be".
+pub struct Runtime {
+ macro_api: MacroApi,
+ harness: Harness,
+ live: Arc<AtomicBool>,
+}
+
+impl Runtime {
+ /// A runtime that dials with the given credentials and spawns the given
+ /// harness.
+ pub fn new(macro_api: MacroApi, harness: Harness) -> Self {
+ Self {
+ macro_api,
+ harness,
+ live: Arc::new(AtomicBool::new(false)),
+ }
+ }
+
+ /// Ensure this bot's runtime is connected, dialing if it is not. Returns
+ /// once the dial has succeeded (or was unnecessary), with the harness
+ /// bridged in a background task.
+ pub async fn ensure_connected(&self) -> Result<(), tungstenite::Error> {
+ if self
+ .live
+ .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
+ .is_err()
+ {
+ return Ok(());
+ }
+
+ let url = self.macro_api.gateway_url();
+ let channel = match dial(&self.macro_api, &url, dial_strategy()).await {
+ Ok(channel) => channel,
+ Err(error) => {
+ self.live.store(false, Ordering::Release);
+ return Err(error);
+ }
+ };
+
+ tokio::spawn(serve(
+ url,
+ channel,
+ self.macro_api.clone(),
+ self.harness.clone(),
+ Arc::clone(&self.live),
+ ));
+ Ok(())
+ }
+}
+
+/// Bridge the harness until the connection ends for good, rebuilding through
+/// failures that look transient. Holds the claim for its whole life - including
+/// across rebuilds, so a reconnecting runtime is never raced by a second one -
+/// and releases it on the way out.
+async fn serve(
+ gateway_url: String,
+ channel: RuntimeChannel,
+ macro_api: MacroApi,
+ harness: Harness,
+ live: Arc<AtomicBool>,
+) {
+ tracing::info!("harness bridge starting");
+ // A bridge that ends cleanly is a runtime that is done being asked for
+ // anything; the next delivery dials again.
+ match harness::bridge(&harness, channel).await {
+ Ok(()) => tracing::info!("harness bridge ended"),
+ Err(error) => {
+ tracing::warn!(error = ?error, "harness bridge ended with an error");
+ rebuild(&gateway_url, &macro_api, &harness).await;
+ }
+ }
+ live.store(false, Ordering::Release);
+}
+
+/// Dial and serve again, as one retried operation: ending cleanly stops it, as
+/// does a gateway verdict no retry can change.
+async fn rebuild(gateway_url: &str, macro_api: &MacroApi, harness: &Harness) {
+ let outcome = RetryIf::start(
+ rebuild_strategy(),
+ || async {
+ let channel = dial(macro_api, gateway_url, dial_strategy())
+ .await
+ .map_err(ServeError::Dial)?;
+ tracing::info!("harness bridge restarting");
+ harness::bridge(harness, channel)
+ .await
+ .map_err(ServeError::Bridge)
+ },
+ worth_rebuilding,
+ )
+ .await;
+
+ match outcome {
+ Ok(()) => tracing::info!("harness bridge ended"),
+ Err(error) => tracing::warn!(
+ error = ?error,
+ "could not keep a harness bridge up; waiting for the next delivery"
+ ),
+ }
+}
+
+/// Why serving the runtime stopped.
+#[derive(Debug, thiserror::Error)]
+enum ServeError {
+ #[error(transparent)]
+ Dial(tungstenite::Error),
+ #[error(transparent)]
+ Bridge(harness::BridgeError),
+}
+
+/// Whether rebuilding could plausibly go better. A failed bridge says nothing
+/// about the next one, so only the gateway's own verdict stops this.
+fn worth_rebuilding(error: &ServeError) -> bool {
+ match error {
+ ServeError::Dial(error) => worth_redialing(error),
+ ServeError::Bridge(_) => true,
+ }
+}
+
+/// Dial the gateway, retrying on the failures a retry can fix.
+async fn dial(
+ macro_api: &MacroApi,
+ gateway_url: &str,
+ strategy: impl IntoIterator<Item = Duration>,
+) -> Result<RuntimeChannel, tungstenite::Error> {
+ RetryIf::start(
+ strategy,
+ || link::dial(gateway_url, &macro_api.bot_token, &macro_api.bot_scope),
+ worth_redialing,
+ )
+ .await
+}
+
+/// Whether dialing again could plausibly answer differently. A 4xx is the
+/// gateway's verdict on this bot - not an agent bot, credentials refused - and
+/// asking again only repeats it.
+fn worth_redialing(error: &tungstenite::Error) -> bool {
+ !matches!(
+ error,
+ tungstenite::Error::Http(response) if response.status().is_client_error()
+ )
+}
+
+fn dial_strategy() -> impl Iterator<Item = Duration> {
+ FixedInterval::new(DIAL_RETRY_DELAY).take(DIAL_ATTEMPTS - 1)
+}
+
+fn rebuild_strategy() -> impl Iterator<Item = Duration> {
+ ExponentialBackoff::from_millis(2)
+ .factor(500)
+ .take(REBUILD_ATTEMPTS - 1)
+}
diff --git a/crates/coding_agent_worker/src/webhook.rs b/crates/coding_agent_worker/src/webhook.rs
new file mode 100644
index 0000000000..2c7ea379ce
--- /dev/null
+++ b/crates/coding_agent_worker/src/webhook.rs
@@ -0,0 +1,181 @@
+//! Signed webhook ingest: agent-trigger events delivered over HTTP, driving
+//! sessions the same way a human driving the API by hand would - create,
+//! dial, prompt.
+//!
+//! Non-2xx responses make the deliverer redeliver, so failures are only
+//! signalled for work worth retrying: an undecodable payload or an event
+//! this daemon has nothing to do for is acked and dropped.
+
+use std::sync::Arc;
+
+use agent_session::domain::model::AgentSessionId;
+use agent_trigger::domain::broker_events::{
+ AgentTriggerTopicEvent, ExistingAgentSessionEvent, NewAgentSessionEvent,
+};
+use axum::Router;
+use axum::body::Bytes;
+use axum::extract::State;
+use axum::http::{HeaderMap, StatusCode};
+use axum::routing::post;
+use macro_event_broker::Event;
+use macro_user_id::user_id::MacroUserIdStr;
+use macro_uuid::Uuid;
+use webhook_signature::{SIGNATURE_HEADER, TIMESTAMP_HEADER};
+
+#[cfg(test)]
+mod test;
+
+/// What one trigger event asks this daemon to do.
+///
+/// Pure translation from the event vocabulary, split out so it can be tested
+/// without HTTP or a live service - the same shape as the harness service's
+/// own Kafka inbound.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum TriggerWork {
+ /// Open a session for a mention, serve it, and forward the mention as
+ /// its first prompt.
+ OpenAndPrompt {
+ /// Who asked; owns the session and authors the prompt.
+ sender: MacroUserIdStr<'static>,
+ /// Channel the mention was posted in.
+ channel_id: Uuid,
+ /// Thread the mention roots.
+ thread_id: Uuid,
+ /// The mentioning message.
+ message_id: Uuid,
+ /// The mention's text: the first prompt, and the announcement quote.
+ content: String,
+ },
+ /// Forward a message into a session that already exists, serving it
+ /// first if this daemon is not already. Just the prompt: the harness
+ /// service announces the reply into its channel from the trigger event
+ /// it observed.
+ PromptExisting {
+ /// The session to feed.
+ session: AgentSessionId,
+ /// Who sent the message.
+ sender: MacroUserIdStr<'static>,
+ /// The message's text.
+ content: String,
+ },
+}
+
+/// Why an event yielded no work. Only for logging - none of these are
+/// errors, and the deliverer is acked either way.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Skipped {
+ /// The sender is not a user, so there is nobody to act for.
+ NotFromUser,
+ /// An event shape this daemon does not recognise yet - the trigger's
+ /// vocabulary is non-exhaustive on purpose.
+ Unrecognized,
+}
+
+/// Translate one trigger event into this daemon's work, or a reason to skip.
+pub fn trigger_to_work(event: AgentTriggerTopicEvent) -> Result<TriggerWork, Skipped> {
+ match event {
+ AgentTriggerTopicEvent::New(NewAgentSessionEvent::TopLevelMentioned(mentioned)) => {
+ let message = mentioned.message;
+ let sender = message
+ .sender
+ .as_user()
+ .cloned()
+ .ok_or(Skipped::NotFromUser)?;
+ Ok(TriggerWork::OpenAndPrompt {
+ sender,
+ channel_id: message.channel_id,
+ // A top-level mention roots its own thread; a mention inside
+ // a thread answers into that thread.
+ thread_id: message.thread_id.unwrap_or(message.message_id),
+ message_id: message.message_id,
+ content: message.content,
+ })
+ }
+ AgentTriggerTopicEvent::Existing(ExistingAgentSessionEvent::Channel(metadata)) => {
+ let sender = metadata
+ .message
+ .sender
+ .as_user()
+ .cloned()
+ .ok_or(Skipped::NotFromUser)?;
+ Ok(TriggerWork::PromptExisting {
+ session: metadata.session_id,
+ sender,
+ content: metadata.message.content,
+ })
+ }
+ _ => Err(Skipped::Unrecognized),
+ }
+}
+
+/// Executes translated work. The one capability the route needs, so tests
+/// can drive it without a live service or harness.
+pub trait WorkExecutor: Send + Sync + 'static {
+ /// Do one event's work; an error is worth a redelivery.
+ fn execute(
+ &self,
+ work: TriggerWork,
+ ) -> impl Future<Output = Result<(), crate::dispatch::DispatchError>> + Send;
+}
+
+/// State for the events route.
+pub struct WebhookState<Executor> {
+ /// Where translated work goes.
+ pub executor: Executor,
+ /// The webhook's signing secret, shared with the deliverer.
+ pub signing_secret: String,
+}
+
+/// Build the router serving `POST /macro-events`.
+pub fn webhook_router<Executor: WorkExecutor>(state: WebhookState<Executor>) -> Router {
+ Router::new()
+ .route("/macro-events", post(ingest::<Executor>))
+ .with_state(Arc::new(state))
+}
+
+/// Verify, decode, translate, execute.
+async fn ingest<Executor: WorkExecutor>(
+ State(state): State<Arc<WebhookState<Executor>>>,
+ headers: HeaderMap,
+ body: Bytes,
+) -> StatusCode {
+ let header = |name: &str| headers.get(name).and_then(|value| value.to_str().ok());
+ let (Some(timestamp), Some(signature)) = (header(TIMESTAMP_HEADER), header(SIGNATURE_HEADER))
+ else {
+ return StatusCode::UNAUTHORIZED;
+ };
+ if !webhook_signature::verify(&state.signing_secret, timestamp, &body, signature) {
+ return StatusCode::UNAUTHORIZED;
+ }
+
+ let Ok(event) = serde_json::from_slice::<Event<AgentTriggerTopicEvent>>(&body) else {
+ // The webhook service's validation probe is the everyday case here:
+ // signed, not a trigger event, and answered 200 - which is exactly
+ // what marks the feed valid. Anything else undecodable will not
+ // improve on redelivery either: ack and drop.
+ if serde_json::from_slice::<serde_json::Value>(&body)
+ .ok()
+ .and_then(|value| value.get("event").cloned())
+ .is_some_and(|name| name == "webhook.validation.test")
+ {
+ tracing::info!("acknowledged the feed validation probe");
+ } else {
+ tracing::warn!("undecodable agent-trigger webhook payload; acked");
+ }
+ return StatusCode::OK;
+ };
+
+ match trigger_to_work(event.event) {
+ Ok(work) => match state.executor.execute(work).await {
+ Ok(()) => StatusCode::OK,
+ Err(error) => {
+ tracing::error!(error = ?error, "agent-trigger webhook work failed");
+ StatusCode::INTERNAL_SERVER_ERROR
+ }
+ },
+ Err(skipped) => {
+ tracing::debug!(?skipped, "agent-trigger webhook event skipped");
+ StatusCode::OK
+ }
+ }
+}
diff --git a/crates/coding_agent_worker/src/webhook/test.rs b/crates/coding_agent_worker/src/webhook/test.rs
new file mode 100644
index 0000000000..106708fe86
--- /dev/null
+++ b/crates/coding_agent_worker/src/webhook/test.rs
@@ -0,0 +1,193 @@
+use super::*;
+use agent_trigger::domain::broker_events::AgentBotMentionedEvent;
+use channel_sender::ChannelSender;
+use channels::domain::broker_events::ChannelMessagePostedMetadata;
+use channels::domain::models::ChannelType;
+use chrono::Utc;
+use std::sync::Mutex;
+
+const SECRET: &str = "signing-secret";
+
+fn test_session() -> AgentSessionId {
+ AgentSessionId::new_from_uuid(Uuid::from_u128(0xA))
+}
+
+fn sender() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from_email("[email protected]").unwrap()
+}
+
+fn message(content: &str, thread_id: Option<Uuid>) -> ChannelMessagePostedMetadata {
+ ChannelMessagePostedMetadata {
+ channel_id: Uuid::from_u128(1),
+ message_id: Uuid::from_u128(2),
+ thread_id,
+ sender: ChannelSender::new_from_user(sender()),
+ triggered_by: None,
+ channel_type: ChannelType::Public,
+ content: content.to_owned(),
+ mentions: vec![],
+ attachments: vec![],
+ created_at: Utc::now(),
+ }
+}
+
+fn mention(content: &str) -> AgentTriggerTopicEvent {
+ AgentTriggerTopicEvent::New(NewAgentSessionEvent::TopLevelMentioned(
+ AgentBotMentionedEvent {
+ bot_id: bot_id::BotId::TEST_A,
+ message: message(content, None),
+ },
+ ))
+}
+
+fn follow_up(content: &str) -> AgentTriggerTopicEvent {
+ AgentTriggerTopicEvent::Existing(ExistingAgentSessionEvent::Channel(
+ agent_trigger::domain::broker_events::ChannelEventMetadata {
+ bot_id: bot_id::BotId::TEST_A,
+ session_id: test_session(),
+ message: message(content, Some(Uuid::from_u128(7))),
+ },
+ ))
+}
+
+#[test]
+fn a_mention_becomes_open_and_prompt_rooting_its_own_thread() {
+ let work = trigger_to_work(mention("fix the test")).expect("a mention is work");
+ assert_eq!(
+ work,
+ TriggerWork::OpenAndPrompt {
+ sender: sender(),
+ channel_id: Uuid::from_u128(1),
+ thread_id: Uuid::from_u128(2),
+ message_id: Uuid::from_u128(2),
+ content: "fix the test".to_owned(),
+ }
+ );
+}
+
+#[test]
+fn a_follow_up_becomes_prompt_existing() {
+ let work = trigger_to_work(follow_up("keep going")).expect("a follow-up is work");
+ assert_eq!(
+ work,
+ TriggerWork::PromptExisting {
+ session: test_session(),
+ sender: sender(),
+ content: "keep going".to_owned(),
+ }
+ );
+}
+
+#[test]
+fn a_bots_own_message_is_skipped() {
+ let mut event = mention("self talk");
+ if let AgentTriggerTopicEvent::New(NewAgentSessionEvent::TopLevelMentioned(mentioned)) =
+ &mut event
+ {
+ mentioned.message.sender = ChannelSender::new_from_bot(bot_id::BotId::TEST_B);
+ }
+ assert_eq!(trigger_to_work(event), Err(Skipped::NotFromUser));
+}
+
+/// Records executed work instead of doing anything.
+#[derive(Default)]
+struct RecordingExecutor {
+ executed: Mutex<Vec<TriggerWork>>,
+ fail: bool,
+}
+
+impl WorkExecutor for std::sync::Arc<RecordingExecutor> {
+ async fn execute(&self, work: TriggerWork) -> Result<(), crate::dispatch::DispatchError> {
+ self.executed.lock().unwrap().push(work);
+ if self.fail {
+ return Err(crate::dispatch::DispatchError::Api(
+ crate::outbound::agent_session::ApiError::Refused {
+ status: reqwest::StatusCode::INTERNAL_SERVER_ERROR,
+ message: "boom".to_owned(),
+ },
+ ));
+ }
+ Ok(())
+ }
+}
+
+fn delivery(event: &AgentTriggerTopicEvent, secret: &str) -> (HeaderMap, Bytes) {
+ let body = serde_json::to_vec(&Event::new(event.clone())).unwrap();
+ let timestamp = "1755188000";
+ let signature = webhook_signature::sign(secret, timestamp, &body).unwrap();
+ let mut headers = HeaderMap::new();
+ headers.insert(TIMESTAMP_HEADER, timestamp.parse().unwrap());
+ headers.insert(SIGNATURE_HEADER, signature.parse().unwrap());
+ (headers, Bytes::from(body))
+}
+
+fn state(
+ executor: std::sync::Arc<RecordingExecutor>,
+) -> Arc<WebhookState<std::sync::Arc<RecordingExecutor>>> {
+ Arc::new(WebhookState {
+ executor,
+ signing_secret: SECRET.to_owned(),
+ })
+}
+
+#[tokio::test]
+async fn a_signed_mention_executes() {
+ let executor = std::sync::Arc::new(RecordingExecutor::default());
+ let (headers, body) = delivery(&mention("fix it"), SECRET);
+
+ let status = ingest(State(state(executor.clone())), headers, body).await;
+
+ assert_eq!(status, StatusCode::OK);
+ assert_eq!(executor.executed.lock().unwrap().len(), 1);
+}
+
+#[tokio::test]
+async fn a_bad_signature_is_rejected_before_anything_runs() {
+ let executor = std::sync::Arc::new(RecordingExecutor::default());
+ let (headers, body) = delivery(&mention("fix it"), "wrong-secret");
+
+ let status = ingest(State(state(executor.clone())), headers, body).await;
+
+ assert_eq!(status, StatusCode::UNAUTHORIZED);
+ assert!(executor.executed.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn missing_signature_headers_are_rejected() {
+ let executor = std::sync::Arc::new(RecordingExecutor::default());
+ let (_, body) = delivery(&mention("fix it"), SECRET);
+
+ let status = ingest(State(state(executor.clone())), HeaderMap::new(), body).await;
+
+ assert_eq!(status, StatusCode::UNAUTHORIZED);
+ assert!(executor.executed.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn an_undecodable_payload_is_acked_and_dropped() {
+ let executor = std::sync::Arc::new(RecordingExecutor::default());
+ let body = Bytes::from_static(b"not json");
+ let timestamp = "1755188000";
+ let signature = webhook_signature::sign(SECRET, timestamp, &body).unwrap();
+ let mut headers = HeaderMap::new();
+ headers.insert(TIMESTAMP_HEADER, timestamp.parse().unwrap());
+ headers.insert(SIGNATURE_HEADER, signature.parse().unwrap());
+
+ let status = ingest(State(state(executor.clone())), headers, body).await;
+
+ assert_eq!(status, StatusCode::OK);
+ assert!(executor.executed.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn failed_work_asks_for_redelivery() {
+ let executor = std::sync::Arc::new(RecordingExecutor {
+ fail: true,
+ ..Default::default()
+ });
+ let (headers, body) = delivery(&mention("fix it"), SECRET);
+
+ let status = ingest(State(state(executor.clone())), headers, body).await;
+
+ assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
+}
diff --git a/crates/macro_db_client/migrations/20260819214237_agent_session_workspace.down.sql b/crates/macro_db_client/migrations/20260819214237_agent_session_workspace.down.sql
new file mode 100644
index 0000000000..d2a6c6cfe1
--- /dev/null
+++ b/crates/macro_db_client/migrations/20260819214237_agent_session_workspace.down.sql
@@ -0,0 +1,2 @@
+ALTER TABLE agent_session
+ DROP COLUMN workspace;
diff --git a/crates/macro_db_client/migrations/20260819214237_agent_session_workspace.up.sql b/crates/macro_db_client/migrations/20260819214237_agent_session_workspace.up.sql
new file mode 100644
index 0000000000..7388d9cec3
--- /dev/null
+++ b/crates/macro_db_client/migrations/20260819214237_agent_session_workspace.up.sql
@@ -0,0 +1,14 @@
+-- The working directory the session's harness runs in, snapshotted at
+-- creation like model/harness/repo_url. Managed containers pass the path
+-- baked into their image; external (self-hosted) runtimes state theirs when
+-- they create the session. Snapshotting is what keeps resume/load correct:
+-- they re-enter the directory the session actually ran in, not whatever the
+-- runtime is configured with today.
+--
+-- The default exists only to backfill rows created before this column, and
+-- is dropped immediately: every new row states its workspace explicitly.
+ALTER TABLE agent_session
+ ADD COLUMN workspace TEXT NOT NULL DEFAULT '/workspace';
+
+ALTER TABLE agent_session
+ ALTER COLUMN workspace DROP DEFAULT;
diff --git a/crates/macro_db_client/migrations/20260819214239_agent_session_repo_url_nullable.down.sql b/crates/macro_db_client/migrations/20260819214239_agent_session_repo_url_nullable.down.sql
new file mode 100644
index 0000000000..fd3299c030
--- /dev/null
+++ b/crates/macro_db_client/migrations/20260819214239_agent_session_repo_url_nullable.down.sql
@@ -0,0 +1,4 @@
+UPDATE agent_session SET repo_url = '' WHERE repo_url IS NULL;
+
+ALTER TABLE agent_session
+ ALTER COLUMN repo_url SET NOT NULL;
diff --git a/crates/macro_db_client/migrations/20260819214239_agent_session_repo_url_nullable.up.sql b/crates/macro_db_client/migrations/20260819214239_agent_session_repo_url_nullable.up.sql
new file mode 100644
index 0000000000..f708de710f
--- /dev/null
+++ b/crates/macro_db_client/migrations/20260819214239_agent_session_repo_url_nullable.up.sql
@@ -0,0 +1,5 @@
+-- The repository a session works against becomes optional: external
+-- runtimes own their workspace contents, and stating the repo is a courtesy
+-- they may skip. Managed sessions keep stamping theirs.
+ALTER TABLE agent_session
+ ALTER COLUMN repo_url DROP NOT NULL;
diff --git a/crates/webhook/Cargo.toml b/crates/webhook/Cargo.toml
index 26f4c82a91..6f57624dd5 100644
--- a/crates/webhook/Cargo.toml
+++ b/crates/webhook/Cargo.toml
@@ -31,6 +31,7 @@ inbound = [
"rate_limit/axum",
]
ingestion = [
+ "dep:agent_trigger",
"dep:channels",
"dep:documents",
"dep:entity_access",
@@ -39,11 +40,9 @@ ingestion = [
"ports",
]
outbound = [
- "dep:hex",
- "dep:hmac",
+ "dep:webhook_signature",
"dep:macro_uuid",
"dep:reqwest",
- "dep:sha2",
"dep:sqlx",
"dep:sqs_client",
"dep:tokio",
@@ -57,6 +56,7 @@ worker = ["dep:tokio", "ports"]
anyhow = { workspace = true }
axum = { workspace = true, optional = true }
axum-extra = { workspace = true, optional = true }
+agent_trigger = { path = "../agent_trigger", optional = true }
channels = { path = "../channels", default-features = false, optional = true }
chrono = { workspace = true }
documents = { path = "../documents", default-features = false, optional = true }
@@ -64,8 +64,6 @@ entity_access = { path = "../entity_access", default-features = false, features
"ports",
], optional = true }
futures = { workspace = true, optional = true }
-hex = { workspace = true, optional = true }
-hmac = { workspace = true, optional = true }
kafka_util = { path = "../kafka_util", optional = true }
macro_authorization = { path = "../macro_authorization", optional = true, default-features = false, features = [
"axum",
@@ -82,7 +80,7 @@ reqwest = { workspace = true, optional = true }
rootcause = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true, optional = true }
-sha2 = { workspace = true, optional = true }
+webhook_signature = { path = "../webhook_signature", optional = true }
sqlx = { workspace = true, optional = true }
sqs_client = { path = "../sqs_client", default-features = false, optional = true }
thiserror = { workspace = true }
@@ -95,7 +93,8 @@ uuid = { workspace = true, optional = true }
workspace-hack = { version = "0.1", path = "../workspace-hack" }
[dev-dependencies]
-bot_id = { path = "../bot_id" }
+agent_session = { path = "../agent_session", features = ["test-utils"] }
+bot_id = { path = "../bot_id", features = ["test-utils"] }
channel_sender = { path = "../channel_sender" }
macro_db_migrator = { path = "../macro_db_migrator" }
rate_limit = { path = "../rate_limit", default-features = false, features = [
diff --git a/crates/webhook/src/domain/ingestion.rs b/crates/webhook/src/domain/ingestion.rs
index 4c1c1a9550..d74598f963 100644
--- a/crates/webhook/src/domain/ingestion.rs
+++ b/crates/webhook/src/domain/ingestion.rs
@@ -13,6 +13,7 @@ use crate::domain::{
models::{NormalizedWebhookEvent, WebhookEventQueueMessage},
ports::{WebhookEventEnqueuer, WebhookRepo, WebhookWorkspaceResolver},
};
+use agent_trigger::domain::broker_events::AgentTriggerTopicEvent;
use channels::domain::broker_events::ChannelTopicEvent;
use chrono::Utc;
use documents::domain::events::DocumentTopicEvent;
@@ -98,6 +99,12 @@ pub trait WebhookEventIngestionService: Clone + Send + Sync + 'static {
&self,
event: Event<WebhookTopicEvent>,
) -> impl Future<Output = Result<(), WebhookEventIngestionError>> + Send;
+
+ /// Ingest one `macro.agent_sessions` event envelope.
+ fn ingest_agent_trigger_event(
+ &self,
+ event: Event<AgentTriggerTopicEvent>,
+ ) -> impl Future<Output = Result<(), WebhookEventIngestionError>> + Send;
}
/// Webhook event ingestion service implementation.
@@ -197,7 +204,14 @@ where
.await
.map_err(|error| WebhookEventIngestionError::Repository(error.into()))?;
tracing::Span::current().record("match_count", webhooks.len());
+ self.enqueue_all(webhooks, event).await
+ }
+ async fn enqueue_all(
+ &self,
+ webhooks: Vec<crate::domain::models::Webhook>,
+ event: NormalizedWebhookEvent,
+ ) -> Result<(), WebhookEventIngestionError> {
let enqueue_results = join_all(webhooks.into_iter().map(|webhook| {
let enqueuer = self.enqueuer.clone();
let webhook_id = webhook.id;
@@ -362,6 +376,73 @@ fn normalized_event(
}
}
+/// Whose access decides who may see one trigger event.
+///
+/// Not the bot the event names: that is what a subscriber filters on, and a
+/// bot is not an entity anyone holds access to.
+struct TriggerAudience {
+ entity_id: String,
+ entity_type: EntityType,
+}
+
+/// Normalize one agent-trigger event.
+///
+/// The entity - and the ordering key, mirroring the broker's partitioning -
+/// is the bot: a subscriber consumes a bot's whole trigger stream, in order.
+/// Returned alongside is whose access gates it, which differs by shape.
+///
+/// A mention that opens a session has no session yet, so the channel it was
+/// posted in is the only thing to ask. Once a session exists it carries its
+/// own grants - its owner, and the channel it came from - so the session is
+/// the authoritative audience, and whatever channel a later message happened
+/// to land in is incidental to it.
+fn normalized_agent_trigger_event(
+ event: &Event<AgentTriggerTopicEvent>,
+) -> Result<(NormalizedWebhookEvent, TriggerAudience), WebhookEventIngestionError> {
+ use agent_trigger::domain::broker_events::{
+ AgentTriggerEventName, ExistingAgentSessionEvent, NewAgentSessionEvent,
+ };
+
+ let (bot_id, audience) = match &event.event {
+ AgentTriggerTopicEvent::New(NewAgentSessionEvent::TopLevelMentioned(mentioned)) => (
+ mentioned.bot_id,
+ TriggerAudience {
+ entity_id: mentioned.message.channel_id.to_string(),
+ entity_type: EntityType::Channel,
+ },
+ ),
+ AgentTriggerTopicEvent::Existing(ExistingAgentSessionEvent::Channel(metadata)) => (
+ metadata.bot_id,
+ TriggerAudience {
+ entity_id: metadata.session_id.to_string(),
+ entity_type: EntityType::AgentSession,
+ },
+ ),
+ // Both trigger enums are non-exhaustive on purpose; an unknown shape
+ // has no bot to route to. Permanent, so the consumer skips it.
+ _ => {
+ return Err(WebhookEventIngestionError::InvalidEntityId {
+ entity_type: "bot",
+ entity_id: "unrecognized agent-trigger event shape".to_owned(),
+ });
+ }
+ };
+ let event_name: &'static str = AgentTriggerEventName::from(&event.event).into();
+ let broker_envelope = serde_json::to_value(event)?;
+ let bot_id = bot_id.to_string();
+ Ok((
+ normalized_event(
+ event.event_id,
+ event.schema_version,
+ event_name,
+ "bot",
+ &bot_id,
+ broker_envelope,
+ ),
+ audience,
+ ))
+}
+
impl<A, R, Q> WebhookEventIngestionService for WebhookEventIngestionServiceImpl<A, R, Q>
where
A: EntityAccessService,
@@ -398,4 +479,21 @@ where
let (event, workspace_id) = normalized_webhook_event(&event)?;
self.match_and_enqueue(event, vec![workspace_id]).await
}
+
+ #[tracing::instrument(skip(self, event), fields(event_id = %event.event_id), err)]
+ async fn ingest_agent_trigger_event(
+ &self,
+ event: Event<AgentTriggerTopicEvent>,
+ ) -> Result<(), WebhookEventIngestionError> {
+ let (event, audience) = normalized_agent_trigger_event(&event)?;
+ let accessors = self
+ .users_with_access(&audience.entity_id, audience.entity_type)
+ .await?;
+ let workspace_ids = self
+ .repository
+ .resolve_workspace_ids(accessors)
+ .await
+ .map_err(|error| WebhookEventIngestionError::WorkspaceResolution(error.into()))?;
+ self.match_and_enqueue(event, workspace_ids).await
+ }
}
diff --git a/crates/webhook/src/domain/ingestion/test.rs b/crates/webhook/src/domain/ingestion/test.rs
index 8452946fcc..fe28ba09a8 100644
--- a/crates/webhook/src/domain/ingestion/test.rs
+++ b/crates/webhook/src/domain/ingestion/test.rs
@@ -1301,3 +1301,137 @@ async fn entity_access_internal_error_is_transient() {
));
assert!(error.is_transient());
}
+
+fn agent_trigger_new_event() -> Event<agent_trigger::domain::broker_events::AgentTriggerTopicEvent>
+{
+ use agent_trigger::domain::broker_events::{
+ AgentBotMentionedEvent, AgentTriggerTopicEvent, NewAgentSessionEvent,
+ };
+ use channels::domain::broker_events::ChannelMessagePostedMetadata;
+ use channels::domain::models::ChannelType;
+
+ Event::new(AgentTriggerTopicEvent::New(
+ NewAgentSessionEvent::TopLevelMentioned(AgentBotMentionedEvent {
+ bot_id: bot_id::BotId::new_from_uuid(uuid::Uuid::from_u128(0xB07)),
+ message: ChannelMessagePostedMetadata {
+ channel_id: uuid::Uuid::from_u128(1),
+ message_id: uuid::Uuid::from_u128(2),
+ thread_id: None,
+ sender: sender("macro|[email protected]"),
+ triggered_by: None,
+ channel_type: ChannelType::Public,
+ content: "fix the flaky test".to_owned(),
+ mentions: vec![],
+ attachments: vec![],
+ created_at: timestamp(),
+ },
+ }),
+ ))
+}
+
+fn agent_trigger_existing_event()
+-> Event<agent_trigger::domain::broker_events::AgentTriggerTopicEvent> {
+ use agent_trigger::domain::broker_events::{
+ AgentTriggerTopicEvent, ChannelEventMetadata, ExistingAgentSessionEvent,
+ };
+ use channels::domain::broker_events::ChannelMessagePostedMetadata;
+ use channels::domain::models::ChannelType;
+
+ Event::new(AgentTriggerTopicEvent::Existing(
+ ExistingAgentSessionEvent::Channel(ChannelEventMetadata {
+ bot_id: bot_id::BotId::new_from_uuid(uuid::Uuid::from_u128(0xB07)),
+ session_id: agent_session::domain::model::AgentSessionId::TEST_A,
+ message: ChannelMessagePostedMetadata {
+ channel_id: uuid::Uuid::from_u128(1),
+ message_id: uuid::Uuid::from_u128(2),
+ thread_id: None,
+ sender: sender("macro|[email protected]"),
+ triggered_by: None,
+ channel_type: ChannelType::Public,
+ content: "and now the other one".to_owned(),
+ mentions: vec![],
+ attachments: vec![],
+ created_at: timestamp(),
+ },
+ }),
+ ))
+}
+
+/// A follow-up on a session that exists asks the session, not the channel:
+/// the session carries its own grants, so whatever channel a later message
+/// landed in is incidental.
+#[tokio::test]
+async fn an_existing_session_trigger_is_gated_by_the_session() {
+ let access = MockAccessService::with_users(vec![user_id(PERSONAL_WORKSPACE_ID)]);
+ let repository = MockRepository::new(
+ vec![PERSONAL_WORKSPACE_ID.to_string()],
+ vec![webhook("wh_agent_feed", PERSONAL_WORKSPACE_ID)],
+ );
+ let service = service(access.clone(), repository.clone(), MockEnqueuer::default());
+
+ service
+ .ingest_agent_trigger_event(agent_trigger_existing_event())
+ .await
+ .expect("agent trigger events are ingested");
+
+ assert_eq!(
+ lock(&access.calls).as_slice(),
+ &[(
+ agent_session::domain::model::AgentSessionId::TEST_A.to_string(),
+ EntityType::AgentSession
+ )],
+ );
+}
+
+#[tokio::test]
+async fn agent_trigger_events_are_scoped_by_the_channel_but_named_by_the_bot() {
+ let access = MockAccessService::with_users(vec![user_id(PERSONAL_WORKSPACE_ID)]);
+ let repository = MockRepository::new(
+ vec![PERSONAL_WORKSPACE_ID.to_string()],
+ vec![webhook("wh_agent_feed", PERSONAL_WORKSPACE_ID)],
+ );
+ let enqueuer = MockEnqueuer::default();
+ let service = service(access.clone(), repository.clone(), enqueuer.clone());
+ let event = agent_trigger_new_event();
+
+ service
+ .ingest_agent_trigger_event(event.clone())
+ .await
+ .expect("agent trigger events are ingested");
+
+ let bot_id = bot_id::BotId::new_from_uuid(uuid::Uuid::from_u128(0xB07)).to_string();
+ // Who may see it is decided by the channel the mention sits in - the same
+ // question a channel event asks - not by the bot.
+ assert_eq!(
+ lock(&access.calls).as_slice(),
+ &[(uuid::Uuid::from_u128(1).to_string(), EntityType::Channel)],
+ );
+ let repository_state = lock(&repository.state);
+ // ...but the entity matched on is the bot, so a filter's `ids` scopes a
+ // subscriber to exactly one bot's triggers.
+ assert_eq!(repository_state.match_calls.len(), 1);
+ assert_eq!(repository_state.match_calls[0].entity_id, bot_id);
+ assert_eq!(
+ repository_state.match_calls[0].event_name,
+ "agent_trigger.new"
+ );
+ assert_eq!(
+ repository_state.match_calls[0].workspace_ids,
+ vec![PERSONAL_WORKSPACE_ID.to_string()]
+ );
+ drop(repository_state);
+
+ // The delivered body is the broker envelope, verbatim: exactly what the
+ // daemon on the other end decodes.
+ let enqueuer_state = lock(&enqueuer.state);
+ assert_eq!(enqueuer_state.attempted_messages.len(), 1);
+ let normalized = &enqueuer_state.attempted_messages[0].event;
+ assert_eq!(normalized.event_name, "agent_trigger.new");
+ assert_eq!(normalized.entity_type, "bot");
+ assert_eq!(normalized.entity_id, bot_id);
+ assert_eq!(normalized.ordering_key, bot_id);
+ assert_eq!(
+ normalized.broker_envelope,
+ serde_json::to_value(&event).expect("a serializable envelope"),
+ );
+}
diff --git a/crates/webhook/src/domain/models.rs b/crates/webhook/src/domain/models.rs
index 46c1031026..e6fcb310c7 100644
--- a/crates/webhook/src/domain/models.rs
+++ b/crates/webhook/src/domain/models.rs
@@ -318,7 +318,9 @@ impl std::str::FromStr for WebhookStatus {
}
/// Scope that owns a newly-created webhook.
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
+///
+/// Clients serialize this, so both derives are used.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
#[serde(rename_all = "snake_case")]
pub enum WebhookScope {
@@ -351,7 +353,9 @@ impl WebhookEndpointSchemePolicy {
}
/// Request to create a webhook.
-#[derive(Debug, Clone, Deserialize)]
+///
+/// Clients serialize this, so both derives are used.
+#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
pub struct CreateWebhookRequest {
/// Scope that owns the webhook.
@@ -397,6 +401,8 @@ pub enum CreateWebhookOutcome {
}
/// Webhook row returned by application APIs.
+///
+/// Clients deserialize this, so both derives are used.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
pub struct Webhook {
@@ -434,6 +440,8 @@ pub struct Webhook {
}
/// Webhook returned after creation, including its signing secret.
+///
+/// Clients deserialize this, so both derives are used.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
pub struct CreateWebhookResponse {
@@ -490,6 +498,8 @@ impl From<Webhook> for CreateWebhookResponse {
}
/// Webhooks visible to the caller across their personal and team workspaces.
+///
+/// Clients deserialize this, so both derives are used.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "inbound", derive(utoipa::ToSchema))]
pub struct ListWebhooksResponse {
diff --git a/crates/webhook/src/domain/ports.rs b/crates/webhook/src/domain/ports.rs
index 4d2440b597..1f24c856bf 100644
--- a/crates/webhook/src/domain/ports.rs
+++ b/crates/webhook/src/domain/ports.rs
@@ -49,6 +49,9 @@ pub trait WebhookRepo: Clone + Send + Sync + 'static {
///
/// Delivery-eligible webhooks are active, valid, and not soft-deleted. A filter without
/// `ids` matches every entity id.
+ /// List active, valid, non-bot-owned webhooks in the given workspaces
+ /// whose filters match `event` (and `entity_id`, when a filter names
+ /// ids).
fn list_active_webhooks_matching_event(
&self,
workspace_ids: Vec<String>,
diff --git a/crates/webhook/src/inbound/axum_router/test.rs b/crates/webhook/src/inbound/axum_router/test.rs
index d884b7e0ad..f90a090e1f 100644
--- a/crates/webhook/src/inbound/axum_router/test.rs
+++ b/crates/webhook/src/inbound/axum_router/test.rs
@@ -43,6 +43,10 @@ enum ServiceCall {
Delete(MacroUserIdStr<'static>, WebhookId),
}
+#[allow(
+ clippy::large_enum_variant,
+ reason = "a test fake's canned answers; boxing would only obscure them"
+)]
enum ServiceResponse {
Webhook(Webhook),
List(ListWebhooksResponse),
@@ -98,6 +102,30 @@ impl MacroAuthorizationService for FakeAuthorizationService {
})
}
+ async fn authorize_bot(
+ &self,
+ bot_token: &str,
+ bot_scope: macro_authorization::BotScope,
+ acting_user: Option<macro_authorization::BotActingUserClaims>,
+ ) -> Result<macro_authorization::BotAuthentication, Report<MacroAuthorizationError>> {
+ if bot_token != "mbot_feed_test" {
+ return Err(Report::new(MacroAuthorizationError::InvalidCredentials));
+ }
+ let acting_user = acting_user
+ .and_then(|claims| claims.user_id)
+ .map(|user_id| macro_authorization::MacroUserAuthentication {
+ macro_user_id: MacroUserIdStr::try_from(user_id).unwrap(),
+ user_context: UserContext::default(),
+ });
+ Ok(macro_authorization::BotAuthentication {
+ bot_id: bot_id::BotId::TEST_A,
+ token_id: uuid::Uuid::new_v4(),
+ bot_scope,
+ team_id: None,
+ acting_user,
+ })
+ }
+
async fn authorize_internal(
&self,
provided_key: &str,
diff --git a/crates/webhook/src/inbound/kafka_consumer.rs b/crates/webhook/src/inbound/kafka_consumer.rs
index 9ad9219557..d9793789da 100644
--- a/crates/webhook/src/inbound/kafka_consumer.rs
+++ b/crates/webhook/src/inbound/kafka_consumer.rs
@@ -25,6 +25,7 @@ use crate::domain::{
events::WebhookMacroEvent,
ingestion::{WebhookEventIngestionError, WebhookEventIngestionService},
};
+use agent_trigger::domain::broker_events::AgentSessionMacroEvent;
use anyhow::Context as _;
use channels::domain::broker_events::ChannelMacroEvent;
use documents::domain::events::DocumentMacroEvent;
@@ -54,6 +55,7 @@ macro_event_broker::declare_topics!(
DeclaredMacroEvent: DocumentMacroEvent,
ChannelMacroEvent,
WebhookMacroEvent,
+ AgentSessionMacroEvent,
);
/// Maximum in-process ingestion attempts per event before the consumer bails
@@ -118,6 +120,11 @@ async fn ingest_with_retry<S: WebhookEventIngestionService>(
DeclaredMacroEvent::WebhookMacroEvent(event) => {
service.ingest_webhook_event(event.event().clone()).await
}
+ DeclaredMacroEvent::AgentSessionMacroEvent(event) => {
+ service
+ .ingest_agent_trigger_event(event.event().clone())
+ .await
+ }
};
match &result {
diff --git a/crates/webhook/src/inbound/kafka_consumer/test.rs b/crates/webhook/src/inbound/kafka_consumer/test.rs
index 1e456c670f..6ae93d2a98 100644
--- a/crates/webhook/src/inbound/kafka_consumer/test.rs
+++ b/crates/webhook/src/inbound/kafka_consumer/test.rs
@@ -62,7 +62,12 @@ fn declared_webhook_event() -> DeclaredMacroEvent {
fn subscribes_to_all_ingestion_topics() {
assert_eq!(
DeclaredMacroEvent::topics(),
- ["macro.documents", "macro.channels", "macro.webhooks"]
+ [
+ "macro.documents",
+ "macro.channels",
+ "macro.webhooks",
+ "macro.agent_sessions"
+ ]
);
}
@@ -75,9 +80,7 @@ fn decodes_document_events() {
match decoded {
DeclaredMacroEvent::DocumentMacroEvent(decoded) => assert_eq!(decoded.event(), &event),
- DeclaredMacroEvent::ChannelMacroEvent(_) | DeclaredMacroEvent::WebhookMacroEvent(_) => {
- panic!("decoded into the wrong topic variant")
- }
+ _ => panic!("decoded into the wrong topic variant"),
}
}
@@ -94,9 +97,7 @@ fn decodes_channel_events() {
match decoded {
DeclaredMacroEvent::ChannelMacroEvent(decoded) => assert_eq!(decoded.event(), &event),
- DeclaredMacroEvent::DocumentMacroEvent(_) | DeclaredMacroEvent::WebhookMacroEvent(_) => {
- panic!("decoded into the wrong topic variant")
- }
+ _ => panic!("decoded into the wrong topic variant"),
}
}
@@ -109,9 +110,7 @@ fn decodes_webhook_events() {
match decoded {
DeclaredMacroEvent::WebhookMacroEvent(decoded) => assert_eq!(decoded.event(), &event),
- DeclaredMacroEvent::DocumentMacroEvent(_) | DeclaredMacroEvent::ChannelMacroEvent(_) => {
- panic!("decoded into the wrong topic variant")
- }
+ _ => panic!("decoded into the wrong topic variant"),
}
}
@@ -182,6 +181,13 @@ impl WebhookEventIngestionService for FlakyIngestionService {
) -> Result<(), WebhookEventIngestionError> {
self.ingest()
}
+
+ async fn ingest_agent_trigger_event(
+ &self,
+ _event: Event<agent_trigger::domain::broker_events::AgentTriggerTopicEvent>,
+ ) -> Result<(), WebhookEventIngestionError> {
+ self.ingest()
+ }
}
fn flaky_service(failures: u32, transient: bool) -> (FlakyIngestionService, Arc<AtomicU32>) {
diff --git a/crates/webhook/src/outbound/http_delivery.rs b/crates/webhook/src/outbound/http_delivery.rs
index 6ec8f78b50..2b590168e6 100644
--- a/crates/webhook/src/outbound/http_delivery.rs
+++ b/crates/webhook/src/outbound/http_delivery.rs
@@ -23,8 +23,7 @@ use std::time::{Duration, Instant};
const EVENT_HEADER: &str = "x-macro-event";
const EVENT_ID_HEADER: &str = "x-macro-event-id";
-const TIMESTAMP_HEADER: &str = "x-macro-timestamp";
-const SIGNATURE_HEADER: &str = "x-macro-signature";
+use webhook_signature::{SIGNATURE_HEADER, TIMESTAMP_HEADER};
const REDACTED_HEADER_VALUE: &str = "[REDACTED]";
const RESPONSE_PREVIEW_MAX_BYTES: usize = 4096;
diff --git a/crates/webhook/src/outbound/http_validator.rs b/crates/webhook/src/outbound/http_validator.rs
index abd39af699..0352bdbdfe 100644
--- a/crates/webhook/src/outbound/http_validator.rs
+++ b/crates/webhook/src/outbound/http_validator.rs
@@ -10,17 +10,13 @@ use crate::domain::{
},
ports::WebhookValidationClient,
};
-use hmac::{Hmac, Mac};
use reqwest::{Client, StatusCode, Url, redirect::Policy};
-use sha2::Sha256;
use std::{net::IpAddr, time::Duration};
use tokio::net::lookup_host;
const EVENT_NAME: &str = "webhook.validation.test";
pub(super) const REQUEST_TIMEOUT: Duration = Duration::from_secs(5);
-type HmacSha256 = Hmac<Sha256>;
-
/// Reqwest-backed implementation of [`WebhookValidationClient`].
#[derive(Clone)]
pub struct ReqwestWebhookValidationClient {
@@ -129,11 +125,8 @@ pub(super) fn signature_header(
timestamp: &str,
raw_body: &[u8],
) -> Result<String, anyhow::Error> {
- let mut mac = HmacSha256::new_from_slice(secret.as_bytes())?;
- mac.update(timestamp.as_bytes());
- mac.update(b".");
- mac.update(raw_body);
- Ok(format!("v1={}", hex::encode(mac.finalize().into_bytes())))
+ webhook_signature::sign(secret, timestamp, raw_body)
+ .ok_or_else(|| anyhow::anyhow!("failed to key the delivery signature"))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
diff --git a/crates/webhook/src/outbound/pg_repository.rs b/crates/webhook/src/outbound/pg_repository.rs
index d3aaa4e68a..b6b2b2664b 100644
--- a/crates/webhook/src/outbound/pg_repository.rs
+++ b/crates/webhook/src/outbound/pg_repository.rs
@@ -176,8 +176,8 @@ impl WebhookRepo for PgRepository {
let inserted = sqlx::query!(
r#"
INSERT INTO webhook (
- id, workspace_id, namespace, name, endpoint_url, signing_secret, headers,
- filters, status, is_valid, created_by_user_id
+ id, workspace_id, namespace, name, endpoint_url, signing_secret,
+ headers, filters, status, is_valid, created_by_user_id
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, false, $10)
ON CONFLICT (workspace_id, namespace) WHERE deleted_at IS NULL DO NOTHING
diff --git a/crates/webhook/src/outbound/pg_repository_test.rs b/crates/webhook/src/outbound/pg_repository_test.rs
index f6b0c02ce1..1d7b052877 100644
--- a/crates/webhook/src/outbound/pg_repository_test.rs
+++ b/crates/webhook/src/outbound/pg_repository_test.rs
@@ -284,6 +284,12 @@ async fn object_shaped_filters_are_rejected_by_check_constraint(
Ok(())
}
+// EXPLAIN output is planner text rather than application data, so the SQLx
+// macros have no types to check here.
+#[allow(
+ clippy::disallowed_methods,
+ reason = "EXPLAIN output is planner text; the macros have nothing to validate"
+)]
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn containment_query_uses_filters_gin_index(pool: PgPool) -> anyhow::Result<()> {
let mut connection = pool.acquire().await?;
diff --git a/crates/webhook_signature/Cargo.toml b/crates/webhook_signature/Cargo.toml
new file mode 100644
index 0000000000..b6065cdec7
--- /dev/null
+++ b/crates/webhook_signature/Cargo.toml
@@ -0,0 +1,11 @@
+[package]
+edition = "2024"
+name = "webhook_signature"
+publish = false
+version = "0.1.0"
+
+[dependencies]
+hex = { workspace = true }
+hmac = { workspace = true }
+sha2 = { workspace = true }
+workspace-hack = { version = "0.1", path = "../workspace-hack" }
diff --git a/crates/webhook_signature/src/lib.rs b/crates/webhook_signature/src/lib.rs
new file mode 100644
index 0000000000..70adaedaca
--- /dev/null
+++ b/crates/webhook_signature/src/lib.rs
@@ -0,0 +1,54 @@
+//! Macro webhook delivery signatures: one crate owning both halves, so the
+//! signer (webhook delivery) and verifiers (webhook receivers) cannot drift.
+//!
+//! Deliveries are signed as `v1=<hex>` where the digest is HMAC-SHA256 over
+//! `"{timestamp}.{raw_body}"` keyed by the webhook's signing secret. The
+//! TypeScript counterpart is `packages/sdk/src/events/verify.ts`.
+
+#![deny(missing_docs)]
+
+use hmac::{Hmac, Mac};
+use sha2::Sha256;
+
+#[cfg(test)]
+mod test;
+
+type HmacSha256 = Hmac<Sha256>;
+
+/// Header carrying the signature on a delivery.
+pub const SIGNATURE_HEADER: &str = "x-macro-signature";
+
+/// Header carrying the timestamp the signature covers.
+pub const TIMESTAMP_HEADER: &str = "x-macro-timestamp";
+
+/// Sign a delivery: the `x-macro-signature` header value.
+///
+/// `None` only when the secret cannot key an HMAC, which for HMAC-SHA256
+/// cannot happen for any length - kept fallible so a future algorithm
+/// change cannot silently panic.
+#[must_use]
+pub fn sign(secret: &str, timestamp: &str, raw_body: &[u8]) -> Option<String> {
+ let mut mac = HmacSha256::new_from_slice(secret.as_bytes()).ok()?;
+ mac.update(timestamp.as_bytes());
+ mac.update(b".");
+ mac.update(raw_body);
+ Some(format!("v1={}", hex::encode(mac.finalize().into_bytes())))
+}
+
+/// Verify a delivery's `x-macro-signature` value in constant time.
+#[must_use]
+pub fn verify(secret: &str, timestamp: &str, raw_body: &[u8], signature: &str) -> bool {
+ let Some(hex_digest) = signature.strip_prefix("v1=") else {
+ return false;
+ };
+ let Ok(expected) = hex::decode(hex_digest) else {
+ return false;
+ };
+ let Ok(mut mac) = HmacSha256::new_from_slice(secret.as_bytes()) else {
+ return false;
+ };
+ mac.update(timestamp.as_bytes());
+ mac.update(b".");
+ mac.update(raw_body);
+ mac.verify_slice(&expected).is_ok()
+}
diff --git a/crates/webhook_signature/src/test.rs b/crates/webhook_signature/src/test.rs
new file mode 100644
index 0000000000..8a7550528e
--- /dev/null
+++ b/crates/webhook_signature/src/test.rs
@@ -0,0 +1,32 @@
+use super::*;
+
+#[test]
+fn sign_and_verify_round_trip() {
+ let signature = sign("secret", "1755188000", b"{\"a\":1}").unwrap();
+ assert!(signature.starts_with("v1="));
+ assert!(verify("secret", "1755188000", b"{\"a\":1}", &signature));
+}
+
+#[test]
+fn tampering_fails_verification() {
+ let signature = sign("secret", "1755188000", b"{\"a\":1}").unwrap();
+ assert!(!verify("secret", "1755188000", b"{\"a\":2}", &signature));
+ assert!(!verify("secret", "1755188001", b"{\"a\":1}", &signature));
+ assert!(!verify("other", "1755188000", b"{\"a\":1}", &signature));
+ assert!(!verify("secret", "1755188000", b"{\"a\":1}", "v1=zz"));
+ assert!(!verify("secret", "1755188000", b"{\"a\":1}", "nope"));
+}
+
+/// Pin the digest so the scheme can never drift from the TS verifier
+/// (`packages/sdk/src/events/verify.ts`) without a test moving.
+#[test]
+fn the_wire_format_is_pinned() {
+ assert_eq!(
+ sign("secret", "1700000000", b"body").unwrap(),
+ format!("v1={}", {
+ let mut mac = HmacSha256::new_from_slice(b"secret").unwrap();
+ mac.update(b"1700000000.body");
+ hex::encode(mac.finalize().into_bytes())
+ })
+ );
+}
diff --git a/deny.toml b/deny.toml
index a802868bd6..2d946ec2f6 100644
--- a/deny.toml
+++ b/deny.toml
@@ -201,6 +201,7 @@ deny = [
], reason = "Use macro_aws_config for AWS configuration in workspace crates" },
{ crate = "tracing-subscriber", wrappers = [
"channels", # Dev logging only
+ "coding_agent_worker", # Standalone daemon logging setup
"documents", # Dev logging only
"email", # Dev logging only
"lambda_runtime_api_client", # External crate allowed to use tracing-subscriber
@@ -339,7 +340,10 @@ unknown-git = "warn"
# if not specified. If it is specified but empty, no registries are allowed.
allow-registry = ["https://github.com/rust-lang/crates.io-index"]
# List of URLs for allowed Git repositories
-allow-git = ["git+https://github.com/whutchinson98/jsonwebtoken"]
+allow-git = [
+ "git+https://github.com/agentclientprotocol/rust-sdk",
+ "git+https://github.com/whutchinson98/jsonwebtoken",
+]
[sources.allow-org]
# github.com organizations to allow git sources for
diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml
index b1e602f4f3..9fee5b771a 100644
--- a/docker/docker-compose.yml
+++ b/docker/docker-compose.yml
@@ -322,8 +322,8 @@ services:
<<: [*common-env, *rust-services-image]
command: ["/app/out/agent_harness_service"]
restart: on-failure
- ports:
- - "8101:8101"
+ # No host port: everything reaches this through the proxy, and a second
+ # local instance would collide on a fixed publish.
environment:
# In-network gateway address; the local default (http://localhost:8082)
# would point at this container itself.
diff --git a/flake.lock b/flake.lock
index 156199515f..e252057b51 100644
--- a/flake.lock
+++ b/flake.lock
@@ -69,6 +69,27 @@
"type": "github"
}
},
+ "flake-parts_2": {
+ "inputs": {
+ "nixpkgs-lib": [
+ "hermes-agent",
+ "nixpkgs"
+ ]
+ },
+ "locked": {
+ "lastModified": 1782949081,
+ "narHash": "sha256-vp6Y/Grm98ESt6ceOkWiHWyZRDV3J1RID4w+6NWK9yA=",
+ "owner": "hercules-ci",
+ "repo": "flake-parts",
+ "rev": "17c9d6cdfc60c64f4ee8d306f9bc0b4ccb51481e",
+ "type": "github"
+ },
+ "original": {
+ "owner": "hercules-ci",
+ "repo": "flake-parts",
+ "type": "github"
+ }
+ },
"flake-utils": {
"inputs": {
"systems": "systems"
@@ -87,6 +108,31 @@
"type": "github"
}
},
+ "hermes-agent": {
+ "inputs": {
+ "flake-parts": "flake-parts_2",
+ "nixpkgs": [
+ "nixpkgs"
+ ],
+ "npm-lockfile-fix": "npm-lockfile-fix",
+ "pyproject-build-systems": "pyproject-build-systems",
+ "pyproject-nix": "pyproject-nix",
+ "uv2nix": "uv2nix"
+ },
+ "locked": {
+ "lastModified": 1786997573,
+ "narHash": "sha256-uQ5E+B73AV8wr18or+yH0DvmUes6qhIEVtJ+17D3jHI=",
+ "owner": "NousResearch",
+ "repo": "hermes-agent",
+ "rev": "aeabff6aec6fe0e8a32ed96cf76b9a692eaf705f",
+ "type": "github"
+ },
+ "original": {
+ "owner": "NousResearch",
+ "repo": "hermes-agent",
+ "type": "github"
+ }
+ },
"import-tree": {
"locked": {
"lastModified": 1784254960,
@@ -133,6 +179,77 @@
"type": "github"
}
},
+ "npm-lockfile-fix": {
+ "inputs": {
+ "nixpkgs": [
+ "hermes-agent",
+ "nixpkgs"
+ ]
+ },
+ "locked": {
+ "lastModified": 1775903712,
+ "narHash": "sha256-2GV79U6iVH4gKAPWYrxUReB0S41ty/Y3dBLquU8AlaA=",
+ "owner": "jeslie0",
+ "repo": "npm-lockfile-fix",
+ "rev": "c6093acb0c0548e0f9b8b3d82918823721930fe8",
+ "type": "github"
+ },
+ "original": {
+ "owner": "jeslie0",
+ "repo": "npm-lockfile-fix",
+ "type": "github"
+ }
+ },
+ "pyproject-build-systems": {
+ "inputs": {
+ "nixpkgs": [
+ "hermes-agent",
+ "nixpkgs"
+ ],
+ "pyproject-nix": [
+ "hermes-agent",
+ "pyproject-nix"
+ ],
+ "uv2nix": [
+ "hermes-agent",
+ "uv2nix"
+ ]
+ },
+ "locked": {
+ "lastModified": 1785115949,
+ "narHash": "sha256-8AM37BfyGaL2v/SZyg4PupRxJ01Y4htvM+WrTjWrPpo=",
+ "owner": "pyproject-nix",
+ "repo": "build-system-pkgs",
+ "rev": "62c0d86027edb1c4f39a5facc09876348144f7c9",
+ "type": "github"
+ },
+ "original": {
+ "owner": "pyproject-nix",
+ "repo": "build-system-pkgs",
+ "type": "github"
+ }
+ },
+ "pyproject-nix": {
+ "inputs": {
+ "nixpkgs": [
+ "hermes-agent",
+ "nixpkgs"
+ ]
+ },
+ "locked": {
+ "lastModified": 1784591072,
+ "narHash": "sha256-zP/WaDxrRu8GANZM61+V2LT/7ycEEdoyLWn7M6WzU7M=",
+ "owner": "pyproject-nix",
+ "repo": "pyproject.nix",
+ "rev": "e3b599ca2e7fcf93d4edf65d7f19bbf6491724f3",
+ "type": "github"
+ },
+ "original": {
+ "owner": "pyproject-nix",
+ "repo": "pyproject.nix",
+ "type": "github"
+ }
+ },
"root": {
"inputs": {
"crane": "crane",
@@ -140,6 +257,7 @@
"fenix": "fenix",
"flake-parts": "flake-parts",
"flake-utils": "flake-utils",
+ "hermes-agent": "hermes-agent",
"import-tree": "import-tree",
"nixpkgs": "nixpkgs"
}
@@ -175,6 +293,31 @@
"repo": "default",
"type": "github"
}
+ },
+ "uv2nix": {
+ "inputs": {
+ "nixpkgs": [
+ "hermes-agent",
+ "nixpkgs"
+ ],
+ "pyproject-nix": [
+ "hermes-agent",
+ "pyproject-nix"
+ ]
+ },
+ "locked": {
+ "lastModified": 1785277507,
+ "narHash": "sha256-9Tq3UDX2hD/aveW/HvkBlAmEwJTOlY5HQXJM+L5BGmE=",
+ "owner": "pyproject-nix",
+ "repo": "uv2nix",
+ "rev": "5a836d395cbf5fc22670eb98dd4aa4fc4d406977",
+ "type": "github"
+ },
+ "original": {
+ "owner": "pyproject-nix",
+ "repo": "uv2nix",
+ "type": "github"
+ }
}
},
"root": "root",
diff --git a/flake.nix b/flake.nix
index 24aa0fd121..50bc8f0e93 100644
--- a/flake.nix
+++ b/flake.nix
@@ -9,6 +9,8 @@
fenix.inputs.nixpkgs.follows = "nixpkgs";
crane.url = "github:ipetkov/crane";
crane-tauri.url = "github:JPHutchins/crane-tauri";
+ hermes-agent.url = "github:NousResearch/hermes-agent";
+ hermes-agent.inputs.nixpkgs.follows = "nixpkgs";
};
outputs = inputs: inputs.flake-parts.lib.mkFlake { inherit inputs; } (inputs.import-tree ./nix);
diff --git a/nix/cloud-storage.nix b/nix/cloud-storage.nix
index 35ac6f3f7c..4b43777942 100644
--- a/nix/cloud-storage.nix
+++ b/nix/cloud-storage.nix
@@ -7,6 +7,7 @@
nixpkgs
fenix
crane
+ hermes-agent
;
pkgs = import nixpkgs {
system = system;
@@ -760,6 +761,7 @@
shellTools =
with pkgs;
[
+ hermes-agent.packages.${system}.default
daytona
nsc
parallel
diff --git a/packages/sdk/generated/storage/index.ts b/packages/sdk/generated/storage/index.ts
index bba7ee37b6..28242f32a1 100644
--- a/packages/sdk/generated/storage/index.ts
+++ b/packages/sdk/generated/storage/index.ts
@@ -1,4 +1,4 @@
// This file is auto-generated by @hey-api/openapi-ts
export { type Options, Sdk } from './sdk.gen';
-export type { AccessLevel, ActivityType, AddFavoriteData, AddFavoriteError, AddFavoriteErrors, AddFavoriteRequest, AddFavoriteResponse, AddFavoriteResponses, AddParticipantsData, AddParticipantsError, AddParticipantsErrors, AddParticipantsRequest, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerError, AddPinHandlerErrors, AddPinHandlerResponse, AddPinHandlerResponses, AddPinRequest, Anchor, AnchorId, AnchorRequest, AnchorResponse, AnnotationIncrementalUpdate, ApiActivity, ApiAttachmentChannelReference, ApiAttachmentEntityReference, ApiAttachmentGenericReference, ApiChannelAttachment, ApiChannelAttachmentsPage, ApiChannelContextMessage, ApiChannelDetail, ApiChannelListMessage, ApiChannelListPage, ApiChannelListParticipant, ApiChannelListType, ApiChannelMessage, ApiChannelMessageKind, ApiChannelMessagesPage, ApiChannelParticipant, ApiChannelWithLatest, ApiCountedReaction, ApiEntityFilterAst, ApiGroupByField, ApiGroupMeta, ApiMessageAttachment, ApiMessageSender, ApiMessageSenderType, ApiParticipantListRole, ApiParticipantRole, ApiPropertyEntityType, ApiResolvedChannelMessage, ApiThreadInfo, ApiThreadReply, AttendeeResponseStatus, BasicDocument, BasicDocumentSubType, BomPart, Bot, BotChannel, BotChannelType, BotId, BotKind, BotOwner, BotToken, BranchNameResponse, BTreeMap, BulkWakeupRequest, BulkWakeupResponse, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponse, BulkWakeupSyncServiceDocumentsResponses, CalendarAttendee, CalendarEvent, CalendarEventFilters, CalendarMentionEvent, CalendarMentionPreviewItem, CalendarMentionPreviewKind, CalendarMentionPreviewRequest, CalendarMentionPreviewRequestItem, CalendarMentionPreviewResponse, CalendarOccurrence, CalendarOccurrenceItem, CalendarOccurrenceResponse, CalendarSyncStatus, CallActiveResponse, CallFilters, CallRecord, CallRecordParticipant, CallRecordPreview, CallRecordPreviewData, CallRecordTranscriptSegment, CallStatus, CallTokenResponse, CallWebhookData, CallWebhookError, CallWebhookErrors, CallWebhookResponses, Channel, ChannelCreatedMetadata, ChannelDeletedMetadata, ChannelEventAttachment, ChannelFilters, ChannelJoinCodeResponse, ChannelMentionedMetadata, ChannelMessage, ChannelMessageAttachmentCreatedMetadata, ChannelMessageAttachmentRemovedMetadata, ChannelMessageDeletedMetadata, ChannelMessageFilters, ChannelMessagePatchedMetadata, ChannelMessagePostedMetadata, ChannelParticipant, ChannelParticipantAddedMetadata, ChannelParticipantRemovedMetadata, ChannelPreview, ChannelPreviewData, ChannelSender, ChannelSharePermission, ChannelThreadFilters, ChannelTopicEvent, ChannelType, ChannelUpdatedMetadata, ChannelWebhookRequest, ChannelWebhookResponse, ChannelWithParticipants, Chat, ChatFilters, CheckActiveCallData, CheckActiveCallError, CheckActiveCallErrors, CheckActiveCallResponse, CheckActiveCallResponses, ClientOptions, CloudStorageItemType, Comment, CommentThread, ConferenceProvider, CopyDocumentData, CopyDocumentError, CopyDocumentErrors, CopyDocumentQueryParams, CopyDocumentRequest, CopyDocumentResponse, CopyDocumentResponse2, CopyDocumentResponses, CreateAnchorData, CreateAnchorError, CreateAnchorErrors, CreateAnchorResponse, CreateAnchorResponses, CreateBulkDocumentResponse, CreateBulkDocumentResponseData, CreateChannelData, CreateChannelError, CreateChannelErrors, CreateChannelRequest, CreateChannelResponse, CreateChannelResponse2, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotError, CreateChannelScopedBotErrors, CreateChannelScopedBotRequest, CreateChannelScopedBotResponse, CreateChannelScopedBotResponse2, CreateChannelScopedBotResponses, CreateCommentData, CreateCommentError, CreateCommentErrors, CreateCommentRequest, CreateCommentResponse, CreateCommentResponse2, CreateCommentResponses, CreateCrmCommentData, CreateCrmCommentError, CreateCrmCommentErrors, CreateCrmCommentRequest, CreateCrmCommentResponse, CreateCrmCommentResponses, CreateCrmCompanyData, CreateCrmCompanyError, CreateCrmCompanyErrors, CreateCrmCompanyRequest, CreateCrmCompanyResponse, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactError, CreateCrmContactErrors, CreateCrmContactRequest, CreateCrmContactResponse, CreateCrmContactResponses, CreateDocumentData, CreateDocumentError, CreateDocumentErrors, CreateDocumentRequest, CreateDocumentResponse, CreateDocumentResponseData, CreateDocumentResponses, CreateEntityMentionData, CreateEntityMentionError, CreateEntityMentionErrors, CreateEntityMentionRequest, CreateEntityMentionResponse, CreateEntityMentionResponse2, CreateEntityMentionResponses, CreateInstructionsDocumentResponse, CreateInstructionsHandlerData, CreateInstructionsHandlerError, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponse, CreateInstructionsHandlerResponses, CreateMarkdownDocumentRequest, CreateMarkdownDocumentResponse, CreateMarkdownHandlerData, CreateMarkdownHandlerError, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponse, CreateMarkdownHandlerResponses, CreateProjectHandlerData, CreateProjectHandlerError, CreateProjectHandlerErrors, CreateProjectHandlerResponse, CreateProjectHandlerResponses, CreateProjectRequest, CreateProjectResponse, CreateReminderData, CreateReminderError, CreateReminderErrors, CreateReminderRequest, CreateReminderResponse, CreateReminderResponses, CreateSkillHandlerData, CreateSkillHandlerError, CreateSkillHandlerErrors, CreateSkillHandlerResponse, CreateSkillHandlerResponses, CreateSkillRequest, CreateSkillResponse, CreateSnippetHandlerData, CreateSnippetHandlerError, CreateSnippetHandlerErrors, CreateSnippetHandlerResponse, CreateSnippetHandlerResponses, CreateSnippetRequest, CreateSnippetResponse, CreateTaskHandlerData, CreateTaskHandlerError, CreateTaskHandlerErrors, CreateTaskHandlerResponse, CreateTaskHandlerResponses, CreateTaskRequest, CreateTaskResponse, CreateUnthreadedAnchorRequest, CreateUnthreadedAnchorResponse, CreateUnthreadedPdfAnchorRequest, CreateViewHandlerData, CreateViewHandlerError, CreateViewHandlerErrors, CreateViewHandlerResponse, CreateViewHandlerResponses, CreateViewRequest, CreateWebhookData, CreateWebhookError, CreateWebhookErrors, CreateWebhookRequest, CreateWebhookResponse, CreateWebhookResponse2, CreateWebhookResponses, CrmComment, CrmCommentEntityType, CrmCommentThread, CrmCompanyFilters, CrmCompanyResponse, CrmContactResponse, CrmDomainResponse, CrmPermissionRole, CrmTeamSettingsResponse, CrmThread, CustomSpeakerAssignment, DataType, DeleteAnchorData, DeleteAnchorError, DeleteAnchorErrors, DeleteAnchorInfo, DeleteAnchorResponse, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordError, DeleteCallRecordErrors, DeleteCallRecordResponse, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelError, DeleteChannelErrors, DeleteChannelResponse, DeleteChannelResponses, DeleteCommentData, DeleteCommentError, DeleteCommentErrors, DeleteCommentRequest, DeleteCommentResponse, DeleteCommentResponse2, DeleteCommentResponses, DeleteCrmCommentData, DeleteCrmCommentError, DeleteCrmCommentErrors, DeleteCrmCommentResponse, DeleteCrmCommentResponses, DeleteCrmCommentResult, DeleteDocumentData, DeleteDocumentError, DeleteDocumentErrors, DeleteDocumentResponse, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionError, DeleteEntityMentionErrors, DeleteEntityMentionResponse, DeleteEntityMentionResponse2, DeleteEntityMentionResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerError, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponse, DeleteHistoryHandlerResponses, DeleteMessageData, DeleteMessageError, DeleteMessageErrors, DeleteMessageQuery, DeleteMessageResponse, DeleteMessageResponses, DeleteProjectHandlerData, DeleteProjectHandlerError, DeleteProjectHandlerErrors, DeleteProjectHandlerResponse, DeleteProjectHandlerResponses, DeleteReminderData, DeleteReminderError, DeleteReminderErrors, DeleteReminderResponse, DeleteReminderResponses, DeleteThreadInfo, DeleteUnthreadedAnchorRequest, DeleteUnthreadedAnchorResponse, DeleteUnthreadedPdfAnchorRequest, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationError, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponse, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerError, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookError, DeleteWebhookErrors, DeleteWebhookResponse, DeleteWebhookResponses, DocumentBasic, DocumentContent, DocumentContentLocation, DocumentContentState, DocumentContentUploadedMetadata, DocumentCopiedMetadata, DocumentCreatedMetadata, DocumentDeletedMetadata, DocumentFilters, DocumentInteractionMetadata, DocumentMetadata, DocumentMetadataWithContent, DocumentPermissionsToken, DocumentPermissionsTokenRequest, DocumentPermissionsTokenResponse, DocumentPreview, DocumentPreviewData, DocumentPreviewDataSubType, DocumentPurgedMetadata, DocumentResponse, DocumentResponseMetadata, DocumentResponseMetadataWithContent, DocumentStorageServiceApiVersion, DocumentSubType, DocumentSyncContentUpdatedMetadata, DocumentTeamShareResponse, DocumentTopicEvent, DocumentUpdatedMetadata, EditAnchorData, EditAnchorError, EditAnchorErrors, EditAnchorRequest, EditAnchorResponse, EditAnchorResponse2, EditAnchorResponses, EditCallRecordData, EditCallRecordError, EditCallRecordErrors, EditCallRecordRequest, EditCallRecordResponse, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptError, EditCallTranscriptErrors, EditCallTranscriptRequest, EditCallTranscriptResponse, EditCallTranscriptResponses, EditCommentData, EditCommentError, EditCommentErrors, EditCommentRequest, EditCommentResponse, EditCommentResponse2, EditCommentResponses, EditCrmCommentData, EditCrmCommentError, EditCrmCommentErrors, EditCrmCommentRequest, EditCrmCommentResponse, EditCrmCommentResponses, EditDocumentData, EditDocumentError, EditDocumentErrors, EditDocumentResponse, EditDocumentResponse2, EditDocumentResponses, EditDocumentServiceArgs, EditPdfAnchorRequest, EditPdfPlaceableCommentAnchorRequest, EditProjectV2Data, EditProjectV2Error, EditProjectV2Errors, EditProjectV2Response, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Error, EditThreadV2Errors, EditThreadV2Response, EditThreadV2Responses, EmailFilters, EmptyResponse, EntityFilters, EntityPermission, EntityPermissionResponse, EntityReference, EntityType, ErrorResponse, EventReminderOverride, EventReminders, EventStatus, EventTime, EventTransparency, EventVisibility, ExcludedDefaultView, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerError, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExcludeDefaultViewRequest, ExportDocumentData, ExportDocumentError, ExportDocumentErrors, ExportDocumentResponse, ExportDocumentResponse2, ExportDocumentResponses, Favorite, FavoriteEntityRef, FavoritesList, FileSystemNodeWithIds, FileType, FileTypeUpdate, FolderItem, ForeignEntity, ForeignEntityFilters, GenericErrorResponse, GenericResponse, GenericSuccessResponse, GetActivityData, GetActivityError, GetActivityErrors, GetActivityResponse, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesError, GetAttachmentReferencesErrors, GetAttachmentReferencesResponse, GetAttachmentReferencesResponse2, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewError, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewRequest, GetBatchCallRecordPreviewResponse, GetBatchCallRecordPreviewResponse2, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewError, GetBatchChannelPreviewErrors, GetBatchChannelPreviewRequest, GetBatchChannelPreviewResponse, GetBatchChannelPreviewResponse2, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerError, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponse, GetBatchPreviewHandlerResponses, GetBatchPreviewRequest, GetBatchPreviewResponse, GetBatchProjectPreviewData, GetBatchProjectPreviewError, GetBatchProjectPreviewErrors, GetBatchProjectPreviewRequest, GetBatchProjectPreviewResponse, GetBatchProjectPreviewResponse2, GetBatchProjectPreviewResponses, GetCallRecordData, GetCallRecordError, GetCallRecordErrors, GetCallRecordResponse, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsError, GetChannelAttachmentsErrors, GetChannelAttachmentsResponse, GetChannelAttachmentsResponses, GetChannelData, GetChannelError, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkError, GetChannelJoinLinkErrors, GetChannelJoinLinkResponse, GetChannelJoinLinkResponses, GetChannelMessagesData, GetChannelMessagesError, GetChannelMessagesErrors, GetChannelMessagesResponse, GetChannelMessagesResponses, GetChannelParticipantsData, GetChannelParticipantsError, GetChannelParticipantsErrors, GetChannelParticipantsResponse, GetChannelParticipantsResponses, GetChannelResponse, GetChannelResponses, GetChannelsData, GetChannelsError, GetChannelsErrors, GetChannelsResponse, GetChannelsResponses, GetCompanyData, GetCompanyError, GetCompanyErrors, GetCompanyResponse, GetCompanyResponses, GetContactByEmailData, GetContactByEmailError, GetContactByEmailErrors, GetContactByEmailResponse, GetContactByEmailResponse2, GetContactByEmailResponses, GetContactData, GetContactError, GetContactErrors, GetContactResponse, GetContactResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsError, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponse, GetCrmTeamSettingsResponses, GetDocumentAnchorsData, GetDocumentAnchorsError, GetDocumentAnchorsErrors, GetDocumentAnchorsResponse, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameError, GetDocumentBranchNameErrors, GetDocumentBranchNameResponse, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugError, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponse, GetDocumentByTeamSlugResponses, GetDocumentCommentsData, GetDocumentCommentsError, GetDocumentCommentsErrors, GetDocumentCommentsResponse, GetDocumentCommentsResponses, GetDocumentData, GetDocumentError, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsError, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponse, GetDocumentGithubPullRequestsResponses, GetDocumentKeyResponse, GetDocumentKeyResponseData, GetDocumentListHandlerData, GetDocumentListHandlerError, GetDocumentListHandlerErrors, GetDocumentListHandlerResponse, GetDocumentListHandlerResponses, GetDocumentListResult, GetDocumentLocationV3Data, GetDocumentLocationV3Error, GetDocumentLocationV3Errors, GetDocumentLocationV3Response, GetDocumentLocationV3Responses, GetDocumentPermissionsResponseDataV2, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenError, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponse, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Error, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Response, GetDocumentPermissionsV2Responses, GetDocumentProcessingResult, GetDocumentProcessingResultData, GetDocumentProcessingResultError, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponse, GetDocumentProcessingResultResponse2, GetDocumentProcessingResultResponses, GetDocumentResponse, GetDocumentResponse2, GetDocumentResponseData, GetDocumentResponses, GetDocumentSearchResponse, GetDocumentShortIdData, GetDocumentShortIdError, GetDocumentShortIdErrors, GetDocumentShortIdResponse, GetDocumentShortIdResponses, GetDocumentsResponse, GetDocumentTeamShareData, GetDocumentTeamShareError, GetDocumentTeamShareErrors, GetDocumentTeamShareResponse, GetDocumentTeamShareResponses, GetDocumentUserAccessLevelResponse, GetDocumentVersionData, GetDocumentVersionError, GetDocumentVersionErrors, GetDocumentVersionResponse, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerError, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponse, GetDocumentViewsHandlerResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponse, GetEntityPermissionResponses, GetForeignEntityData, GetForeignEntityError, GetForeignEntityErrors, GetForeignEntityResponse, GetForeignEntityResponses, GetHistoryHandlerData, GetHistoryHandlerError, GetHistoryHandlerErrors, GetHistoryHandlerResponse, GetHistoryHandlerResponses, GetInstructionsDocumentResponse, GetInstructionsHandlerData, GetInstructionsHandlerError, GetInstructionsHandlerErrors, GetInstructionsHandlerResponse, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupError, GetItemsSoupErrors, GetItemsSoupResponse, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerError, GetLocationHandlerErrors, GetLocationHandlerResponse, GetLocationHandlerResponses, GetMessageWithContextData, GetMessageWithContextError, GetMessageWithContextErrors, GetMessageWithContextResponse, GetMessageWithContextResponse2, GetMessageWithContextResponses, GetOrCreateAction, GetOrCreateCallData, GetOrCreateCallError, GetOrCreateCallErrors, GetOrCreateCallResponse, GetOrCreateCallResponses, GetOrCreateChannelResponse, GetOrCreateDmData, GetOrCreateDmError, GetOrCreateDmErrors, GetOrCreateDmRequest, GetOrCreateDmResponse, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateError, GetOrCreatePrivateErrors, GetOrCreatePrivateRequest, GetOrCreatePrivateResponse, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerError, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponse, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerError, GetPinsHandlerErrors, GetPinsHandlerResponse, GetPinsHandlerResponses, GetPinsResponse, GetProjectContentHandlerData, GetProjectContentHandlerError, GetProjectContentHandlerErrors, GetProjectContentHandlerResponse, GetProjectContentHandlerResponses, GetProjectContentResponse, GetProjectHandlerData, GetProjectHandlerError, GetProjectHandlerErrors, GetProjectHandlerResponse, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Error, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Response, GetProjectPermissionsV2Responses, GetProjectResponse, GetProjectResponseData, GetProjectsHandlerData, GetProjectsHandlerError, GetProjectsHandlerErrors, GetProjectsHandlerResponse, GetProjectsHandlerResponses, GetProjectsResponse, GetProjectUserAccessLevelData, GetProjectUserAccessLevelError, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponse, GetProjectUserAccessLevelResponses, GetReminderData, GetReminderError, GetReminderErrors, GetReminderResponse, GetReminderResponses, GetRingStatusData, GetRingStatusError, GetRingStatusErrors, GetRingStatusResponse, GetRingStatusResponses, GetSelfBotData, GetSelfBotError, GetSelfBotErrors, GetSelfBotResponse, GetSelfBotResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerError, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponse, GetSystemSkillsHandlerResponses, GetThreadRepliesData, GetThreadRepliesError, GetThreadRepliesErrors, GetThreadRepliesResponse, GetThreadRepliesResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerError, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponse, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationError, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponse, GetUserDocumentViewLocationResponses, GetUserHistoryResponse, GetViewsHandlerData, GetViewsHandlerError, GetViewsHandlerErrors, GetViewsHandlerResponse, GetViewsHandlerResponses, GetWebhookData, GetWebhookError, GetWebhookErrors, GetWebhookResponse, GetWebhookResponses, GithubPullRequest, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestsResponse, GroupedInitialParams, GroupedPageParams, GroupedSoupGroupPage, GroupedSoupInitialPage, GroupedSoupPage, GroupedSoupSort, HandlerData, HandlerError, HandlerErrors, HandlerResponse, HandlerResponses, HashMap, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HighlightType, IngestTranscriptData, IngestTranscriptError, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsError, InitializeUserDocumentsErrors, InitializeUserDocumentsResponse, InitializeUserDocumentsResponses, InstallSyncData, InstallSyncErrors, InteractionReason, Item, ItemWithUserAccessLevel, JobProcessingResultHandlerData, JobProcessingResultHandlerError, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponse, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeError, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelError, JoinChannelErrors, JoinChannelResponses, LatestMessage, LeaveCallResponse, LeaveChannelData, LeaveChannelError, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallError, LeaveOrEndCallErrors, LeaveOrEndCallResponse, LeaveOrEndCallResponses, LinkShare, ListBotChannelsData, ListBotChannelsError, ListBotChannelsErrors, ListBotChannelsResponse, ListBotChannelsResponses, ListCompanyContactsData, ListCompanyContactsError, ListCompanyContactsErrors, ListCompanyContactsResponse, ListCompanyContactsResponses, ListCrmCommentsData, ListCrmCommentsError, ListCrmCommentsErrors, ListCrmCommentsResponse, ListCrmCommentsResponses, ListFavoritesData, ListFavoritesError, ListFavoritesErrors, ListFavoritesResponse, ListFavoritesResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponse, ListOccurrencesResponses, ListRemindersData, ListRemindersError, ListRemindersErrors, ListRemindersResponse, ListRemindersResponses, ListWebhooksData, ListWebhooksError, ListWebhooksErrors, ListWebhooksResponse, ListWebhooksResponse2, ListWebhooksResponses, LocationResponseData, LocationResponseV3, MacroUserIdStr, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponse, MentionPreviewsResponses, Mentions, NewChannelAttachment, NotificationFilters, Params, ParticipantRole, PatchChannelData, PatchChannelError, PatchChannelErrors, PatchChannelRequest, PatchChannelResponse, PatchChannelResponses, PatchMessageData, PatchMessageError, PatchMessageErrors, PatchMessageRequest, PatchMessageResponse, PatchMessageResponses, PatchProjectRequestV2, PatchThreadRequestV2, PatchViewHandlerData, PatchViewHandlerError, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookError, PatchWebhookErrors, PatchWebhookRequest, PatchWebhookResponse, PatchWebhookResponses, PdfAnchor, PdfAnchorId, PdfAnchorRequest, PdfHighlightAnchor, PdfHighlightAnchorRequest, PdfHighlightRect, PdfHighlightRectAnchorRequest, PdfPlaceableCommentAnchor, PdfPlaceableCommentAnchorRequest, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentError, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponse, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectError, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponse, PermanentlyDeleteProjectResponses, PinnedItem, PinRequest, PostActivityData, PostActivityError, PostActivityErrors, PostActivityRequest, PostActivityResponse, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookError, PostChannelBotWebhookErrors, PostChannelBotWebhookResponse, PostChannelBotWebhookResponses, PostChannelMessagesData, PostChannelMessagesError, PostChannelMessagesErrors, PostChannelMessagesResponse, PostChannelMessagesResponses, PostGroupedSoupAstGroupPageRequest, PostGroupedSoupAstInitialRequest, PostGroupedSoupAstRequest, PostItemsSoupAstData, PostItemsSoupAstError, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedError, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponse, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponse, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupError, PostItemsSoupErrors, PostItemsSoupResponse, PostItemsSoupResponses, PostMessageData, PostMessageError, PostMessageErrors, PostMessageRequest, PostMessageResponse, PostMessageResponse2, PostMessageResponses, PostReactionData, PostReactionError, PostReactionErrors, PostReactionRequest, PostReactionResponse, PostReactionResponses, PostSoupAstRequest, PostSoupRequest, PostTypingData, PostTypingError, PostTypingErrors, PostTypingRequest, PostTypingResponse, PostTypingResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerError, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponse, PresaveDocumentHandlerResponses, PreSaveDocumentRequest, PreSaveDocumentResponse, PreSaveDocumentResponseData, PresignedUrl, Project, ProjectDeleteResponseData, ProjectDocumentStatus, ProjectFilters, ProjectPreview, ProjectPreviewData, PropertyDefinition, PropertyFilter, PropertyInput, PropertyOwner, PropertyValue, PutCrmTeamSettingsData, PutCrmTeamSettingsError, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponse, PutCrmTeamSettingsResponses, ReactionAction, RecentlyDeletedData, RecentlyDeletedError, RecentlyDeletedErrors, RecentlyDeletedResponse, RecentlyDeletedResponseData, RecentlyDeletedResponses, Reminder, ReminderFilters, ReminderSchedule, RemindersList, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotError, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponse, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityError, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsError, RemoveParticipantsErrors, RemoveParticipantsRequest, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerError, RemovePinHandlerErrors, RemovePinHandlerResponse, RemovePinHandlerResponses, ReorderFavoritesData, ReorderFavoritesError, ReorderFavoritesErrors, ReorderFavoritesRequest, ReorderFavoritesResponses, ReorderPinRequest, ReorderPinsHandlerData, ReorderPinsHandlerError, ReorderPinsHandlerErrors, ReorderPinsHandlerResponse, ReorderPinsHandlerResponses, ResolveChannelMessageData, ResolveChannelMessageError, ResolveChannelMessageErrors, ResolveChannelMessageResponse, ResolveChannelMessageResponses, RevertDeleteDocumentData, RevertDeleteDocumentError, RevertDeleteDocumentErrors, RevertDeleteDocumentResponse, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectError, RevertDeleteProjectErrors, RevertDeleteProjectResponse, RevertDeleteProjectResponses, RingStatus, RingStatusResponse, S3ObjectInfo, SaveBomPart, SaveDocumentHandlerData, SaveDocumentHandlerError, SaveDocumentHandlerErrors, SaveDocumentHandlerResponse, SaveDocumentHandlerResponses, SaveDocumentRequest, SaveDocumentResponse, SaveDocumentResponseData, SetCompanyHiddenData, SetCompanyHiddenError, SetCompanyHiddenErrors, SetCompanyHiddenRequest, SetCompanyHiddenResponse, SetCompanyHiddenResponses, SetCompanyNameRequest, SetContactHiddenData, SetContactHiddenError, SetContactHiddenErrors, SetContactHiddenRequest, SetContactHiddenResponse, SetContactHiddenResponses, SetContactNameRequest, SetCrmCompanyNameData, SetCrmCompanyNameError, SetCrmCompanyNameErrors, SetCrmCompanyNameResponse, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameError, SetCrmContactNameErrors, SetCrmContactNameResponse, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareError, SetDocumentTeamShareErrors, SetDocumentTeamShareRequest, SetDocumentTeamShareResponse, SetDocumentTeamShareResponses, SetEmailSyncData, SetEmailSyncError, SetEmailSyncErrors, SetEmailSyncRequest, SetEmailSyncResponse, SetEmailSyncResponses, SetPropertyValue, SharedEmailFilter, SharePermissionV2, ShortIdResponse, SimpleMention, SimpleSaveData, SimpleSaveError, SimpleSaveErrors, SimpleSaveResponse, SimpleSaveResponses, SoupApiItem, SoupApiSort, SoupApiSortDirection, SoupAttachment, SoupCalendarEventSoupPropertiesField, SoupCalendarEventTime, SoupCallRecordParticipant, SoupCallRecordSoupPropertiesField, SoupChannel, SoupChannelThread, SoupChatSoupPropertiesField, SoupContact, SoupCountedReaction, SoupCrmCompanySoupPropertiesField, SoupCrmDomain, SoupDocumentSoupPropertiesField, SoupDocumentSubType, SoupEmailThreadPreview, SoupEnrichedEmailThreadPreviewSoupPropertiesField, SoupForeignEntity, SoupItem, SoupLabel, SoupLabelListVisibility, SoupLabelType, SoupMessageAttachment, SoupMessageListVisibility, SoupMessageSender, SoupMessageSenderType, SoupPage, SoupProjectSoupPropertiesField, SoupPropertiesField, SoupProperty, SoupReminderReference, SoupReminderSchedule, SoupReminderSoupPropertiesField, SoupThreadInfo, SoupThreadReply, StarterDocumentsResponse, String, SuccessResponse, SyncServiceVersionId, SystemSkillSummary, TagFilterMode, TaskFilters, TeamRole, Thread, ThreadResponse, ToggleShareWithTeamData, ToggleShareWithTeamError, ToggleShareWithTeamErrors, ToggleShareWithTeamResponse, ToggleShareWithTeamResponses, TranscriptSegmentRequest, TypedSuccessResponse, TypedSuccessResponseGetDocumentResponseData, TypingAction, UnthreadedPdfUuidRequest, UpdateChannelSharePermission, UpdateCrmTeamSettingsRequest, UpdateOperation, UpdateReminderData, UpdateReminderError, UpdateReminderErrors, UpdateReminderRequest, UpdateReminderResponse, UpdateReminderResponses, UpdateSharePermissionRequestV2, UploadDocumentStatus, UploadExtractFolderHandlerData, UploadExtractFolderHandlerError, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponse, UploadExtractFolderHandlerResponses, UploadExtractFolderRequest, UploadFolderHandlerData, UploadFolderHandlerError, UploadFolderHandlerErrors, UploadFolderHandlerResponse, UploadFolderHandlerResponses, UploadFolderRequest, UpsertHistoryHandlerData, UpsertHistoryHandlerError, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponse, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationError, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationRequest, UpsertUserDocumentViewLocationResponse, UpsertUserDocumentViewLocationResponses, UserDocumentsResponse, UserDocumentViewLocation, UserDocumentViewLocationResponse, UserPinsResponse, UserViewsResponse, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenError, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponse, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookError, ValidateWebhookErrors, ValidateWebhookResponse, ValidateWebhookResponse2, ValidateWebhookResponses, Vec, View, ViewPatch, ViewsResponse, Webhook, WebhookEvent, WebhookFilter, WebhookScope, WebhookStatus, WebhookValidationTestEvent, WithCallId, WithChannelId, WithDocumentId, WithProjectId } from './types.gen';
+export type { AccessLevel, ActivityType, AddFavoriteData, AddFavoriteError, AddFavoriteErrors, AddFavoriteRequest, AddFavoriteResponse, AddFavoriteResponses, AddParticipantsData, AddParticipantsError, AddParticipantsErrors, AddParticipantsRequest, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerError, AddPinHandlerErrors, AddPinHandlerResponse, AddPinHandlerResponses, AddPinRequest, Anchor, AnchorId, AnchorRequest, AnchorResponse, AnnotationIncrementalUpdate, ApiActivity, ApiAttachmentChannelReference, ApiAttachmentEntityReference, ApiAttachmentGenericReference, ApiChannelAttachment, ApiChannelAttachmentsPage, ApiChannelContextMessage, ApiChannelDetail, ApiChannelListMessage, ApiChannelListPage, ApiChannelListParticipant, ApiChannelListType, ApiChannelMessage, ApiChannelMessageKind, ApiChannelMessagesPage, ApiChannelParticipant, ApiChannelWithLatest, ApiCountedReaction, ApiEntityFilterAst, ApiGroupByField, ApiGroupMeta, ApiMessageAttachment, ApiMessageSender, ApiMessageSenderType, ApiParticipantListRole, ApiParticipantRole, ApiPropertyEntityType, ApiResolvedChannelMessage, ApiThreadInfo, ApiThreadReply, AttendeeResponseStatus, BasicDocument, BasicDocumentSubType, BomPart, Bot, BotChannel, BotChannelType, BotId, BotKind, BotOwner, BotToken, BranchNameResponse, BTreeMap, BulkWakeupRequest, BulkWakeupResponse, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponse, BulkWakeupSyncServiceDocumentsResponses, CalendarAttendee, CalendarEvent, CalendarEventFilters, CalendarMentionEvent, CalendarMentionPreviewItem, CalendarMentionPreviewKind, CalendarMentionPreviewRequest, CalendarMentionPreviewRequestItem, CalendarMentionPreviewResponse, CalendarOccurrence, CalendarOccurrenceItem, CalendarOccurrenceResponse, CalendarSyncStatus, CallActiveResponse, CallFilters, CallRecord, CallRecordParticipant, CallRecordPreview, CallRecordPreviewData, CallRecordTranscriptSegment, CallStatus, CallTokenResponse, CallWebhookData, CallWebhookError, CallWebhookErrors, CallWebhookResponses, Channel, ChannelCreatedMetadata, ChannelDeletedMetadata, ChannelEventAttachment, ChannelFilters, ChannelJoinCodeResponse, ChannelMentionedMetadata, ChannelMessage, ChannelMessageAttachmentCreatedMetadata, ChannelMessageAttachmentRemovedMetadata, ChannelMessageDeletedMetadata, ChannelMessageFilters, ChannelMessagePatchedMetadata, ChannelMessagePostedMetadata, ChannelParticipant, ChannelParticipantAddedMetadata, ChannelParticipantRemovedMetadata, ChannelPreview, ChannelPreviewData, ChannelSender, ChannelSharePermission, ChannelThreadFilters, ChannelTopicEvent, ChannelType, ChannelUpdatedMetadata, ChannelWebhookRequest, ChannelWebhookResponse, ChannelWithParticipants, Chat, ChatFilters, CheckActiveCallData, CheckActiveCallError, CheckActiveCallErrors, CheckActiveCallResponse, CheckActiveCallResponses, ClientOptions, CloudStorageItemType, Comment, CommentThread, ConferenceProvider, CopyDocumentData, CopyDocumentError, CopyDocumentErrors, CopyDocumentQueryParams, CopyDocumentRequest, CopyDocumentResponse, CopyDocumentResponse2, CopyDocumentResponses, CreateAnchorData, CreateAnchorError, CreateAnchorErrors, CreateAnchorResponse, CreateAnchorResponses, CreateBotRequest, CreateBulkDocumentResponse, CreateBulkDocumentResponseData, CreateChannelData, CreateChannelError, CreateChannelErrors, CreateChannelRequest, CreateChannelResponse, CreateChannelResponse2, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotError, CreateChannelScopedBotErrors, CreateChannelScopedBotRequest, CreateChannelScopedBotResponse, CreateChannelScopedBotResponse2, CreateChannelScopedBotResponses, CreateCommentData, CreateCommentError, CreateCommentErrors, CreateCommentRequest, CreateCommentResponse, CreateCommentResponse2, CreateCommentResponses, CreateCrmCommentData, CreateCrmCommentError, CreateCrmCommentErrors, CreateCrmCommentRequest, CreateCrmCommentResponse, CreateCrmCommentResponses, CreateCrmCompanyData, CreateCrmCompanyError, CreateCrmCompanyErrors, CreateCrmCompanyRequest, CreateCrmCompanyResponse, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactError, CreateCrmContactErrors, CreateCrmContactRequest, CreateCrmContactResponse, CreateCrmContactResponses, CreateDocumentData, CreateDocumentError, CreateDocumentErrors, CreateDocumentRequest, CreateDocumentResponse, CreateDocumentResponseData, CreateDocumentResponses, CreateEntityMentionData, CreateEntityMentionError, CreateEntityMentionErrors, CreateEntityMentionRequest, CreateEntityMentionResponse, CreateEntityMentionResponse2, CreateEntityMentionResponses, CreateInstructionsDocumentResponse, CreateInstructionsHandlerData, CreateInstructionsHandlerError, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponse, CreateInstructionsHandlerResponses, CreateMarkdownDocumentRequest, CreateMarkdownDocumentResponse, CreateMarkdownHandlerData, CreateMarkdownHandlerError, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponse, CreateMarkdownHandlerResponses, CreateProjectHandlerData, CreateProjectHandlerError, CreateProjectHandlerErrors, CreateProjectHandlerResponse, CreateProjectHandlerResponses, CreateProjectRequest, CreateProjectResponse, CreateReminderData, CreateReminderError, CreateReminderErrors, CreateReminderRequest, CreateReminderResponse, CreateReminderResponses, CreateSkillHandlerData, CreateSkillHandlerError, CreateSkillHandlerErrors, CreateSkillHandlerResponse, CreateSkillHandlerResponses, CreateSkillRequest, CreateSkillResponse, CreateSnippetHandlerData, CreateSnippetHandlerError, CreateSnippetHandlerErrors, CreateSnippetHandlerResponse, CreateSnippetHandlerResponses, CreateSnippetRequest, CreateSnippetResponse, CreateTaskHandlerData, CreateTaskHandlerError, CreateTaskHandlerErrors, CreateTaskHandlerResponse, CreateTaskHandlerResponses, CreateTaskRequest, CreateTaskResponse, CreateUnthreadedAnchorRequest, CreateUnthreadedAnchorResponse, CreateUnthreadedPdfAnchorRequest, CreateViewHandlerData, CreateViewHandlerError, CreateViewHandlerErrors, CreateViewHandlerResponse, CreateViewHandlerResponses, CreateViewRequest, CreateWebhookData, CreateWebhookError, CreateWebhookErrors, CreateWebhookRequest, CreateWebhookResponse, CreateWebhookResponse2, CreateWebhookResponses, CrmComment, CrmCommentEntityType, CrmCommentThread, CrmCompanyFilters, CrmCompanyResponse, CrmContactResponse, CrmDomainResponse, CrmPermissionRole, CrmTeamSettingsResponse, CrmThread, CustomSpeakerAssignment, DataType, DeleteAnchorData, DeleteAnchorError, DeleteAnchorErrors, DeleteAnchorInfo, DeleteAnchorResponse, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordError, DeleteCallRecordErrors, DeleteCallRecordResponse, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelError, DeleteChannelErrors, DeleteChannelResponse, DeleteChannelResponses, DeleteCommentData, DeleteCommentError, DeleteCommentErrors, DeleteCommentRequest, DeleteCommentResponse, DeleteCommentResponse2, DeleteCommentResponses, DeleteCrmCommentData, DeleteCrmCommentError, DeleteCrmCommentErrors, DeleteCrmCommentResponse, DeleteCrmCommentResponses, DeleteCrmCommentResult, DeleteDocumentData, DeleteDocumentError, DeleteDocumentErrors, DeleteDocumentResponse, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionError, DeleteEntityMentionErrors, DeleteEntityMentionResponse, DeleteEntityMentionResponse2, DeleteEntityMentionResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerError, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponse, DeleteHistoryHandlerResponses, DeleteMessageData, DeleteMessageError, DeleteMessageErrors, DeleteMessageQuery, DeleteMessageResponse, DeleteMessageResponses, DeleteProjectHandlerData, DeleteProjectHandlerError, DeleteProjectHandlerErrors, DeleteProjectHandlerResponse, DeleteProjectHandlerResponses, DeleteReminderData, DeleteReminderError, DeleteReminderErrors, DeleteReminderResponse, DeleteReminderResponses, DeleteThreadInfo, DeleteUnthreadedAnchorRequest, DeleteUnthreadedAnchorResponse, DeleteUnthreadedPdfAnchorRequest, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationError, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponse, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerError, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookError, DeleteWebhookErrors, DeleteWebhookResponse, DeleteWebhookResponses, DocumentBasic, DocumentContent, DocumentContentLocation, DocumentContentState, DocumentContentUploadedMetadata, DocumentCopiedMetadata, DocumentCreatedMetadata, DocumentDeletedMetadata, DocumentFilters, DocumentInteractionMetadata, DocumentMetadata, DocumentMetadataWithContent, DocumentPermissionsToken, DocumentPermissionsTokenRequest, DocumentPermissionsTokenResponse, DocumentPreview, DocumentPreviewData, DocumentPreviewDataSubType, DocumentPurgedMetadata, DocumentResponse, DocumentResponseMetadata, DocumentResponseMetadataWithContent, DocumentStorageServiceApiVersion, DocumentSubType, DocumentSyncContentUpdatedMetadata, DocumentTeamShareResponse, DocumentTopicEvent, DocumentUpdatedMetadata, EditAnchorData, EditAnchorError, EditAnchorErrors, EditAnchorRequest, EditAnchorResponse, EditAnchorResponse2, EditAnchorResponses, EditCallRecordData, EditCallRecordError, EditCallRecordErrors, EditCallRecordRequest, EditCallRecordResponse, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptError, EditCallTranscriptErrors, EditCallTranscriptRequest, EditCallTranscriptResponse, EditCallTranscriptResponses, EditCommentData, EditCommentError, EditCommentErrors, EditCommentRequest, EditCommentResponse, EditCommentResponse2, EditCommentResponses, EditCrmCommentData, EditCrmCommentError, EditCrmCommentErrors, EditCrmCommentRequest, EditCrmCommentResponse, EditCrmCommentResponses, EditDocumentData, EditDocumentError, EditDocumentErrors, EditDocumentResponse, EditDocumentResponse2, EditDocumentResponses, EditDocumentServiceArgs, EditPdfAnchorRequest, EditPdfPlaceableCommentAnchorRequest, EditProjectV2Data, EditProjectV2Error, EditProjectV2Errors, EditProjectV2Response, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Error, EditThreadV2Errors, EditThreadV2Response, EditThreadV2Responses, EmailFilters, EmptyResponse, EntityFilters, EntityPermission, EntityPermissionResponse, EntityReference, EntityType, ErrorResponse, EventReminderOverride, EventReminders, EventStatus, EventTime, EventTransparency, EventVisibility, ExcludedDefaultView, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerError, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExcludeDefaultViewRequest, ExportDocumentData, ExportDocumentError, ExportDocumentErrors, ExportDocumentResponse, ExportDocumentResponse2, ExportDocumentResponses, Favorite, FavoriteEntityRef, FavoritesList, FileSystemNodeWithIds, FileType, FileTypeUpdate, FolderItem, ForeignEntity, ForeignEntityFilters, GenericErrorResponse, GenericResponse, GenericSuccessResponse, GetActivityData, GetActivityError, GetActivityErrors, GetActivityResponse, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesError, GetAttachmentReferencesErrors, GetAttachmentReferencesResponse, GetAttachmentReferencesResponse2, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewError, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewRequest, GetBatchCallRecordPreviewResponse, GetBatchCallRecordPreviewResponse2, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewError, GetBatchChannelPreviewErrors, GetBatchChannelPreviewRequest, GetBatchChannelPreviewResponse, GetBatchChannelPreviewResponse2, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerError, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponse, GetBatchPreviewHandlerResponses, GetBatchPreviewRequest, GetBatchPreviewResponse, GetBatchProjectPreviewData, GetBatchProjectPreviewError, GetBatchProjectPreviewErrors, GetBatchProjectPreviewRequest, GetBatchProjectPreviewResponse, GetBatchProjectPreviewResponse2, GetBatchProjectPreviewResponses, GetCallRecordData, GetCallRecordError, GetCallRecordErrors, GetCallRecordResponse, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsError, GetChannelAttachmentsErrors, GetChannelAttachmentsResponse, GetChannelAttachmentsResponses, GetChannelData, GetChannelError, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkError, GetChannelJoinLinkErrors, GetChannelJoinLinkResponse, GetChannelJoinLinkResponses, GetChannelMessagesData, GetChannelMessagesError, GetChannelMessagesErrors, GetChannelMessagesResponse, GetChannelMessagesResponses, GetChannelParticipantsData, GetChannelParticipantsError, GetChannelParticipantsErrors, GetChannelParticipantsResponse, GetChannelParticipantsResponses, GetChannelResponse, GetChannelResponses, GetChannelsData, GetChannelsError, GetChannelsErrors, GetChannelsResponse, GetChannelsResponses, GetCompanyData, GetCompanyError, GetCompanyErrors, GetCompanyResponse, GetCompanyResponses, GetContactByEmailData, GetContactByEmailError, GetContactByEmailErrors, GetContactByEmailResponse, GetContactByEmailResponse2, GetContactByEmailResponses, GetContactData, GetContactError, GetContactErrors, GetContactResponse, GetContactResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsError, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponse, GetCrmTeamSettingsResponses, GetDocumentAnchorsData, GetDocumentAnchorsError, GetDocumentAnchorsErrors, GetDocumentAnchorsResponse, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameError, GetDocumentBranchNameErrors, GetDocumentBranchNameResponse, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugError, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponse, GetDocumentByTeamSlugResponses, GetDocumentCommentsData, GetDocumentCommentsError, GetDocumentCommentsErrors, GetDocumentCommentsResponse, GetDocumentCommentsResponses, GetDocumentData, GetDocumentError, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsError, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponse, GetDocumentGithubPullRequestsResponses, GetDocumentKeyResponse, GetDocumentKeyResponseData, GetDocumentListHandlerData, GetDocumentListHandlerError, GetDocumentListHandlerErrors, GetDocumentListHandlerResponse, GetDocumentListHandlerResponses, GetDocumentListResult, GetDocumentLocationV3Data, GetDocumentLocationV3Error, GetDocumentLocationV3Errors, GetDocumentLocationV3Response, GetDocumentLocationV3Responses, GetDocumentPermissionsResponseDataV2, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenError, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponse, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Error, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Response, GetDocumentPermissionsV2Responses, GetDocumentProcessingResult, GetDocumentProcessingResultData, GetDocumentProcessingResultError, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponse, GetDocumentProcessingResultResponse2, GetDocumentProcessingResultResponses, GetDocumentResponse, GetDocumentResponse2, GetDocumentResponseData, GetDocumentResponses, GetDocumentSearchResponse, GetDocumentShortIdData, GetDocumentShortIdError, GetDocumentShortIdErrors, GetDocumentShortIdResponse, GetDocumentShortIdResponses, GetDocumentsResponse, GetDocumentTeamShareData, GetDocumentTeamShareError, GetDocumentTeamShareErrors, GetDocumentTeamShareResponse, GetDocumentTeamShareResponses, GetDocumentUserAccessLevelResponse, GetDocumentVersionData, GetDocumentVersionError, GetDocumentVersionErrors, GetDocumentVersionResponse, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerError, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponse, GetDocumentViewsHandlerResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponse, GetEntityPermissionResponses, GetForeignEntityData, GetForeignEntityError, GetForeignEntityErrors, GetForeignEntityResponse, GetForeignEntityResponses, GetHistoryHandlerData, GetHistoryHandlerError, GetHistoryHandlerErrors, GetHistoryHandlerResponse, GetHistoryHandlerResponses, GetInstructionsDocumentResponse, GetInstructionsHandlerData, GetInstructionsHandlerError, GetInstructionsHandlerErrors, GetInstructionsHandlerResponse, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupError, GetItemsSoupErrors, GetItemsSoupResponse, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerError, GetLocationHandlerErrors, GetLocationHandlerResponse, GetLocationHandlerResponses, GetMessageWithContextData, GetMessageWithContextError, GetMessageWithContextErrors, GetMessageWithContextResponse, GetMessageWithContextResponse2, GetMessageWithContextResponses, GetOrCreateAction, GetOrCreateCallData, GetOrCreateCallError, GetOrCreateCallErrors, GetOrCreateCallResponse, GetOrCreateCallResponses, GetOrCreateChannelResponse, GetOrCreateDmData, GetOrCreateDmError, GetOrCreateDmErrors, GetOrCreateDmRequest, GetOrCreateDmResponse, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateError, GetOrCreatePrivateErrors, GetOrCreatePrivateRequest, GetOrCreatePrivateResponse, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerError, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponse, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerError, GetPinsHandlerErrors, GetPinsHandlerResponse, GetPinsHandlerResponses, GetPinsResponse, GetProjectContentHandlerData, GetProjectContentHandlerError, GetProjectContentHandlerErrors, GetProjectContentHandlerResponse, GetProjectContentHandlerResponses, GetProjectContentResponse, GetProjectHandlerData, GetProjectHandlerError, GetProjectHandlerErrors, GetProjectHandlerResponse, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Error, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Response, GetProjectPermissionsV2Responses, GetProjectResponse, GetProjectResponseData, GetProjectsHandlerData, GetProjectsHandlerError, GetProjectsHandlerErrors, GetProjectsHandlerResponse, GetProjectsHandlerResponses, GetProjectsResponse, GetProjectUserAccessLevelData, GetProjectUserAccessLevelError, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponse, GetProjectUserAccessLevelResponses, GetReminderData, GetReminderError, GetReminderErrors, GetReminderResponse, GetReminderResponses, GetRingStatusData, GetRingStatusError, GetRingStatusErrors, GetRingStatusResponse, GetRingStatusResponses, GetSelfBotData, GetSelfBotError, GetSelfBotErrors, GetSelfBotResponse, GetSelfBotResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerError, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponse, GetSystemSkillsHandlerResponses, GetThreadRepliesData, GetThreadRepliesError, GetThreadRepliesErrors, GetThreadRepliesResponse, GetThreadRepliesResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerError, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponse, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationError, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponse, GetUserDocumentViewLocationResponses, GetUserHistoryResponse, GetViewsHandlerData, GetViewsHandlerError, GetViewsHandlerErrors, GetViewsHandlerResponse, GetViewsHandlerResponses, GetWebhookData, GetWebhookError, GetWebhookErrors, GetWebhookResponse, GetWebhookResponses, GithubPullRequest, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestsResponse, GroupedInitialParams, GroupedPageParams, GroupedSoupGroupPage, GroupedSoupInitialPage, GroupedSoupPage, GroupedSoupSort, HandlerData, HandlerError, HandlerErrors, HandlerResponse, HandlerResponses, HashMap, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HighlightType, IngestTranscriptData, IngestTranscriptError, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsError, InitializeUserDocumentsErrors, InitializeUserDocumentsResponse, InitializeUserDocumentsResponses, InstallSyncData, InstallSyncErrors, InteractionReason, Item, ItemWithUserAccessLevel, JobProcessingResultHandlerData, JobProcessingResultHandlerError, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponse, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeError, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelError, JoinChannelErrors, JoinChannelResponses, LatestMessage, LeaveCallResponse, LeaveChannelData, LeaveChannelError, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallError, LeaveOrEndCallErrors, LeaveOrEndCallResponse, LeaveOrEndCallResponses, LinkShare, ListBotChannelsData, ListBotChannelsError, ListBotChannelsErrors, ListBotChannelsResponse, ListBotChannelsResponses, ListCompanyContactsData, ListCompanyContactsError, ListCompanyContactsErrors, ListCompanyContactsResponse, ListCompanyContactsResponses, ListCrmCommentsData, ListCrmCommentsError, ListCrmCommentsErrors, ListCrmCommentsResponse, ListCrmCommentsResponses, ListFavoritesData, ListFavoritesError, ListFavoritesErrors, ListFavoritesResponse, ListFavoritesResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponse, ListOccurrencesResponses, ListRemindersData, ListRemindersError, ListRemindersErrors, ListRemindersResponse, ListRemindersResponses, ListWebhooksData, ListWebhooksError, ListWebhooksErrors, ListWebhooksResponse, ListWebhooksResponse2, ListWebhooksResponses, LocationResponseData, LocationResponseV3, MacroUserIdStr, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponse, MentionPreviewsResponses, Mentions, NewChannelAttachment, NotificationFilters, Params, ParticipantRole, PatchBotRequest, PatchChannelData, PatchChannelError, PatchChannelErrors, PatchChannelRequest, PatchChannelResponse, PatchChannelResponses, PatchMessageData, PatchMessageError, PatchMessageErrors, PatchMessageRequest, PatchMessageResponse, PatchMessageResponses, PatchProjectRequestV2, PatchThreadRequestV2, PatchViewHandlerData, PatchViewHandlerError, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookError, PatchWebhookErrors, PatchWebhookRequest, PatchWebhookResponse, PatchWebhookResponses, PdfAnchor, PdfAnchorId, PdfAnchorRequest, PdfHighlightAnchor, PdfHighlightAnchorRequest, PdfHighlightRect, PdfHighlightRectAnchorRequest, PdfPlaceableCommentAnchor, PdfPlaceableCommentAnchorRequest, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentError, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponse, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectError, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponse, PermanentlyDeleteProjectResponses, PinnedItem, PinRequest, PostActivityData, PostActivityError, PostActivityErrors, PostActivityRequest, PostActivityResponse, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookError, PostChannelBotWebhookErrors, PostChannelBotWebhookResponse, PostChannelBotWebhookResponses, PostChannelMessagesData, PostChannelMessagesError, PostChannelMessagesErrors, PostChannelMessagesResponse, PostChannelMessagesResponses, PostGroupedSoupAstGroupPageRequest, PostGroupedSoupAstInitialRequest, PostGroupedSoupAstRequest, PostItemsSoupAstData, PostItemsSoupAstError, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedError, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponse, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponse, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupError, PostItemsSoupErrors, PostItemsSoupResponse, PostItemsSoupResponses, PostMessageData, PostMessageError, PostMessageErrors, PostMessageRequest, PostMessageResponse, PostMessageResponse2, PostMessageResponses, PostReactionData, PostReactionError, PostReactionErrors, PostReactionRequest, PostReactionResponse, PostReactionResponses, PostSoupAstRequest, PostSoupRequest, PostTypingData, PostTypingError, PostTypingErrors, PostTypingRequest, PostTypingResponse, PostTypingResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerError, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponse, PresaveDocumentHandlerResponses, PreSaveDocumentRequest, PreSaveDocumentResponse, PreSaveDocumentResponseData, PresignedUrl, Project, ProjectDeleteResponseData, ProjectDocumentStatus, ProjectFilters, ProjectPreview, ProjectPreviewData, PropertyDefinition, PropertyFilter, PropertyInput, PropertyOwner, PropertyValue, PutCrmTeamSettingsData, PutCrmTeamSettingsError, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponse, PutCrmTeamSettingsResponses, ReactionAction, RecentlyDeletedData, RecentlyDeletedError, RecentlyDeletedErrors, RecentlyDeletedResponse, RecentlyDeletedResponseData, RecentlyDeletedResponses, Reminder, ReminderFilters, ReminderSchedule, RemindersList, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotError, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponse, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityError, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsError, RemoveParticipantsErrors, RemoveParticipantsRequest, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerError, RemovePinHandlerErrors, RemovePinHandlerResponse, RemovePinHandlerResponses, ReorderFavoritesData, ReorderFavoritesError, ReorderFavoritesErrors, ReorderFavoritesRequest, ReorderFavoritesResponses, ReorderPinRequest, ReorderPinsHandlerData, ReorderPinsHandlerError, ReorderPinsHandlerErrors, ReorderPinsHandlerResponse, ReorderPinsHandlerResponses, ResolveChannelMessageData, ResolveChannelMessageError, ResolveChannelMessageErrors, ResolveChannelMessageResponse, ResolveChannelMessageResponses, RevertDeleteDocumentData, RevertDeleteDocumentError, RevertDeleteDocumentErrors, RevertDeleteDocumentResponse, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectError, RevertDeleteProjectErrors, RevertDeleteProjectResponse, RevertDeleteProjectResponses, RingStatus, RingStatusResponse, S3ObjectInfo, SaveBomPart, SaveDocumentHandlerData, SaveDocumentHandlerError, SaveDocumentHandlerErrors, SaveDocumentHandlerResponse, SaveDocumentHandlerResponses, SaveDocumentRequest, SaveDocumentResponse, SaveDocumentResponseData, SetCompanyHiddenData, SetCompanyHiddenError, SetCompanyHiddenErrors, SetCompanyHiddenRequest, SetCompanyHiddenResponse, SetCompanyHiddenResponses, SetCompanyNameRequest, SetContactHiddenData, SetContactHiddenError, SetContactHiddenErrors, SetContactHiddenRequest, SetContactHiddenResponse, SetContactHiddenResponses, SetContactNameRequest, SetCrmCompanyNameData, SetCrmCompanyNameError, SetCrmCompanyNameErrors, SetCrmCompanyNameResponse, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameError, SetCrmContactNameErrors, SetCrmContactNameResponse, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareError, SetDocumentTeamShareErrors, SetDocumentTeamShareRequest, SetDocumentTeamShareResponse, SetDocumentTeamShareResponses, SetEmailSyncData, SetEmailSyncError, SetEmailSyncErrors, SetEmailSyncRequest, SetEmailSyncResponse, SetEmailSyncResponses, SetPropertyValue, SharedEmailFilter, SharePermissionV2, ShortIdResponse, SimpleMention, SimpleSaveData, SimpleSaveError, SimpleSaveErrors, SimpleSaveResponse, SimpleSaveResponses, SoupApiItem, SoupApiSort, SoupApiSortDirection, SoupAttachment, SoupCalendarEventSoupPropertiesField, SoupCalendarEventTime, SoupCallRecordParticipant, SoupCallRecordSoupPropertiesField, SoupChannel, SoupChannelThread, SoupChatSoupPropertiesField, SoupContact, SoupCountedReaction, SoupCrmCompanySoupPropertiesField, SoupCrmDomain, SoupDocumentSoupPropertiesField, SoupDocumentSubType, SoupEmailThreadPreview, SoupEnrichedEmailThreadPreviewSoupPropertiesField, SoupForeignEntity, SoupItem, SoupLabel, SoupLabelListVisibility, SoupLabelType, SoupMessageAttachment, SoupMessageListVisibility, SoupMessageSender, SoupMessageSenderType, SoupPage, SoupProjectSoupPropertiesField, SoupPropertiesField, SoupProperty, SoupReminderReference, SoupReminderSchedule, SoupReminderSoupPropertiesField, SoupThreadInfo, SoupThreadReply, StarterDocumentsResponse, String, SuccessResponse, SyncServiceVersionId, SystemSkillSummary, TagFilterMode, TaskFilters, TeamRole, Thread, ThreadResponse, ToggleShareWithTeamData, ToggleShareWithTeamError, ToggleShareWithTeamErrors, ToggleShareWithTeamResponse, ToggleShareWithTeamResponses, TranscriptSegmentRequest, TypedSuccessResponse, TypedSuccessResponseGetDocumentResponseData, TypingAction, UnthreadedPdfUuidRequest, UpdateChannelSharePermission, UpdateCrmTeamSettingsRequest, UpdateOperation, UpdateReminderData, UpdateReminderError, UpdateReminderErrors, UpdateReminderRequest, UpdateReminderResponse, UpdateReminderResponses, UpdateSharePermissionRequestV2, UploadDocumentStatus, UploadExtractFolderHandlerData, UploadExtractFolderHandlerError, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponse, UploadExtractFolderHandlerResponses, UploadExtractFolderRequest, UploadFolderHandlerData, UploadFolderHandlerError, UploadFolderHandlerErrors, UploadFolderHandlerResponse, UploadFolderHandlerResponses, UploadFolderRequest, UpsertHistoryHandlerData, UpsertHistoryHandlerError, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponse, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationError, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationRequest, UpsertUserDocumentViewLocationResponse, UpsertUserDocumentViewLocationResponses, UserDocumentsResponse, UserDocumentViewLocation, UserDocumentViewLocationResponse, UserPinsResponse, UserViewsResponse, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenError, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponse, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookError, ValidateWebhookErrors, ValidateWebhookResponse, ValidateWebhookResponse2, ValidateWebhookResponses, Vec, View, ViewPatch, ViewsResponse, Webhook, WebhookEvent, WebhookFilter, WebhookScope, WebhookStatus, WebhookValidationTestEvent, WithCallId, WithChannelId, WithDocumentId, WithProjectId } from './types.gen';
diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.ts
index 98818728ae..418329504a 100644
--- a/packages/sdk/generated/storage/types.gen.ts
+++ b/packages/sdk/generated/storage/types.gen.ts
@@ -1000,6 +1000,8 @@ export type BomPart = {
/**
* Bot row.
+ *
+ * Clients deserialize this, so both derives are used.
*/
export type Bot = {
/**
@@ -2583,6 +2585,36 @@ export type CopyDocumentResponse = {
error: boolean;
};
+/**
+ * Request to create a bot.
+ */
+export type CreateBotRequest = {
+ /**
+ * Optional avatar URL.
+ */
+ avatar_url?: string | null;
+ /**
+ * Optional description.
+ */
+ description?: string | null;
+ /**
+ * Stable handle.
+ */
+ handle: string;
+ /**
+ * Whether mentioning this bot opens a sandboxed coding-agent session. Defaults to false.
+ */
+ has_agent?: boolean | null;
+ /**
+ * Display name.
+ */
+ name: string;
+ /**
+ * Team owner. The caller must be a team administrator or owner. Omit for a user-owned bot.
+ */
+ team_id?: string | null;
+};
+
export type CreateBulkDocumentResponse = {
/**
* Data to be returned
@@ -2655,6 +2687,10 @@ export type CreateChannelScopedBotRequest = {
* Stable handle.
*/
handle: string;
+ /**
+ * Whether mentioning this bot opens a sandboxed coding-agent session. Defaults to false.
+ */
+ has_agent?: boolean | null;
/**
* Display name.
*/
@@ -3122,6 +3158,8 @@ export type CreateViewRequest = {
/**
* Request to create a webhook.
+ *
+ * Clients serialize this, so both derives are used.
*/
export type CreateWebhookRequest = {
/**
@@ -3150,6 +3188,8 @@ export type CreateWebhookRequest = {
/**
* Webhook returned after creation, including its signing secret.
+ *
+ * Clients deserialize this, so both derives are used.
*/
export type CreateWebhookResponse = {
/**
@@ -5513,6 +5553,8 @@ export type LinkShare = 'PUBLIC' | 'TEAM';
/**
* Webhooks visible to the caller across their personal and team workspaces.
+ *
+ * Clients deserialize this, so both derives are used.
*/
export type ListWebhooksResponse = {
/**
@@ -5642,6 +5684,32 @@ export type Params = {
*/
export type ParticipantRole = 'owner' | 'admin' | 'member';
+/**
+ * Request to patch a bot.
+ */
+export type PatchBotRequest = {
+ /**
+ * Optional avatar URL.
+ */
+ avatar_url?: string | null;
+ /**
+ * Optional description.
+ */
+ description?: string | null;
+ /**
+ * Stable handle.
+ */
+ handle?: string | null;
+ /**
+ * Whether mentioning this bot opens a sandboxed coding-agent session. Omit to leave unchanged.
+ */
+ has_agent?: boolean | null;
+ /**
+ * Display name.
+ */
+ name?: string | null;
+};
+
/**
* Request to patch a channel.
*/
@@ -8210,6 +8278,8 @@ export type ViewsResponse = {
/**
* Webhook row returned by application APIs.
+ *
+ * Clients deserialize this, so both derives are used.
*/
export type Webhook = {
/**
@@ -8293,6 +8363,8 @@ export type WebhookFilter = {
/**
* Scope that owns a newly-created webhook.
+ *
+ * Clients serialize this, so both derives are used.
*/
export type WebhookScope = 'user' | 'team';
diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.json
index 84b69e314e..3b615d3ef3 100644
--- a/packages/sdk/specs/storage.json
+++ b/packages/sdk/specs/storage.json
@@ -12614,7 +12614,7 @@
},
"Bot": {
"type": "object",
- "description": "Bot row.",
+ "description": "Bot row.\n\nClients deserialize this, so both derives are used.",
"required": [
"id",
"kind",
@@ -14844,6 +14844,38 @@
}
}
},
+ "CreateBotRequest": {
+ "type": "object",
+ "description": "Request to create a bot.",
+ "required": ["name", "handle"],
+ "properties": {
+ "avatar_url": {
+ "type": ["string", "null"],
+ "description": "Optional avatar URL."
+ },
+ "description": {
+ "type": ["string", "null"],
+ "description": "Optional description."
+ },
+ "handle": {
+ "type": "string",
+ "description": "Stable handle."
+ },
+ "has_agent": {
+ "type": ["boolean", "null"],
+ "description": "Whether mentioning this bot opens a sandboxed coding-agent session. Defaults to false."
+ },
+ "name": {
+ "type": "string",
+ "description": "Display name."
+ },
+ "team_id": {
+ "type": ["string", "null"],
+ "format": "uuid",
+ "description": "Team owner. The caller must be a team administrator or owner. Omit for a user-owned bot."
+ }
+ }
+ },
"CreateBulkDocumentResponse": {
"type": "object",
"required": ["error", "data"],
@@ -14954,6 +14986,10 @@
"type": "string",
"description": "Stable handle."
},
+ "has_agent": {
+ "type": ["boolean", "null"],
+ "description": "Whether mentioning this bot opens a sandboxed coding-agent session. Defaults to false."
+ },
"name": {
"type": "string",
"description": "Display name."
@@ -15607,7 +15643,7 @@
},
"CreateWebhookRequest": {
"type": "object",
- "description": "Request to create a webhook.",
+ "description": "Request to create a webhook.\n\nClients serialize this, so both derives are used.",
"required": ["scope", "namespace", "name", "endpoint_url", "filters"],
"properties": {
"endpoint_url": {
@@ -15645,7 +15681,7 @@
},
"CreateWebhookResponse": {
"type": "object",
- "description": "Webhook returned after creation, including its signing secret.",
+ "description": "Webhook returned after creation, including its signing secret.\n\nClients deserialize this, so both derives are used.",
"required": [
"id",
"workspace_id",
@@ -19725,7 +19761,7 @@
},
"ListWebhooksResponse": {
"type": "object",
- "description": "Webhooks visible to the caller across their personal and team workspaces.",
+ "description": "Webhooks visible to the caller across their personal and team workspaces.\n\nClients deserialize this, so both derives are used.",
"required": ["webhooks"],
"properties": {
"webhooks": {
@@ -19939,6 +19975,32 @@
"description": "The role a user has within a channel.",
"enum": ["owner", "admin", "member"]
},
+ "PatchBotRequest": {
+ "type": "object",
+ "description": "Request to patch a bot.",
+ "properties": {
+ "avatar_url": {
+ "type": ["string", "null"],
+ "description": "Optional avatar URL."
+ },
+ "description": {
+ "type": ["string", "null"],
+ "description": "Optional description."
+ },
+ "handle": {
+ "type": ["string", "null"],
+ "description": "Stable handle."
+ },
+ "has_agent": {
+ "type": ["boolean", "null"],
+ "description": "Whether mentioning this bot opens a sandboxed coding-agent session. Omit to leave unchanged."
+ },
+ "name": {
+ "type": ["string", "null"],
+ "description": "Display name."
+ }
+ }
+ },
"PatchChannelRequest": {
"type": "object",
"description": "Request to patch a channel.",
@@ -24282,7 +24344,7 @@
},
"Webhook": {
"type": "object",
- "description": "Webhook row returned by application APIs.",
+ "description": "Webhook row returned by application APIs.\n\nClients deserialize this, so both derives are used.",
"required": [
"id",
"workspace_id",
@@ -24392,7 +24454,7 @@
},
"WebhookScope": {
"type": "string",
- "description": "Scope that owns a newly-created webhook.",
+ "description": "Scope that owns a newly-created webhook.\n\nClients serialize this, so both derives are used.",
"enum": ["user", "team"]
},
"WebhookStatus": {
diff --git a/rust-toolchain.toml b/rust-toolchain.toml
index 0fb4ad2dc1..6181559ea1 100644
--- a/rust-toolchain.toml
+++ b/rust-toolchain.toml
@@ -9,4 +9,9 @@ targets = [
"wasm32-unknown-unknown",
"aarch64-unknown-linux-gnu",
"x86_64-unknown-linux-gnu",
+ # The musl targets carry the statically linked `coding_agent_worker` release
+ # builds (see `build_agent_daemon_on_tag`): self-hosters run the daemon on
+ # whatever distro they have, so it must not link a host libc.
+ "aarch64-unknown-linux-musl",
+ "x86_64-unknown-linux-musl",
]
diff --git a/services/agent_harness_service/Cargo.toml b/services/agent_harness_service/Cargo.toml
index 4deb7f4aa1..e7740216b3 100644
--- a/services/agent_harness_service/Cargo.toml
+++ b/services/agent_harness_service/Cargo.toml
@@ -34,6 +34,7 @@ notification = { path = "../../crates/notification" }
rdkafka = { workspace = true }
channels = { path = "../../crates/channels", features = ["ports", "outbound"] }
anyhow = { workspace = true }
+macro_user_id = { path = "../../crates/macro_user_id" }
axum = { workspace = true }
aws-sdk-secretsmanager = { workspace = true }
kafka_util = { path = "../../crates/kafka_util" }
diff --git a/services/agent_harness_service/src/api.rs b/services/agent_harness_service/src/api.rs
index 1103745b76..92c77b2683 100644
--- a/services/agent_harness_service/src/api.rs
+++ b/services/agent_harness_service/src/api.rs
@@ -3,11 +3,14 @@
//! This process owns the complete agent-session HTTP API: durable metadata and
//! log reads as well as operations against the live in-memory transport.
-use agent_session::domain::ports::AgentSessionNotificationRecipient;
+use agent_harness::inbound::runtime_gateway::{RuntimeGatewayState, runtime_gateway_router};
+use agent_session::domain::ports::{
+ AgentSessionNotificationRecipient, BotDirectory, ExternalSessionOpener,
+};
use agent_session::domain::service::AgentSessionService;
use agent_session::inbound::axum_router::{
- AgentSessionControlState, AgentSessionRouterState, agent_session_control_router,
- agent_session_read_router,
+ AgentSessionControlState, AgentSessionRouterState, CreateSessionState,
+ agent_session_control_router, agent_session_create_router, agent_session_read_router,
};
use anyhow::Context;
use axum::Router;
@@ -20,19 +23,23 @@ use utoipa_swagger_ui::SwaggerUi;
pub mod swagger;
/// Build the router and serve it until the process is asked to stop.
-pub async fn setup_and_serve<T, R, Access, Auth>(
+pub async fn setup_and_serve<T, R, Opener, Bots, Access, Auth>(
read_state: AgentSessionRouterState<T, Access, Auth>,
control_state: AgentSessionControlState<R, Access, Auth>,
+ create_state: CreateSessionState<Opener, Bots, Auth>,
+ gateway_state: RuntimeGatewayState<Bots, Auth>,
port: u16,
shutdown: impl Future<Output = ()> + Send + 'static,
) -> anyhow::Result<()>
where
T: AgentSessionService,
R: AgentSessionNotificationRecipient,
+ Opener: ExternalSessionOpener,
+ Bots: BotDirectory,
Access: EntityAccessService,
Auth: MacroAuthorizationService,
{
- let app = api_router(read_state, control_state)
+ let app = api_router(read_state, control_state, create_state, gateway_state)
.layer(macro_cors::cors_layer())
.merge(SwaggerUi::new("/docs").url("/api-doc/openapi.json", swagger::ApiDoc::openapi()));
@@ -48,21 +55,27 @@ where
.context("agent harness service http failed")
}
-fn api_router<T, R, Access, Auth>(
+fn api_router<T, R, Opener, Bots, Access, Auth>(
read_state: AgentSessionRouterState<T, Access, Auth>,
control_state: AgentSessionControlState<R, Access, Auth>,
+ create_state: CreateSessionState<Opener, Bots, Auth>,
+ gateway_state: RuntimeGatewayState<Bots, Auth>,
) -> Router
where
T: AgentSessionService,
R: AgentSessionNotificationRecipient,
+ Opener: ExternalSessionOpener,
+ Bots: BotDirectory,
Access: EntityAccessService,
Auth: MacroAuthorizationService,
{
- let agent_sessions =
- agent_session_read_router(read_state).merge(agent_session_control_router(control_state));
+ let agent_sessions = agent_session_read_router(read_state)
+ .merge(agent_session_control_router(control_state))
+ .merge(agent_session_create_router(create_state));
Router::new()
.route("/health", get(health))
.nest("/agent-sessions", agent_sessions)
+ .nest("/runtime", runtime_gateway_router(gateway_state))
}
async fn health() -> &'static str {
diff --git a/services/agent_harness_service/src/api/swagger.rs b/services/agent_harness_service/src/api/swagger.rs
index 05a3e1c0bd..a92c581b6c 100644
--- a/services/agent_harness_service/src/api/swagger.rs
+++ b/services/agent_harness_service/src/api/swagger.rs
@@ -4,7 +4,8 @@ use agent_runtime_protocol::domain::action::{AgentAction, AgentActionId};
use agent_session::domain::model::SessionBot;
use agent_session::inbound::axum_router::{
self, AgentSessionLogEntryDto, AgentSessionLogResponse, AgentSessionResponse, ControlRequest,
- LogDirectionDto, LogFrameDto, SessionStatusDto,
+ CreateAgentSessionRequest, CreateAgentSessionResponse, CreateSessionThread, LogDirectionDto,
+ LogFrameDto, SessionStatusDto,
};
use utoipa::OpenApi;
@@ -12,12 +13,16 @@ use utoipa::OpenApi;
#[openapi(
info(terms_of_service = "https://macro.com/terms"),
paths(
+ axum_router::create_agent_session_handler,
axum_router::get_agent_session_handler,
axum_router::get_agent_session_log_handler,
axum_router::control_agent_session_handler,
axum_router::delete_agent_session_handler,
),
components(schemas(
+ CreateAgentSessionRequest,
+ CreateAgentSessionResponse,
+ CreateSessionThread,
ControlRequest,
AgentAction,
AgentActionId,
diff --git a/services/agent_harness_service/src/bots_directory.rs b/services/agent_harness_service/src/bots_directory.rs
new file mode 100644
index 0000000000..1c756db884
--- /dev/null
+++ b/services/agent_harness_service/src/bots_directory.rs
@@ -0,0 +1,55 @@
+//! Postgres-backed [`BotDirectory`] for the agent-session create route.
+//!
+//! A composition-root adapter: the port in `agent_session` asks for the few
+//! facts that gate opening sessions, and this answers them from the bots
+//! repo without either domain crate growing a dependency on `bots`.
+
+use agent_harness::domain::model::is_managed_bot;
+use agent_session::domain::error::{AgentSessionError, Result};
+use agent_session::domain::ports::{BotDirectory, BotFacts};
+use bot_id::BotId;
+use bots::domain::models::BotOwner;
+use bots::domain::ports::BotRepo;
+use bots::outbound::pg_bots_repo::PgBotsRepo;
+use macro_user_id::user_id::MacroUserIdStr;
+
+/// [`BotDirectory`] over the bots table.
+#[derive(Clone)]
+pub struct PgBotDirectory {
+ repo: PgBotsRepo,
+}
+
+impl PgBotDirectory {
+ /// Wrap a bots repo.
+ pub fn new(repo: PgBotsRepo) -> Self {
+ Self { repo }
+ }
+}
+
+impl BotDirectory for PgBotDirectory {
+ async fn bot_facts(&self, bot: BotId) -> Result<Option<BotFacts>> {
+ let Some(row) = self
+ .repo
+ .get_bot(bot)
+ .await
+ .map_err(AgentSessionError::Unknown)?
+ else {
+ return Ok(None);
+ };
+ let owner_user_id = match row.owner {
+ Some(BotOwner::User { user_id }) => {
+ Some(MacroUserIdStr::try_from(user_id).map_err(|error| {
+ AgentSessionError::Unknown(anyhow::anyhow!(
+ "bot has an unparseable owner: {error}"
+ ))
+ })?)
+ }
+ Some(BotOwner::Team { .. }) | None => None,
+ };
+ Ok(Some(BotFacts {
+ has_agent: row.has_agent,
+ is_managed: is_managed_bot(bot),
+ owner_user_id,
+ }))
+ }
+}
diff --git a/services/agent_harness_service/src/config.rs b/services/agent_harness_service/src/config.rs
index d400e9b2d1..acbd8408a7 100644
--- a/services/agent_harness_service/src/config.rs
+++ b/services/agent_harness_service/src/config.rs
@@ -26,14 +26,20 @@ pub struct Config {
/// Base URL of the Daytona REST API.
#[macro_config_default(String::from("https://app.daytona.io/api"))]
pub daytona_api_url: String,
- /// API key the Daytona client authenticates with.
+ /// API key the Daytona client authenticates with. Empty means the
+ /// managed (sandbox-provisioning) path is unarmed: external sessions
+ /// still work, and a managed spawn fails loudly at spawn time.
+ #[macro_config_default(String::new())]
pub daytona_api_key: String,
/// Name of the prebuilt Daytona snapshot to create sandboxes from. The
/// image is expected to be built and pushed as a snapshot out of band,
/// keeping image builds off the first-prompt critical path.
#[macro_config_default(String::from("macro-agent-harness"))]
pub daytona_snapshot: String,
- /// Token with read access to the repo cloned into sandboxes.
+ /// Token with read access to the repo cloned into sandboxes. Empty
+ /// means managed sandboxes cannot clone; external sessions are
+ /// unaffected.
+ #[macro_config_default(String::new())]
pub github_token: String,
/// The bot this deployment answers for.
///
diff --git a/services/agent_harness_service/src/main.rs b/services/agent_harness_service/src/main.rs
index 7584f36d29..c9d51aa602 100644
--- a/services/agent_harness_service/src/main.rs
+++ b/services/agent_harness_service/src/main.rs
@@ -6,6 +6,7 @@
//! announcements, then drives the orchestrator from `macro.agent_sessions`.
mod api;
+mod bots_directory;
mod config;
use std::sync::Arc;
@@ -13,20 +14,26 @@ use std::sync::Arc;
use agent_fold::domain::service::FoldedMessageService;
use agent_harness::domain::model::SessionDefaults;
use agent_harness::domain::service::AgentHarnessService;
-use agent_harness::inbound::kafka::agent_trigger_to_harness_command;
+use agent_harness::inbound::kafka::{RoutedTrigger, route_agent_trigger};
+use agent_harness::inbound::runtime_gateway::RuntimeGatewayState;
use agent_harness::outbound::channel_announcer::ChannelAnnouncer;
use agent_harness::outbound::daytona::{
DaytonaApiKey as DaytonaApiKeySecret, DaytonaContainerManager, DaytonaSettings,
GithubToken as GithubTokenSecret, Snapshot,
};
+use agent_harness::outbound::runtime_registry::RuntimeRegistry;
use agent_session::domain::ports::NoOpRealtime;
use agent_session::domain::service::AgentSessionServiceImpl;
-use agent_session::inbound::axum_router::{AgentSessionControlState, AgentSessionRouterState};
+use agent_session::inbound::axum_router::{
+ AgentSessionControlState, AgentSessionRouterState, CreateSessionState,
+};
use agent_session::outbound::connection_gateway_realtime::ConnectionGatewayAgentSessionRealtime;
use agent_session::outbound::postgres::PgAgentSessionRepo;
use agent_trigger::domain::broker_events::AgentSessionMacroEvent;
use anyhow::Context as _;
use bot_id::BotId;
+use bots::outbound::pg_bots_repo::PgBotsRepo;
+use bots_directory::PgBotDirectory;
use channels::domain::service::ChannelServiceImpl;
use channels::domain::side_effects::{ChannelSideEffectService, SpawnedChannelEventDispatcher};
use channels::outbound::connection_gateway_realtime::ConnectionGatewayChannelRealtimePublisher;
@@ -82,14 +89,13 @@ async fn main() -> anyhow::Result<()> {
agent_harness::install_tls_provider();
let config = Config::from_env()?;
let bot_id = BotId::new_from_uuid(config.harness_bot_id);
- anyhow::ensure!(
- !config.daytona_api_key.trim().is_empty(),
- "DAYTONA_API_KEY is required"
- );
- anyhow::ensure!(
- !config.github_token.trim().is_empty(),
- "GITHUB_TOKEN is required"
- );
+ // Credential-less boot is deliberate: external sessions need neither.
+ // A managed spawn without them fails at spawn time instead, loudly.
+ if config.daytona_api_key.trim().is_empty() || config.github_token.trim().is_empty() {
+ tracing::warn!(
+ "DAYTONA_API_KEY and/or GITHUB_TOKEN are unset: managed sandboxes are unarmed; external agent sessions are unaffected"
+ );
+ }
let pool = PgPoolOptions::new()
.min_connections(1)
@@ -161,17 +167,21 @@ async fn main() -> anyhow::Result<()> {
));
let announcer = ChannelAnnouncer::new(
channel_service,
- bot_id,
LexicalClient::new(
config.internal_api_key.clone(),
LexicalServiceUrl::new()?.to_string(),
),
);
+ // One connection per bot, shared by every session that bot runs. Held
+ // here because the gateway puts dialed-in sockets into it and the harness
+ // takes sessions out of it.
+ let runtimes = RuntimeRegistry::new();
let harness = Arc::new(AgentHarnessService::new(
sessions,
containers,
announcer,
+ Arc::clone(&runtimes),
SessionDefaults {
model: config.harness_model.clone(),
harness: config.harness_slug.clone(),
@@ -206,7 +216,7 @@ async fn main() -> anyhow::Result<()> {
let read_state = AgentSessionRouterState::new(
AgentSessionServiceImpl::new(
session_repo.clone(),
- FoldedMessageService::new(session_repo),
+ FoldedMessageService::new(session_repo.clone()),
NoOpRealtime,
),
entity_access.clone(),
@@ -215,12 +225,30 @@ async fn main() -> anyhow::Result<()> {
let control_state = AgentSessionControlState::new(
harness.clone(),
entity_access,
+ MacroAuthorizationState::new(Arc::new(authorization_service.clone())),
+ );
+ let bots_directory = Arc::new(PgBotDirectory::new(PgBotsRepo::new(pool.clone())));
+ let create_state = CreateSessionState::new(
+ harness.clone(),
+ bots_directory.clone(),
+ MacroAuthorizationState::new(Arc::new(authorization_service.clone())),
+ );
+ let gateway_state = RuntimeGatewayState::new(
+ runtimes,
+ bots_directory,
MacroAuthorizationState::new(Arc::new(authorization_service)),
);
let http_port = config.port;
let http = tokio::spawn(async move {
- if let Err(error) =
- api::setup_and_serve(read_state, control_state, http_port, shutdown_signal()).await
+ if let Err(error) = api::setup_and_serve(
+ read_state,
+ control_state,
+ create_state,
+ gateway_state,
+ http_port,
+ shutdown_signal(),
+ )
+ .await
{
tracing::error!(error = ?error, "agent harness service http stopped");
}
@@ -281,8 +309,8 @@ async fn main() -> anyhow::Result<()> {
}
};
- let (session_id, command) = match agent_trigger_to_harness_command(event.event().event.clone(), bot_id) {
- Ok(command) => command,
+ let routed = match route_agent_trigger(event.event().event.clone(), bot_id) {
+ Ok(routed) => routed,
Err(skipped) => {
tracing::debug!(?skipped, "skipped an agent session event");
match commit_message(&consumer, kafka_message) {
@@ -301,15 +329,30 @@ async fn main() -> anyhow::Result<()> {
run_error = Some(error);
break;
}
- let execution = harness.execute(session_id, command);
- tasks.spawn(async move {
- match execution.await {
- Ok(()) => tracing::info!(%session_id, "executed an agent harness command"),
- Err(error) => {
- tracing::error!(error = ?error, %session_id, "failed to execute an agent harness command");
- }
+ match routed {
+ RoutedTrigger::Command(session_id, command) => {
+ let execution = harness.execute(session_id, command);
+ tasks.spawn(async move {
+ match execution.await {
+ Ok(()) => tracing::info!(%session_id, "executed an agent harness command"),
+ Err(error) => {
+ tracing::error!(error = ?error, %session_id, "failed to execute an agent harness command");
+ }
+ }
+ });
}
- });
+ RoutedTrigger::Announce(session_id, prompt) => {
+ let harness = harness.clone();
+ tasks.spawn(async move {
+ match harness.announce_external_prompt(session_id, prompt).await {
+ Ok(()) => tracing::info!(%session_id, "announced an external prompt"),
+ Err(error) => {
+ tracing::error!(error = ?error, %session_id, "failed to announce an external prompt");
+ }
+ }
+ });
+ }
+ }
}
Some(result) = tasks.join_next(), if !tasks.is_empty() => {
if let Err(error) = result {
diff --git a/services/document_storage_service/src/api/swagger.rs b/services/document_storage_service/src/api/swagger.rs
index ae3d8ddb07..678bbafbc2 100644
--- a/services/document_storage_service/src/api/swagger.rs
+++ b/services/document_storage_service/src/api/swagger.rs
@@ -545,6 +545,8 @@ use utoipa::OpenApi;
bots::domain::models::BotChannelType,
bots::domain::models::ChannelWebhookRequest,
bots::domain::models::ChannelWebhookResponse,
+ bots::domain::models::CreateBotRequest,
+ bots::domain::models::PatchBotRequest,
bots::domain::models::CreateChannelScopedBotRequest,
bots::domain::models::CreateChannelScopedBotResponse,
diff --git a/tooling/xtask/crates/xtask_deps/Cargo.toml b/tooling/xtask/crates/xtask_deps/Cargo.toml
index 952230a014..1c4ddcb9fd 100644
--- a/tooling/xtask/crates/xtask_deps/Cargo.toml
+++ b/tooling/xtask/crates/xtask_deps/Cargo.toml
@@ -16,7 +16,7 @@ serde_json = { workspace = true }
guppy = { workspace = true }
# For the [xtask] extension table in .config/hakari.toml (path-glob
# traversal excludes); the hakari engine ignores that table.
-toml = "0.5"
+toml = { workspace = true }
# Pinned engine for the generated dependency artifacts. This version lives in
# Cargo.lock, so dev machines and CI always run the identical generator —
# upgrading it is an explicit, reviewed lock change.
diff --git a/tooling/xtask/crates/xtask_local/src/local/frontend.rs b/tooling/xtask/crates/xtask_local/src/local/frontend.rs
index 477f4ef9a1..c55509cfec 100644
--- a/tooling/xtask/crates/xtask_local/src/local/frontend.rs
+++ b/tooling/xtask/crates/xtask_local/src/local/frontend.rs
@@ -273,18 +273,17 @@ pub fn start(
// output) if the child exits first. A bare port poll would mistake a stale
// server already on the port for "ready" while our child has died.
let addr: std::net::SocketAddr = ([127, 0, 0, 1], port).into();
- let wait_buf = Arc::clone(&captured);
- stage.run_step("Starting frontend", || {
- for _ in 0..120 {
+ let startup = stage.run_step("Starting frontend", || {
+ // Cold starts may rebuild optimized Wasm packages before Vite launches.
+ for _ in 0..600 {
// Settle first: a failed bind (e.g. port already in use) makes vite
// exit near-instantly, so if the child is still alive after this it
// genuinely bound the port — rather than us connecting to a stale
// server squatting it.
std::thread::sleep(std::time::Duration::from_millis(300));
if let Some(status) = child.try_wait()? {
- let out = tail_str(&String::from_utf8_lossy(&wait_buf.lock().unwrap()), 30);
anyhow::bail!(
- "frontend dev server exited during startup ({status})\n{out}\n\
+ "frontend dev server exited during startup ({status})\n\
(if the port is in use, free it: `lsof -ti tcp:{port} | xargs kill`)"
);
}
@@ -294,8 +293,23 @@ pub fn start(
return Ok(());
}
}
- anyhow::bail!("frontend dev server did not become ready")
- })?;
+ anyhow::bail!("frontend dev server did not become ready after 180 seconds")
+ });
+
+ if let Err(error) = startup {
+ let pgid = child.id() as i32;
+ // SAFETY: the child leads the process group created above. ESRCH is
+ // harmless when Bun already exited.
+ unsafe {
+ libc::kill(-pgid, libc::SIGKILL);
+ }
+ let _ = child.wait();
+ for handle in drains.drain(..) {
+ let _ = handle.join();
+ }
+ let out = tail_str(&String::from_utf8_lossy(&captured.lock().unwrap()), 30);
+ anyhow::bail!("{error}\nfrontend output (last lines):\n{out}");
+ }
Ok(Some(Frontend {
child,
diff --git a/tooling/xtask/crates/xtask_local/src/local/instance.rs b/tooling/xtask/crates/xtask_local/src/local/instance.rs
index 4746dddbd2..dd08e80ed8 100644
--- a/tooling/xtask/crates/xtask_local/src/local/instance.rs
+++ b/tooling/xtask/crates/xtask_local/src/local/instance.rs
@@ -102,6 +102,8 @@ pub enum Port {
/// per-instance port offsets come from declaration order, and removing a
/// variant would shift every one declared after it.
AgentProxy = 8091,
+ /// Agent session control API.
+ AgentHarness = 8101,
}
impl Port {
diff --git a/tooling/xtask/crates/xtask_local/src/local/inventory.rs b/tooling/xtask/crates/xtask_local/src/local/inventory.rs
index 4f2c344881..696a638b4e 100644
--- a/tooling/xtask/crates/xtask_local/src/local/inventory.rs
+++ b/tooling/xtask/crates/xtask_local/src/local/inventory.rs
@@ -259,7 +259,7 @@ pub const RUST_SERVICES: &[RustService] = &[
compose_name: "agent_harness_service",
cargo_bin: "agent_harness_service",
package: "agent_harness_service",
- host_port: None,
+ host_port: Some(Port::AgentHarness),
path_prefix: Some("/agent-harness"),
is_websocket: false,
// Runs by default. LocalEnv reserves the credential keys so the
diff --git a/tooling/xtask/crates/xtask_local/src/local/inventory/test.rs b/tooling/xtask/crates/xtask_local/src/local/inventory/test.rs
index 8508d0f960..b7a9144731 100644
--- a/tooling/xtask/crates/xtask_local/src/local/inventory/test.rs
+++ b/tooling/xtask/crates/xtask_local/src/local/inventory/test.rs
@@ -43,6 +43,15 @@ fn workers_are_portless() {
}
}
+#[test]
+fn agent_harness_has_an_instance_port() {
+ let svc = RUST_SERVICES
+ .iter()
+ .find(|svc| svc.compose_name == "agent_harness_service")
+ .unwrap();
+ assert_eq!(svc.host_port, Some(Port::AgentHarness));
+}
+
#[test]
fn dev_mode_excludes_workers_and_optin() {
let dev: Vec<&str> = services_for_mode(Mode::Dev)
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/build_agent_daemon_on_tag.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/build_agent_daemon_on_tag.rs
new file mode 100644
index 0000000000..75fb306eb8
--- /dev/null
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/build_agent_daemon_on_tag.rs
@@ -0,0 +1,211 @@
+//! `Build Agent Daemon on Tag` — self-contained `macrod` binaries for Linux
+//! and macOS, attached to the release its tag names.
+//!
+//! Unlike everything else this repo builds, the daemon runs on a machine we
+//! know nothing about: a self-hoster points it at their own checkout and their
+//! own agent harness. So the Linux builds are musl-static (there is no host
+//! libc to match) and the macOS builds link nothing outside the OS. Neither is
+//! taken on faith — `package_agent_daemon.sh` inspects each binary and refuses
+//! to package one that would reach for something that will not be there.
+//!
+//! Separate from [`super::build_desktop_on_tag`] on purpose. It publishes to
+//! the same release off the same tag pattern, but the daemon has no business
+//! waiting on DMG notarization, and a flaky desktop build has no business
+//! holding it back.
+
+use gh_workflow::{
+ Concurrency, Event, Expression, Job, Push, Run, Step, Workflow, WorkflowDispatch,
+ WorkflowDispatchInput,
+};
+
+use crate::workflows::{build_appimage_on_tag, runners, steps, vars};
+
+use std::collections::HashMap;
+
+const RESOLVED_REF: &str = "${{ needs.resolve-ref.outputs.ref }}";
+
+/// One published binary.
+struct DaemonTarget {
+ /// Rust target triple to build.
+ triple: &'static str,
+ /// Job id suffix and artifact name suffix — what a user reads off the
+ /// release page to pick their download.
+ slug: &'static str,
+ /// Whether this runner can execute what it just built. The cross-built
+ /// slices can only be inspected, not run.
+ smoke_run: bool,
+}
+
+/// musl-static, built through cargo-zigbuild so the C in the graph
+/// (aws-lc-sys) gets a compiler that targets musl.
+const LINUX_TARGETS: &[DaemonTarget] = &[
+ DaemonTarget {
+ triple: "x86_64-unknown-linux-musl",
+ slug: "linux-x86_64",
+ smoke_run: true,
+ },
+ DaemonTarget {
+ triple: "aarch64-unknown-linux-musl",
+ slug: "linux-aarch64",
+ smoke_run: false,
+ },
+];
+
+/// Built on the Apple Silicon runner; the Intel slice is a cross-compile
+/// against the same SDK, so it builds here but cannot be run here.
+const MACOS_TARGETS: &[DaemonTarget] = &[
+ DaemonTarget {
+ triple: "aarch64-apple-darwin",
+ slug: "macos-aarch64",
+ smoke_run: true,
+ },
+ DaemonTarget {
+ triple: "x86_64-apple-darwin",
+ slug: "macos-x86_64",
+ smoke_run: false,
+ },
+];
+
+/// Build the workflow.
+pub fn build_agent_daemon_on_tag() -> Workflow {
+ let mut workflow = Workflow::new("Build Agent Daemon on Tag")
+ .on(daemon_events())
+ .concurrency(
+ Concurrency::new(Expression::new(
+ "agent-daemon-${{ inputs.ref || github.ref_name }}",
+ ))
+ .cancel_in_progress(true),
+ )
+ .add_job("resolve-ref", resolve_ref());
+
+ for target in LINUX_TARGETS {
+ workflow = workflow.add_job(job_id(target), linux_job(target).add_needs("resolve-ref"));
+ }
+ for target in MACOS_TARGETS {
+ workflow = workflow.add_job(job_id(target), macos_job(target).add_needs("resolve-ref"));
+ }
+
+ let mut publish = build_appimage_on_tag::publish_job(
+ RESOLVED_REF,
+ xtask_paths::runtime_path!("release-artifacts/*"),
+ )
+ .add_needs("resolve-ref");
+ for target in LINUX_TARGETS.iter().chain(MACOS_TARGETS) {
+ publish = publish.add_needs(job_id(target));
+ }
+
+ workflow.add_job("publish-daemon", publish)
+}
+
+fn job_id(target: &DaemonTarget) -> String {
+ format!("build-daemon-{}", target.slug.replace('_', "-"))
+}
+
+fn daemon_events() -> Event {
+ Event::default()
+ .push(Push::default().add_tag(build_appimage_on_tag::DESKTOP_TAG_PATTERN))
+ .workflow_dispatch(workflow_dispatch())
+}
+
+fn workflow_dispatch() -> WorkflowDispatch {
+ let mut inputs = HashMap::new();
+ inputs.insert(
+ "ref".into(),
+ WorkflowDispatchInput {
+ description: "Optional release tag override (v* or refs/tags/v*). Leave empty to build the branch or tag selected for this workflow run.".into(),
+ required: false,
+ input_type: "string".into(),
+ default: None,
+ },
+ );
+
+ WorkflowDispatch { inputs }
+}
+
+/// Resolve the ref once, so every target job checks out the same commit even
+/// if the tag moves mid-run.
+fn resolve_ref() -> Job {
+ Job::default()
+ .name("Resolve build ref")
+ .runs_on(runners::Runner::TinyNoCache.to_string())
+ .add_output("ref", "${{ steps.resolve.outputs.ref }}")
+ .add_step(resolve_ref_step())
+}
+
+fn resolve_ref_step() -> Step<Run> {
+ Step::new("Resolve ref")
+ .run(include_str!("scripts/resolve_desktop_ref.sh"))
+ .id("resolve")
+ .shell("bash")
+ .add_env(("EVENT_NAME", "${{ github.event_name }}"))
+ .add_env(("INPUT_REF", "${{ inputs.ref }}"))
+ .add_env(("GITHUB_EVENT_REF", "${{ github.event.ref }}"))
+ .add_env(("GITHUB_EVENT_REF_TYPE", "${{ github.event.ref_type }}"))
+ .add_env(("SELECTED_REF", "${{ github.ref }}"))
+}
+
+/// The Nix dev shell is what carries cargo-zigbuild, zig, and cmake, so the
+/// musl builds go through it rather than a bare rustup toolchain.
+fn linux_job(target: &DaemonTarget) -> Job {
+ Job::default()
+ .name(format!("Build daemon ({})", target.slug))
+ .runs_on(runners::Runner::RustCi.to_string())
+ .add_step(steps::checkout_ref(RESOLVED_REF))
+ .add_step(steps::mount_cache_volume())
+ .add_step(steps::setup_nix())
+ .add_step(steps::setup_dev_shell())
+ // The dev shell points RUSTC_WRAPPER at sccache regardless; this aims
+ // it at the shared remote cache so a release build is not a cold
+ // compile of the whole dependency graph. It degrades to the local
+ // cache on failure, so it is never load-bearing.
+ .add_step(steps::configure_namespace_sccache(vars::CI_SCCACHE_NAME))
+ .add_step(steps::derive_artifact_metadata(RESOLVED_REF))
+ .add_step(
+ Step::new("Build daemon")
+ .run(include_str!("scripts/build_agent_daemon_linux.sh"))
+ .shell("bash")
+ .add_env(("TARGET", target.triple)),
+ )
+ .add_step(package_step(target))
+ .add_step(upload_step(target))
+ .add_step(steps::teardown_nix())
+}
+
+/// Apple Silicon, because linking Mach-O needs an Apple SDK and Apple licenses
+/// one only on Apple hardware.
+fn macos_job(target: &DaemonTarget) -> Job {
+ Job::default()
+ .name(format!("Build daemon ({})", target.slug))
+ .runs_on(runners::Runner::MacOsArm.to_string())
+ .add_step(steps::checkout_ref(RESOLVED_REF))
+ .add_step(steps::setup_rust_light())
+ .add_step(steps::derive_artifact_metadata(RESOLVED_REF))
+ .add_step(
+ Step::new("Build daemon")
+ .run(include_str!("scripts/build_agent_daemon_macos.sh"))
+ .shell("bash")
+ .add_env(("TARGET", target.triple)),
+ )
+ .add_step(package_step(target))
+ .add_step(upload_step(target))
+}
+
+fn package_step(target: &DaemonTarget) -> Step<Run> {
+ Step::new("Package daemon")
+ .run(include_str!("scripts/package_agent_daemon.sh"))
+ .shell("bash")
+ .add_env(("TARGET", target.triple))
+ .add_env(("SLUG", target.slug))
+ .add_env(("SAFE_TAG", "${{ steps.metadata.outputs.safe_tag }}"))
+ .add_env(("SMOKE_RUN", if target.smoke_run { "1" } else { "0" }))
+}
+
+fn upload_step(target: &DaemonTarget) -> Step<gh_workflow::Use> {
+ steps::upload_artifact(
+ &format!(
+ "macrod-{}-${{{{ steps.metadata.outputs.safe_tag }}}}",
+ target.slug
+ ),
+ xtask_paths::runtime_path!("artifacts/*"),
+ )
+}
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/mod.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/mod.rs
index 95219fd6a5..de957eba45 100644
--- a/tooling/xtask/crates/xtask_workflows/src/workflows/mod.rs
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/mod.rs
@@ -11,6 +11,7 @@
mod assign_author;
mod assign_labels;
+mod build_agent_daemon_on_tag;
mod build_appimage_on_tag;
mod build_desktop_on_tag;
mod build_dmg_on_tag;
@@ -109,6 +110,11 @@ const WORKFLOWS: &[WorkflowFile] = &[
file_name: "assign-labels.yml",
render_yaml: || render_gh_workflow(assign_labels::assign_labels)(),
},
+ WorkflowFile {
+ slug: "build_agent_daemon_on_tag",
+ file_name: "build_agent_daemon_on_tag.yml",
+ render_yaml: || render_gh_workflow(build_agent_daemon_on_tag::build_agent_daemon_on_tag)(),
+ },
WorkflowFile {
slug: "build_appimage_on_tag",
file_name: "build_appimage_on_tag.yml",
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/runners.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/runners.rs
index eae6f06bd1..adef778a79 100644
--- a/tooling/xtask/crates/xtask_workflows/src/workflows/runners.rs
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/runners.rs
@@ -1,7 +1,8 @@
//! GitHub Actions runner labels.
//!
-//! We run on Namespace (namespace.so) hosted runners, selected by the dashboard
-//! *profile* name — the same convention the deploy workflows already use. Each
+//! We run on Namespace (namespace.so) hosted runners, mostly selected by the
+//! dashboard *profile* name — the same convention the deploy workflows already
+//! use. Each
//! profile's persisted cache volume is configured in the Namespace dashboard;
//! that volume backs Cargo/Nix state while compiled objects use Namespace's
//! official remote sccache (see
@@ -25,6 +26,9 @@ pub enum Runner {
/// cache volume, isolated from the deploy profiles so deploy's churn can't
/// evict the CI Cargo/Nix caches.
RustCi,
+ /// Apple Silicon, for jobs that need a real Apple SDK. A machine label
+ /// rather than a dashboard profile, so it needs no setup outside this file.
+ MacOsArm,
}
impl fmt::Display for Runner {
@@ -34,6 +38,7 @@ impl fmt::Display for Runner {
Runner::Small => "namespace-profile-linux-small",
Runner::Mid => "namespace-profile-linux-mid",
Runner::RustCi => "namespace-profile-linux-rust-ci",
+ Runner::MacOsArm => "nscloud-macos-sequoia-arm64-6x14",
})
}
}
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/build_agent_daemon_linux.sh b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/build_agent_daemon_linux.sh
new file mode 100644
index 0000000000..5ffa833299
--- /dev/null
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/build_agent_daemon_linux.sh
@@ -0,0 +1,20 @@
+set -euo pipefail
+
+# Statically linked musl build of the self-hosted coding-agent daemon.
+#
+# The musl std that ships with the toolchain links pure-Rust crates on its own,
+# but aws-lc-sys — rustls' crypto provider, and so the whole reason the daemon
+# can talk HTTPS and WSS — is C, and needs a compiler that targets musl. zig is
+# that compiler, which is what cargo-zigbuild wires up; it also makes the
+# aarch64 build a cross-compile rather than a second runner.
+#
+# aws-lc-sys' own cc builder rejects zig, so force its cmake builder instead.
+# The Lambda builds hit the same wall and take the same way out
+# (see nix/cloud-storage.nix).
+export AWS_LC_SYS_CMAKE_BUILDER=1
+
+# The daemon runs no queries of its own, but crates in its dependency graph
+# carry sqlx macros; offline mode keeps a release build from wanting a database.
+export SQLX_OFFLINE=true
+
+cargo zigbuild --release --package coding_agent_worker --target "$TARGET"
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/build_agent_daemon_macos.sh b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/build_agent_daemon_macos.sh
new file mode 100644
index 0000000000..5a4da4fcca
--- /dev/null
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/build_agent_daemon_macos.sh
@@ -0,0 +1,20 @@
+set -euo pipefail
+
+# macOS build of the self-hosted coding-agent daemon.
+#
+# No zig here: the Apple targets link against the SDK the runner already has,
+# and the arm64 runner cross-compiles the x86_64 slice on its own. All this
+# step needs is the matching rust-std.
+#
+# See build_agent_daemon_linux.sh for why sqlx runs offline.
+export SQLX_OFFLINE=true
+
+rustup target add "$TARGET"
+
+# aws-lc-sys compiles its C through cmake. The GitHub macOS image ships cmake
+# today, but the build is too far downstream to discover that it stopped.
+if ! command -v cmake >/dev/null 2>&1; then
+ brew install cmake
+fi
+
+cargo build --release --package coding_agent_worker --target "$TARGET"
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/package_agent_daemon.sh b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/package_agent_daemon.sh
new file mode 100644
index 0000000000..0e9c181d3a
--- /dev/null
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/scripts/package_agent_daemon.sh
@@ -0,0 +1,71 @@
+set -euo pipefail
+
+# Package one built daemon binary as a release asset — and prove it is as
+# self-contained as its platform allows before it ships. A binary that resolves
+# a library at startup on the build runner and not on a user's machine is
+# exactly the failure this whole pipeline exists to prevent, so it is checked
+# here rather than assumed.
+
+binary="target/$TARGET/release/macrod"
+if [ ! -x "$binary" ]; then
+ echo "no daemon binary at $binary" >&2
+ exit 1
+fi
+
+case "$TARGET" in
+ *-linux-musl)
+ # Statically linked: nothing may be left to resolve at run time. `ldd`
+ # exits non-zero with "not a dynamic executable" for a static binary, so
+ # a successful ldd that names shared objects is the failure case.
+ if ldd "$binary" 2>/dev/null | grep -q '=>'; then
+ echo "expected a static binary, but $binary still links:" >&2
+ ldd "$binary" >&2
+ exit 1
+ fi
+ ;;
+ *-apple-darwin)
+ # macOS has no static libSystem, so "self-contained" means nothing from
+ # outside the OS: a Homebrew or Nix-store path is one that will not exist
+ # on the machine that downloads this.
+ strays=$(otool -L "$binary" | tail -n +2 | awk '{ print $1 }' \
+ | grep -Ev '^(/usr/lib/|/System/Library/)' || true)
+ if [ -n "$strays" ]; then
+ echo "daemon links libraries that will not exist on a user's Mac:" >&2
+ echo "$strays" >&2
+ exit 1
+ fi
+ ;;
+ *)
+ echo "no self-containment check defined for $TARGET" >&2
+ exit 1
+ ;;
+esac
+
+# It has to actually run, too — a binary that links cleanly and dies on its
+# first instruction still ships broken. `--version` is the cheapest end-to-end
+# proof, and the caller says whether this runner can execute this slice: the
+# cross-built ones (aarch64 anywhere, x86_64 on an Apple Silicon runner) cannot.
+if [ "$SMOKE_RUN" = "1" ]; then
+ "$binary" --version
+else
+ echo "skipping smoke run: $TARGET does not execute on this runner"
+fi
+
+mkdir -p artifacts
+name="macrod-${SAFE_TAG}-${SLUG}"
+stage=$(mktemp -d)
+install -m 755 "$binary" "$stage/macrod"
+tar -czf "artifacts/${name}.tar.gz" -C "$stage" macrod
+rm -rf "$stage"
+
+# coreutils on Linux, BSD/perl on macOS.
+(
+ cd artifacts
+ if command -v sha256sum >/dev/null 2>&1; then
+ sha256sum "${name}.tar.gz" >"${name}.tar.gz.sha256"
+ else
+ shasum -a 256 "${name}.tar.gz" >"${name}.tar.gz.sha256"
+ fi
+)
+
+echo "packaged ${name}.tar.gz"