Skip to content

feat(chat): run agents from schedules and signals, within their caps (W2-16) - #1874

Merged
gkhngyk merged 4 commits into
ansvisor:mainfrom
cihan-gyk:feature/chat-agent-runner
Oct 31, 2026
Merged

gkhngyk merged 4 commits into
ansvisor:mainfrom
cihan-gyk:feature/chat-agent-runner

Conversation

@cihan-gyk

Copy link
Copy Markdown
Collaborator

Summary

Chat W2-16: agents run on their own, from schedules and signals, each step held within the agent run's cap (CHAT-21 §G–§H, CHAT-27 items 19–22, 30, 33). Built on main (after #1864 and #1867). Everything stays behind CHAT_AGENTIC / CHAT_AGENTIC_ORGS. The server's cron doesn't start while the flag is off, and the internal endpoints answer 404.

The driver (web/src/lib/chat/agent-driver.ts)

  • A queued agent run opens its own chat (origin 'agent', agent_run_id) and runs headless with the version's mode, effort and model.
  • Who it acts as:
    • a triggered run acts as the agent's owner;
    • Run now and Run agent act as the person who clicked.
    • Role and plan are read again at start. An owner who is no longer an Admin or Manager pauses the agent. So does a plan or mode refusal, a deleted brand, or the month's AI limit.
  • A read-only workspace or Chat turned off starts nothing.
  • The message carries the skills and instructions. Evidence ids stay in the server-side scope, never in the text.
  • Status follows the chat run:
    • a card waiting → needs_you;
    • the month's limit → paused_cap, and the agent pauses at its cap;
    • a triggered run at its own cap → stopped, "Stopped at its limit";
    • 7 days without an answer → no_answer;
    • 3 failures in a row pause the agent;
    • a run that shipped something → outcome pending.
  • A finished run doesn't start the next one inside the same request (after() would cut it at Vercel's 300 s). The minute tick starts the next queued run.

The budget (server/src/lib/chat-budget.js)

  • The engine sends feature: 'agent' and agentRunId. The server computes the run's cap itself, max_share × the month's included budget, and passes p_agent_run_id and p_run_cap to reserve_chat_ai_usage (00419).
  • A step past the cap is refused as run_cap (429), not ai_limit.
  • After each charge or release, usage_share is updated.
  • Credits: the part paid by purchased AI credits counts toward the run's cap and share. ai-credits.js now copies agent_id, agent_run_id and parent_run_id onto the split rows; until now they were dropped. The cap stays a share of the included budget, so buying credits doesn't raise it. The agents list shares use the same base.

Schedules: the server's minute cron (server/src/lib/chat-agents.js) calls POST /api/internal/chat/agents/tick with CHAT_INTERNAL_SECRET.

  • The secret is compared in constant time and is required.
  • A due slot fires once in its own time zone, DST included. The claim is a CAS on last_fired_at, so two servers don't fire it twice.
  • A missed slot isn't replayed: slots older than 1 hour, or from before a Resume, are skipped.

Signals: a non-blocking, non-throwing hook at the end of the Action Center's recordSignalsForBrand posts the new signals' kinds and categories to /api/internal/chat/agents/signals.

  • Matching coalesces within 15 min.
  • 6 h cooldown.
  • The plan's daily limit (UTC day).
  • At most 3 queued runs.

Sweep (same tick):

  • sweepChatRuns is wired.
  • Agent runs follow their chat runs.
  • A run whose chat didn't open in 5 min fails.
  • Queued rows older than 6 h stop.
  • An agent paused at the month's limit resumes when there's room.
  • Each job (schedules, signals, sweep), each trigger and each brand is isolated: one failure doesn't stop the rest, and it's counted.
  • Reads go past PostgREST's 1,000 rows:
    • triggers are paged;
    • only each agent's current version is read, in chunks;
    • recent runs are read per brand, newest first;
    • the daily limit is a count.

Env: CHAT_INTERNAL_SECRET is documented in both .env.example files and in docs/self-host/env-variables.mdx. Help: help/chat/agents.md (approved: false).

Related issue

None. Chat Wave 2 (W2-16).

Type of change

  • feat — New feature
  • fix — Bug fix
  • chore — Maintenance / dependencies
  • docs — Documentation only
  • refactor — Code change that neither fixes a bug nor adds a feature
  • test — Adding or updating tests

How to test

  1. Set CHAT_AGENTIC=true in web and server, the same CHAT_INTERNAL_SECRET in both, and the server's PUBLIC_APP_URL to the web app.
  2. Create an agent with a schedule a minute ahead. On the next tick it runs once, in its own chat, as its owner.
  3. Run now on an agent with max_share 1%: the run pauses at its cap (paused_cap). A triggered run at its cap stops ("Stopped at its limit").
  4. Demote the owner to Analyst: the next triggered run doesn't start, and the agent pauses.
  5. Manual tick: node server/src/scripts/chat-agents-tick.js, or curl the tick endpoint with the bearer secret. A wrong secret gives 401; with Chat off, 404.
  6. Unit tests:
    • agent-driver, agent-triggers, agent-sweep;
    • the tick route;
    • engine.test;
    • chat-budget.test.js, chat-agents.test.js.

