Skip to content

Agents v1 (11/17): Agent Tank usage / cost gate for scheduled and unattended runs #2810

Closed

Description

@propr-dev

Context

Scheduled and externally triggered runs happen with nobody watching, which makes them the main cost risk of Agents: a 15-minute schedule against a provider that is already at 95% of its subscription window would burn the remaining quota that interactive work needs. ProPR already has the two ingredients:

  • the instance's existing "pause at % of subscription usage" control (the operator-chosen threshold), and
  • Agent Tank usage data per provider/credential, exposed in core via AliasSpecificAgentTankSnapshotProvider (packages/core/src/services/syntheticUsageSnapshotProvider.ts), which src/jobs/ultrafixEscalation.ts already uses to skip models at 100% before an escalation handoff.

This issue adds a single gate function consulted before starting any unattended run (trigger schedule, api, mcp, cli), before a deferred run is retried, and before an auto acting step starts. Agents v1 performs no model escalation; the gate is exported so any future escalation path must call it (documented).

Requirements

  1. New packages/core/src/services/agents/agentRunCostGate.ts:
    • loadUsagePauseThreshold() — reads the existing "pause at % of subscription usage" setting. Locate it first (search packages/api/mcp/settingsCatalog.ts, packages/api/routes/configSettings.ts and the synthetic-pool usage routing for the usage-pause threshold) and read it through the same loader that feature uses. Only if no instance-wide control exists, add agent_run_usage_pause_percent (integer 50-100, default 90) to the settings validation, SETTINGS_CATALOG and get/update_execution_settings.
    • evaluateProviderCapacity(agentAlias, threshold) → { status: 'ok' | 'near_limit' | 'unknown'; sessionPercent?; weeklyPercent?; resetsInMs? ; provider }. Synthetic pools: evaluate every enabled member alias; the pool is near_limit only if all members are.
    • createAgentRunCostGate({ now, maxDeferrals = 6, deferStepMs = 30 min }) returning the gate(definition, trigger, run?) callback used by triggerAgentRun (issue 4):
      • manual (UI Run now) → always proceed (attended; the UI shows the capacity warning instead).
      • capacity unknown (Agent Tank disabled/unreachable) → proceed and log once — the same fail-open rule ultrafixEscalation uses, so a monitoring outage never silently stops all automation. Documented.
      • weekly usage ≥ threshold → skip ("weekly subscription usage for claude is at 93% (pause threshold 90%)") — a weekly window will not recover within hours.
      • session usage ≥ threshold → defer until min(now + resetsIn + 2 min, now + deferStepMs); after maxDeferrals deferrals → skip.
  2. Wire the gate:
    • REST trigger (issue 5): services.gate defaults to createAgentRunCostGate(); manual passes through.
    • startActing (issue 10) for auto: when the gate says not proceed for an unattended run, transition report_ready → awaiting_approval instead, with skipReason "Acting paused: …" so a human can approve later. No tokens are spent.
    • Deferred retry (issue 12) calls the gate with the existing run to apply maxDeferrals.
  3. GET /api/agent-definitions/:id/capacity → current evaluateProviderCapacity for the UI warning (issue 16).
  4. Tests test/agentRunCostGate.test.ts with an injected snapshot provider.

Implementation Specification

  • Never call the bundled Agent Tank refresh from the gate (it may start a container); read the cached snapshot the provider exposes. A stale snapshot is acceptable; the gate is a brake, not an accounting system.
  • Every skip/defer reason is a full human-readable sentence: it is shown verbatim in run history.

Acceptance Criteria

  • Scheduled trigger with Claude session at 95% and threshold 90% → run recorded deferred with a reason; no job enqueued.
  • Same with weekly at 95% → skipped.
  • After 6 deferrals the 7th evaluation skips.
  • manual trigger at 99% proceeds.
  • Agent Tank disabled → proceeds (logged as unknown).
  • auto acting over threshold parks the run in awaiting_approval.

