Compare commits

...
Author SHA1 Message Date
BaaRai d07abf006e fix(server): keep operator chat revival and prove the budget reservation
Review of #714 found three issues before it could ship in 0.7.1.

The Main Agent chat path used reviveTaskFromAgent, which refuses a timed-out
task by logging only, so an operator could no longer resume from the chat and
got no explanation. The chat is an explicit operator turn: it uses reviveTask
like the console again, and the admission guards still refuse a settling or
budget-exhausted task. Automatic agent revival through delegateToTask keeps
the stricter guard.

TestBudgetStopReservesPlannerRoundCost pre-marked the wrap-up before calling
budgetStop, so it passed because wrap-up was already set, not because the
planner+worker reservation worked. It now calls budgetStop from Plan alone,
with a bounded context that only shortens the settle wait.

README documents the planner+worker reservation, the skipped final judgment
past the hard ceiling, and which revivals are refused.

Verified: gofmt on the committed blobs, go build ./..., go vet ./...,
and the full ./agent ./server suites on disposable PostgreSQL 16, including
TestHardExhaustedBudgetSkipsFinalPlannerRound.
2026-11-30 22:39:55 +01:00
Brixton Pham 9b5fa4b6d6 fix(server,agent): enforce planner run budgets and stop revive loops (#705) 2026-11-30 22:38:54 +01:00
BaaRai c03fd8cc9d Merge pull request #725 from BaaRai/release/0.7.1-changelog-721
docs(changelog): cover the egress bot-checkpoint fix from #721
2026-11-30 22:04:57 +01:00
BaaRai 7730f2ffae docs(changelog): cover the egress bot-checkpoint fix
#721 merged without an entry. The 0.7.1 Fixed section now states what
changed: a 403/429/503 that serves a Vercel, Cloudflare or AWS WAF
challenge is no longer treated as a rate limit, and the agent is pointed
at browser tooling instead of retrying a response raw HTTP cannot pass.
2026-11-30 22:04:23 +01:00
BaaRai 7728faa474 Merge pull request #724 from BaaRai/fix/cors-ipv4-canonical
fix(verify): reject non-canonical IPv4 origins in CORS proofs
2026-11-30 22:04:03 +01:00
BaaRai b63b57fdc9 Merge pull request #721 from tausifzaman/fix/detect-js-bot-checkpoints
fix(egress): stop retrying JS bot-mitigation checkpoints
2026-11-30 21:56:34 +01:00
BaaRai 8434e1040e fix(verify): reject non-canonical IPv4 origins in CORS proofs
The Fetch host parser runs the IPv4 parser whenever the last label of a
host is a number, and a browser serializes the result as a dotted quad.
Legacy spellings such as 0x7f.1, 1.2.3.4.5, 2130706433 or a label with a
leading zero are therefore normalized before they can appear in an Origin
header. ValidateBrowserOrigin accepted them as ordinary domain labels, so
a CORS proof could still be marked verified with an origin no browser
sends.

A numeric host must now parse as a canonical IPv4 address whose String()
equals the host. Domains, canonical dotted quads and localhost are
unchanged.

The five new rejection cases fail against the previous implementation.
2026-11-30 21:48:57 +01:00
BaaRai 4e3f7682bb Merge pull request #723 from BaaRai/release/0.7.1-notes
docs(changelog): dedupe the 0.7.1 notes and cover the CORS proof check
2026-11-30 21:42:08 +01:00
BaaRai 8fb9e365e3 docs(changelog): dedupe the 0.7.1 notes and cover the CORS proof check
Five entries in the 0.7.1 Fixed section described the same change twice:
browser capture truncation, the #542 indexing move, the (host, ts) traffic
index, the traffic host delete directory guard, and the skill endpoint
error text. Each keeps the version that matches the code and the facts the
other copy added are folded in.

The CORS proof validation from #720 gets its entry: a CORS finding now
stays unverified unless the bound exchange carries a browser-serialized
Origin and an Access-Control-Allow-Origin that authorizes it.
2026-11-30 21:41:16 +01:00
BaaRai 1ba49e04f0 Merge pull request #720 from tausifzaman/fix/cors-origin-proof-validation
security: validate CORS Origin proof evidence
2026-11-30 21:40:26 +01:00
Tausif Zaman cef7400217 fix(egress): stop retrying JS bot-mitigation checkpoints 2026-12-01 01:32:03 +06:00
Tausif Zaman f3b0df7f2c security: validate CORS Origin proof evidence 2026-12-01 00:52:33 +06:00
21 changed files with 1523 additions and 54 deletions
+4 -6
View File
@@ -66,12 +66,8 @@ The execution-scope gap and its remediation were tracked in public before the No
- **`traffic_get` keeps compressed binary responses encoded** (follow-up to #606): the decoded view judged a body as binary only by a NUL byte in its first 512 bytes, so a gzip `application/pdf` without one was shown as text. It now uses the response `Content-Type` as well, the same check the body index applies. The response head is read before the body, so an exchange without a `Content-Encoding` no longer loads its spilled blobs, and the request blob is never loaded.
- **`traffic_search` host matching**: a port search such as `host:8443` matched any capture of that host whose URL quoted `host:8443` in its query string (`?next=http://host:8443/`, typical of open-redirect and SSRF probes), because the authority prefix was not anchored to the scheme. It is now anchored to `http`, `https`, `ws` and `wss`. The recorded host keeps the client's case while the search is lowercased, so a capture of `https://Mixed.Example.com/` was not found by any host search; the comparison now ignores case. A compressed body with a bad checksum or trailing garbage now keeps the text decoded before the error instead of dropping out of the index, and the store directory guard on host delete ignores case for case-insensitive filesystems.
- **Browser capture keeps a bounded request map**: unfinished debugger requests are capped at 500, and a request that fails to load is dropped instead of waiting for eviction. A stored body longer than 256K JavaScript characters is cut and marked `[truncated by extension]`. That count is UTF-16 code units, not bytes; the server still enforces its byte cap on ingest.
- **Browser capture keeps a bounded request map**: unfinished debugger requests are capped at 500, and a stored request body is cut at the same 256 KiB limit as ingest.
- **The capture proxy no longer holds a response while indexing it** (#542): recording wrote the trigram full-text index of each body (up to 4 MiB) before the client got its response, under the recorder's global lock, so a 1 MB script added about 160 ms to its own response and to every response recorded behind it. The index is now written by a background worker. Body searches wait for entries queued before them, so they still find every exchange recorded before the search. An entry whose exchange was deleted in the meantime is dropped.
- **The capture proxy no longer holds a response while indexing it** (#542): recording wrote the trigram full-text index of each body (up to 4 MiB) before the client got its response, so a 1 MB script added about 160 ms to its own response. The index text is now committed with the exchange into `ex_fts_pending` and indexed by a background worker; with the indexer idle, recording a 1 MiB script takes about 5 ms. Under a burst of large bodies a recording can still wait behind the entry being indexed, since both need the recorder's write lock. Body searches wait (up to 30 s) for entries queued before them, so they still find every exchange recorded before the search. Entries left by a crash or a stop are indexed on the next start, and shutdown no longer drains the queue.
- **The capture proxy no longer holds a response while indexing it** (#542): recording wrote the trigram full-text index of each body (up to 4 MiB) before the client got its response, so a 1 MB script added about 160 ms to its own response. The index text is now committed with the exchange into `ex_fts_pending` and indexed by a background worker; with the indexer idle, recording a 1 MiB script takes about 5 ms. Under a burst of large bodies a recording can still wait behind the entry being indexed, since both need the recorder's write lock. Body searches wait (up to 30 s) for entries queued before them, so they still find every exchange recorded before the search. Entries left by a crash or a stop are indexed on the next start, and shutdown no longer drains the queue. An entry whose exchange was deleted after it was queued is dropped.
- **Host-filtered traffic searches no longer sort a host's whole history**: the capture index had `host` and `ts` indexed separately, so `traffic_search` and `Search` (`WHERE host=? ORDER BY ts DESC`) sorted every exchange of the host to return the newest few, and the host picker (`Hosts()`, polled every 5 s) scanned the table. A `(host, ts)` index replaces the `host` one. With 45k exchanges on one host, a host search drops from about 42 ms to 0.04 ms and the host list from 20 ms to 8 ms. The traffic page's own list (`Page()`) is unchanged. The index is built once, synchronously, on the first start after upgrading; on a store with millions of exchanges that delays startup and needs temporary disk space about the size of the index.
- **Traffic host lists no longer sort a host's whole history**: the capture index had `host` and `ts` indexed separately, so `traffic_search` and the traffic page's host filter sorted every exchange of the host to return the newest few, and the host picker (polled every 5 s) scanned the table. A `(host, ts)` index replaces the `host` one. With 45k exchanges on one host, a host search drops from about 42 ms to 0.04 ms and the host list from 20 ms to 8 ms.
- **Traffic host delete leaves the store directories in place**: a requested host whose sanitized name is `_index`, `_blobs`, `_ca`, `_delete_staging`, `.`, or `..` is not used as a directory. Those paths are the capture index, the blob store, the MITM CA, the delete staging area, or the traffic directory itself. Index rows for that host are still removed.
- **The SOCKS5 listener refuses non-loopback clients for every auth method**: username/password was offered to any client and accepted any credentials, so a remote client got past the loopback-only rule for no-auth by offering method `0x02`. Credentials are still not verified (the username carries only the pace marker), so both methods are now accepted from loopback clients only; binding `ARTEX_SOCKS5_ADDR` to a non-loopback address no longer exposes an open proxy.
- **Request bodies labelled multipart are capped**: the 32 MiB body cap skipped any request with a multipart `Content-Type`, so a JSON handler reading the body directly could be sent an unbounded body. Multipart bodies now get an upload-sized cap (the largest limit an upload handler sets).
- **The `traffic_search` host example no longer names a real IP**: the tool description shown to the model used a routable third-party address; it now uses `192.0.2.10` (RFC 5737).
@@ -80,7 +76,6 @@ The execution-scope gap and its remediation were tracked in public before the No
- **Asset insert applies the JSON body cap**: `POST /api/assets` decodes through the shared JSON limit, including a `multipart/` request that the upload middleware leaves uncapped. A body over the cap is rejected before the database is touched.
- **The LLM connection test honours the output-cap field name**: `POST /api/llm/test` never read a profile's `max_tokens_field`, so the Test button always sent the cap as `max_tokens`. An OpenAI reasoning model (o-series, GPT-5) rejects that with `unsupported_parameter` and a 400, so a profile set to `max_completion_tokens` failed the test even though conversations with it worked. The test now resolves the field from the form, falling back to the stored profile for the list-view test button, and normalises it the same way a profile save does (only the openai format with `max_completion_tokens` is kept).
- **Skill endpoints no longer return database driver text**: a failure loading skill usage, missing-skill stats, or skill visibility is logged on the server and the client receives a fixed message.
- **Skill endpoints no longer return database driver text**: a failure loading skill usage or missing-skill stats is logged on the server and the client receives a fixed message.
- **Hook `ReplaceAll` counts against the memory budget before it runs**: `strings.ReplaceAll`, `bytes.ReplaceAll` and `regexp.ReplaceAllString` built their result first and charged it after, so a hook that repeats a long string over many matches allocated far past the 4 MiB budget. With 1 MiB replaced into each byte of 1 MiB, the runtime asked for 1 TiB and the server process exited with `fatal error: runtime: out of memory`, in a dry run as on live traffic. The size of the result is now charged before it is built, and the hook stops with the memory limit.
- **Agent list tools cap their page size**: `list_worker_traces`, `list_assets`, and `list_untested_assets` clamp a model-supplied limit or page size to 100, and clamp the page number and offset. A limit is no longer used raw as a slice capacity or a SQL page size.
- **Legacy MCP SSE refuses an overlong line**: the endpoint announcement and the legacy event reader stop a line that grows past the existing JSON-RPC buffer cap, instead of buffering it with an unbounded read.
@@ -102,6 +97,9 @@ The execution-scope gap and its remediation were tracked in public before the No
- **Uploads do not follow a symlink**: chat and workspace uploads `Lstat` the destination and refuse to write when it is already a symlink. A dangling link is no longer treated as a free name.
- **Hardening follow-up for the upload and capture fixes**: existing spill blob directories and files are tightened on startup, hook `range` charges 32 bytes per pair, and uploads open with `O_NOFOLLOW` on Unix. The Windows upload path keeps the `Lstat` check.
- **Docker Compose database passwords with URL-special characters**: `docker-compose.yml` no longer pastes `POSTGRES_PASSWORD` into `ARTEX_PG_DSN`. The server builds the URL from `ARTEX_PG_HOST`, `ARTEX_PG_PORT`, `ARTEX_PG_USER`, `ARTEX_PG_PASSWORD`, `ARTEX_PG_DBNAME` and `ARTEX_PG_SSLMODE`, percent-encoding the user and password, so `/`, `?`, `%`, `@`, `:` and spaces connect. An explicit `ARTEX_PG_DSN` still wins and is not rewritten. `ARTEX_PG_PASSWORD` is removed from the environment with the other startup secrets (#450).
- **A CORS proof must use a browser-serialized origin and a matching response**: a finding could reach `verified` when the bound exchange carried an `Origin` header no browser sends, or a response that never authorized that origin, because verification only checked that the quoted body was present. CORS-class findings now parse the bound request and response heads, require an RFC 6454 serialized origin, and require `Access-Control-Allow-Origin` to be that exact origin or `*` without credentials; otherwise the finding stays `unverified` with the reason in the verification note. The check reads the finding's own class, so other verification paths are unchanged (#720).
- **Egress stops retrying JavaScript bot-mitigation checkpoints**: a `403`, `429` or `503` serving a Vercel, Cloudflare or AWS WAF challenge was treated as a rate limit and retried with backoff, spending the request budget and model tokens on responses a raw HTTP retry cannot get past. An explicit mitigation header, or a Vercel challenge marker in the first 8 KiB of the body, now closes the response and returns a `BotCheckpoint` error that points the agent at browser tooling. Ordinary `429`/`503` rate limits and plain `403` responses keep their retry behavior (#721).
- **Run budgets now bound planner rounds and revive loops** (#705): a task could exhaust its run budget while planner rounds kept starting, and an agent-driven `set_goals` could revive a timed-out task indefinitely, which is how the report reached 18.4M tokens against a 250k cap. A normal planner round now starts only when the remaining budget covers the planner estimate plus the next worker, each round has its own turn allowance and usage meter, and once lifetime spend passes the task budget plus the wrap-up reserve the settle sequence skips the final planner round instead of spending more. Automatic agent revival refuses timed-out, settling and budget-exhausted tasks; an operator resume from the console or the chat still works while no run budget is exhausted. A task without a configured budget behaves exactly as before (#705, #714).
### Other changes since 0.6.0
+11 -2
View File
@@ -287,7 +287,10 @@ worker remains confined to the intent it claimed.
- **Budgets**: `ARTEX_TASK_BUDGET_TOKENS` / `ARTEX_TASK_BUDGET_TURNS` cap a whole task (planner and
workers); `ARTEX_INTENT_BUDGET_TOKENS` / `ARTEX_INTENT_BUDGET_TURNS` cap one worker run. Near the
limit the task enters a forced wrap-up; a worker is not started when the remaining budget cannot
cover it. Spend already in `llm_usage` is restored after a restart. A task that is already inside
cover it. A normal planner round is only started when the remaining budget covers the planner
estimate and the next worker; past the task budget plus the reserve the final goal judgment is
skipped, so an over-budget task cannot spend more. Spend already in `llm_usage` is restored
after a restart. A task that is already inside
the wrap-up reserve only has that reserve left, so the revived run wraps up instead of starting
another worker. The per-worker cost estimate starts again from the defaults (50,000 tokens and
10 turns) until a worker finishes in this process.
@@ -688,11 +691,17 @@ started when the remaining task budget cannot cover its estimated cost (the aver
workers, else 50,000 tokens and 10 turns). Near the wrap-up reserve (the larger of 5% and 20,000
tokens, and 2 turns) the task enters a forced wrap-up: the planner writes a summary and final goal
judgment, and workers may only write back. The task then ends `done` if its goals are met, else
`timeout`. Practical floor: below 50,000 tokens no worker starts; 50,000-70,000 typically gives one
`timeout`. A normal planner round is only started when the remaining budget covers the planner
estimate and the next worker's; once spend exceeds the task budget plus the reserve, the final
planner round is skipped and the task settles without a final goal judgment (`timeout`).
Practical floor: below 50,000 tokens no worker starts; 50,000-70,000 typically gives one
worker then wrap-up; pick well above 70,000 for real exploration. Planner, worker, judge, and
compactor rows in `llm_usage` are counted back into the cap when a ledger is created, including
after a restart and after a revived run drops its ledger. A restored task already inside the
wrap-up reserve does not get another worker: only that reserve remains, and the run wraps up.
Automatic revival from agent tools (`set_goals`, `add_intent`) refuses timed-out, settling and
budget-exhausted tasks; an operator resume from the console or the chat still works while no run
budget is exhausted.
Chat, goal decomposition, and side questions are stored on the same task and are not counted.
The per-worker average is not restored (usage rows have no run boundary), so the estimate starts
from the defaults until a worker finishes in this process.
+246 -16
View File
@@ -2,6 +2,7 @@ package agent
import (
"context"
"errors"
"fmt"
"math"
"os"
@@ -9,6 +10,7 @@ import (
"strings"
"sync"
"github.com/Autumn-27/norma/harness"
"github.com/Autumn-27/norma/llm"
)
@@ -25,13 +27,20 @@ import (
const Unlimited int64 = math.MaxInt64
const (
BudgetMarginPercent = 5 // wrap-up reserve = max(5% of the task budget, floor)
BudgetMarginMinTokens = 20_000 // token floor of the reserve
BudgetMarginMinTurns = 2 // turn floor of the reserve
DefaultWorkerEstimateTokens = 50_000 // one worker run, until a worker of this task finished
DefaultWorkerEstimateTurns = 10
BudgetMarginPercent = 5 // wrap-up reserve = max(5% of the task budget, floor)
BudgetMarginMinTokens = 20_000 // token floor of the reserve
BudgetMarginMinTurns = 2 // turn floor of the reserve
DefaultWorkerEstimateTokens = 50_000 // one worker run, until a worker of this task finished
DefaultWorkerEstimateTurns = 10
DefaultPlannerEstimateTokens = 10_000 // one planner round, until a normal planner round finishes
DefaultPlannerEstimateTurns = 2
BudgetWrapupMaxTurns = 4 // upper bound on turns in a forced budget wrap-up planner round
)
// ErrTaskBudgetExhausted is returned by a planner provider when the task's
// lifetime spend has exceeded its configured budget plus wrap-up reserve.
var ErrTaskBudgetExhausted = errors.New("task run budget exhausted")
// Budget caps tokens and turns; a dimension equal to Unlimited has no cap.
type Budget struct{ Tokens, Turns int64 }
@@ -100,6 +109,8 @@ type BudgetLedger struct {
spent Spend // planner rounds + worker runs
workerRuns int64
workerSpent Spend
plannerRuns int64
plannerSpent Spend
wrapup bool // the forced wrap-up has started
}
@@ -137,14 +148,19 @@ func (l *BudgetLedger) Record(u llm.Usage) {
type BudgetState struct {
Task, Remaining, Margin Budget
Spent, Estimate Spend
AtMargin bool // remaining is at or under the wrap-up reserve
Dispatch bool // a new worker may start
PlannerEstimate Spend // estimated cost of one normal planner round
AtMargin bool // remaining is at or under the wrap-up reserve
Dispatch bool // a new worker may start
Plan bool // a new normal planner round may start
HardExhausted bool // lifetime spend exceeded task budget + wrap-up reserve
}
// State reports the remaining budget and whether a worker may be dispatched:
// not once the wrap-up started or the reserve is reached, and not when the
// remaining budget is below one worker's estimated cost (the average of this
// task's finished worker runs, else the defaults; never above the intent cap).
// State reports the remaining budget and whether a worker or planner round may
// start: not once the wrap-up started or the reserve is reached, and not when
// the remaining budget is below the estimated cost (the average of this task's
// finished worker/planner runs, else the defaults; worker estimate never above
// the intent cap). HardExhausted is the lifetime circuit breaker once total
// spend has consumed both the task budget and the wrap-up reserve.
func (l *BudgetLedger) State() BudgetState {
l.mu.Lock()
defer l.mu.Unlock()
@@ -154,9 +170,32 @@ func (l *BudgetLedger) State() BudgetState {
est = Spend{l.workerSpent.Tokens / l.workerRuns, l.workerSpent.Turns / l.workerRuns}
}
est = Spend{min(est.Tokens, l.intent.Tokens), min(est.Turns, l.intent.Turns)}
pEst := Spend{DefaultPlannerEstimateTokens, DefaultPlannerEstimateTurns}
if l.plannerRuns > 0 {
pEst = Spend{l.plannerSpent.Tokens / l.plannerRuns, l.plannerSpent.Turns / l.plannerRuns}
}
at := (rem.Tokens != Unlimited && rem.Tokens <= m.Tokens) || (rem.Turns != Unlimited && rem.Turns <= m.Turns)
return BudgetState{Task: l.task, Remaining: rem, Margin: m, Spent: l.spent, Estimate: est, AtMargin: at,
Dispatch: !l.wrapup && !at && rem.Tokens >= est.Tokens && rem.Turns >= est.Turns}
dispatch := !l.wrapup && !at && rem.Tokens >= est.Tokens && rem.Turns >= est.Turns
avail := Budget{left(rem.Tokens, m.Tokens), left(rem.Turns, m.Turns)}
canPlan := dispatch && avail.Tokens >= pEst.Tokens && avail.Turns >= pEst.Turns
if canPlan && (l.plannerRuns > 0 || l.spent.Tokens > 0 || l.spent.Turns > 0) {
canPlan = (rem.Tokens == Unlimited || (rem.Tokens >= est.Tokens && rem.Tokens-est.Tokens >= pEst.Tokens)) &&
(rem.Turns == Unlimited || (rem.Turns >= est.Turns && rem.Turns-est.Turns >= pEst.Turns))
}
hardExhausted := (l.task.Tokens != Unlimited && l.spent.Tokens >= l.task.Tokens && l.spent.Tokens-l.task.Tokens >= m.Tokens) ||
(l.task.Turns != Unlimited && l.spent.Turns >= l.task.Turns && l.spent.Turns-l.task.Turns >= m.Turns)
return BudgetState{
Task: l.task,
Remaining: rem,
Margin: m,
Spent: l.spent,
Estimate: est,
PlannerEstimate: pEst,
AtMargin: at,
Dispatch: dispatch,
Plan: canPlan,
HardExhausted: hardExhausted,
}
}
// BeginWrapup marks the forced wrap-up; true only for the first caller, so the
@@ -225,21 +264,136 @@ func (m *IntentMeter) Finish() {
m.l.workerSpent = Spend{m.l.workerSpent.Tokens + m.spent.Tokens, m.l.workerSpent.Turns + m.spent.Turns}
}
// PlannerMeter meters one planner round against the task's remaining budget.
// Normal rounds spend only above the wrap-up reserve; forced wrap-up rounds
// spend only within the wrap-up reserve.
type PlannerMeter struct {
l *BudgetLedger
wrapup bool
spent Spend // guarded by l.mu
finished bool // guarded by l.mu
}
// StartPlannerRound opens the meter for one planner round.
func (l *BudgetLedger) StartPlannerRound(wrapup bool) *PlannerMeter {
return &PlannerMeter{l: l, wrapup: wrapup}
}
// Record meters one planner LLM call into this round and the task ledger.
func (m *PlannerMeter) Record(u llm.Usage) {
if m == nil || m.l == nil {
return
}
m.l.mu.Lock()
defer m.l.mu.Unlock()
m.spent, m.l.spent = addUsage(m.spent, u), addUsage(m.l.spent, u)
}
// Remaining is this planner round's effective remaining budget. Normal rounds
// drop to zero once the wrap-up reserve is reached or forced wrap-up begins.
func (m *PlannerMeter) Remaining() Budget {
if m == nil || m.l == nil {
return NewBudget(0, 0)
}
l := m.l
l.mu.Lock()
defer l.mu.Unlock()
rem, res := l.task.Remaining(l.spent), WrapupMargin(l.task)
if m.wrapup {
tokens := rem.Tokens
if res.Tokens > 0 && tokens != Unlimited {
tokens = min(tokens, res.Tokens)
}
turns := rem.Turns
if res.Turns > 0 && turns != Unlimited {
turns = min(turns, res.Turns)
}
return Budget{tokens, turns}
}
if l.wrapup {
return Budget{}
}
return Budget{left(rem.Tokens, res.Tokens), left(rem.Turns, res.Turns)}
}
// Exhausted reports whether this planner round has no budget left in some dimension.
func (m *PlannerMeter) Exhausted() bool {
if m == nil || m.l == nil {
return false
}
r := m.Remaining()
return r.Tokens == 0 || r.Turns == 0
}
// HardExhausted reports whether lifetime task spend has exceeded the configured
// task budget plus its wrap-up reserve (circuit breaker).
func (m *PlannerMeter) HardExhausted() bool {
if m == nil || m.l == nil {
return false
}
return m.l.State().HardExhausted
}
// Finish folds a normal planner round into the task's per-round average.
// Idempotent; wrap-up rounds are excluded so they do not skew normal estimates.
func (m *PlannerMeter) Finish() {
if m == nil || m.l == nil {
return
}
m.l.mu.Lock()
defer m.l.mu.Unlock()
if m.finished || m.wrapup || (m.spent.Tokens == 0 && m.spent.Turns == 0) {
m.finished = true
return
}
m.finished = true
m.l.plannerRuns++
m.l.plannerSpent = Spend{m.l.plannerSpent.Tokens + m.spent.Tokens, m.l.plannerSpent.Turns + m.spent.Turns}
}
// BudgetWrapupBlocks reports whether a worker tool is refused once its budget is
// exhausted: all but the write-back tools, so the run records facts and stops.
func BudgetWrapupBlocks(tool string) bool {
return tool != "record_fact" && tool != "insert_assets" && tool != "report_finding" && tool != "update_finding_report" && tool != "record_coverage"
}
// PlannerWrapupBlocks reports whether a tool is forbidden during a forced budget
// wrap-up planner round: no new intents, no goal/constraint mutations (which
// could revive the task), no scope changes, and no active probing or editing.
func PlannerWrapupBlocks(tool string) bool {
switch tool {
case "add_intent", "set_goals", "set_constraints",
"add_task_scope", "add_company_scope",
"Bash", "WebFetch", "web_search",
"Write", "Edit", "MultiEdit",
"shell_open", "shell_exec", "shell_write", "shell_read", "shell_close":
return true
default:
return false
}
}
// PlannerBudgetExhaustedBlocks reports whether a planner tool is refused once
// the round's budget is exhausted: only final goal judgment and finding
// write-back remain allowed.
func PlannerBudgetExhaustedBlocks(tool string) bool {
return tool != "prove_goal" && tool != "goal_met" && tool != "report_finding" && tool != "update_finding_report"
}
// WorkerBudgetWrapup is returned in place of a refused tool call.
const WorkerBudgetWrapup = "[Budget reached] This intent's token/turn budget is used up; the tool call was not executed. Do not run any more commands or probes. Write back what you identified but have not persisted yet (insert_assets, record_fact, report_finding), then, in a single standalone sentence of plain text, summarize what you did and your key conclusions."
// PlannerBudgetWrapup is returned in place of a refused planner tool call when
// the task budget is exhausted or the forced wrap-up round forbids the tool.
const PlannerBudgetWrapup = "[Budget reached] This task's token/turn budget is used up; the tool call was not executed. Do not dispatch new intents, add goals, or run probes. Only call prove_goal or report_finding/update_finding_report if already proven by existing evidence, then finish with a single standalone sentence summarizing where the task stands."
const plannerBudgetWrapup = "**The task's token/turn budget is exhausted and the task is about to end** (a normal end, not an error). Based on the current facts and findings, make the final goal judgment: call prove_goal for goals proven met by evidence. **Do not generate any new intents** (they will not be executed). Then, in a single standalone sentence of plain text, summarize where the task stands."
// BudgetRound carries one planner round's budget on ctx (zero = no budget).
type BudgetRound struct {
Line string // one-line remaining budget for the planner context
WrapUp bool // the forced wrap-up round
Line string // one-line remaining budget for the planner context
WrapUp bool // the forced wrap-up round
Meter *PlannerMeter // live per-round meter (nil when no budget is configured)
}
type budgetRoundKey struct{}
@@ -250,6 +404,11 @@ func WithBudgetRound(ctx context.Context, r BudgetRound) context.Context {
return context.WithValue(ctx, budgetRoundKey{}, r)
}
func budgetRoundFrom(ctx context.Context) BudgetRound {
r, _ := ctx.Value(budgetRoundKey{}).(BudgetRound)
return r
}
// WithIntentMeter attaches a worker run's meter to ctx (turn clamp).
func WithIntentMeter(ctx context.Context, m *IntentMeter) context.Context {
return context.WithValue(ctx, intentMeterKey{}, m)
@@ -258,7 +417,7 @@ func WithIntentMeter(ctx context.Context, m *IntentMeter) context.Context {
// plannerBudgetBlock is the code-owned budget text appended to the planner's
// situational block (same pattern as the endgame words); empty without a budget.
func plannerBudgetBlock(ctx context.Context) string {
r, _ := ctx.Value(budgetRoundKey{}).(BudgetRound)
r := budgetRoundFrom(ctx)
s := ""
if r.Line != "" {
s += "\n\n" + r.Line
@@ -269,6 +428,77 @@ func plannerBudgetBlock(ctx context.Context) string {
return s
}
// plannerBudgetHooks enforces planner round budget rules in PreToolUse.
type plannerBudgetHooks struct {
inner harness.HookRunner
meter *PlannerMeter
wrapup bool
}
func wrapPlannerBudgetHooks(hooks harness.HookRunner, r BudgetRound) harness.HookRunner {
if r.Meter == nil && !r.WrapUp {
return hooks
}
return plannerBudgetHooks{inner: hooks, meter: r.Meter, wrapup: r.WrapUp}
}
func (h plannerBudgetHooks) PreToolUse(ctx context.Context, name string, input []byte) (bool, string, []byte) {
if h.wrapup && PlannerWrapupBlocks(name) {
return true, PlannerBudgetWrapup, nil
}
if h.meter != nil && PlannerBudgetExhaustedBlocks(name) && h.meter.Exhausted() {
return true, PlannerBudgetWrapup, nil
}
if h.inner != nil {
return h.inner.PreToolUse(ctx, name, input)
}
return false, "", nil
}
func (h plannerBudgetHooks) PostToolUse(ctx context.Context, name string, input, result []byte, isErr bool) {
if h.inner != nil {
h.inner.PostToolUse(ctx, name, input, result, isErr)
}
}
func (h plannerBudgetHooks) Stop(ctx context.Context, messages []llm.Message) (bool, []string, string) {
if h.inner != nil {
return h.inner.Stop(ctx, messages)
}
return false, nil, ""
}
// turnCap is the planner's MaxTurns for this round: its own, clamped by the
// round's remaining turn budget (and tightly bounded on forced budget wrap-up).
func (p *Planner) turnCap(ctx context.Context) int {
r := budgetRoundFrom(ctx)
if r.Meter == nil {
if r.WrapUp && (p.maxTurns <= 0 || BudgetWrapupMaxTurns < p.maxTurns) {
return BudgetWrapupMaxTurns
}
return p.maxTurns
}
rem := r.Meter.Remaining()
capTurns := rem.Turns
if r.WrapUp {
if capTurns == Unlimited {
capTurns = BudgetWrapupMaxTurns
} else {
capTurns = min(capTurns, BudgetWrapupMaxTurns)
}
if rem.Tokens == 0 {
capTurns = min(capTurns, BudgetMarginMinTurns)
}
}
if capTurns == Unlimited {
return p.maxTurns
}
if c := int(max(capTurns, 1)); p.maxTurns <= 0 || c < p.maxTurns {
return c
}
return p.maxTurns
}
// turnCap is the worker's MaxTurns for this run: its own, clamped by the
// intent's effective remaining turns (never 0, which harness reads as unlimited).
func (w *Worker) turnCap(ctx context.Context) int {
+177
View File
@@ -2,6 +2,8 @@ package agent
import (
"context"
"errors"
"iter"
"strings"
"testing"
@@ -155,3 +157,178 @@ func TestRestoreSpendCountsTowardCap(t *testing.T) {
var none *BudgetLedger
none.RestoreSpend(Spend{Tokens: 1, Turns: 1})
}
func TestPlannerRoundReservationAndMetering(t *testing.T) {
// Exact config from #705: task 250k / 150 turns, intent 30k / 10 turns.
// Wrap-up reserve is max(5% = 12.5k, 20k) = 20k tokens, max(5% = 7, 2) = 7 turns.
l := NewBudgetLedger(NewBudget(250_000, 150), NewBudget(30_000, 10))
if st := l.State(); !st.Dispatch || !st.Plan || st.HardExhausted {
t.Fatalf("fresh state = %+v, want Dispatch=true Plan=true HardExhausted=false", st)
}
// Finish one normal planner round costing 35k tokens / 3 turns.
pm := l.StartPlannerRound(false)
pm.Record(llm.Usage{InputTokens: 10_000, OutputTokens: 2_000})
pm.Record(llm.Usage{InputTokens: 12_000, OutputTokens: 1_000})
pm.Record(llm.Usage{InputTokens: 9_000, OutputTokens: 1_000})
pm.Finish()
pm.Finish() // idempotent
st := l.State()
if st.PlannerEstimate != (Spend{35_000, 3}) {
t.Fatalf("PlannerEstimate = %+v, want {35000 3}", st.PlannerEstimate)
}
// Spend up to 195k total (55k remaining): still enough for one 30k worker
// (Dispatch=true), but not enough for a 35k planner round + 30k worker (Plan=false).
spend(l, 160_000)
st = l.State()
if !st.Dispatch || st.AtMargin || st.Plan {
t.Fatalf("at 55k remaining: Dispatch=%v AtMargin=%v Plan=%v, want Dispatch=true AtMargin=false Plan=false",
st.Dispatch, st.AtMargin, st.Plan)
}
// Normal planner round meter stops at the 20k wrap-up reserve (35k available above reserve).
pm2 := l.StartPlannerRound(false)
if got := pm2.Remaining(); got.Tokens != 35_000 || pm2.Exhausted() {
t.Fatalf("normal planner remaining = %+v exhausted=%v, want 35000 tokens", got, pm2.Exhausted())
}
pm2.Record(llm.Usage{InputTokens: 35_000}) // total spent 230k (remaining == 20k reserve)
if !pm2.Exhausted() || pm2.HardExhausted() {
t.Fatalf("at reserve: exhausted=%v hard=%v, want exhausted=true hard=false", pm2.Exhausted(), pm2.HardExhausted())
}
// Concurrent BeginWrapup exhausts any in-flight normal planner meter immediately.
l2 := NewBudgetLedger(NewBudget(250_000, 150), NewBudget(30_000, 10))
inFlight := l2.StartPlannerRound(false)
if inFlight.Exhausted() {
t.Fatal("fresh in-flight planner meter must not be exhausted")
}
l2.BeginWrapup()
if !inFlight.Exhausted() {
t.Fatal("BeginWrapup must exhaust in-flight normal planner meter")
}
// Wrap-up round meter does not alter PlannerEstimate, and HardExhausted flips
// once lifetime spend crosses task + wrap-up reserve (250k + 20k = 270k).
wm := l.StartPlannerRound(true)
if got := wm.Remaining(); got.Tokens != 20_000 || wm.Exhausted() {
t.Fatalf("wrap-up remaining = %+v exhausted=%v, want 20000 tokens", got, wm.Exhausted())
}
wm.Record(llm.Usage{InputTokens: 20_000}) // total spent 250k (remaining == 0, not yet hard ceiling)
if !wm.Exhausted() || wm.HardExhausted() {
t.Fatalf("at 100%% cap: exhausted=%v hard=%v, want exhausted=true hard=false", wm.Exhausted(), wm.HardExhausted())
}
wm.Record(llm.Usage{InputTokens: 20_000}) // total spent 270k == task + margin
if !wm.HardExhausted() || !l.State().HardExhausted {
t.Fatalf("at 270k (task+margin): HardExhausted=false, want true")
}
wm.Finish()
if got := l.State().PlannerEstimate; got != (Spend{35_000, 3}) {
t.Fatalf("wrap-up Finish modified PlannerEstimate to %+v, want {35000 3}", got)
}
}
func TestPlannerBudgetHooksAndTurnCap(t *testing.T) {
// Without a budget on ctx, turnCap and hooks are passthrough.
p := &Planner{maxTurns: 25}
if got := p.turnCap(context.Background()); got != 25 {
t.Fatalf("turnCap without budget = %d, want 25", got)
}
if got := wrapPlannerBudgetHooks(nil, BudgetRound{}); got != nil {
t.Fatalf("wrapPlannerBudgetHooks without budget = %#v, want nil", got)
}
// Normal round with turn budget clamps even unlimited planner maxTurns (0).
l := NewBudgetLedger(NewBudget(250_000, 10), NewBudget(30_000, 5)) // margin = 2 turns, 8 normal turns
pm := l.StartPlannerRound(false)
normalCtx := WithBudgetRound(context.Background(), BudgetRound{Meter: pm})
if got := (&Planner{maxTurns: 0}).turnCap(normalCtx); got != 8 {
t.Fatalf("normal turnCap with unlimited maxTurns = %d, want 8", got)
}
// Wrap-up round clamps unlimited turns to BudgetWrapupMaxTurns, and to
// BudgetMarginMinTurns when token budget is already at zero.
lTokOnly := NewBudgetLedger(NewBudget(100_000, 0), NewBudget(0, 0))
spend(lTokOnly, 80_000) // 20k reserve left
wm := lTokOnly.StartPlannerRound(true)
wrapCtx := WithBudgetRound(context.Background(), BudgetRound{WrapUp: true, Meter: wm})
if got := (&Planner{maxTurns: 0}).turnCap(wrapCtx); got != BudgetWrapupMaxTurns {
t.Fatalf("wrap-up turnCap with reserve remaining = %d, want %d", got, BudgetWrapupMaxTurns)
}
wm.Record(llm.Usage{InputTokens: 20_000}) // tokens now 0
if got := (&Planner{maxTurns: 0}).turnCap(wrapCtx); got != BudgetMarginMinTurns {
t.Fatalf("wrap-up turnCap at 0 tokens = %d, want %d", got, BudgetMarginMinTurns)
}
// Wrap-up hook blocks add_intent/set_goals/Bash even while reserve remains,
// allows read/judgment tools, and once exhausted allows only final judgment tools.
lWrap := NewBudgetLedger(NewBudget(100_000, 0), NewBudget(0, 0))
spend(lWrap, 80_000)
wm2 := lWrap.StartPlannerRound(true)
h := wrapPlannerBudgetHooks(nil, BudgetRound{WrapUp: true, Meter: wm2})
for _, blocked := range []string{"add_intent", "set_goals", "Bash", "WebFetch"} {
if ok, msg, _ := h.PreToolUse(context.Background(), blocked, nil); !ok || msg != PlannerBudgetWrapup {
t.Fatalf("wrap-up PreToolUse(%q) = (%v, %q), want blocked with PlannerBudgetWrapup", blocked, ok, msg)
}
}
for _, allowed := range []string{"node_detail", "prove_goal", "report_finding"} {
if ok, _, _ := h.PreToolUse(context.Background(), allowed, nil); ok {
t.Fatalf("wrap-up PreToolUse(%q) blocked while reserve remains", allowed)
}
}
wm2.Record(llm.Usage{InputTokens: 20_000}) // reserve exhausted
if ok, msg, _ := h.PreToolUse(context.Background(), "node_detail", nil); !ok || msg != PlannerBudgetWrapup {
t.Fatalf("exhausted wrap-up PreToolUse(node_detail) = (%v, %q), want blocked", ok, msg)
}
for _, allowed := range []string{"prove_goal", "goal_met", "report_finding", "update_finding_report"} {
if ok, _, _ := h.PreToolUse(context.Background(), allowed, nil); ok {
t.Fatalf("exhausted PreToolUse(%q) blocked final judgment tool", allowed)
}
}
}
type budgetCountingProvider struct{ calls int }
func (p *budgetCountingProvider) Complete(context.Context, llm.CompletionRequest) (llm.Message, string, llm.Usage, error) {
p.calls++
return llm.Message{Role: llm.RoleAssistant}, "end_turn", llm.Usage{}, nil
}
func (p *budgetCountingProvider) Stream(context.Context, llm.CompletionRequest) iter.Seq2[llm.StreamEvent, error] {
return func(yield func(llm.StreamEvent, error) bool) {
p.calls++
yield(llm.StreamEvent{Type: llm.SEMessageStop, StopReason: "end_turn"}, nil)
}
}
func TestPlanningProviderHardExhaustedRefusesBeforeTransport(t *testing.T) {
l := NewBudgetLedger(NewBudget(100_000, 0), NewBudget(0, 0))
pm := l.StartPlannerRound(false)
inner := &budgetCountingProvider{}
prov := &planningProvider{Provider: inner, budget: pm}
// Below hard ceiling (100k + 20k = 120k): request reaches inner provider.
if _, _, _, err := prov.Complete(context.Background(), llm.CompletionRequest{}); err != nil {
t.Fatalf("below ceiling Complete err = %v", err)
}
if inner.calls != 1 {
t.Fatalf("below ceiling calls = %d, want 1", inner.calls)
}
// Exceed hard ceiling: both Complete and Stream fail closed with 0 transport calls.
pm.Record(llm.Usage{InputTokens: 120_000})
if _, _, _, err := prov.Complete(context.Background(), llm.CompletionRequest{}); !errors.Is(err, ErrTaskBudgetExhausted) {
t.Fatalf("hard-exhausted Complete err = %v, want ErrTaskBudgetExhausted", err)
}
var streamErr error
for _, err := range prov.Stream(context.Background(), llm.CompletionRequest{}) {
streamErr = err
}
if !errors.Is(streamErr, ErrTaskBudgetExhausted) {
t.Fatalf("hard-exhausted Stream err = %v, want ErrTaskBudgetExhausted", streamErr)
}
if inner.calls != 1 {
t.Fatalf("hard-exhausted provider still invoked inner transport: calls=%d, want 1", inner.calls)
}
}
+6 -5
View File
@@ -640,7 +640,7 @@ func (p *Planner) planOnce(ctx context.Context, taskID int64, as *db.AssetStore,
situational += plannerBudgetBlock(ctx)
// Coverage ledger (coverage-only): compact line each round; capped gap list on a
// wrap-up round. Its agent-reported gap lines are framed with this message's env.
budgetRound, _ := ctx.Value(budgetRoundKey{}).(BudgetRound)
budgetRound := budgetRoundFrom(ctx)
situational += tsx.coverageLedgerBlock(tc.Final || budgetRound.WrapUp, env)
// The main run directory <workDir>/tasks/<taskID>/main; create it first.
taskDir := ensureRunDir(p.workDir, taskID, 0)
@@ -660,7 +660,7 @@ func (p *Planner) planOnce(ctx context.Context, taskID int64, as *db.AssetStore,
if tc.DeadlineUnix > 0 {
settle = wrapupSettlementForTask("planner", nil, clamped)
}
observedProvider := &planningProvider{Provider: p.prov}
observedProvider := &planningProvider{Provider: p.prov, budget: budgetRound.Meter}
opts := agentcore.Options{
Provider: observedProvider,
SystemPrompt: system,
@@ -684,8 +684,8 @@ func (p *Planner) planOnce(ctx context.Context, taskID int64, as *db.AssetStore,
BashEnv: proxyEnv(p.proxyAddr, p.proxyCACert), // Bash subcommands go through the proxy + trust its CA by default
WorkingDir: taskDir, // the main run directory <workDir>/tasks/<taskID>/main
ToolOutputDir: TaskToolOutputDir(p.workDir, taskID, taskDir),
MaxTurns: p.maxTurns, // 0 = unlimited (configurable in agent management)
MaxDuration: maxDur, // 0=unlimited; with a deadline = time remaining until it
MaxTurns: p.turnCap(ctx), // 0 = unlimited; clamped by task turn budget and forced wrap-up cap
MaxDuration: maxDur, // 0=unlimited; with a deadline = time remaining until it
Compaction: compactionConfig(p.compactionWindow()),
// Planning todos shared across wake-ups: keep the serial chain across rounds (the session is new; the store isn't).
Todos: p.todoFor(ts.ID()),
@@ -704,6 +704,7 @@ func (p *Planner) planOnce(ctx context.Context, taskID int64, as *db.AssetStore,
if hooks != nil { // typed-nil guard: only set when concrete (avoids harness panic)
opts.Hooks = hooks
}
opts.Hooks = wrapPlannerBudgetHooks(opts.Hooks, budgetRound)
opts.Hooks = SpillHooks(opts.Hooks, opts.ToolOutputDir)
// The session id is the provider-side identity (session header, usage metering)
// with or without persistence; Norma only puts it on ctx when it writes a transcript.
@@ -755,7 +756,7 @@ func (p *Planner) planOnce(ctx context.Context, taskID int64, as *db.AssetStore,
emit(r)
}
})
if err == nil && !tsx.GoalMet && !tc.Final {
if err == nil && !tsx.GoalMet && !tc.Final && !budgetRound.WrapUp && (budgetRound.Meter == nil || !budgetRound.Meter.Exhausted()) {
err = p.checkPlanningProgress(ctx, ts, tsx, before, terminal, observedProvider.refused.Load(), toolErrors)
}
return tsx.GoalMet, tsx.Reason, err
+19 -2
View File
@@ -39,10 +39,13 @@ func (e *PlanningNoProgressError) Error() string {
}
// The wrapper observes explicit provider refusal flags, without interpreting
// natural-language refusal text or retrying it on a different provider.
// natural-language refusal text or retrying it on a different provider. When a
// planner budget meter is attached, it also enforces the lifetime hard ceiling
// before sending any further LLM requests.
type planningProvider struct {
llm.Provider
refused atomic.Bool
budget *PlannerMeter
}
func (p *planningProvider) observe(stop string) {
@@ -51,12 +54,19 @@ func (p *planningProvider) observe(stop string) {
}
}
func (p *planningProvider) Complete(ctx context.Context, req llm.CompletionRequest) (llm.Message, string, llm.Usage, error) {
if p.budget != nil && p.budget.HardExhausted() {
return llm.Message{}, "", llm.Usage{}, ErrTaskBudgetExhausted
}
m, s, u, e := p.Provider.Complete(ctx, req)
p.observe(s)
return m, s, u, e
}
func (p *planningProvider) Stream(ctx context.Context, req llm.CompletionRequest) iter.Seq2[llm.StreamEvent, error] {
return func(yield func(llm.StreamEvent, error) bool) {
if p.budget != nil && p.budget.HardExhausted() {
yield(llm.StreamEvent{}, ErrTaskBudgetExhausted)
return
}
for ev, err := range p.Provider.Stream(ctx, req) {
p.observe(ev.StopReason)
if !yield(ev, err) {
@@ -92,8 +102,12 @@ func (p *Planner) Plan(ctx context.Context, taskID int64, as *db.AssetStore, ts
if err := ctx.Err(); err != nil {
return false, "", err
}
budgetRound := budgetRoundFrom(ctx)
if budgetRound.Meter != nil {
defer budgetRound.Meter.Finish()
}
p.compactor.OnPlannerRound(ctx, ts)
if taskClockFrom(ctx).Final {
if taskClockFrom(ctx).Final || budgetRound.WrapUp {
return p.planOnce(ctx, taskID, as, ts, goal, triggers, hooks, emit)
}
parentCtx := ctx
@@ -124,6 +138,9 @@ func (p *Planner) Plan(ctx context.Context, taskID int64, as *db.AssetStore, ts
if err == nil || met {
return met, reason, err
}
if errors.Is(err, ErrTaskBudgetExhausted) || (budgetRound.Meter != nil && budgetRound.Meter.Exhausted()) {
return false, reason, err
}
if ctx.Err() != nil {
err = ctx.Err()
break
+301
View File
@@ -0,0 +1,301 @@
package db
import (
"bufio"
"fmt"
"net/http"
"net/netip"
"net/textproto"
"strconv"
"strings"
)
// ValidateBrowserOrigin validates an Origin header value as a browser origin
// serialized by RFC 6454 / the Fetch standard. The opaque origin "null" is
// valid and is handled separately from network origins. The Fetch grammar is
// intentionally stricter than a general URL parser: browser serialization is
// lowercase ASCII, uses canonical IP literals, and omits default ports.
func ValidateBrowserOrigin(raw string) error {
if raw == "" {
return fmt.Errorf("origin is empty")
}
if raw == "null" {
return nil
}
for i := 0; i < len(raw); i++ {
if raw[i] < 0x21 || raw[i] > 0x7e {
return fmt.Errorf("origin contains a non-ASCII or whitespace byte")
}
}
separator := strings.Index(raw, "://")
if separator <= 0 {
return fmt.Errorf("origin must be a serialized origin")
}
scheme := raw[:separator]
if !validSerializedScheme(scheme) {
return fmt.Errorf("origin scheme is not a lowercase serialized scheme")
}
authority := raw[separator+3:]
if authority == "" {
return fmt.Errorf("origin host is empty")
}
host, port, hasPort, err := splitSerializedAuthority(authority)
if err != nil {
return err
}
if err := validateSerializedHost(host); err != nil {
return err
}
if hasPort {
if err := validateSerializedPort(port); err != nil {
return err
}
if port == defaultOriginPort(scheme) {
return fmt.Errorf("origin must omit the default port")
}
}
return nil
}
func validSerializedScheme(scheme string) bool {
if scheme == "" || scheme[0] < 'a' || scheme[0] > 'z' {
return false
}
for i := 1; i < len(scheme); i++ {
c := scheme[i]
if (c < 'a' || c > 'z') && (c < '0' || c > '9') && c != '+' && c != '-' && c != '.' {
return false
}
}
return true
}
func splitSerializedAuthority(authority string) (host, port string, hasPort bool, err error) {
if strings.HasPrefix(authority, "[") {
close := strings.IndexByte(authority, ']')
if close < 0 {
return "", "", false, fmt.Errorf("origin IPv6 host is not bracketed")
}
rest := authority[close+1:]
if rest != "" && rest[0] != ':' {
return "", "", false, fmt.Errorf("origin has an invalid authority")
}
if rest != "" {
return authority[1:close], rest[1:], true, nil
}
return authority[1:close], "", false, nil
}
if strings.ContainsAny(authority, "[]/@\\/?#") {
return "", "", false, fmt.Errorf("origin authority contains an invalid character")
}
if colon := strings.IndexByte(authority, ':'); colon >= 0 {
return authority[:colon], authority[colon+1:], true, nil
}
return authority, "", false, nil
}
func validateSerializedHost(host string) error {
if host == "" {
return fmt.Errorf("origin host is empty")
}
if strings.Contains(host, ":") {
addr, err := netip.ParseAddr(host)
if err != nil || !addr.Is6() || addr.String() != host {
return fmt.Errorf("origin IPv6 host is not canonical")
}
return nil
}
// The Fetch host parser runs the IPv4 parser whenever the last label is a
// number, and rejects the host when that fails. Legacy spellings such as
// 0x7f.1, 1.2.3.4.5 or 2130706433 are parsed by a browser into a dotted
// quad and serialized in that form, so they never appear as an origin. A
// numeric host is therefore only serialized when it is already canonical.
if labels := strings.Split(host, "."); isNumericLabel(labels[len(labels)-1]) {
addr, err := netip.ParseAddr(host)
if err != nil || !addr.Is4() || addr.String() != host {
return fmt.Errorf("origin IPv4 host is not canonical")
}
return nil
}
for _, label := range strings.Split(host, ".") {
if label == "" || !isSerializedDomainLabel(label) {
return fmt.Errorf("origin host is not a serialized domain")
}
}
return nil
}
// isNumericLabel reports whether label is one or more ASCII digits. A
// non-empty all-digit label sends the Fetch host parser down the IPv4 path.
func isNumericLabel(label string) bool {
if label == "" {
return false
}
for i := 0; i < len(label); i++ {
if label[i] < '0' || label[i] > '9' {
return false
}
}
return true
}
func isSerializedDomainLabel(label string) bool {
if !isLowerAlphaNum(label[0]) || !isLowerAlphaNum(label[len(label)-1]) {
return false
}
for i := 1; i < len(label)-1; i++ {
if !isLowerAlphaNum(label[i]) && label[i] != '-' {
return false
}
}
return true
}
func isLowerAlphaNum(c byte) bool {
return (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9')
}
func validateSerializedPort(port string) error {
if port == "" || len(port) > 5 || (len(port) > 1 && port[0] == '0') {
return fmt.Errorf("origin port is not a serialized port")
}
for i := 0; i < len(port); i++ {
if port[i] < '0' || port[i] > '9' {
return fmt.Errorf("origin port is not a serialized port")
}
}
n, err := strconv.ParseUint(port, 10, 16)
if err != nil || n > 65535 {
return fmt.Errorf("origin port is out of range")
}
return nil
}
func defaultOriginPort(scheme string) string {
switch scheme {
case "http", "ws":
return "80"
case "https", "wss":
return "443"
case "ftp":
return "21"
default:
return ""
}
}
// ValidateCORSProof validates the request Origin and the response CORS
// headers that claim to authorize it.
func ValidateCORSProof(reqHeaders, respHeaders http.Header) error {
origin, err := singleHeaderValue(reqHeaders, "Origin")
if err != nil {
return fmt.Errorf("invalid Origin header: %w", err)
}
if err := ValidateBrowserOrigin(origin); err != nil {
return fmt.Errorf("invalid Origin header: %w", err)
}
acao, err := singleHeaderValue(respHeaders, "Access-Control-Allow-Origin")
if err != nil {
return fmt.Errorf("invalid Access-Control-Allow-Origin header: %w", err)
}
acao = strings.TrimSpace(acao)
if acao == "" {
return fmt.Errorf("Access-Control-Allow-Origin is empty")
}
acac, err := singleHeaderValueOptional(respHeaders, "Access-Control-Allow-Credentials")
if err != nil {
return fmt.Errorf("invalid Access-Control-Allow-Credentials header: %w", err)
}
if acao == "*" && strings.EqualFold(strings.TrimSpace(acac), "true") {
return fmt.Errorf("wildcard Access-Control-Allow-Origin is invalid with credentials")
}
if acao != "*" && acao != origin {
return fmt.Errorf("Access-Control-Allow-Origin %q does not match Origin %q", acao, origin)
}
return nil
}
// ValidateCORSProofHeads parses the raw request and response head blocks used
// by traffic evidence and validates their CORS headers.
func ValidateCORSProofHeads(reqHead, respHead string) error {
reqHeaders, err := parseStoredHeaders(reqHead)
if err != nil {
return fmt.Errorf("invalid request head: %w", err)
}
respHeaders, err := parseStoredHeaders(respHead)
if err != nil {
return fmt.Errorf("invalid response head: %w", err)
}
return ValidateCORSProof(reqHeaders, respHeaders)
}
// IsCORSFinding reports whether vulnclass identifies a CORS finding. Finding
// class is the canonical vulnerability type stored on a findings row; task
// categories are not part of this decision.
func IsCORSFinding(vulnClass string) bool {
for _, token := range strings.FieldsFunc(strings.ToLower(strings.TrimSpace(vulnClass)), func(r rune) bool {
return r < 'a' || r > 'z'
}) {
if token == "cors" {
return true
}
}
return false
}
func singleHeaderValue(headers http.Header, name string) (string, error) {
values := headerValues(headers, name)
if len(values) == 0 {
return "", fmt.Errorf("header is missing")
}
if len(values) != 1 {
return "", fmt.Errorf("header has multiple values")
}
return values[0], nil
}
func singleHeaderValueOptional(headers http.Header, name string) (string, error) {
values := headerValues(headers, name)
if len(values) == 0 {
return "", nil
}
if len(values) != 1 {
return "", fmt.Errorf("header has multiple values")
}
return values[0], nil
}
// headerValues performs a case-insensitive lookup even for maps constructed
// directly by callers rather than through Header.Set, while preserving duplicate
// values so malformed CORS responses fail closed.
func headerValues(headers http.Header, name string) []string {
var values []string
for key, current := range headers {
if strings.EqualFold(key, name) {
values = append(values, current...)
}
}
return values
}
// parseStoredHeaders parses the first-line-prefixed raw header format used by
// traffic evidence. MIMEHeader is deliberately used here instead of splitting
// on colons so folded/malformed header lines follow the standard parser.
func parseStoredHeaders(raw string) (http.Header, error) {
raw = strings.ReplaceAll(raw, "\r\n", "\n")
raw = strings.ReplaceAll(raw, "\r", "\n")
lineEnd := strings.IndexByte(raw, '\n')
if lineEnd < 0 {
return nil, fmt.Errorf("missing HTTP start line")
}
headerBlock := strings.ReplaceAll(raw[lineEnd+1:], "\n", "\r\n") + "\r\n"
mime, err := textproto.NewReader(bufio.NewReader(strings.NewReader(headerBlock))).ReadMIMEHeader()
if err != nil {
return nil, err
}
return http.Header(mime), nil
}
+137
View File
@@ -0,0 +1,137 @@
package db
import (
"net/http"
"strings"
"testing"
)
func TestValidateBrowserOrigin(t *testing.T) {
tests := []struct {
name string
origin string
wantOK bool
}{
{name: "https", origin: "https://evil.com", wantOK: true},
{name: "http port", origin: "http://attacker.example:8443", wantOK: true},
{name: "custom scheme", origin: "chrome-extension://abcdefghijklmnop", wantOK: true},
{name: "IPv6", origin: "https://[2001:db8::1]", wantOK: true},
{name: "opaque", origin: "null", wantOK: true},
{name: "canonical IPv4", origin: "https://127.0.0.1", wantOK: true},
{name: "canonical IPv4 zero", origin: "https://0.0.0.0", wantOK: true},
{name: "canonical IPv4 with port", origin: "http://192.0.2.10:8080", wantOK: true},
{name: "IPv4 too many labels", origin: "https://1.2.3.4.5"},
{name: "IPv4 hex label", origin: "https://0x7f.1"},
{name: "IPv4 out of range", origin: "https://999.1.1.1"},
{name: "IPv4 single integer", origin: "https://2130706433"},
{name: "IPv4 leading zero label", origin: "https://1.2.3.04"},
{name: "numeric last domain label", origin: "https://evil.123"},
{name: "missing scheme", origin: "evil.com"},
{name: "trailing slash", origin: "https://evil.com/"},
{name: "empty fragment", origin: "https://evil.com#"},
{name: "path", origin: "https://evil.com/path"},
{name: "query", origin: "https://evil.com?x=1"},
{name: "fragment", origin: "https://evil.com#frag"},
{name: "userinfo", origin: "https://user:pass@evil.com"},
{name: "internal whitespace", origin: "https://target.com\tevil.com"},
{name: "uppercase scheme", origin: "HTTPS://evil.com"},
{name: "uppercase host", origin: "https://EVIL.com"},
{name: "explicit default port", origin: "https://evil.com:443"},
{name: "leading zero port", origin: "https://evil.com:0443"},
{name: "empty port", origin: "https://evil.com:"},
{name: "invalid IPv6 serialization", origin: "https://[2001:0DB8::1]"},
{name: "domain underscore", origin: "https://evil_site.com"},
{name: "unicode host", origin: "https://例え.テスト"},
{name: "javascript", origin: "javascript:alert(1)"},
{name: "empty", origin: ""},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := ValidateBrowserOrigin(tt.origin)
if tt.wantOK && err != nil {
t.Fatalf("ValidateBrowserOrigin(%q) = %v, want success", tt.origin, err)
}
if !tt.wantOK && err == nil {
t.Fatalf("ValidateBrowserOrigin(%q) succeeded, want error", tt.origin)
}
})
}
}
func TestValidateCORSProof(t *testing.T) {
tests := []struct {
name string
origin string
acao string
acac string
wantOK bool
wantReason string
}{
{name: "wildcard without credentials", origin: "https://evil.com", acao: "*", wantOK: true},
{name: "wildcard credentials", origin: "https://evil.com", acao: "*", acac: "TrUe", wantReason: "wildcard"},
{name: "mismatch", origin: "https://evil.com", acao: "https://other.example", wantReason: "does not match"},
{name: "missing ACAO", origin: "https://evil.com", wantReason: "missing"},
{name: "valid reflection with credentials", origin: "https://evil.com", acao: "https://evil.com", acac: "true", wantOK: true},
{name: "opaque reflection", origin: "null", acao: "null", wantOK: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req := http.Header{}
req.Set("Origin", tt.origin)
resp := http.Header{}
if tt.acao != "" {
resp.Set("Access-Control-Allow-Origin", tt.acao)
}
if tt.acac != "" {
resp.Set("Access-Control-Allow-Credentials", tt.acac)
}
err := ValidateCORSProof(req, resp)
if tt.wantOK && err != nil {
t.Fatalf("ValidateCORSProof() = %v, want success", err)
}
if !tt.wantOK {
if err == nil {
t.Fatal("ValidateCORSProof() succeeded, want error")
}
if !strings.Contains(strings.ToLower(err.Error()), strings.ToLower(tt.wantReason)) {
t.Fatalf("error %q does not contain %q", err, tt.wantReason)
}
}
})
}
}
func TestValidateCORSProofHeads(t *testing.T) {
err := ValidateCORSProofHeads(
"GET / HTTP/1.1\nOrigin: https://evil.com\n",
"HTTP/1.1 200 OK\nAccess-Control-Allow-Origin: https://evil.com\nAccess-Control-Allow-Credentials: true\n",
)
if err != nil {
t.Fatalf("ValidateCORSProofHeads() = %v, want success", err)
}
err = ValidateCORSProofHeads(
"GET / HTTP/1.1\nOrigin: https://evil.com\n",
"HTTP/1.1 200 OK\nAccess-Control-Allow-Origin: https://other.example\n",
)
if err == nil || !strings.Contains(err.Error(), "does not match") {
t.Fatalf("invalid head proof error = %v, want mismatch", err)
}
}
func TestIsCORSFinding(t *testing.T) {
for _, tc := range []struct {
class string
want bool
}{
{class: "CORS", want: true},
{class: "cors misconfiguration", want: true},
{class: "cors_misconfiguration", want: true},
{class: "course injection", want: false},
{class: "XSS", want: false},
} {
if got := IsCORSFinding(tc.class); got != tc.want {
t.Errorf("IsCORSFinding(%q) = %v, want %v", tc.class, got, tc.want)
}
}
}
+98
View File
@@ -0,0 +1,98 @@
package egress
import (
"bytes"
"fmt"
"io"
"net/http"
"strings"
)
// BotCheckpoint identifies a non-retryable JS bot-mitigation checkpoint. It is
// returned as an error so HTTP tools that omit response headers still surface
// the browser fallback guidance to the agent.
type BotCheckpoint struct {
Provider string
Reason string
}
func (c BotCheckpoint) Error() string {
return fmt.Sprintf("egress: non-retryable %s JS bot-mitigation checkpoint (%s); stop raw HTTP retries and use browser tooling (playwright-cli / Playwright MCP)", c.Provider, c.Reason)
}
// DetectBotCheckpoint recognizes explicit mitigation headers or Vercel HTML
// markers on 403/429/503 responses. Generic CDN headers and Retry-After alone
// are not evidence of a JS checkpoint.
func DetectBotCheckpoint(statusCode int, h http.Header, bodyPrefix string) (BotCheckpoint, bool) {
if !botCheckpointStatus(statusCode) {
return BotCheckpoint{}, false
}
switch {
case checkpointHeader(h, "X-Vercel-Mitigated", ""):
return BotCheckpoint{Provider: "vercel", Reason: "x-vercel-mitigated"}, true
case checkpointHeader(h, "Cf-Mitigated", "challenge"):
return BotCheckpoint{Provider: "cloudflare", Reason: "cf-mitigated"}, true
case checkpointHeader(h, "X-Amzn-Waf-Action", "challenge"):
return BotCheckpoint{Provider: "aws-waf", Reason: "x-amzn-waf-action"}, true
}
bodyPrefix = strings.ToLower(bodyPrefix)
if strings.Contains(bodyPrefix, "vercel security checkpoint") || strings.Contains(bodyPrefix, "/.well-known/vercel/security/request-challenge") {
return BotCheckpoint{Provider: "vercel", Reason: "html-challenge-marker"}, true
}
return BotCheckpoint{}, false
}
func botCheckpointStatus(code int) bool {
return code == http.StatusForbidden || code == http.StatusTooManyRequests || code == http.StatusServiceUnavailable
}
// An empty value matches header presence, including an empty field value.
// Iterate keys as well as values to support non-canonical RoundTripper headers.
func checkpointHeader(h http.Header, name, value string) bool {
for k, values := range h {
if !strings.EqualFold(k, name) {
continue
}
if value == "" {
return true
}
for _, v := range values {
if strings.EqualFold(strings.TrimSpace(v), value) {
return true
}
}
}
return false
}
const maxCheckpointBodyPrefix = 8 << 10
func detectResponseBotCheckpoint(resp *http.Response) (BotCheckpoint, bool) {
c, ok := DetectBotCheckpoint(resp.StatusCode, resp.Header, "")
if ok || !botCheckpointStatus(resp.StatusCode) || resp.Body == nil {
return c, ok
}
// Only peek when headers are inconclusive. Replay both bytes and any read
// error so an ordinary error response retains its body and Close contract.
prefix, err := io.ReadAll(io.LimitReader(resp.Body, maxCheckpointBodyPrefix))
resp.Body = &checkpointBody{ReadCloser: resp.Body, prefix: bytes.NewReader(prefix), err: err}
return DetectBotCheckpoint(resp.StatusCode, resp.Header, string(prefix))
}
type checkpointBody struct {
io.ReadCloser
prefix *bytes.Reader
err error
}
func (b *checkpointBody) Read(p []byte) (int, error) {
if b.prefix.Len() > 0 {
return b.prefix.Read(p)
}
if b.err != nil {
err := b.err
b.err = nil
return 0, err
}
return b.ReadCloser.Read(p)
}
+152
View File
@@ -0,0 +1,152 @@
package egress
import (
"errors"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func TestDetectBotCheckpoint(t *testing.T) {
for _, code := range []int{http.StatusForbidden, http.StatusTooManyRequests, http.StatusServiceUnavailable} {
t.Run(http.StatusText(code), func(t *testing.T) {
for _, tc := range []struct {
name string
h http.Header
body string
want BotCheckpoint
}{
{name: "vercel challenge", h: http.Header{"X-Vercel-Mitigated": {"challenge"}}, want: BotCheckpoint{"vercel", "x-vercel-mitigated"}},
{name: "vercel deny mixed case", h: http.Header{"x-vErCeL-mItIgAtEd": {"DeNy"}}, want: BotCheckpoint{"vercel", "x-vercel-mitigated"}},
{name: "vercel empty header", h: http.Header{"X-Vercel-Mitigated": {""}}, want: BotCheckpoint{"vercel", "x-vercel-mitigated"}},
{name: "cloudflare", h: http.Header{"Cf-Mitigated": {"challenge"}}, want: BotCheckpoint{"cloudflare", "cf-mitigated"}},
{name: "cloudflare mixed case and whitespace", h: http.Header{"cF-mItIgAtEd": {" CHALLENGE "}}, want: BotCheckpoint{"cloudflare", "cf-mitigated"}},
{name: "cloudflare multiple values", h: http.Header{"Cf-Mitigated": {"other", "challenge"}}, want: BotCheckpoint{"cloudflare", "cf-mitigated"}},
{name: "aws waf", h: http.Header{"X-Amzn-Waf-Action": {"challenge"}}, want: BotCheckpoint{"aws-waf", "x-amzn-waf-action"}},
{name: "aws waf mixed case and whitespace", h: http.Header{"x-amzn-waf-action": {" Challenge "}}, want: BotCheckpoint{"aws-waf", "x-amzn-waf-action"}},
{name: "vercel title", body: "<title>VeRcEl SeCuRiTy ChEcKpOiNt</title>", want: BotCheckpoint{"vercel", "html-challenge-marker"}},
{name: "vercel script", body: `<script src="/.well-known/vercel/security/request-challenge"></script>`, want: BotCheckpoint{"vercel", "html-challenge-marker"}},
{name: "vercel script mixed case", body: "/.WELL-KNOWN/VERCEL/SECURITY/REQUEST-CHALLENGE", want: BotCheckpoint{"vercel", "html-challenge-marker"}},
{name: "headers take precedence", h: http.Header{"Cf-Mitigated": {"challenge"}}, body: "Vercel Security Checkpoint", want: BotCheckpoint{"cloudflare", "cf-mitigated"}},
{name: "plain error", body: "Forbidden"},
{name: "ordinary rate limit", h: http.Header{"Retry-After": {"1"}}, body: "Too Many Requests"},
{name: "cloudflare CDN only", h: http.Header{"Server": {"cloudflare"}, "Cf-Ray": {"12345"}}},
{name: "vercel CDN only", h: http.Header{"Server": {"Vercel"}, "X-Vercel-Id": {"12345"}}},
{name: "aws CDN only", h: http.Header{"Server": {"CloudFront"}, "X-Amzn-Requestid": {"12345"}}},
{name: "cloudflare not challenge", h: http.Header{"Cf-Mitigated": {"deny"}}},
{name: "cloudflare empty", h: http.Header{"Cf-Mitigated": {""}}},
{name: "aws captcha not JS challenge", h: http.Header{"X-Amzn-Waf-Action": {"captcha"}}},
{name: "aws substring not challenge", h: http.Header{"X-Amzn-Waf-Action": {"not-challenge"}}},
{name: "generic JS page", body: "Please enable JavaScript to continue"},
} {
t.Run(tc.name, func(t *testing.T) {
got, ok := DetectBotCheckpoint(code, tc.h, tc.body)
if got != tc.want || ok != (tc.want.Provider != "") {
t.Fatalf("DetectBotCheckpoint = %+v, %v; want %+v, %v", got, ok, tc.want, tc.want.Provider != "")
}
})
}
})
}
}
func TestDetectBotCheckpointOtherStatuses(t *testing.T) {
for _, code := range []int{http.StatusOK, http.StatusFound, http.StatusNotFound, http.StatusInternalServerError} {
for _, h := range []http.Header{
nil,
{"X-Vercel-Mitigated": {"challenge"}},
{"Cf-Mitigated": {"challenge"}},
{"X-Amzn-Waf-Action": {"challenge"}},
} {
if got, ok := DetectBotCheckpoint(code, h, "Vercel Security Checkpoint"); ok || got != (BotCheckpoint{}) {
t.Errorf("status %d, headers %v: got %+v, %v; want no checkpoint", code, h, got, ok)
}
}
}
}
type checkpointTestBody struct {
io.Reader
reads, bytes, closes int
}
func (b *checkpointTestBody) Read(p []byte) (int, error) {
b.reads++
n, err := b.Reader.Read(p)
b.bytes += n
return n, err
}
func (b *checkpointTestBody) Close() error { b.closes++; return nil }
type checkpointTestTransport func(*http.Request) (*http.Response, error)
func (f checkpointTestTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
func TestCheckpointHeadersSkipBodyAndReleaseSlots(t *testing.T) {
for _, method := range []string{http.MethodGet, http.MethodHead, http.MethodOptions, http.MethodPost} {
t.Run(method, func(t *testing.T) {
body := &checkpointTestBody{Reader: strings.NewReader("body must not be read")}
g := New(open)
tr := g.Transport("test", checkpointTestTransport(func(req *http.Request) (*http.Response, error) {
return &http.Response{StatusCode: http.StatusTooManyRequests, Header: http.Header{"X-Vercel-Mitigated": {"challenge"}}, Body: body, Request: req}, nil
}))
req := httptest.NewRequest(method, "https://example.test/", nil)
resp, err := tr.RoundTrip(req)
var checkpoint BotCheckpoint
if resp != nil || !errors.As(err, &checkpoint) || checkpoint.Provider != "vercel" {
t.Fatalf("response = %v, error = %v; want vercel checkpoint error", resp, err)
}
if body.reads != 0 || body.closes != 1 {
t.Fatalf("body reads=%d closes=%d; want 0, 1", body.reads, body.closes)
}
if s := g.Snapshot(); len(s) != 1 || s[0].RPM != 1 || s[0].Inflight != 0 {
t.Fatalf("snapshot = %+v; want one attempt and no occupied slots", s)
}
})
}
}
func TestCheckpointPeekBoundedAndPreservesBody(t *testing.T) {
// A marker beyond the peek limit must not trigger detection or be consumed.
want := strings.Repeat("x", maxCheckpointBodyPrefix) + "Vercel Security Checkpoint"
body := &checkpointTestBody{Reader: strings.NewReader(want)}
resp := &http.Response{StatusCode: http.StatusForbidden, Body: body, ContentLength: int64(len(want))}
if c, ok := detectResponseBotCheckpoint(resp); ok {
t.Fatalf("marker beyond prefix detected: %+v", c)
}
if body.bytes != maxCheckpointBodyPrefix || body.closes != 0 || resp.ContentLength != int64(len(want)) {
t.Fatalf("peek: bytes=%d closes=%d content-length=%d", body.bytes, body.closes, resp.ContentLength)
}
got, err := io.ReadAll(resp.Body)
if err != nil || string(got) != want {
t.Fatalf("body not preserved: len=%d, err=%v", len(got), err)
}
resp.Body.Close()
if body.closes != 1 {
t.Fatalf("body closed %d times; want 1", body.closes)
}
}
type checkpointReadError struct{ err error }
func (r checkpointReadError) Read([]byte) (int, error) { return 0, r.err }
func TestCheckpointPeekPreservesReadError(t *testing.T) {
wantErr := errors.New("body read failed")
body := &checkpointTestBody{Reader: io.MultiReader(strings.NewReader("partial body"), checkpointReadError{wantErr})}
resp := &http.Response{StatusCode: http.StatusForbidden, Body: body}
if c, ok := detectResponseBotCheckpoint(resp); ok {
t.Fatalf("unexpected checkpoint: %+v", c)
}
got, err := io.ReadAll(resp.Body)
if string(got) != "partial body" || !errors.Is(err, wantErr) {
t.Fatalf("body = %q, error = %v; want partial body and original read error", got, err)
}
resp.Body.Close()
if body.closes != 1 {
t.Fatalf("body closed %d times; want 1", body.closes)
}
}
+7 -2
View File
@@ -525,8 +525,9 @@ type stored struct {
// send makes one request within the host's limits. A 429/503 pauses the host
// and, for a bodiless GET/HEAD/OPTIONS, is retried up to MaxRetries times; a
// request that may change state is never retried. The slots are held until
// the response body is closed.
// request that may change state is never retried. JS bot checkpoints on
// 403/429/503 instead close the body and return a BotCheckpoint error before
// backoff. The slots are held until the response body is closed.
func (t *transport) send(req *http.Request) (*http.Response, error) {
host := HostKey(req.URL)
for attempt := 0; ; attempt++ {
@@ -540,6 +541,10 @@ func (t *transport) send(req *http.Request) (*http.Response, error) {
return nil, err
}
resp.Body = &releaseBody{resp.Body, release}
if checkpoint, ok := detectResponseBotCheckpoint(resp); ok {
resp.Body.Close()
return nil, checkpoint
}
if resp.StatusCode != http.StatusTooManyRequests && resp.StatusCode != http.StatusServiceUnavailable {
return resp, nil
}
+75
View File
@@ -2,6 +2,7 @@ package egress
import (
"context"
"errors"
"io"
"net/http"
"net/http/httptest"
@@ -151,6 +152,80 @@ func TestBackoff(t *testing.T) {
}
}
func TestBotCheckpointStopsRetries(t *testing.T) {
for _, code := range []int{http.StatusForbidden, http.StatusTooManyRequests, http.StatusServiceUnavailable} {
t.Run(http.StatusText(code), func(t *testing.T) {
for _, tc := range []struct {
name, header, value, body, provider string
}{
{"vercel", "X-Vercel-Mitigated", "challenge", "checkpoint body", "vercel"},
{"vercel deny", "X-Vercel-Mitigated", "deny", "checkpoint body", "vercel"},
{"cloudflare", "Cf-Mitigated", "ChAlLeNgE", "checkpoint body", "cloudflare"},
{"aws waf", "X-Amzn-Waf-Action", "CHALLENGE", "checkpoint body", "aws-waf"},
{"vercel title", "", "", "<title>Vercel Security Checkpoint</title>", "vercel"},
{"vercel script", "", "", `<script src="/.well-known/vercel/security/request-challenge"></script>`, "vercel"},
{"ordinary error", "", "", "ordinary error body", ""},
} {
t.Run(tc.name, func(t *testing.T) {
for _, shared := range []bool{false, true} {
name := "unshared"
ctx := t.Context()
if shared {
name, ctx = "task", task("checkpoint")
}
t.Run(name, func(t *testing.T) {
g := New(open)
s := newServer(t, 0, func(_ int64, w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Retry-After", "0")
if tc.header != "" {
w.Header().Set(tc.header, tc.value)
}
w.WriteHeader(code)
_, _ = io.WriteString(w, tc.body)
})
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, s.URL, nil)
resp, err := (&http.Client{Transport: g.Transport("test", nil)}).Do(req)
wantAttempts := int64(1)
if tc.provider != "" {
var checkpoint BotCheckpoint
if resp != nil || !errors.As(err, &checkpoint) || checkpoint.Provider != tc.provider {
t.Fatalf("response=%v error=%v; want %s checkpoint error", resp, err, tc.provider)
}
for _, hint := range []string{"non-retryable", "stop raw HTTP retries", "playwright-cli", "Playwright MCP"} {
if !strings.Contains(err.Error(), hint) {
t.Errorf("error %q missing guidance %q", err, hint)
}
}
} else {
if err != nil {
t.Fatal(err)
}
got, readErr := io.ReadAll(resp.Body)
resp.Body.Close()
if resp.StatusCode != code || string(got) != tc.body || readErr != nil {
t.Fatalf("ordinary response changed: status=%d body=%q error=%v", resp.StatusCode, got, readErr)
}
if code != http.StatusForbidden {
wantAttempts += int64(open.MaxRetries)
}
}
if s.hits.Load() != wantAttempts {
t.Errorf("attempts=%d; want %d", s.hits.Load(), wantAttempts)
}
if snapshot := g.Snapshot(); len(snapshot) != 1 || snapshot[0].RPM != int(wantAttempts) || snapshot[0].Inflight != 0 {
t.Errorf("snapshot=%+v; want %d sends and no occupied slots", snapshot, wantAttempts)
}
if h := g.host(HostKey(req.URL)); (tc.provider != "" || code == http.StatusForbidden) && !h.notBefore.IsZero() {
t.Errorf("unexpected host backoff: %v", h.notBefore)
}
})
}
})
}
})
}
}
func TestDedupeAndCache(t *testing.T) {
p := open
p.CacheTTL = 200 * time.Millisecond
+44
View File
@@ -0,0 +1,44 @@
package server
import (
"fmt"
"strings"
"testing"
"github.com/Autumn-27/artex/db"
)
func TestCORSVerificationRejectsInvalidBoundProof(t *testing.T) {
s, finding, request := trafficEvidenceServer(t)
if _, err := s.m.pg.Exec(`UPDATE findings SET vulnclass='CORS' WHERE id=$1`, finding.FindingID); err != nil {
t.Fatal(err)
}
trafficID := "cors-invalid-proof"
_, err := s.m.traffic.DB().Exec(`INSERT INTO exchanges(id,ts,host,method,url_template,url,status,content_type,req_len,resp_len,path)
VALUES(?,1,'evidence.local','GET','/','https://evidence.local/',200,'text/plain',0,?,'')`, trafficID, len("cors proof body"))
if err != nil {
t.Fatal(err)
}
_, err = s.m.traffic.DB().Exec(`INSERT INTO exchange_bodies(id,req_head,resp_head,req_body,resp_body)
VALUES(?, ?, ?, ?, ?)`, trafficID,
"GET / HTTP/1.1\nOrigin: https://evil.com\n",
"HTTP/1.1 200 OK\nAccess-Control-Allow-Origin: https://other.example\n",
[]byte{}, []byte("cors proof body"))
if err != nil {
t.Fatal(err)
}
bindPath := fmt.Sprintf("/api/exploration/findings/%d/traffic", finding.FindingID)
if w := request("POST", bindPath, fmt.Sprintf(`{"traffic_refs":[{"traffic_id":%q,"role":"proof"}]}`, trafficID)); w.Code != 200 {
t.Fatalf("bind: %d %s", w.Code, w.Body)
}
msg, isErr := updateReport(t, s, finding.NodeID, `,"poe_level":3,"evidence_quotes":["cors proof body"]`)
if isErr || !strings.Contains(msg, "verification: unverified") {
t.Fatalf("unexpected result: err=%v %q", isErr, msg)
}
status, _, note, report := storedVerification(t, s, finding.FindingID)
if status != db.VerificationUnverified || !strings.Contains(note, "CORS proof validation failed") || report == "" {
t.Fatalf("stored: status=%s note=%q report=%q", status, note, report)
}
}
+1 -1
View File
@@ -1219,7 +1219,7 @@ func (e *Engine) plannerLoop(ctx context.Context, t *Task) {
if fp, err := t.Store.OpenGoalFingerprint(); err == nil {
e.goalFP.Store(t.ID, fp)
}
if e.budgetBlocksClaim(t.ID) {
if e.budgetBlocksPlan(t.ID) {
t.Notify() // this round crossed the budget: settle on the next round, not at the next heartbeat
}
e.touch(t.ID)
+26 -9
View File
@@ -50,9 +50,9 @@ func (e *Engine) seedBudget(taskID string, ledger *agent.BudgetLedger) {
}
// budgetStop is the enforcement point of a planner round: it logs the remaining
// budget and, once no worker can be dispatched any more, starts the forced
// wrap-up (exactly once: the settle sequence with the budget words) and reports
// that the normal round must not run. ctx is the planner loop's context.
// budget and, once no planner+worker cycle can be afforded any more, starts the
// forced wrap-up (exactly once: the settle sequence with the budget words) and
// reports that the normal round must not run. ctx is the planner loop's context.
func (e *Engine) budgetStop(ctx context.Context, t *Task) bool {
l := e.budgetFor(t.ID)
if l == nil {
@@ -60,26 +60,28 @@ func (e *Engine) budgetStop(ctx context.Context, t *Task) bool {
}
st := l.State()
log.Printf("[budget] task %s planner round: %s", t.ID, st.Line())
if st.Dispatch {
if st.Plan {
return false
}
if l.BeginWrapup() {
log.Printf("[budget] task %s cannot afford another worker (estimate %d tokens / %d turns), forced wrap-up",
t.ID, st.Estimate.Tokens, st.Estimate.Turns)
log.Printf("[budget] task %s cannot afford another planner+worker cycle (planner estimate %d tokens / %d turns, worker estimate %d tokens / %d turns), forced wrap-up",
t.ID, st.PlannerEstimate.Tokens, st.PlannerEstimate.Turns, st.Estimate.Tokens, st.Estimate.Turns)
e.settleTask(ctx, t, true)
}
return true
}
// budgetRoundCtx attaches a planner round's budget (the one-line remaining
// budget, the wrap-up flag) and meters the round's own calls into the task.
// budget, the wrap-up flag, and its per-round meter) and meters the round's
// own calls into both the round meter and the task ledger.
func (e *Engine) budgetRoundCtx(ctx context.Context, t *Task, wrapup bool) context.Context {
l := e.budgetFor(t.ID)
if l == nil {
return ctx
}
ctx = agent.WithBudgetRound(ctx, agent.BudgetRound{Line: l.State().Line(), WrapUp: wrapup})
return llmrec.WithUsageSink(ctx, l.Record)
m := l.StartPlannerRound(wrapup)
ctx = agent.WithBudgetRound(ctx, agent.BudgetRound{Line: l.State().Line(), WrapUp: wrapup, Meter: m})
return llmrec.WithUsageSink(ctx, m.Record)
}
// budgetBlocksClaim reports whether a worker must not claim a new intent: the
@@ -89,6 +91,21 @@ func (e *Engine) budgetBlocksClaim(taskID string) bool {
return l != nil && !l.State().Dispatch
}
// budgetBlocksPlan reports whether a normal planner round (or terminal revival)
// must not start: the remaining task budget cannot cover a planner+worker cycle,
// or the wrap-up has already started.
func (e *Engine) budgetBlocksPlan(taskID string) bool {
l := e.budgetFor(taskID)
return l != nil && !l.State().Plan
}
// budgetHardExhausted reports whether lifetime task spend has exceeded the
// configured task budget plus its wrap-up reserve (circuit breaker).
func (e *Engine) budgetHardExhausted(taskID string) bool {
l := e.budgetFor(taskID)
return l != nil && l.State().HardExhausted
}
// budgetIntent opens the meter of one worker run: ctx meters its calls and
// clamps its turns; the returned meter feeds the tool hook. nil = no budget.
func (e *Engine) budgetIntent(ctx context.Context, taskID string) (context.Context, *agent.IntentMeter) {
+147
View File
@@ -2,12 +2,15 @@ package server
import (
"context"
"errors"
"strconv"
"strings"
"testing"
"time"
"github.com/Autumn-27/artex/agent"
pgdb "github.com/Autumn-27/artex/db"
"github.com/Autumn-27/artex/llmrec"
"github.com/Autumn-27/norma/llm"
)
@@ -131,3 +134,147 @@ func TestResetSettledRunReseedsBudgetFromUsage(t *testing.T) {
got.Remaining.Tokens, got.Margin.Tokens, got.Dispatch)
}
}
// Repro for #705: a task whose lifetime spend has already exceeded its budget
// plus wrap-up reserve must cancel any in-flight exec and skip the final
// planner round during settleTask (0 additional LLM calls).
func TestHardExhaustedBudgetSkipsFinalPlannerRound(t *testing.T) {
for _, k := range []string{"ARTEX_TASK_BUDGET_TURNS", "ARTEX_INTENT_BUDGET_TOKENS", "ARTEX_INTENT_BUDGET_TURNS"} {
t.Setenv(k, "")
}
t.Setenv("ARTEX_TASK_BUDGET_TOKENS", "250000")
e := NewEngine(nil)
plannerCalls := 0
e.SetAuthoritativeAgentResolver(func(*Task) (*agent.Planner, *agent.Worker) {
plannerCalls++
return nil, nil
})
task := &Task{ID: "705"}
execCtx := e.execContextFor(context.Background(), task.ID)
l := e.budgetFor(task.ID)
// Exact scale from #705: 347,003 tokens spent against a 250,000 token cap.
l.RestoreSpend(agent.Spend{Tokens: 347_003, Turns: 12})
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
if !e.budgetStop(ctx, task) {
t.Fatal("budgetStop did not stop a hard-exhausted task")
}
if plannerCalls != 0 {
t.Fatalf("hard-exhausted budgetStop attempted final planner round (resolver called %d times)", plannerCalls)
}
if !errors.Is(context.Cause(execCtx), agent.AbortSettleDrainTimeout) {
t.Fatalf("hard-exhausted settle did not cancel in-flight exec context: cause=%v", context.Cause(execCtx))
}
}
// budgetStop must account for the planner round's own estimated cost, not just
// the next worker's estimate, so it stops before starting a planner round whose
// cost would leave too little budget to dispatch any worker.
func TestBudgetStopReservesPlannerRoundCost(t *testing.T) {
t.Setenv("ARTEX_TASK_BUDGET_TOKENS", "250000")
t.Setenv("ARTEX_TASK_BUDGET_TURNS", "150")
t.Setenv("ARTEX_INTENT_BUDGET_TOKENS", "30000")
t.Setenv("ARTEX_INTENT_BUDGET_TURNS", "10")
e := NewEngine(nil)
task := &Task{ID: "706"}
// Run one metered planner round via budgetRoundCtx + llmrec.Wrap (40k tokens).
rctx := e.budgetRoundCtx(context.Background(), task, false)
rec := llmrec.Wrap(stopReasonProvider{stop: "end_turn"}, nil, "model", "profile", "", "", func() bool { return false })
for _, err := range rec.Stream(rctx, llm.CompletionRequest{}) {
if err != nil {
t.Fatal(err)
}
}
// Simulate a 40k-token planner round and finish its meter.
l := e.budgetFor(task.ID)
pm := l.StartPlannerRound(false)
pm.Record(llm.Usage{InputTokens: 39_959}) // +41 from stream = 40,000 total
pm.Finish()
// Add 155k worker/other spend -> 195k spent, 55k remaining:
// Worker estimate (30k) still fits (budgetBlocksClaim == false),
// but planner (40k) + worker (30k) = 70k > 55k (budgetBlocksPlan == true).
l.Record(llm.Usage{InputTokens: 155_000})
if e.budgetBlocksClaim(task.ID) {
t.Fatal("worker claim should still fit at 55k remaining vs 30k intent cap")
}
if !e.budgetBlocksPlan(task.ID) {
t.Fatal("budgetBlocksPlan must stop new planner round when planner+worker estimate exceeds remaining")
}
// budgetStop must reach the same decision from Plan alone, without a pre-marked
// wrap-up. The bounded context only shortens the settle sequence's final-round
// wait; it does not affect the gate under test.
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
if !e.budgetStop(ctx, task) {
t.Fatal("budgetStop did not stop a planner round that cannot afford planner+worker")
}
}
// Repro for #705: agent-triggered revival (set_goals / add_intent via
// reviveTaskFromAgent) must not revive timed-out, settling, or budget-exhausted
// tasks, and admitTask must refuse reviving any terminal task whose configured
// run budget is already exhausted.
func TestReviveGuardsPreventTimeoutSettlingAndBudgetLoops(t *testing.T) {
newTestServer := func(task *Task) *Server {
e := NewEngine(nil)
m := &Manager{tasks: map[string]*Task{task.ID: task}}
return &Server{m: m, engine: e, ctx: context.Background()}
}
t.Run("agent revival refuses timed-out task even without token budget", func(t *testing.T) {
for _, k := range []string{"ARTEX_TASK_BUDGET_TOKENS", "ARTEX_TASK_BUDGET_TURNS", "ARTEX_INTENT_BUDGET_TOKENS", "ARTEX_INTENT_BUDGET_TURNS"} {
t.Setenv(k, "")
}
task := &Task{ID: "101", Status: "timeout"}
s := newTestServer(task)
if _, err := s.admitTaskWhen(task, "resume", false, true); err == nil || !strings.Contains(err.Error(), "timed out") {
t.Fatalf("agent revival of timed-out task = %v, want timed-out refusal", err)
}
s.reviveTaskFromAgent(task)
if got := task.lifecycleSnapshot().Status; got != "timeout" {
t.Fatalf("status after reviveTaskFromAgent = %q, want timeout", got)
}
})
t.Run("admission refuses while in-flight settlement is active", func(t *testing.T) {
for _, k := range []string{"ARTEX_TASK_BUDGET_TOKENS", "ARTEX_TASK_BUDGET_TURNS", "ARTEX_INTENT_BUDGET_TOKENS", "ARTEX_INTENT_BUDGET_TURNS"} {
t.Setenv(k, "")
}
task := &Task{ID: "102", Status: "running"}
s := newTestServer(task)
s.engine.settling.Store(task.ID, true)
if _, err := s.admitTask(task, "resume"); err == nil || !strings.Contains(err.Error(), "settling") {
t.Fatalf("admitTask during in-flight settle = %v, want settling refusal", err)
}
if _, err := s.admitTaskWhen(task, "resume", false, true); err == nil || !strings.Contains(err.Error(), "settling") {
t.Fatalf("agent revival during in-flight settle = %v, want settling refusal", err)
}
if !s.engine.isSettling(task.ID) {
t.Fatal("refused revival cleared settling barrier")
}
})
t.Run("terminal task with exhausted budget cannot be revived", func(t *testing.T) {
t.Setenv("ARTEX_TASK_BUDGET_TOKENS", "250000")
t.Setenv("ARTEX_TASK_BUDGET_TURNS", "")
t.Setenv("ARTEX_INTENT_BUDGET_TOKENS", "30000")
t.Setenv("ARTEX_INTENT_BUDGET_TURNS", "")
for _, status := range []string{"timeout", "done"} {
task := &Task{ID: "103", Status: status}
s := newTestServer(task)
l := s.engine.budgetFor(task.ID)
l.RestoreSpend(agent.Spend{Tokens: 250_000, Turns: 20})
if _, err := s.admitTask(task, "resume"); err == nil || !strings.Contains(err.Error(), "budget is exhausted") {
t.Fatalf("admitTask on budget-exhausted %s task = %v, want budget exhaustion refusal", status, err)
}
if _, err := s.admitTaskWhen(task, "resume", false, true); err == nil {
t.Fatalf("agent revival on budget-exhausted %s task succeeded, want refusal", status)
}
if got := s.engine.budgetFor(task.ID); got != l {
t.Fatal("refused revival dropped or replaced the budget ledger")
}
}
})
}
+28 -3
View File
@@ -233,6 +233,14 @@ func (e *Engine) settleTask(ctx context.Context, t *Task, budget bool) {
log.Printf("[deadline] task %s reached the timeout limit, entering the settle sequence", t.ID)
}
hardBudget := budget && e.budgetHardExhausted(t.ID)
if hardBudget {
// Lifetime spend already exceeded budget + wrap-up reserve: cancel any
// in-flight planner/worker calls immediately instead of letting them burn
// through the full drain grace window.
e.cancelExec(t.ID, agent.AbortSettleDrainTimeout)
}
// ④ wait for running workers/planners to drain (running runs enter wrap-up on their own
// via the clamped MaxDuration); if not drained within the grace period, hard-cancel the
// task's exec ctx (the settling-aware branches classify it correctly).
@@ -250,7 +258,16 @@ func (e *Engine) settleTask(ctx context.Context, t *Task, budget bool) {
}
// ⑤ one final planner round (task-timeout words, final goal judgment, no new intents).
met := e.runFinalPlannerRound(ctx, t, budget)
// Circuit breaker: once lifetime spend has already exceeded the task budget plus
// its wrap-up reserve, skip the final planner round so an over-budget task never
// burns extra LLM calls while settling.
var met bool
if hardBudget || (budget && e.budgetHardExhausted(t.ID)) {
hardBudget = true
log.Printf("[budget] task %s lifetime spend exceeded hard ceiling, skipping final planner round", t.ID)
} else {
met = e.runFinalPlannerRound(ctx, t, budget)
}
if !e.beginTaskOperation(t.ID) {
return
}
@@ -269,8 +286,16 @@ func (e *Engine) settleTask(ctx context.Context, t *Task, budget bool) {
endReason := ""
if budget {
endReason = db.EndReasonBudget
e.emitActivity(t, db.Activity{Worker: "system", Kind: "text",
Summary: "Task run budget exhausted: forced wrap-up done, task stopped (final state " + status + ")"})
if t.Store != nil {
summary := "Task run budget exhausted: forced wrap-up done, task stopped (final state " + status + ")"
if hardBudget {
summary = "Task run budget exhausted beyond wrap-up reserve: skipped final planner round, task stopped (final state " + status + ")"
}
e.emitActivity(t, db.Activity{Worker: "system", Kind: "text", Summary: summary})
}
}
if e.m == nil {
return
}
won, err := e.m.SetTaskStatusGuarded(t.ID, status, endReason)
switch {
+14
View File
@@ -138,6 +138,13 @@ func readBoundResponse(store *evidence.Store, snap db.TrafficEvidenceSnapshot) (
// its bound traffic and the quotes the agent supplied. poe is the declared POE
// level (0 when absent). It never returns "verified" unless every rule passes.
func (s *Server) assessFindingVerification(ctx context.Context, findingID int64, poe int, quotes []string) (status, note string) {
finding, err := s.m.pg.GetFinding(findingID)
if err != nil {
return db.VerificationNotAssessed, "finding read error: " + err.Error()
}
if finding == nil {
return db.VerificationNotAssessed, "finding not found"
}
tr, err := s.m.pg.GetFindingTraffic(ctx, findingID)
if err != nil {
return db.VerificationNotAssessed, "binding read error: " + err.Error()
@@ -151,6 +158,13 @@ func (s *Server) assessFindingVerification(ctx context.Context, findingID int64,
if len(proofs) == 0 {
return db.VerificationUnverified, "no proof traffic bound"
}
if db.IsCORSFinding(finding.VulnClass) {
for _, proof := range proofs {
if err := db.ValidateCORSProofHeads(proof.Snapshot.ReqHead, proof.Snapshot.RespHead); err != nil {
return db.VerificationUnverified, "CORS proof validation failed: " + err.Error()
}
}
}
if poe < verificationMinPOE {
return db.VerificationUnverified, fmt.Sprintf("POE L%d below L3", poe)
}
+25 -3
View File
@@ -115,17 +115,17 @@ func (s *Server) runningTaskCount(excludeID string) int {
// work. It atomically either starts the task or appends it to the persistent FIFO
// queue. mode is bootstrap for a freshly-created task and resume otherwise.
func (s *Server) admitTask(t *Task, mode string) (queued bool, err error) {
return s.admitTaskWhen(t, mode, false)
return s.admitTaskWhen(t, mode, false, false)
}
// admitPausedTask is the task-control resume path. The paused precondition is
// checked under the same scheduler lock as admission so a concurrent pause,
// dequeue or FIFO promotion cannot leave database and Engine state divergent.
func (s *Server) admitPausedTask(t *Task) (queued bool, err error) {
return s.admitTaskWhen(t, "resume", true)
return s.admitTaskWhen(t, "resume", true, false)
}
func (s *Server) admitTaskWhen(t *Task, mode string, requirePaused bool) (queued bool, err error) {
func (s *Server) admitTaskWhen(t *Task, mode string, requirePaused, blockTimeoutRevive bool) (queued bool, err error) {
if t == nil {
return false, fmt.Errorf("task not found")
}
@@ -156,6 +156,15 @@ func (s *Server) admitTaskWhen(t *Task, mode string, requirePaused bool) (queued
mode = s.resumeAdmissionMode(t)
}
wasTerminal := isTerminalStatus(lifecycle.Status)
if !wasTerminal && s.engine.isSettling(t.ID) {
return false, fmt.Errorf("task %s is settling and cannot be admitted", t.ID)
}
if blockTimeoutRevive && lifecycle.Status == "timeout" {
return false, fmt.Errorf("task %s is timed out and cannot be revived automatically", t.ID)
}
if wasTerminal && s.engine.budgetBlocksPlan(t.ID) {
return false, fmt.Errorf("task %s run budget is exhausted", t.ID)
}
wasPaused := lifecycle.Paused || s.engine.IsPaused(t.ID)
wasQueued := lifecycle.Queued
engineWasPaused := s.engine.IsPaused(t.ID)
@@ -383,6 +392,19 @@ func (s *Server) reviveTask(t *Task) {
}
}
// reviveTaskFromAgent is the automatic revival callback for agent tools
// (set_goals / add_intent via orchestration or mainagent). Unlike explicit UI
// actions, it refuses to pull a timed-out task back to running, and shares the
// in-flight settlement and run-budget exhaustion guards inside admitTaskWhen.
func (s *Server) reviveTaskFromAgent(t *Task) {
if t == nil {
return
}
if _, err := s.admitTaskWhen(t, "resume", false, true); err != nil {
log.Printf("[revive] task %s skipped automatic agent revival: %v", t.ID, err)
}
}
// createGoals materializes the goal node(s) under the task root (rel objective)
// through the LLM Goal Decomposer's structured set_goals tool call. It returns an
// explicit error if the task has no goal or if the decomposer fails to submit at
+4 -4
View File
@@ -169,10 +169,10 @@ func (s *Server) delegateToTask(ctx context.Context, in json.RawMessage, pick fu
if s.m.Assets() != nil {
tsx.SetAssetStore(s.m.Assets(), s.m.Assets().Companies())
}
tsx.SetNotify(t.Notify) // generic wake-up (write ops without a dedicated callback go through it; no-op for read tools)
tsx.SetResumeTask(func() { s.reviveTask(t) }) // set_goals → pulls a completed/paused task back to running
tsx.SetNotifyGoal(t.NotifyGoal) // set_goals → records a goal-added trigger and wakes the planner
tsx.SetNotifyHint(t.NotifyHint) // add_hint → records an "orchestrator added N strategic hints: ..." entry and wakes the planner
tsx.SetNotify(t.Notify) // generic wake-up (write ops without a dedicated callback go through it; no-op for read tools)
tsx.SetResumeTask(func() { s.reviveTaskFromAgent(t) }) // set_goals → pulls a completed/paused task back to running (never timed-out/settling/budget-exhausted)
tsx.SetNotifyGoal(t.NotifyGoal) // set_goals → records a goal-added trigger and wakes the planner
tsx.SetNotifyHint(t.NotifyHint) // add_hint → records an "orchestrator added N strategic hints: ..." entry and wakes the planner
return pick(tsx).Call(ctx, inner, nil)
}
+1 -1
View File
@@ -4600,7 +4600,7 @@ func (s *Server) startTaskChat(t *Task, turn taskChatTurn) (mode, reply string,
s.engine.emitActivity(t, rec)
}
maTaskID, _ := strconv.ParseInt(t.ID, 10, 64)
resume := func() { s.reviveTask(t) } // set_goals added a goal → pulls the task back to running
resume := func() { s.reviveTask(t) } // an operator turn in the chat adds a goal → resumes the task like the console; the admission guards still refuse a settling or budget-exhausted task
// Splice the list of [absolute paths] of uploaded attachments into the message sent to the agent; it uses them to open files via Read/Bash.
// mainDir = the main agent's run directory (its CWD, tasks/<id>/main), the same call as chatUpload's target dir and the agent itself.
mainDir := agent.EnsureRunDir(s.m.dir, maTaskID, 0)