Checklist

  • Branch follows the naming convention
  • Commits follow Conventional Commits
  • yarn lint passes (0 errors; 7 old warnings in files this PR doesn't touch)
  • yarn typecheck passes
  • yarn format:check passes
  • Changes are focused — one concern per PR
  • Help article updated under help/ (or no user-visible change)

On this branch:

  • web: 758 files / 7,660 tests pass, and yarn build passes (NODE_OPTIONS=--max-old-space-size=4096 on an 8 GB machine);
  • server: npm run format changes nothing, lint is clean, and 334 files / 4,603 tests pass (3 skipped).

For production (@gkhngyk):

  1. 00419 (feat(chat): add Wave 2's tables for questions, tasks, agents, Why, impact and suggestions (00417–00422) #1853) must be on prod.
  2. Set CHAT_INTERNAL_SECRET to the same value on Vercel and on the server (openssl rand -hex 32). The server's PUBLIC_APP_URL points at the web app. CHAT_AGENTIC=true goes on both sides.
  3. Deploy the server first, then the web. The old server's budget schema is strict and would reject agentRunId with a 400.
  4. No separate cron: it starts inside server.js.

Small decisions, taken as recommended:

  • the daily limit counts by UTC day;
  • queued runs expire after 6 h;
  • the prompt-tag filter stays hidden in the create form until tag data exists (follow-up on W2-15's form).

Follow-ups, not in this PR

  • A small DB PR:
    • stop_reason values ai_limit and owner_role;
    • an advisory-locked enqueue RPC, so concurrent signals can't queue twice and evidence merges don't race.
  • needs_you → running doesn't check the workspace's concurrency limit.
  • usage_share should be written in one SQL update, and the refusal reason returned by the RPC.
  • Orphan chat_run_state rows; a needs_you run without a chat.
  • The sweep should page with a cursor.
  • The signals endpoint should re-read signals from the DB.
  • Notifications beyond the owner's Inbox (e-mail, notify_user_ids), and Admin approval of another person's agent card.
  • The KPI trigger is registered but doesn't start runs yet.
  • Self-hosted without a budget has no per-run cap. Document it.

🤖 Generated with Claude Code

…(W2-16)

The agent run driver hands a started agent run to Chat: a chat of its own
(origin agent, agent_run_id) for the person it acts as (the clicker for Run
now, the agent's owner now for a trigger, an Admin or a Manager still),
after the checks before a run read again for them; a triggered agent
pauses for the reason (owner_role, plan, brand_gone, cap). Nothing starts
in a read-only workspace or with Chat off. The engine drives it headless;
each step, the help answer's too, is held as the agent's within the run's
cap: max_share of the plan's included monthly budget, worked out on the
server (run_cap past it), the run's spend counting every part (own key,
included budget, credits: a step's credit parts keep its agent run). The
server keeps the run's usage_share on the same base, and the Agents list's
shares now use it too.

The agent run follows its Chat run: Needs you on a card, paused_cap at a
limit (the month's pauses the agent), Stopped at its limit for a triggered
run at its own cap or a run held at a limit for 7 days, No answer in 7
days, done or failed. Three failures in a row pause the agent; a run that
shipped gets a Pending outcome.

Triggers: the server's minute cron calls the web's internal tick
(CHAT_INTERNAL_SECRET, constant-time compare) to fire due schedules in
their time zone (no catch-up, claimed once) and to sweep (Chat's own
sweep, lost and stale runs, failures, the AI limit's auto-resume, and the
start of queued runs: never chained in a finished run's request). The
signal pass tells the web which new signals feed which definitions, so
Signal triggers fire; 15-minute coalescing, a 6-hour cooldown and the
plan's daily event runs (UTC day) apply. Reads page past PostgREST's 1000
rows; each job, trigger and brand fails on its own. KPI and watch-rule
triggers don't fire yet.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@mintlify

mintlify Bot commented Oct 30, 2026 •

Copy link
Copy Markdown

Preview approval required

This pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit cc4808d.

Approve preview

The driver now checks the agent's own monthly cap (max_month_share)
before a run starts, not only when a trigger fires: a Run now on an agent
paused at its cap stops before it starts, and a triggered run at the cap
pauses the agent (cap). The cap comparison allows for floating point
(0.18 + 0.02 is just under 0.2), here and in the sweep's resume.
gkhngyk
gkhngyk previously approved these changes Oct 31, 2026

@gkhngyk gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good with 540cbe0: current main merged in and one fix commit, described below.

Fix (on this branch)

The agent's own monthly cap now holds for Run now too. The monthly cap (max_month_share) was only checked when a trigger fired (monthCapUsed). The driver didn't check it, and neither did Run now. So Run now on an agent paused at its cap (cap) still started, as long as the workspace's AI limit had room. Only the per-run cap limited it.

  • openAgentRun now checks the cap before every run, after runChecks, through a new agentMonthCapReached in agent-triggers.ts. monthCapUsed now uses it too.
  • At the cap, a Run now ends stopped before it starts. A triggered run also pauses the agent (cap), as before.
  • The comparison allows for floating point: 0.18 + 0.02 comes out just under 0.2, which used to count as under the cap. The sweep's resume uses the same check, so an agent at exactly its cap doesn't resume early.
  • Tests: a new driver test (Run now on an agent paused at its cap, a triggered run on an active agent at its cap, and a Run now under the cap), plus one more case in the sweep's monthly-cap test. Both fail without the fix.

What we checked

  • Chat off. internalCallRefusal answers 404 when CHAT_AGENTIC isn't on, before it reads the secret. The server's cron and signal hook don't start or send anything without chatAgenticDeployed() and a secret. The hook also checks chatAgenticEnabled for the brand's workspace.
    • readArmedOrgs filters by CHAT_AGENTIC_ORGS, so the tick doesn't claim schedules for other workspaces.
    • openAgentRun and the sweep's settle and failures steps check the flag per workspace.
  • Internal endpoints.
    • The bearer CHAT_INTERNAL_SECRET is compared in constant time, with equal lengths checked first. An empty or missing secret on either side gives 401.
    • Bodies are strict schemas with size limits (200 signals, 50 urls and engines, 20 definitions).
    • Members can't reach them, so they can't fake signals.
  • Who a run acts as, read again at start.
    • Triggered runs act as the owner at that moment, Run now and Run agent as the clicker. acting_user_id is updated to match.
    • A null person stops the run, and a triggered agent pauses (owner_role).
    • readAgentContext reads membership, organization and role live. A removed member, someone in another workspace, or a role below Manager stops the run, and a triggered agent pauses (owner_role).
    • An archived or missing agent, or a missing version, ends the run.
    • A read-only workspace starts nothing.
    • runChecks uses the person's role: Full auto against the plan and Settings › Chat, engines, brands in scope, and the AI limit. A plan refusal pauses a triggered agent (plan).
    • Demo brands are filtered out by runnableBrands, and signals on a demo brand are ignored.
  • Card resume. Answering a card in an agent run's chat goes through the engine's resume path. That path re-reads the person's context and refuses a read-only workspace, and each segment's tools are re-decided with the live role.
  • Run cap. The engine sends agentRunId for every chat whose conversation is an agent run's, manual runs included. The server works out the cap itself (max_share × the included budget) and passes it to reserve_chat_ai_usage, under the same lock. A step past the cap is a run_cap refusal.
    • No route continues a paused_cap run, so the cap can't be passed. A triggered run at its cap is stopped.
    • Credit splits now keep agent_run_id, so purchased credits count toward the cap.
    • No dollar amount reaches the browser: shares only.
  • Several servers, retries.
    • A schedule is claimed with a compare-and-set on last_fired_at, so two ticks fire a slot once.
    • Runs start through chat_start_next_agent_run (advisory lock). Paused agents' triggered runs don't start there.
    • Every status move in the driver and sweep is conditional on the state it read. fail_count uses compare-and-set, and the one-chat-per-run unique index stops a second driver.
    • Each server's cron runs one tick at a time. The call times out in 50 s.
  • Bounded work. The sweep's reads are capped at 500 rows each. Triggers are paged and versions read in chunks. Recent runs are read per brand (500), and the daily limit is a count.
  • Schedules fire at most once per slot, never before the last fire, creation or Resume, and at most 1 h late. A missed slot isn't replayed.
  • Embeds: none. Every new .select() lists plain columns.

Follow-ups (not blocking)

  1. Archive and held runs. Archive stops queued runs only. A needs_you run of an archived agent can still be continued from its card. Archive could also stop held runs, or the resume path could check the agent's state.
  2. Run now could refuse at the click when the agent is at its monthly cap (ai_limit-style), so it isn't shown as a run that stopped.
  3. The follow-ups in the PR body still apply. The most important are the locked enqueue RPC for signals that arrive at the same moment, and needs_you → running passing the workspace's concurrency limit.
  4. After a downgrade, the plan's active-agent cap isn't checked at run time. The plan check covers Full auto and engines only.

Base

this branch is built from:

  1. This PR's head (e3214e01f).
  2. Current main (703a68600), merged in cleanly with no conflicts.
  3. The fix.

Tests

Run on this branch:

  • agent-driver, agent-sweep and agent-triggers: 47 passing. The two new cases fail without the fix.
  • Chat lib, the Chat and internal API routes, lib/guards (with plan-row.test.ts), subscription-guard-coverage and lib/demo: 1,090 tests. One engine.test.ts case failed once under full parallel load. Run alone, the file passes three times out of three (106 tests). It's a timing flake.
  • Server: chat-agents, chat-budget, internal-chat-budget, ai-credits and signals: 218 passing.
  • Web tsc --noEmit: clean. Eslint and prettier on the changed files, web and server: clean.
  • Build: the only client-side files changed are run-state.ts and events.ts, and they change types only. plan-row.test.ts passes.

@gkhngyk gkhngyk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Merging in order with the other approved PRs. This head merges current main; its tree is what main will be after this squash, checked with the full server and web suites, tsc, lint, format and next build.

@gkhngyk
gkhngyk merged commit d63b547 into ansvisor:main Oct 31, 2026
4 of 6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants