Repository navigation
Description
Context
Once synthetic configuration exists, every LLM call that targets a virtual identity must resolve to a concrete direct agent and model. Selection must account for enabled state, strict priority tiers, configured usage ceilings, context-window requirements, and members already attempted for that call.
The physical model must be selected before context-sensitive work calculates a prompt budget. Otherwise a plan, review, or indexing batch could be assembled for a large-context model and later routed to a smaller model that cannot accept it.
A failed physical execution must automatically retry through normal selection logic while excluding members already attempted for that call.
Requirements
- Add a central synthetic routing service; do not duplicate selection logic in planners, workers, reviews, chat, and indexing.
- Keep the requested virtual identity stable in task records, labels, and branches.
- Record the physical agent/model for each attempt in LLM-log metadata and task history.
- Implement strict priority tiers:
- Determine all currently eligible members.
- Keep only members at the highest eligible priority.
- Apply the configured strategy within that tier.
- Consider priority-zero members only when no higher-priority member is eligible.
- Implement deterministic round-robin with an atomic persisted cursor per synthetic model.
- Implement usage-based selection by choosing the member with the most remaining normalized headroom within the highest priority tier.
- Treat usage data as unavailable when no fresh alias-specific snapshot exists. A member with an applicable usage cap must not be selected from unknown or stale data.
- Keep uncapped round-robin pools independent of Agent Tank.
- Filter candidates whose context window cannot accommodate the required prompt plus output/runtime reserve.
- Introduce a call-scoped selection session that pins the first physical model early and reuses the required-token constraint for retries.
- On failure, exclude the failed member and select again. Each physical member may be attempted at most once per logical call.
- Do not retry explicit cancellation, security-policy violations, invalid user configuration, or prompt-too-large errors.
- Preserve task/worktree identity across implementation retries, but create a unique execution/container ID per attempt.
- Stop with an aggregated
SyntheticPoolExhaustedErrorwhen no eligible members remain.
Usage Data Contract
Usage-based routing requires usage snapshots keyed by direct agent alias, not merely provider name. This distinction is essential when two Claude or Codex aliases use different subscriptions.
The existing Agent Tank integration may continue displaying provider-level information, but it must not apply a provider-global value to several direct aliases as if it were account-specific. Only a snapshot collected or explicitly mapped for a direct alias may satisfy a synthetic member's usage cap. Unknown data makes that capped member temporarily ineligible and must be visible in diagnostics.
Context-Sensitive Integration Points
- Planner context and plan generation: begin a routing session before calculating model hard limits and token budgets.
- PR review and review-context scouting: select before
resolveReviewContextTokenBudgetand prompt construction. - Repository indexing: select before calculating file/directory batch limits so physical-model overrides apply correctly.
- Repository chat, improvements, lightweight analysis, and playground chat: route immediately before invoking
Agent.analyze. - Implementation and follow-up tasks: retain the virtual task identity while retrying physical executions within the task attempt.
Acceptance Criteria
- Round-robin selection rotates fairly within the highest eligible priority tier and persists across worker processes.
- A priority-100 member is selected before priority-0 members whenever it is eligible.
- When the priority-100 member is disabled, quota-capped, context-ineligible, failed earlier in the call, or unavailable, the priority-0 fallback is selected.
- Usage-based selection chooses the greatest remaining normalized headroom without exceeding any configured cap.
- A capped member with stale or missing alias-specific usage data is not selected.
- An uncapped member remains usable when Agent Tank is disabled.
- Planning, review, and indexing tests prove physical selection occurs before their token or batch budget is calculated.
- A failed member is attempted once, excluded, and followed by the next selection.
- Cancellation and context-limit failures are not retried.
- Exhaustion errors list each attempted or rejected member and its reason without exposing credentials.
- LLM logs contain virtual identity, physical identity, member ID, call ID, attempt number, and selection reason.
- Existing direct-agent behavior remains unchanged when the requested alias is not synthetic.
Created by ProPR AI Planner
Activity
propr-dev commentedon Aug 29, 2026
Suggested Implementation:
Implementation Approach
Use a two-layer design. A pure selector evaluates candidates and is easy to test exhaustively. A routing service supplies live direct-agent state, context limits, usage snapshots, and an atomic cursor, then creates a call-scoped session for execution and failover.
Physical resolution is deliberately deferred until the LLM-call boundary, but context-sensitive callers open that boundary before calculating budgets. Flattening pools when tasks are queued was rejected because availability and quota can change while a job waits. Selecting only inside the Docker adapter was also rejected because context could already have been oversized by then.
Retry orchestration wraps only the agent call. GitHub comments, commits, pushes, PR creation, and other worker finalization must remain outside the retry loop so a failed model cannot duplicate deterministic side effects.
File:
packages/core/src/agents/synthetic/syntheticSelector.ts(new file)Why this file: This pure module contains the complete selection semantics without database, Redis, Agent Tank, or registry dependencies. Keeping it pure makes priority, quota, context, and exclusion behavior deterministic and independently testable.
File:
packages/core/src/agents/synthetic/syntheticRuntimeState.ts(new file)Why this file: Multiple workers can select the same pool concurrently. An in-memory cursor would restart on deployment and let separate processes repeatedly choose the same subscription. Persist and advance a cursor transactionally using the same conflict-safe pattern as summarization runtime state.
Implement these exports:
Implement
readAndAdvanceSyntheticCursorin one database transaction. On SQLite, use compare-and-swap against the originalsystem_configs.value, matchingconfigManagerSummarization.ts; on other databases useFOR UPDATE. Advance the cursor only when a member is actually selected.File:
packages/core/src/agents/synthetic/SyntheticRoutingService.ts(new file)Why this file: This service joins saved pool configuration with the direct
AgentRegistry, context limits, usage snapshots, and cursor store. Callers receive a physical lease without learning selection details.The public surface should be:
Return
nullwhen the configured alias is direct. That keeps the direct path byte-for-byte compatible. Resolve member context limits with the existinggetModelHardLimit/model metadata path and load only direct agents fromAgentRegistry.File:
packages/core/src/agents/synthetic/runSyntheticCall.ts(new file)Why this file: Every execution surface needs identical failover behavior. This wrapper ensures retries exclude failed members and that only the agent invocation is repeated.
File:
packages/core/src/agents/impl/utils/usageTrackingWrapper.tsWhy this file: This is the existing pre/post-call usage boundary. It is the correct place to record a fresh snapshot, but only when the snapshot is attributable to the direct alias whose credentials produced it.
Add an optional
directAgentAliasandonUsageSnapshotcallback to the wrapper options. After a successful post-call probe, normalize session and weekly absolute percentages and callrecordSyntheticUsageSnapshot. Do not write a snapshot when the integration returns only a provider-global record that cannot be mapped to the direct alias.Include a reasoning comment explaining that copying one provider value to several aliases would break the multiple-subscription use case and could deplete the wrong account.
File:
packages/core/src/config/configuredModel.tsWhy this file: This function should continue resolving the public configured identity, including a synthetic identity, without flattening it prematurely.
Update plain-model resolution so
resolveLlmLabelcan discover virtual catalog models. Preserve already-qualified identities. Add a comment that physical resolution belongs tocreateSyntheticCallSession, after live quota and availability are known.Files: context-sensitive call sites
Why these files: They must open a routing session before computing budgets, while ordinary direct calls continue down their current path.
Apply the following sequence in:
packages/core/src/services/taskPlanning/llmCalling.tssrc/jobs/reviewContextScout.tssrc/jobs/prReviewRunner.tsprocessSingleBatchandprocessDirectoryBatchRefactor
SyntheticCallSessionto permit the initial lease to be passed intorunSyntheticCallwithout selecting twice. After the final prompt is built, update or assert the session's required-token floor using measured tokens plus reserve.For indexing, apply physical
getSummarizationBatchLimitOverridebefore constructing each batch. The selected physical model, not the virtual ID, determines model-specific batch caps.File: task execution worker entry point
Why this file: Implementation tasks need call-level failover while commits, pushes, and PR creation remain single-run finalization steps.
Wrap only the existing direct agent execution call with
runSyntheticCall. For each lease:AgentRegistry;lease.physicalModelto it;createContainerExecutionId(taskId);Retain the task-scoped worktree between attempts. Add an explicit retry instruction telling the next model that an earlier execution failed and that it must inspect existing workspace changes before continuing. This preserves potentially useful partial edits; automatically resetting the worktree was rejected because it could destroy valid uncommitted work without knowing whether the previous agent failed before or after editing.
File:
packages/core/src/utils/llmLogger.tsWhy this file: Operators need to understand which subscription actually handled a virtual call. Add optional routing metadata without replacing existing
agentAliasandmodelUsedfields.Merge these fields into existing metadata for synthetic attempts. Do not log config paths, environment variables, API keys, or credential-directory information.
Files:
test/syntheticAgentSelector.test.tsandtest/syntheticAgentFailover.test.ts(new files)Why these files: Selection and retry semantics govern paid subscription use and require deterministic regression coverage.
Use table-driven tests for priority fallback, round-robin cursor advancement, usage headroom, exact-cap exclusion, stale usage, uncapped operation without Agent Tank, context filtering, per-call exclusions, all-members-exhausted diagnostics, failed-result retries, thrown-error retries, and cancellation/context errors that bypass retry.
Extend planning, review-context, and summary-miner tests to assert that the selected physical hard limit or batch override is consulted before prompt/batch construction.
propr-dev commentedon Aug 30, 2026
🤖 AI processing has started for this issue using codex agent with gpt-5.6-sol model.
I'll analyze the problem and work on a solution. This may take a few minutes.
Processing Details:
codexgpt-5.6-sol1991/gpt-5.6-sol-implement-context-aware-s-20260830-0155-r4q1990-epic-synthetic-pool-eusissue-1991-20260830-0155-gpt-5.6-sol-r4q🔍 Track Task Execution
fix(ai): Resolve issue #1991 - Implement context-aware synthetic sele…
fix(ai): Resolve issue #1991 - Implement context-aware synthetic sele…