Created by ProPR AI Planner

Activity

  1. propr-dev commented on Oct 6, 2026

    @propr-dev
    ContributorAuthor

    Suggested Implementation:

    Implementation Approach

    One pure-ish gate function with injected data sources, plugged into the single trigger primitive (issue 4) and the two other places unattended spend can start (deferred retry and auto acting). Reusing the operator's existing usage-pause threshold means there is one knob for "how close to my subscription limit may automation go", not a second, agent-specific one that could disagree.

    Defer vs. skip: a session window (≈5 h) recovers soon, so deferring preserves the operator's intent (the report still arrives, just later). A weekly window does not, so we skip with a clear reason instead of retrying for days. Bounded deferrals (6 × 30 min) prevent a run from lingering indefinitely.

    Fail-open on missing data mirrors ultrafixEscalation.resolveModel ("missing, stale, disabled, or failed usage monitoring never blocks"); the alternative (fail-closed) would turn an Agent Tank outage into silently dead automation.

    File: packages/core/src/services/agents/agentRunCostGate.ts (new file)

    Why this file: The cost brake for unattended Agents, in one testable module.

    import { isUnattendedTrigger, type AgentDefinition, type AgentRunTrigger } from '@propr/shared';
    import logger from '../../utils/logger.js';
    import { getConfig } from '../../config/configStore.js';
    import { loadSyntheticAgents } from '../../config/configManager.js';
    import type { AgentRunGateDecision } from './agentRunTrigger.js';
    
    export interface UsageSnapshot { sessionPercent?: number; weeklyPercent?: number; resetsInMs?: number; provider?: string }
    export interface ProviderCapacity extends UsageSnapshot { status: 'ok' | 'near_limit' | 'unknown'; agentAlias: string }
    
    /**
     * TODO(implementer): point this at the existing "pause at % of subscription
     * usage" control. Keep the fallback only if that control does not exist.
     */
    export const USAGE_PAUSE_SETTING_KEY = 'agent_run_usage_pause_percent';
    export const DEFAULT_USAGE_PAUSE_PERCENT = 90;
    
    export async function loadUsagePauseThreshold(): Promise<number> {
      const value = await getConfig<number>(USAGE_PAUSE_SETTING_KEY, DEFAULT_USAGE_PAUSE_PERCENT);
      // A malformed value must not disable the brake: fall back to the default.
      return Number.isFinite(value) && value >= 50 && value <= 100 ? value : DEFAULT_USAGE_PAUSE_PERCENT;
    }
    
    async function defaultSnapshot(alias: string): Promise<UsageSnapshot | null> {
      const { AliasSpecificAgentTankSnapshotProvider } = await import('../syntheticUsageSnapshotProvider.js');
      return (await new AliasSpecificAgentTankSnapshotProvider().getSnapshot(alias)) as UsageSnapshot | null;
    }
    
    export interface CostGateDeps {
      now?: () => number;
      threshold?: () => Promise<number>;
      snapshot?: (alias: string) => Promise<UsageSnapshot | null>;
      poolMembers?: (alias: string) => Promise<string[] | null>;
      maxDeferrals?: number;
      deferStepMs?: number;
    }
    
    async function defaultPoolMembers(alias: string): Promise<string[] | null> {
      const pool = (await loadSyntheticAgents()).find(agent => agent.enabled && agent.alias === alias);
      if (!pool) return null;
      // Member shape follows the synthetic agent config; collect each member's direct alias.
      return [...new Set(pool.models.flatMap(model => (model as { members?: Array<{ agentAlias: string }> }).members?.map(member => member.agentAlias) ?? []))];
    }
    
    export async function evaluateProviderCapacity(agentAlias: string, threshold: number, deps: CostGateDeps = {}): Promise<ProviderCapacity> {
      const aliases = (await (deps.poolMembers ?? defaultPoolMembers)(agentAlias)) ?? [agentAlias];
      const snapshots: Array<UsageSnapshot & { alias: string }> = [];
      for (const alias of aliases) {
        try {
          const snapshot = await (deps.snapshot ?? defaultSnapshot)(alias);
          if (snapshot) snapshots.push({ ...snapshot, alias });
        } catch { /* treated as unknown below */ }
      }
      if (!snapshots.length) return { status: 'unknown', agentAlias };
      const over = (snapshot: UsageSnapshot) => Math.max(snapshot.sessionPercent ?? 0, snapshot.weeklyPercent ?? 0) >= threshold;
      // A pool can route around one exhausted member; it is limited only when all are.
      const limited = snapshots.every(over);
      const worst = snapshots.reduce((a, b) => (Math.max(a.sessionPercent ?? 0, a.weeklyPercent ?? 0) >= Math.max(b.sessionPercent ?? 0, b.weeklyPercent ?? 0) ? a : b));
      return { status: limited ? 'near_limit' : 'ok', agentAlias, ...worst, provider: worst.alias };
    }
    
    export function createAgentRunCostGate(deps: CostGateDeps = {}) {
      const now = deps.now ?? Date.now;
      const maxDeferrals = deps.maxDeferrals ?? 6;
      const deferStepMs = deps.deferStepMs ?? 30 * 60_000;
    
      return async function gate(definition: AgentDefinition, trigger: AgentRunTrigger, run?: { deferrals: number }): Promise<AgentRunGateDecision> {
        // A human pressing "Run now" decides for themselves; the UI shows the warning.
        if (!isUnattendedTrigger(trigger)) return { action: 'proceed' };
        const threshold = await (deps.threshold ?? loadUsagePauseThreshold)();
        const capacity = await evaluateProviderCapacity(definition.agentAlias, threshold, deps);
        if (capacity.status === 'unknown') {
          logger.info({ definitionId: definition.id, agentAlias: definition.agentAlias }, 'Agent run cost gate: no usage data, proceeding');
          return { action: 'proceed' };
        }
        if (capacity.status === 'ok') return { action: 'proceed' };
        const label = `${capacity.provider ?? definition.agentAlias}`;
        if ((capacity.weeklyPercent ?? 0) >= threshold) {
          return { action: 'skip', reason: `Skipped: weekly subscription usage for ${label} is at ${Math.round(capacity.weeklyPercent!)}% (pause threshold ${threshold}%).` };
        }
        if ((run?.deferrals ?? 0) >= maxDeferrals) {
          return { action: 'skip', reason: `Skipped after ${maxDeferrals} deferrals: ${label} session usage stayed at or above ${threshold}%.` };
        }
        const resetIn = capacity.resetsInMs !== undefined ? capacity.resetsInMs + 2 * 60_000 : deferStepMs;
        return {
          action: 'defer', until: now() + Math.min(resetIn, deferStepMs),
          reason: `Deferred: session usage for ${label} is at ${Math.round(capacity.sessionPercent ?? 0)}% (pause threshold ${threshold}%).`,
        };
      };
    }

    Export from packages/core/src/index.ts (export * from './services/agents/agentRunCostGate.js';).

    File: packages/core/src/services/agents/agentRunAutonomy.ts

    Why this file: auto acting is unattended spend too; when capacity is low the run waits for a human instead of acting.

    --- a/packages/core/src/services/agents/agentRunAutonomy.ts
    +++ b/packages/core/src/services/agents/agentRunAutonomy.ts
    @@ export async function advanceAfterReport(run, deps = {}) {
         case 'auto': {
    +      if (isUnattendedTrigger(run.trigger)) {
    +        const decision = await (deps.gate ?? createAgentRunCostGate())(runDefinitionFromRun(run), run.trigger);
    +        if (decision.action !== 'proceed') {
    +          // Park instead of failing: the report is kept and a human can approve later.
    +          return transitionAgentRun(run.id, ['report_ready'], 'awaiting_approval', { skipReason: `Acting paused. ${decision.reason}` }, deps.database);
    +        }
    +      }
           return startActing(run.id, ['report_ready'], deps);
    +    }

    (runDefinitionFromRun loads the snapshot via getAgentRunRowById + runDefinitionSnapshot.)

    File: packages/api/routes/agentDefinitionRoutes.ts

    Why this file: Default gate for API/CLI triggers and the capacity endpoint for the UI.

    --- a/packages/api/routes/agentDefinitionRoutes.ts
    +++ b/packages/api/routes/agentDefinitionRoutes.ts
    @@ export function createAgentDefinitionRoutes({ db, services = {} }) {
    +  // Unattended triggers are cost-gated; manual "Run now" passes through inside the gate.
    +  const gate = services.gate ?? createAgentRunCostGate();
    @@ triggerRun:
    -      const result = await trigger({ definition, trigger: triggerKind, triggerSource: source, idempotencyKey: key ?? null, gate: services.gate });
    +      const result = await trigger({ definition, trigger: triggerKind, triggerSource: source, idempotencyKey: key ?? null, gate });
    @@ return {
    +    capacity: (req: Request, res: Response) => send(req, res, async () => {
    +      const definition = await ownedDefinition(req, res);
    +      if (!definition) return;
    +      const threshold = await loadUsagePauseThreshold();
    +      res.json({ threshold, capacity: await evaluateProviderCapacity(definition.agentAlias, threshold) });
    +    }),

    Register ['get', '/api/agent-definitions/:id/capacity', agentDefinitionRoutes.capacity].

    File: test/agentRunCostGate.test.ts (new file)

    Why this file: Each branch of the gate with deterministic fake usage.

    import assert from 'node:assert/strict';
    import { after, test } from 'node:test';
    import { closeConnection, createAgentRunCostGate } from '@propr/core';
    
    after(closeConnection);
    const definition = { id: 'd', agentAlias: 'claude' } as never;
    const gateWith = (snapshot: object | null) => createAgentRunCostGate({ now: () => 1_000, threshold: async () => 90, poolMembers: async () => null, snapshot: async () => snapshot as never });
    
    test('defers on session pressure, skips on weekly pressure, passes manual runs', async () => {
      const session = await gateWith({ sessionPercent: 95, weeklyPercent: 40, resetsInMs: 10 * 60_000 })(definition, 'schedule');
      assert.equal(session.action, 'defer');
      assert.equal((session as { until: number }).until, 1_000 + 12 * 60_000);
      assert.equal((await gateWith({ sessionPercent: 10, weeklyPercent: 95 })(definition, 'api')).action, 'skip');
      assert.equal((await gateWith({ sessionPercent: 99, weeklyPercent: 99 })(definition, 'manual')).action, 'proceed');
    });
    
    test('bounded deferrals and fail-open without data', async () => {
      assert.equal((await gateWith({ sessionPercent: 95 })(definition, 'schedule', { deferrals: 6 })).action, 'skip');
      assert.equal((await gateWith(null)(definition, 'schedule')).action, 'proceed');
    });
  2. propr-dev commented on Oct 6, 2026

    @propr-dev
    ContributorAuthor

    🤖 AI processing has started for this issue using claude agent with claude-opus-5-5 model.

    I'll analyze the problem and work on a solution. This may take a few minutes.

    Processing Details:

    • Agent: claude
    • Model: claude-opus-5-5
    • Branch: 2810/claude-opus-5-5-agents-v1-11-17-agent-tan-20261006-2259-j8w
    • Base Branch: 2800-epic-agents-v1-y7t
    • Worktree: issue-2810-20261006-2259-claude-opus-5-5-j8w

    🔍 Track Task Execution

  3. added a commit that references this issue on Oct 6, 2026
  4. added a commit that references this issue on Oct 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions