`ClaudeChatModel._calc_backoff_ms` parsed `Retry-After` with `int()` and
never read `retry-after-ms`, so a decimal hint from a gateway raised,
fell through to HTTP-date parsing, and was dropped. The retry then used
the local 2.4 s schedule and could spend its budget inside the same
throttle window.
Move the header parser into `utils.retry_after.retry_after_hint_ms`
(spellings, float seconds, ms units, HTTP-date fallback, 24 h bound) and
use it from both the Claude and Codex providers, keeping each caller's
clock for HTTP dates.
Fixes#8655
Persist an opt-in for automatic and manually triggered scheduled runs.
Carry unattended guidance through ordinary and durable delegation, and
keep continuation discovery separate from batch argument validation.
Cover the Gateway-to-worker path, including queued batches recovered
after restart, and add the opt-in with Alembic revision 0062.
Co-authored-by: Willem Jiang <willem.jiang@gmail.com>
* fix(agents): preserve reasoning choices across model and chat switches
Apply inherited thinking after selecting the model so a required-thinking profile can admit the run. Keep explicit disable requests subject to the profile policy. Read manual effort choices from the current thread for both the composer and the submitted request.
* fix(frontend): clear stale chat effort on model fallback
Validate a saved chat effort when the composer resolves its current model. Keep supported choices in the same chat and release an obsolete override even if another chat has already resolved the shared fallback.
---------
Co-authored-by: Totoro-qaq <279883115+Totoro-qaq@users.noreply.github.com>
* fix(subagents): keep batch item token usage across attempts
finalize_item replaced the item's token_usage with the finishing attempt's
usage, so a retried item kept only its last attempt and the exception path
(token_usage=None) erased what was stored. Add each attempt's counts to the
stored total instead.
Refs #8646
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Bas Cancrinus <7222814+bascan@users.noreply.github.com>
* fix(subagents): keep an attempt's token usage when its finalize fails
When the finalize that carried an attempt's usage raised (for example a
rolled-back commit), the exception handler finalized the item again with
token_usage=None, so that attempt's tokens were lost. Carry the collected
usage and model name into that call. If the first finalize did commit,
the lease is already released and the second call writes nothing, so
nothing is counted twice.
Refs #8646
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Bas Cancrinus <7222814+bascan@users.noreply.github.com>
---------
Signed-off-by: Bas Cancrinus <7222814+bascan@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Keep explicit instants in UTC and offset-free times in the task zone. Apply the same representation to historical reads while preserving no-op edits and the original execution time.
Co-authored-by: Totoro-qaq <279883115+Totoro-qaq@users.noreply.github.com>
* fix(report-sections): preserve literal hashes in titles
* fix(report-sections): parse ATX markers once per heading
---------
Co-authored-by: Willem Jiang <willem.jiang@gmail.com>
* fix(sandbox): bound network policy event history and fail closed on database errors
The restricted-mode sidecar records every denied destination in a SQLite
database on its only writable space, a 16 MiB tmpfs, and the events table
never deletes rows. A sandbox requesting many unique hosts fills the tmpfs
in minutes; after that record_denial raises, the exception escapes
handle_proxy, and denied connections get a bare TCP reset instead of 403
while the approval CLI fails against the same full database.
Prune inside the existing recording transaction, after the dedup lookup
and before the insert: drop superseded rows first, keep the newest 4000
decided rows, then drop the oldest never-surfaced undecided rows only if
still over the limit. A surfaced undecided card the user is viewing is
never dropped. Both database touch points in handle_proxy now catch
sqlite3.Error and still return 403 with the policy message.
Fixes#8669
* fix(sandbox): truncate the persisted denial method so the row cap bounds bytes
The request line has no token-length limit of its own, so a method can be
nearly MAX_HEADER_BYTES long. Stored verbatim, a few hundred oversized-method
denials fill the 16 MiB tmpfs long before MAX_EVENTS is reached. Truncate the
persisted method to 16 characters (the longest standard method is CONNECT, 7);
the denial response is unchanged. Adds an oversized-method regression through
the proxy request path asserting the stored prefix and a bounded database file.
* fix(sandbox): retain decisions by application time and reserve room for pending approvals
Review findings on the pruning semantics:
- Resolved history was ordered by the denial timestamp, so an old card
answered after newer cards lost its just-applied decision on the next
prune and a resumed run's replay failed. Add a decided_at column (with
an ALTER TABLE migration for existing databases), stamp it wherever a
decision is applied, and order retention by COALESCE(decided_at,
created_at).
- Once resolved history filled the cap, each insert evicted an unsurfaced
denial, reversing the oldest-first order pending_events surfaces in.
Pending approvals now reserve capacity: history trims itself to the room
they leave, keeping at least the most recent decision; unsurfaced rows
are dropped only when they alone exceed the cap with no history left.
- A transient policy-lookup failure fell through to record_denial, which
could create an approval card for a destination already holding a
sandbox-lifetime grant; answering it with Allow temporarily would
replace that grant with an expiring one. Lookup errors now fail closed
without recording.
Adds regressions for the answered-old-card replay, the full-history
pending pair, the pre-decided_at migration, and the lookup failure.
* fix(sandbox): trim unsurfaced denials after retaining decisions
---------
Co-authored-by: Willem Jiang <willem.jiang@gmail.com>
Distinguish reasoning defaults supplied by the chat mode from explicit selections. Keep the configured lead reasoning and Ultra delegation independent while honoring a per-request override.
Co-authored-by: Totoro-qaq <279883115+Totoro-qaq@users.noreply.github.com>
* fix(image-generation): preserve output when a provider returns no bytes
A provider can answer 200 with an empty body, or hand back an empty data
URL. The writer opened the destination and wrote the zero bytes, erasing a
previous image and reporting success. Reject empty image bytes before the
output directory or file is created, covering both the download and data-URL
paths.
* docs(ppt-generation): stop the slide chain when image generation fails
* fix(image-generation): exit nonzero for overlong MiniMax prompts
Exercise the 1500-character boundary and CLI diagnostics. Check that an empty OpenAI-compatible response preserves an existing file and leaves a missing output directory absent.
* fix(image-generation): fail when the selected provider key is missing
Report the missing key on stderr and exit before processing reference images so dependent slide commands stop. Cover the supported provider names and aliases with other providers configured.
Refs https://github.com/bytedance/deer-flow/pull/8668#discussion_r4705644645
---------
Co-authored-by: Nan Gao <thunderggnn@gmail.com>
A SKILL.md directory in a skill archive raised IsADirectoryError in
frontmatter validation. The install routes reported it as a 500 that
echoed the host extraction temp path. Validation now returns
"SKILL.md must be a file", so install raises ValueError and both
routes return 400.
Co-authored-by: Willem Jiang <willem.jiang@gmail.com>
* fix(sandbox): screen embedded IPv4 destinations in the egress proxy address check
The allowlist proxy judged DNS answers by is_global alone, so NAT64
(64:ff9b::/96), IPv4-compatible, and IPv4-translated (::ffff:0:0:0/96)
spellings of loopback, private, or cloud-metadata addresses passed
resolve_public. Unwrap the embedded IPv4 and apply the same check,
mirroring url_safety's unwrapping plus the translated prefix, while
keeping NAT64 spellings of public targets reachable.
Fixes#8616
* test(sandbox): follow interpreter classification for public 6to4 assertion
CPython marks 2002::/16 private only from 3.12.4 (gh-113171); the proxy
uses the interpreter's outer classification when the embedded IPv4 is
public, so pin the expectation to is_global instead of a fixed rejection.
* fix(sandbox): reject the RFC 8215 local-use NAT64 prefix explicitly
CPython classifies 64:ff9b:1::/48 as non-global only from 3.12.4
(gh-113171), and the sidecar image can pin an older interpreter, so
restricted egress must not depend on the interpreter's classification
for this range. A test simulates the pre-3.12.4 flags to pin the
explicit rejection.
---------
Co-authored-by: Willem Jiang <willem.jiang@gmail.com>
* fix(browserless): redact query token from error responses and logs
* fix(browserless): validate/redact response status headers and tighten truncation test
* fix(subagents): authorize local file acceptance checks before metadata probes
The local sandbox gate covered only JSON and CSV criteria, so file_exists, file_non_empty and file_written still resolved paths and probed metadata for callers without sandbox:execute. Run the same admission check for every local file family before path resolution, returning an UNVERIFIED leaf on denial.
Refs #8594
* fix(subagents): reclassify sandbox after a lazy local initialization
The provider-error branch reused the sandbox kind captured before the size probe. That probe can lazily acquire the parent's local sandbox, so a genuine Error:-prefixed report was rejected as a provider failure. Recheck is_local_sandbox after the read and cover the lazy-initialization path.
Refs #8594
* fix(subagents): decide file acceptance admission on the owning event loop
The worker-thread gate reconstructed the authorization provider synchronously. Providers that create loop-affine clients in __init__ fail that construction off-loop, so under fail_closed an authorized batch's missing-file and above-cap verdicts degraded to UNVERIFIED. The task and batch entry points now decide sandbox:execute on the event loop and carry the decision (plus the authorization-scope marker) into the offloaded checklist; the synchronous path keeps its live per-leaf gate.
Refs #8594
* feat(sandbox): add opt-in OpenSandbox capacity rejection
* fix(sandbox): count reclaimed OpenSandbox slots and warn on burst
- Keep a reclaimed warm sandbox reserved until it is registered as active,
so a concurrent create cannot exceed the reject cap while the reclaimed
sandbox's skill view is prepared.
- Release a create reservation under the same lock as the registration, so a
registered sandbox is never counted twice.
- Give the capacity error the 30 second retry hint E2B uses.
- Log a warning when overflow_policy is burst: OpenSandbox keeps the soft cap.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Bas Cancrinus <7222814+bascan@users.noreply.github.com>
* fix(sandbox): keep OpenSandbox slots counted until deletion is confirmed
Review of #8639 (WillemJiang), reproduced with the offline SDK fixture:
- The idle reaper and a failed health check now mark the remotes they
remove as retiring under the same lock, and the reject cap counts them
until their deletion succeeds (new mixin hook, a no-op for the other
providers).
- A failed eviction keeps the slot occupied and returns a retryable
capacity error instead of creating a replacement. An unconfirmed remote
stays counted until its server-side lifetime ends, or until the Gateway
restarts when sandbox_timeout is 0.
- A failed reclaim hands its reservation back to the warm pool under the
same lock that restores the warm entry.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Bas Cancrinus <7222814+bascan@users.noreply.github.com>
---------
Signed-off-by: Bas Cancrinus <7222814+bascan@users.noreply.github.com>
Co-authored-by: Yufeng He <40085740+he-yufeng@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* fix(sandbox): ignore late terminal failure from replaced BoxLite box
* fix(sandbox): bind each BoxLite failure callback to its box
---------
Co-authored-by: Willem Jiang <willem.jiang@gmail.com>
* fix: fix(agents): pair a malformed-id tool result even when an invalid s
Signed-off-by: wangshun <96341168+xixi-box@users.noreply.github.com>
* fix: claim results in two tiers so an invalid sibling neither blocks nor steals them
Addresses both review threads.
The blanket executable-only exclusion from the previous commit fixed#7821 but
regressed #2894: an invalid call whose real ToolMessage is already in history
lost that result to the orphan pass and got the recovery placeholder instead.
Claiming is now two-tier — executable entries first, then invalid ones as a
fallback — so an invalid sibling can neither make the only executable call look
ambiguous nor take a result an executable call can claim, while a real result for
an invalid call still survives.
Adds the regression test the backend TDD convention requires: one turn with an
executable malformed-id call and a same-name invalid sibling plus one real
result. Against the base middleware (12c304f) it fails with exactly the reported
symptom — '1 orphan(s) dropped, 2 placeholder(s) injected' and the real output
replaced by the interrupted placeholder; with this change the output stays on the
executable call and the sibling keeps its argument-error placeholder.
backend/tests/test_dangling_tool_call_middleware.py: 65 passed.
* fix: keep positional pairing on when an invalid sibling owns its own result
_turn_malformed_result_count counts every malformed result in the turn, including
one only an invalid call can claim, so comparing it against the executable-call
count alone marked a fully-accounted turn as incomplete. positional then went
False, every executable-tier match looked ambiguous, and _claim_synthetic_id
returned None for all of them: three real results dropped as orphans and
replaced with error placeholders.
Back to len(assigned), which is the same population the result count measures,
and a regression test for the compound shape (two identical executable calls +
one invalid sibling + three real results).
Signed-off-by: wangshun <96341168+xixi-box@users.noreply.github.com>
* docs(agents): align the relabel docstring with two-tier claiming
Signed-off-by: wangshun <96341168+xixi-box@users.noreply.github.com>
* fix(agents): prioritize exact tool result names
---------
Signed-off-by: wangshun <96341168+xixi-box@users.noreply.github.com>
Co-authored-by: Willem Jiang <willem.jiang@gmail.com>
A trailing ".skill/" requests no archive member at all. The empty internal
path fell through to the archive lookup's fallback match, which matched the
first directory entry (name ends with "/") and returned its empty body with
200 instead of 404.
Reject an empty internal path in the skill branch before extraction. The
regression test ships an archive with the usual explicit directory entry and
asserts the trailing-slash request answers 404.
* fix(skills): append each history record in one O_APPEND write
append_history wrote the JSON record and its LF terminator as two writes
through a text file. A record holding two SKILL.md revisions outgrows the
file buffer, so the record went out directly and the terminator
separately. Appenders that do not share a lock, such as the skill_manage
tool and the skill routes, or two Gateway workers, could land another
record in between. read_history then rejected the joined line, and the
skill's history and rollback routes failed from then on.
Encode the record with its terminator first and write it with one
O_APPEND os.write, continuing after a short write.
* fix(skills): hold the history file lock across a record's retries
O_APPEND makes one write atomic, but finishing a short write takes a
second one, and another writer's record could land between the two.
append_history now holds an exclusive lock on the history file while it
writes the whole record. The operation mirror, the other writer of the
same file, takes the same lock around its read, check and append, so its
records cannot land inside one either.
The lock belongs to the open file, so it serializes threads of one
process as well as processes, and it is always the innermost lock.
* test(skills): skip the operation mirror lock test off POSIX
mirror_operations opens the history directory through POSIX directory
descriptors and open flags that CPython does not expose on Windows. Skip
that case there, as the host mutation suite does, so the portable
history append tests still run.
* fix(skills): read history under the history file's shared lock
read_history read the file without the lock, so a read that landed while
a short write was being retried saw half a record and raised
JSONDecodeError. Readers now hold the lock in shared mode (exclusive on
Windows, where msvcrt.locking has no shared mode).
The guide and the append comment now state the real guarantee: each
record is appended whole under the history file's lock, which can take
more than one write.
* test(skills): wait at the history lock instead of a timed join
The short-write interleaving tests let the other reader, appender or
mirror run for up to 0.5 s and then retried. A lock-free path that was
scheduled after the retry passed them. The holder of the short write now
retries only once the other thread is at the history lock, or has
finished without it; the mirror test waits until the append is blocked
on the mirror's lock or has made its short write.
* test(skills): release the retry once the other thread is blocked on the lock
Waiting only for the other thread's lock attempt let it race the retry
when the retry ran outside the lock, so that variant failed one storage
and passed the other. The retry now waits until the other thread is
blocked on the lock, or has finished without waiting for it. All three
interleaving tests use the same barrier.
* chore(skills): mark the Windows fcntl fallback type: ignore
Match the other fcntl fallbacks, including deerflow/skills/projection.py
and the custom-skill mutation lock.
* feat(mcp): maintain agent credential grants at runtime (grants: runtime)
An mcp_agent_auth binding can declare grants: runtime. config.yaml then keeps
only the server, agent and OAuth client; an administrator maintains the owners
and approved definition digests through /api/mcp/agent-auth, stored with the
agent_storage backend (table mcp_agent_grants, migration 0059, or one JSON file
per binding). A runtime binding without a grant admits nobody.
Run admission reads the grant for each matching binding, and every protected
call rechecks the owners, so a change applies without a Gateway restart:
removing an owner denies the next call, removing a digest stops new runs while
admitted runs keep their definition. An unreadable grant store denies admission
and calls. The API refuses writes to grants: config bindings and owners that
another enabled binding already covers for the same server and agent; admission
also fails closed if overlapping runtime grants race past that check.
grants: config (the default) behaves as before.
Closes#8503
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Bas Cancrinus <7222814+bascan@users.noreply.github.com>
* fix(mcp): bind a runtime grant to the identity it was approved for
A runtime grant was keyed by binding ID only, so its owners and digests stayed
in force after config.yaml pointed the binding at another agent, server or
OAuth client, or the server at another destination. Each grant now records
that subject (agent, server, destination digest, nonsecret credential digest)
when an administrator writes it; admission and every protected call apply the
grant only while the subject still matches. Rotating the client secret keeps
it. The admin API reports approval: current/stale/none/config, and the overlap
check ignores grants that are no longer in force.
Also renumbers the migration to 0060 after upstream's 0059_coordination_grants.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Bas Cancrinus <7222814+bascan@users.noreply.github.com>
* fix(mcp): build grant stores off the event loop; reject owners file storage cannot hold
The admin routes built the grant store on the event loop; with SQLite the
factory resolves the database path on the filesystem. Construct the store in
the worker thread together with the read or drained write.
definition-digest with file-backed agent storage turned an owner such as
"alice@example.com" or "../alice" into a 500 from Paths.user_dir; it now
answers 422. Database-backed owners stay unrestricted.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Bas Cancrinus <7222814+bascan@users.noreply.github.com>
* test(mcp): put 0061_mcp_agent_grants after 0060_coordination_run_settings in the chain test
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Bas Cancrinus <7222814+bascan@users.noreply.github.com>
* fix(mcp): keep stale and retired runtime grants reserved, let admins delete them
- The owner overlap check counts every stored grant for the agent and server
it was approved for, also while it is stale or its binding is gone, so a
configuration rollback cannot reactivate a grant whose owners another
binding took in the meantime.
- A grant whose binding was removed from config.yaml is listed and readable
as approval: retired and can be deleted by its binding ID, which releases
its owners. A grant left behind on a binding moved to grants: config can be
deleted too.
- The file store treats a grant file removed by a concurrent delete as absent
in get, list, put and delete; parse and other I/O errors still raise.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Bas Cancrinus <7222814+bascan@users.noreply.github.com>
* fix(mcp): chain grants after 0061_coordination_coordinator; keep owners of disabled bindings reserved
Rename the grants migration to 0062_mcp_agent_grants with down_revision
0061_coordination_coordinator so main keeps a single Alembic head, and
check the whole upgrade path in the chain test.
A disabled binding now keeps its owners reserved (stored grants and
grants: config owners), and a grant written to a disabled binding is
checked for overlaps too, so enabling it again cannot make admission
reject both bindings.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Bas Cancrinus <7222814+bascan@users.noreply.github.com>
* fix(mcp): show a stored runtime grant on a binding moved to config grants
A grants: config binding whose earlier runtime grant is still stored hid that
grant in both GET routes, while the overlap check still counted its owners:
an administrator could get a 409 for an owner absent from the binding's
details. Both routes now return it as stored_grant (server, agent, owners,
digests) until it is deleted.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Bas Cancrinus <7222814+bascan@users.noreply.github.com>
---------
Signed-off-by: Bas Cancrinus <7222814+bascan@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Willem Jiang <willem.jiang@gmail.com>
* fix(projects): keep shelf index entries line-atomic
* fix(projects): keep the project name on one line in the rendered block
Follow-up from the review of the shelf index fix: the project name is
member-settable untrusted text rendered into the `<project>` open tag.
The attribute escaper leaves line boundaries intact, so a name containing
one pushed attacker-chosen lines into the rendered framework block.
Reuse `_one_line` for the name, as the shelf entries already do. The new
test covers every line boundary `str.splitlines` recognizes and fails on
the previous code.
* test(projects): cover every splitlines boundary in the name fold test
The parametrization omitted \x1c, \x1d and \x1e, three of the boundaries
str.splitlines recognizes. All eleven cases fail without the fold.
The docstring said attribute values are folded; only the name is. The
project id is a server-generated UUID and stays as it is.
* feat(vefaas-sandbox): add snapshots, pause/resume, and image precache
Implement Phase 2 of #8426 on top of #8449:
- Extend VeFaaSClient (OpenAPI Version=2024-06-06) with PauseSandbox,
ResumeSandbox, CreateSandboxSnapshot, DescribeSandboxSnapshot,
ListSandboxSnapshots (paginated), DeleteSandboxSnapshot,
PrecacheSandboxImages, GetSandboxImagePrecacheTicket, plus SnapshotId
and AutoPauseConfig support on CreateSandbox.
- Add opt-in lifecycle controls to VeFaaSSandboxProvider: pause_on_idle,
auto_pause, snapshot_on_idle (with scoped metadata filtering and old
snapshot pruning), base snapshot_id, precache_images, and off-loop
precache_on_startup, plus public snapshot/precache helper methods.
- Preserve ownership lease fencing, dirty-sandbox exclusion, cross-tenant
snapshot isolation, retryable shutdown, and non-blocking event-loop
guarantees with offline unit and Blockbuster tests.
* fix(vefaas-sandbox): harden snapshot teardown lease, auto-pause reclaim, and manual snapshot shutdown fence
Address all review findings on #8513:
- Keep destructive teardown leases alive via a heartbeat and poll-tick
refresh throughout idle pause/snapshot retirement, and re-verify
claim(..., for_destroy=True) right before KillSandbox so a peer-adopted
sandbox is never killed if the lease is lost mid-snapshot.
- Detect paused/transitioning warm instances in _reclaim_warm_pool via
DescribeSandbox and hand them off to discovery/resume instead of
killing them on failed HTTP readiness.
- Fence manual create_snapshot() source sandboxes via
_snapshotting_remote_ids so concurrent shutdown() stays retryable and
leaves the source alive until the snapshot settles.
- Move shared veFaaS offline test helpers into tests/support/vefaas_sandbox.py
and add deterministic regression tests for all three scenarios.
* fix(vefaas-sandbox): keep paused warm sandboxes tracked during reacquire
Resume paused or transitioning warm-pool entries in place inside
_reclaim_warm_pool() instead of popping _warm_pool ahead of
ListSandboxes discovery:
- Keep the owned warm entry tracked in _warm_pool across transient 5xx
control-plane errors (DescribeSandbox / ResumeSandbox), readiness
timeouts, and ownership backend errors so shutdown() after recovery
still sends KillSandbox and retry acquire() resumes without duplicates.
- Only discard a warm entry without teardown once the known remote
instance is authoritatively confirmed absent/terminal (DescribeSandbox
returning None/terminal or ResumeSandbox raising SandboxNotFound) or
confirmed under a peer teardown lease.
- Move unadoptable resumed warm instances (e.g. invalid/mismatched init
marker) atomically to _pending_destroys and tear them down via
_destroy_tracked() rather than forgetting them.
- Handle concurrent shutdown rollback cleanly when resuming/publishing a
paused warm entry and avoid falling through to discovery/create after
shutdown starts.
* feat(vefaas-sandbox): support speculative sandbox prewarm
Fold speculative sandbox prewarm support for VeFaaSSandboxProvider (formerly
#8492) into #8513 so prewarm, snapshots, pause/resume, and image precache
land together on top of #8449.
* chore(vefaas-sandbox): address CodeQL quality findings
- Scope `needs_kill` inside the claimed teardown branch in `_retire_warm_entry`
so the peer-owned branch does not write an unread local variable.
- Catch `Exception` rather than `BaseException` in the concurrent resume test
helper thread.
* fix(vefaas-sandbox): retain teardown fence until async snapshots settle
When `create_snapshot(..., wait=False)` returns early or `wait=True` exits
without an authoritative terminal/ready state (such as `TimeoutError` or a
transient describe error), hand off the `_snapshotting_remote_ids` refcount
to a background completion watcher thread instead of releasing the fence in
`finally`. Keep warm-pool reaping/eviction, shutdown, and client teardown
fenced (while continuing ownership lease renewal) until the control plane
confirms Ready, terminal failure, or SnapshotNotFound.
* fix(benchmark): pass OpenSandbox instance to _invalidate_sandbox
Follow-up to #8507 (`6cefec0c9`), which changed
`OpenSandboxProvider._invalidate_sandbox` to accept an `OpenSandboxSandbox`
instance instead of `sandbox_id: str`. Look up the active or warm sandbox
instance under `self._lock` inside `BenchmarkOpenSandboxProvider.destroy()`
before calling `_invalidate_sandbox()`.
* fix(vefaas-sandbox): keep ownership lease renewal active during manual snapshots
Stop inserting `sandbox_id` into `_acquire_inflight` during `create_snapshot()`.
Local reaping, eviction, teardown, and shutdown are already fenced by
`_snapshotting_remote_ids`, whereas `_acquire_inflight` caused
`_renew_leases_once()` to skip renewing the ownership lease during long
synchronous `create_snapshot(..., wait=True)` waits.
* fix(vefaas-sandbox): hand off and refresh ownership leases across resume waits
- Use `take(sandbox_id)` when resuming a `Paused` sandbox so a turn landing on
another worker can cleanly transfer a normal `own:` lease from a peer holding
an auto-paused warm entry while still rejecting a destructive `del:` lease
with `_PeerTeardownError`.
- Keep the normal `own:` lease refreshed throughout `ResumeSandbox`,
`_wait_for_remote_running()`, and `wait_for_sandbox_ready()` via
`_ownership_lease_heartbeat()` plus poll-tick `_refresh_owned_lease()`
callbacks, and authoritatively verify ownership (`_verify_owned_lease_strict`)
before adopting with `ownership_claimed=True`.
* fix(vefaas-sandbox): reserve cross-worker snapshot fence before manual snapshots
- Reject `create_snapshot()` on stale/peer-owned handles via `claim(sandbox_id)`
before calling `CreateSandboxSnapshot`.
- Reserve a remote-scoped cross-worker snapshot fence
(`snapshot-fence:<remote_id>` with `for_destroy=True`), perform a Dekker
re-check on `claim(sandbox_id)` so teardown and snapshot admission cannot
interleave, and keep the fence refreshed across synchronous waits
(`_teardown_lease_heartbeat` + poll-tick refresh), async completion watchers,
and `_renew_leases_once()` until the snapshot settles.
- Guard `_retire_warm_entry()`, `_destroy_tracked()`, and `shutdown()` against
active cross-worker snapshot fences (unwinding any destructive `del:` lease
and deferring teardown until the remote snapshot settles).
* fix(vefaas-sandbox): address P2 review findings on snapshot fencing, filtering, and restore
- Keep deferred warm-pool `AioSandbox` handles open in `_destroy_tracked()` and
`_retire_warm_entry()`, closing the local handle only once teardown proceeds
or the entry leaves `_warm_pool` (WillemJiang P2).
- Retain local and cross-worker snapshot fences after uncertain
`CreateSandboxSnapshot` failures (timeouts, transport errors, 5xx) and
reconcile via a background watcher polling `ListSandboxSnapshots(SandboxId=...)`
and `DescribeSandbox` until no snapshot is in progress (WillemJiang P2).
- Serialize cross-worker `snapshot-fence:<remote_id>` last-key release with new
reservations via a per-remote `_snapshot_fence_lock()` (Codex P2).
- Pass server-side `Filters` (`Metadata.*` and `Status`) in
`_find_latest_ready_snapshot()`, `_prune_old_snapshots()`, and
`list_snapshots()`, caching graceful fallback if a backend rejects filters
while keeping strict client-side metadata verification (YukoOshima P2).
- Refresh `/mnt/skills` and host `uploads/` (without overwriting snapshot
workspace/outputs) when booting from a snapshot that preserved
`/tmp/.deerflow-vefaas-initialized`, and document snapshot retention/cleanup
in `README.md` (YukoOshima questions).
* feat(sandbox): configure AIO sandbox Pod resource requests and limits
* fix(helm): reject unknown sandbox resource keys
Validate sandboxResources requests and limits against the three resource names the AIO provisioner reads. Helm now reports misspellings and unsupported extended resources during rendering, before a sandbox can start with the default limit.
Cover a misspelled memory limit and an extended resource request in the Helm render tests.
* fix(sandbox): defer fresh OpenSandbox skill-policy acquisition
OpenSandbox acquire now installs the thread's prepared skill view on new
and warm remotes (clearing first, so a failed upload never leaves another
view behind), and the provider opts in to
supports_lazy_agent_skill_isolation. A fresh run with an explicit Agent
skill list, including an empty one, no longer acquires a remote before
its first sandbox tool call.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Bas Cancrinus <7222814+bascan@users.noreply.github.com>
* fix(sandbox): keep eager skill sync when the thread's OpenSandbox remote is active
A deferred acquire reuses an active remote after renew() without installing
the run's prepared skill view, so a policy-scoped run that starts while an
upload holds the thread's remote would keep the previous view. Providers can
now report such a remote (holds_active_thread_sandbox); the middleware then
keeps the eager acquire and strict sync_agent_skills. Fresh runs still defer.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Bas Cancrinus <7222814+bascan@users.noreply.github.com>
* docs: remove changelog changes from OpenSandbox fix
* fix(opensandbox): sync skills when a remote is initializing
---------
Signed-off-by: Bas Cancrinus <7222814+bascan@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Willem Jiang <willem.jiang@gmail.com>
* fix(sandbox): stop the rest of a cancelled AIO command
The AIO persistent shell and the bash.exec script export the cancel marker
after bash has started, so bash's own /proc environ lacks it. Cleanup
terminated only the marked children, and bash then ran the remaining
statements of a `;`, newline, loop, pipeline or subshell command after the
run was cancelled.
Cleanup now first sends SIGINT to every process in a process group that
contains a marked process, as Ctrl-C would, and then terminates the marked
processes as before. An interactive shell drops the rest of the line and
keeps its cwd and exports; a one-off `bash -c` exits. A process group never
spans sessions, so only the shell session that ran the command is reached.
* test(sandbox): keep persistent-shell teardown quiet when the shell is gone
* fix(skills): make skill_manage share the routes' custom-skill mutation lock
The skill routes hold a per-owner lock (a process lock plus a sidecar
flock) around read -> write -> history. skill_manage held only its own
process-local per-skill lock, so a tool edit and a route edit of the same
skill could interleave, in one Gateway process or across several. One
overwrote the other while recording a stale prev_content, and the
overwritten revision dropped out of the history chain rollback walks.
Move the lock into deerflow.skills.mutation_lock and use it from both.
The tool takes it after its scans, so a slow model scan does not queue the
owner's other mutations, and re-reads under it what the scans assumed:
- patch is refused when SKILL.md changed since the patch was derived;
- edit and write_file record the content they actually overwrite;
- write_file does not recreate a skill deleted meanwhile;
- create does not overwrite a skill created meanwhile.
* chore(skills): keep the type: ignore on the Windows fcntl fallback
The routes carried it before the lock moved, and the other fcntl
fallbacks, including deerflow/skills/projection.py, still do.
* fix(agents): keep an unrenderable summary_prompt from failing the run
summary_prompt is a str.format template with a {messages} slot, so a
literal brace has to be doubled. The render runs outside the try that
guards the model call, so an unescaped brace raised KeyError out of
abefore_model and failed the turn instead of skipping compaction.
The middleware already documents the opposite: the automatic path
swallows a summary failure and leaves compaction state unchanged, and
raise_on_failure reports a real failure as SummaryGenerationError so
/compact can tell it from "nothing to compact". Route the render through
_render_summary_prompt, which turns a failure into None with a warning
naming the brace rule, and let the existing None path apply.
docs/summarization.md now states the template syntax.
* fix(agents): cover attribute and index template failures in summary_prompt rendering
Expand the render exception tuple to include AttributeError and TypeError so
{messages.foo} and {messages[missing]} share the same fail-open boundary as
literal braces and unknown placeholders. Add summary_prompt_hash to the
warning so operators can correlate the log line with the offending config
without the template or history appearing in logs.
Rewrite the regression suite around a real create_agent graph with
InMemorySaver: template failures preserve history and the checkpoint, the
summary model is never reached, and a repaired template recovers on the next
attempt. Document the template syntax and failure contract in
summarization.md, the middleware AGENTS.md, and the root README.
* fix(agents): log summary template error types only
---------
Signed-off-by: Yufeng He <40085740+he-yufeng@users.noreply.github.com>
* fix(hitl): warn loudly when hitl_approval is disabled instead of silently skipping the middleware
Raised in #8431: _insert_hitl_approval_middleware returns silently when
hitl_approval is absent or enabled != true, so agents run tools without
runtime human approval and nothing in the logs marks it. This keeps the
default (no behavior change) but makes the fail-open posture visible:
- emit a warning at middleware insertion time, with the exact config
keys to flip and a doc pointer
- state the disabled-by-default posture explicitly in docs/guide
Signed-off-by: DSHCorrectover <correctover@sina.com>
* test(hitl): unit tests for the disabled-visibility warning (three mount states)
- absence of hitl_approval -> warning + no middleware
- enabled=false -> warning + no middleware
- enabled=true -> middleware mounted, no warning
Runs the same assertions as our internal replay (AST guard-uniqueness,
mount-point coverage, behavioral stub replay) against the real package;
maintainer CI is the authoritative run.
Signed-off-by: DSHCorrectover <correctover@sina.com>
* fix(hitl): report disabled approvals at Gateway startup
---------
Signed-off-by: DSHCorrectover <correctover@sina.com>
Co-authored-by: Willem Jiang <willem.jiang@gmail.com>
* fix(nginx): leave multipart headroom above the upload limit
Gateway's default 100 MiB upload ceiling counts file bytes only, while nginx's 100M limit also has to carry multipart headers and boundaries. Two valid 50 MiB files therefore exceed nginx and return 413 before Gateway can apply its limits. Raise the thread-upload and project-document locations to 101M in the Docker, local-dev and Helm configs, and assert the proxy limit is strictly greater than Gateway's total content limit.
* test(nginx): size upload headroom from multipart framing
Compare the proxy ceiling with a representative multipart body: Gateway's maximum content plus part headers, closing boundary and filename slack. Base project-document headroom on its single-file limit. Document that uploads.* is runtime-configurable while the nginx ceilings are static, and drop the hardcoded 101M from unrelated prose.
---------
Co-authored-by: Tong-bit-art <Tong-bit-art@users.noreply.github.com>