Repository navigation
feat(chat): run agents from schedules and signals, within their caps (W2-16) - #1874
Conversation
…(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]>
Preview approval requiredThis pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit |
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
left a comment
There was a problem hiding this comment.
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.
openAgentRunnow checks the cap before every run, afterrunChecks, through a newagentMonthCapReachedinagent-triggers.ts.monthCapUsednow uses it too.- At the cap, a Run now ends
stoppedbefore 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.
internalCallRefusalanswers 404 whenCHAT_AGENTICisn't on, before it reads the secret. The server's cron and signal hook don't start or send anything withoutchatAgenticDeployed()and a secret. The hook also checkschatAgenticEnabledfor the brand's workspace.readArmedOrgsfilters byCHAT_AGENTIC_ORGS, so the tick doesn't claim schedules for other workspaces.openAgentRunand the sweep's settle and failures steps check the flag per workspace.
- Internal endpoints.
- The bearer
CHAT_INTERNAL_SECRETis 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.
- The bearer
- 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_idis updated to match. - A null person stops the run, and a triggered agent pauses (
owner_role). readAgentContextreads 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.
runChecksuses 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.
- Triggered runs act as the owner at that moment, Run now and Run agent as the clicker.
- 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
agentRunIdfor 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 toreserve_chat_ai_usage, under the same lock. A step past the cap is arun_caprefusal.- No route continues a
paused_caprun, 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.
- No route continues a
- 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_countuses 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.
- A schedule is claimed with a compare-and-set on
- 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)
- Archive and held runs. Archive stops queued runs only. A
needs_yourun 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. - 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. - 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 → runningpassing the workspace's concurrency limit. - 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:
- This PR's head (
e3214e01f). - Current main (
703a68600), merged in cleanly with no conflicts. - The fix.
Tests
Run on this branch:
agent-driver,agent-sweepandagent-triggers: 47 passing. The two new cases fail without the fix.- Chat lib, the Chat and internal API routes,
lib/guards(withplan-row.test.ts),subscription-guard-coverageandlib/demo: 1,090 tests. Oneengine.test.tscase 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-creditsandsignals: 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.tsandevents.ts, and they change types only.plan-row.test.tspasses.
gkhngyk
left a comment
There was a problem hiding this comment.
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.
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)origin 'agent',agent_run_id) and runs headless with the version's mode, effort and model.needs_you;paused_cap, and the agent pauses at its cap;no_answer;pending.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)feature: 'agent'andagentRunId. The server computes the run's cap itself,max_share × the month's included budget, and passesp_agent_run_idandp_run_captoreserve_chat_ai_usage(00419).run_cap(429), notai_limit.usage_shareis updated.ai-credits.jsnow copiesagent_id,agent_run_idandparent_run_idonto 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) callsPOST /api/internal/chat/agents/tickwithCHAT_INTERNAL_SECRET.last_fired_at, so two servers don't fire it twice.Signals: a non-blocking, non-throwing hook at the end of the Action Center's
recordSignalsForBrandposts the new signals' kinds and categories to/api/internal/chat/agents/signals.Sweep (same tick):
sweepChatRunsis wired.count.Env:
CHAT_INTERNAL_SECRETis documented in both.env.examplefiles and indocs/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 featurefix— Bug fixchore— Maintenance / dependenciesdocs— Documentation onlyrefactor— Code change that neither fixes a bug nor adds a featuretest— Adding or updating testsHow to test
CHAT_AGENTIC=truein web and server, the sameCHAT_INTERNAL_SECRETin both, and the server'sPUBLIC_APP_URLto the web app.max_share1%: the run pauses at its cap (paused_cap). A triggered run at its cap stops ("Stopped at its limit").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.agent-driver,agent-triggers,agent-sweep;engine.test;chat-budget.test.js,chat-agents.test.js.Checklist
yarn lintpasses (0 errors; 7 old warnings in files this PR doesn't touch)yarn typecheckpassesyarn format:checkpasseshelp/(or no user-visible change)On this branch:
yarn buildpasses (NODE_OPTIONS=--max-old-space-size=4096on an 8 GB machine);npm run formatchanges nothing, lint is clean, and 334 files / 4,603 tests pass (3 skipped).For production (@gkhngyk):
CHAT_INTERNAL_SECRETto the same value on Vercel and on the server (openssl rand -hex 32). The server'sPUBLIC_APP_URLpoints at the web app.CHAT_AGENTIC=truegoes on both sides.agentRunIdwith a 400.server.js.Small decisions, taken as recommended:
Follow-ups, not in this PR
stop_reasonvaluesai_limitandowner_role;needs_you → runningdoesn't check the workspace's concurrency limit.usage_shareshould be written in one SQL update, and the refusal reason returned by the RPC.chat_run_staterows; aneeds_yourun without a chat.notify_user_ids), and Admin approval of another person's agent card.🤖 Generated with Claude Code