Skip to content

feat(agents): add provider-neutral orchestration - #5632

Closed
megascan wants to merge 21 commits into
pingdotgg:mainfrom
megascan:agent/native-agent-orchestration
Closed

feat(agents): add provider-neutral orchestration#5632
megascan wants to merge 21 commits into
pingdotgg:mainfrom
megascan:agent/native-agent-orchestration

Conversation

@megascan

@megascan megascan commented Aug 7, 2026

Copy link
Copy Markdown

What changed

This PR adds a provider-neutral Agents and Rules system to T3 Code. It is one end-to-end product feature spanning contracts, persistence, server orchestration, MCP, all five provider adapters, web/desktop, mobile, migrations, tests, and documentation.

Current size: 141 files, 18,461 additions, and 86 deletions. This exceeds automated approvability limits and requires careful human review; the passing correctness checks should not be mistaken for approval of a diff this large.

Suggested labels: enhancement, documentation, size:XXL, needs-triage, preview:web, and codex. The fork author does not have upstream triage permission, so GitHub only applied the labels available to its automation.

Agent profiles and Rules

  • Adds typed Agent profile and Rule contracts with environment/project scope and content-addressed revisions.
  • Profiles define instructions, preferred model, runtime and workspace policy, tools, hooks, delegation allowlists, provider requirements, and bounded budgets.
  • chatSelectable distinguishes direct-chat Agents from delegation-only specialists. Existing pinned threads retain their Agent even if it is later hidden from new chats.
  • Rules can always apply, match workspace-relative file globs, or attach explicitly to profiles.
  • Environment documents live in T3-owned state. Project documents are explicit t3.json references contained to the canonical project root; the catalog does not recursively scan repositories.
  • Saves use compare-and-swap revisions, atomic replacement, diagnostics, and reversible archive/restore rather than deletion.

Durable orchestration

  • Child work is represented as ordinary durable T3 threads with a pinned profile revision, not provider-native subagents.
  • Adds the event-sourced AgentRun domain, append-only events, transactional projections, immutable profile snapshots, lineage queries, revision waits, deadlines, usage, results, follow-ups, cancellation, and integration.
  • Adds migrations 41 and 42 for Agent run storage and the optional pinned Agent profile on thread projections, plus idempotent migration 43 for databases that recorded the earlier run projection before durable provider-turn binding.
  • Enforces lineage ceilings of depth 4, concurrency 8, 32 runs, and 120 minutes. Child budgets may reduce but cannot expand their parent budget, and descendants inherit the root wall-time origin rather than receiving a fresh deadline.
  • Wait subscribers attach before the durable revision read, avoiding polling and missed transitions.
  • Missing child-thread projections now fail closed with a typed error instead of returning an empty successful result.
  • Each run revision durably binds the canonical provider turn ID; stale completion, abort, and input events from an earlier follow-up cannot terminate or mutate the current turn.

T3-owned Agent tools

Providers receive the same portable MCP toolkit:

  • agent_list
  • agent_spawn
  • agent_status
  • agent_wait
  • agent_result
  • agent_send
  • agent_cancel
  • agent_integrate

Tools are scoped to the invoking T3 project, thread, lineage, and run ownership. Launch is asynchronous and returns a durable run ID; result reads are bounded and paginated.

Provider-neutral boundary

  • Codex, Claude, Cursor, Grok, and OpenCode declare explicit Agent runtime capabilities.
  • Provider-specific behavior stays at the adapter boundary. Catalog, persistence, orchestration, MCP handlers, and clients do not branch on provider type.
  • Compatibility is deny-by-default. Spawn is rejected when an adapter cannot honestly enforce a requested guarantee, such as exact native tool restriction, system instruction delivery, or usage accounting.
  • Future providers join the same orchestration path by declaring capabilities and supporting T3's existing MCP boundary.

Shared and isolated workspaces

  • Shared runs use the invoking workspace and obey profile write-concurrency policy.
  • Isolated runs use dedicated Git worktrees and require explicit integration.
  • Integration verifies canonical paths and Git common-directory identity, refuses dirty targets and untracked child files, generates a bounded tracked binary patch, preflights it with git apply --check --3way, and then applies it.
  • Conflicts remain visible rather than being resolved through guessed staging or merge decisions.

Web, desktop, mobile, and remote behavior

  • Adds Settings -> Agents for environment/project profiles, policies, Rules, diagnostics, and archive/restore.
  • Adds a searchable Agent picker beside the web/desktop model picker.
  • Projects native T3-managed AgentRun lifecycle into the existing parent-thread Agents panel, including model, profile ID, short run ID, follow-up turns, waiting, completion, failure, and cancellation. These activity rows are an explicitly best-effort view; durable AgentRun state remains authoritative.
  • Adds Agent selection to mobile new-task and existing-thread composer flows using native platform menus.
  • Explicit No agent selections are preserved rather than falling back to stale thread or draft state.
  • Profile and Rule editors validate id, scope, and revision before hydrating query results, preventing stale responses from overwriting another selection.
  • Typed WebSocket RPCs keep local, LAN, relay, and tunnel clients connected to the host-owned catalog and durable run state.

Why

ACP is a clean provider transport, but an ACP provider does not inherently know that it is running inside T3 and cannot reliably orchestrate another provider. Provider-native subagent systems also differ in naming, policy, lifetime, and availability.

This puts orchestration in the layer that has the required context: T3. A user can chat with an inexpensive coordinator, delegate architecture or implementation to specialized models, and keep every child run inspectable as an ordinary T3 thread without coupling core behavior to OpenGrok, GrokBuild, or any single provider.

UI evidence

Before: no Agent settings surface

Settings before Agents

After: first-party profile and Rule management

The selected specialist is marked delegation only. The host identifier is redacted from the public evidence image.

Settings with Agent profiles and direct-chat visibility

After: searchable picker beside the model picker

Search filters direct-chat profiles immediately. Delegation-only specialists remain available through orchestration but are absent from new top-level chat choices.

Searchable Agent picker

After: selected Agent shown in the composer

Selected Agent in the composer

After: native Agent run in the parent Agents panel

Native Agent run in the Agents panel

After: file-aware Rules

File-aware Rule editor

Short picker interaction recording

Evidence is published on a separate fork branch so binary review artifacts do not enter the product diff.

Verification

  • Original focused feature matrix: 185/185 tests passed.
  • First post-review regression matrix: 116/116 tests passed.
  • CodeRabbit response matrix: 105/105 tests passed.
  • Additional review-hardening matrices: 94/94, 57/57, 29/29, 43/43, and 29/29 passed.
  • Provider-capability regressions for OpenCode, Cursor, and Grok: 3/3 passed.
  • Final paginated review-response matrix covering mobile selection/settings, web mutation locking, and fail-closed result reads: 35/35 passed.
  • Native Agent panel projection, latest-main merge, and pinned mobile environment matrix: 104/104 focused server, client-runtime, migration, and mobile tests passed.
  • Provider-turn correlation review matrix: 55/55 focused AgentRun, repository, reactor, lifecycle, deadline, and migration tests passed.
  • Mobile post-save editor continuity matrix: 7/7 focused tests passed, plus the full mobile typecheck.
  • Latest lineage-deadline and migration-compatibility matrix: 58/58 focused AgentRun, repository, reactor, lifecycle, deadline, and migration tests passed.
  • Latest-main changed-test matrix: 318/320 passed. The two failures are unchanged Windows limitations: one POSIX path-separator assertion and one symlink test blocked by local EPERM.
  • Contracts, shared runtime, server, web, and mobile typechecks: passed.
  • Targeted lint and formatting: passed with zero diagnostics.
  • Web production build: passed.
  • Server executable bundle: passed.
  • git diff --check: passed.
  • Branch state: 21 commits ahead, 0 behind current upstream/main.
  • Macroscope correctness and Effect conventions: passed on 1062149af.
  • Macroscope and Cursor Bugbot findings through f445d85 are addressed in 502d128; the latest-head workflows are being monitored.
  • CodeRabbit: passed on 1062149af.
  • Review threads: 116/116 resolved.

Integrated browser coverage used an isolated .t3 environment and exercised:

  1. creating multiple environment Agent profiles and a file-aware Rule;
  2. preserving brace globs such as src/**/*.{ts,tsx} across save and reload;
  3. searching for and selecting a chat-selectable Agent beside the model picker;
  4. excluding delegation-only specialists from direct-chat search;
  5. applying preferred models when available and safely falling back when unavailable;
  6. archiving and restoring profiles and Rules;
  7. retaining an archived-but-pinned Agent label on an existing thread;
  8. opening a fresh draft without leaking the previous route's Agent selection;
  9. preserving a real Grok 4.5 turn and its selected profile across watcher restarts.

Honest scope and known limitations

  • This is a large architectural PR. Although it represents one product concern, it does not satisfy the repository preference for small contributions and is not eligible for automated approvability review.
  • Agents are T3-managed child threads, not wrappers around provider-native subagent APIs. Provider-native team/agent UIs are not surfaced here.
  • chatSelectable controls discovery, not authorization. Delegation policy and provider compatibility remain execution gates.
  • Web/desktop has text search; mobile currently uses the native platform menu without text search.
  • Token and monetary budgets can only be enforced when the provider adapter reports the required usage. Unsupported guarantees reject spawn rather than being approximated.
  • Isolated integration rejects untracked child files and dirty targets.
  • Profiles and Rules are environment-local or repository-referenced. There is no cloud marketplace, sync, or import/export workflow.
  • Catalog RPC responses cap profiles, Rules, and diagnostics at 100 each to bound WebSocket payloads.
  • Agents-panel activities are a best-effort projection of authoritative AgentRun state. A failed auxiliary append is logged and may temporarily omit or stale a row until a later lifecycle transition; it cannot roll back, fail, or strand the underlying run.
  • Mobile received focused tests and a full TypeScript check but was not exercised on a simulator or physical device.
  • No production-scale concurrency soak, relay/tunnel latency test, or screen-reader audit was performed.
  • The server typecheck emits existing non-failing Effect style suggestions; there are no type errors.
  • Complete Cursor/Grok adapter files hit existing Unix .sh mock-wrapper limitations on this Windows host. The complete OpenCode file hits the existing privileged-symlink EPERM limitation. The new provider assertions pass directly; Linux CI remains authoritative for those complete files.
  • Terminal hooks remain inline because afterResult participates in the durable success decision and provider events must stay ordered per thread. A future optimization requires a keyed bounded scheduler with explicit drain and shutdown semantics.
  • Agent MCP toolkit groups are discoverable by provider sessions, but authorization is enforced by selected profiles, delegation allowlists, project/thread lineage, and run ownership. t3McpCapabilities is compatibility metadata, not an ACL.
  • During an early contributor-machine startup, migration 40 was applied to the developer's live T3 home before startup failed. The process was stopped, no feature records were intentionally written there, and all subsequent runtime/UI testing used isolated state. This affected contributor-machine state only, not repository or production data.
  • Vercel's marketing deployment remains red because the fork requires Ping Labs deployment authorization; it is not a code failure.

Checklist

  • This PR is small and focused - it is one focused feature, but the end-to-end implementation is intentionally large.
  • I explained what changed and why.
  • I included before/after screenshots for the UI changes.
  • I included a short video for the picker interaction.
  • I documented validation gaps and external blockers honestly.

Implemented with GPT-5.6 Sol through the Codex harness in T3 Code.

Note

Add provider-neutral agent orchestration with profile/rule management and MCP tool surface

  • Introduces a full native agent orchestration system: AgentOrchestration service interface, AgentRunRepository for durable event storage, AgentRunReactor/AgentRunDeadlineReactor for state management and wall-time budget enforcement, and AgentPromptResolver for profile-aware prompt compilation.
  • Adds AgentProfileStore and AgentRuleStore for filesystem-backed, revision-checked persistence of agent profiles and rules in Markdown+YAML frontmatter format, coordinated via AgentProjectFileCoordinator to avoid races.
  • Exposes nine new WebSocket RPC endpoints (agents.catalog, agents.getProfile, agents.saveProfile, agents.archiveProfile, agents.restoreProfile, and rule equivalents) with scope-appropriate auth enforcement.
  • Registers a full suite of agent_* MCP tools (agent_spawn, agent_wait, agent_result, agent_send, agent_cancel, agent_integrate, etc.) gated on a new 'agents' MCP capability granted by default to all sessions.
  • Adds agent profile/rule settings UIs to both the web (/settings/agents) and mobile (SettingsAgents) apps, including catalog browsing, draft editing, save/archive/restore, and environment/project scoping.
  • Integrates agent profile selection into the chat composer on web and mobile; selecting a profile may auto-apply the profile's default model selection.
  • Adds three database migrations (041–043) creating agent_profile_snapshots, projection_agent_runs, agent_run_events tables and adding agent_profile_json to projection_threads.
  • Risk: MCP sessions now receive the 'agents' capability by default; existing credential checks for 'preview' are unaffected but all sessions gain access to agent tools without explicit opt-in.

Macroscope summarized 502d128.


Note

Medium Risk
Changes thread bootstrap and outbox schema (agent profile pinning) and adds large new settings/orchestration surfaces; incorrect revision or selection merging could mis-pin agents on turns, though logic is covered by focused tests.

Overview
Mobile adds an Agents entry under Settings (stack route agents) with a new screen to pick environment/project context, browse profile and rule catalogs, create and edit drafts, and save/archive/restore via existing agentEnvironment RPC atoms. Supporting modules (agentProfile.logic, agentRule.logic, agentSettings.logic) handle document building, revision-safe hydration, and optimistic selection after saves.

Composer flows now expose an Agent toolbar menu on new-task and thread composers. Choices are limited to chat-selectable profiles (with delegation-only profiles still visible when already pinned). Selecting a profile can apply its default model; AgentProfileRef is stored on composer drafts, queued outbox messages, and thread.turn.start / thread-creation bootstrap payloads, with explicit “No agent” preserved via resolveAgentProfileSelection.

Server (partial in this diff) introduces read-only AgentCatalog (environment Markdown dirs + explicit t3.json project refs, bounded RPC lists), AgentHookRunner for staged context/shell hooks, the AgentOrchestration service boundary, and orchestration lifecycle/integration test coverage; the orchestration integration harness stubs AgentPromptResolver when profiles are unused.

Reviewed by Cursor Bugbot for commit 502d128. Bugbot is set up for automated code reviews on this repo. Configure here.

Summary by CodeRabbit

  • New Features
    • Added Agents settings on web and mobile for creating, editing, archiving, and restoring agent profiles and rules.
    • Added agent selection to chat and new-task composers, including profile-based model defaults.
    • Added agent orchestration for delegated runs, follow-ups, monitoring, cancellation, results, and integration.
    • Added support for reusable rules, hooks, workspace context, budgets, and provider capability checks.
  • Bug Fixes
    • Improved validation, revision-conflict handling, persistence, queued-task recovery, and diagnostics.
  • Documentation
    • Added user and internal documentation for agents, runs, profiles, and rules.

Loading
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:XXL 1,000+ changed lines (additions + deletions). vouch:unvouched PR author is not yet trusted in the VOUCHED list.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants