FastAPI backend for MindsHub Cowork . Manages projects, conversations, files, scheduling, memory, and agent orchestration with a SQLite-backed data layer.
This repo is the Python backend . The frontend (Electron shell + React SPA) lives in a separate repo: mindsdb/cowork . They are developed and released independently. At runtime, the frontend spawns cowork-server as a local sidecar and communicates over HTTP ( 127.0.0.1:26866 ).
Requires Python 3.12+ and uv .
The server starts on . Confirm with:
Reviewed release dependencies
uv.lock is the runtime selection for this repository. CI, Docker and release smoke tests refuse a stale lock. cowork/release-requirements.txt is its generated runtime export, with environment markers and artifact hashes. Every wheel and source distribution carries that exact file; publishing checks both artifacts against the lock.
The release workflow selects Anton from uv.lock . Publishing a newer Anton alone does not change this server release. To move a dependency deliberately:
Review both the lock and export diffs, run the release checks, and publish a new server release. Change a declared compatibility constraint first when the intended version is outside it. Use the same process for any other dependency. Do not run a general upgrade while preparing a source-only release.
Cowork's release installer consumes the contract from the selected wheel or Git commit. Direct pip install and uv tool install cowork-server still resolve the public library compatibility ranges; they do not automatically consume this export. For a standalone server with this repository's reviewed selection, check out a reviewed release tag and run uv sync --locked --no-dev , then uv run --locked --no-dev cowork-server .
The eight platform/Python wheel checks use release constraints. When the lock selects an Anton release candidate, the required wheel gate waits for that exact version to reach PyPI's Simple index before resolving it; the publish runner repeats the wait before building. The weekly --floating check separately probes the public compatibility ranges and never rewrites the release lock. Build backends, the Python interpreter and operating-system packages are separate inputs; this policy fixes the application dependency selection, not every byte of an image.
When running alongside the Electron app in dev mode, the app spawns the server automatically — no manual start needed. The Electron app looks for a sibling cowork-server/ directory by convention (override with COWORK_SERVER_DIR ).
cowork-server imports anton's artifact folder constants ( anton.core.artifacts.internal_files ) at startup, with no fallback. An anton without those constants ( NON_CONTENT_NAMES and REVISIONS_DIRNAME , which mindsdb/anton#521 added, first in 2.26.10.2.1rc2 and first in a stable release in 2.26.10.4.1) makes the server fail to start with ImportError .
Initializes the database and validates configuration.
The existing CI jobs retain case inventories, phase timings and JUnit results. See test evidence and execution cohorts for collection, comparison and preservation checks.
make test/unit , make test/unit/coverage and make coverage/html run the unit tests in parallel, one pytest-xdist worker per logical CPU, and CI runs the same target. Each worker is its own process with its own temporary database and COWORK_HOME . Set PYTEST_WORKERS to choose the number of workers, or 0 to run serially, for example make test/unit PYTEST_WORKERS=0 . A plain uv run --locked pytest runs serially. A test that passes alone but fails in a parallel run usually depends on state an earlier test left in the process; rerun it serially with the tests that ran before it on the same worker ( -v names the worker).
Tests use an isolated in-memory database and temporary directories — no side effects on your local ~/.cowork/ data.
Every unit test runs under a guard for blocking work where it stops other requests ( tests/_blocking_guard.py ). A test fails when cowork code checks out a pooled database connection on the event loop. It also fails when, in org tenancy, cowork code reads, lists, writes, moves, deletes or closes a file under COWORK_HOME on the event loop, or on a worker thread that run_efs didn't start, such as the file a returned Starlette FileResponse opens on anyio's threads. Move such work into run_db or run_efs ( cowork/db/units.py ). The sites the code has today are listed in the guard with their reasons, each by the function that blocks and the cowork call nearest the work, past the shared file helpers in cowork/common/paths.py , so new work below a listed function fails too. A listed site that no test reaches fails a full run, so remove its entry when you move the work. A run that can't tell, such as one test file or --setup-only , says in one line that it skipped that check.
The guard sees only what the tests drive. File store work counts only in a test that sets org tenancy in the environment, as the org_deployment fixture does, or on the settings the app already holds. A test that patches one module's own check, such as its _org_mode , switches that module alone, so the guard doesn't see its file work. The guard also sees only the calls it wraps: the os calls in its _PATH_PARAMETERS , open and io.open . A read on a file object opened earlier, fcntl.flock , os.readv , os.writev and os.sendfile go unseen. On a worker thread it watches anyio's threads and the event loop's default executor, not a plain threading.Thread or an executor of your own.
A few tests need a real Redis or PostgreSQL, because hosted Cowork runs on both: two replicas reading one Redis ( tests/integration/test_two_replicas.py ), the Redis clients through a killed connection, a demoted primary, a connection closed during its handshake and a lost ( tests/integration/test_redis_failover.py ), and the migration and launch-lock contracts on PostgreSQL. They carry the redis_service or postgres_service marker and skip when their service is absent. make test/services runs only them. Point it at a disposable Redis and database. The failover tests empty the database COWORK_TEST_REDIS_URL names and run REPLICAOF , CLIENT KILL and ACL SETUSER on that Redis, putting the server back afterwards, so they run only when the URL is set and skip otherwise, even with a Redis on localhost:6379 . The migration test downgrades the database to an empty schema:
On every pull request and every push to staging , .github/workflows/tests-services.yml runs them against Redis 8.2.3 and PostgreSQL 16.13 service containers with COWORK_REQUIRE_SERVICES=true , so a missing service fails the job instead of skipping. The desktop wheel release doesn't wait on that job.
A run that requires every prerequisite ( COWORK_REQUIRE_INTEGRATION=true or COWORK_REQUIRE_SERVICES=true ) fails when a test skips, or is left out with --deselect , unless tests/skip_allowlist.yaml names it with a reason ( tests/skip_guard.py ). Any run that sets either flag lists what it left out at the end of its report and in the GitHub job summary. The allowlist names two tests: the remote-worker disconnect check, an operator-run proof described under Streaming & scheduling , and the post-deploy cancel check, which skips when the model ends its turn before the turn can be seen running, so there is nothing to cancel.
Post-deploy integration runs use the target cluster's self-hosted runner. Dev and staging obtain the fixed cowork test suite through MindsHub's cluster-only service URL. Production must not mutate that shared @emailsink.dev identity while the fixed password remains committed. The production test path therefore accepts a dedicated COWORK_TEST_API_KEY secret, a reviewed COWORK_TEST_USER_EMAIL variable on the non-staff @mindshub.ai domain, and the immutable dedicated organization id in COWORK_TEST_ORG_ID . The suite resolves and matches that principal and organization through production MindsHub, and refuses an employee-classified or MindsHub-admin identity before testing. A missing or mismatched identity fails the required prod run instead of falling back to provisioning or reporting skipped tests. Standing-identity mode also requires the test target to be exactly before the first network call, so a changed environment file or workflow cannot send the production key to another origin.
Do not store or use COWORK_TEST_API_KEY yet, or configure its paired email and organization id for a production run. The live prod GitHub Environment has no protection rules or deployment-branch policy. Although publish.yml refuses to enter its production build/deploy job from a non-main ref, a manually selected branch runs that branch's workflow text and can remove the check. Workflow code is therefore defense in depth, not the authority that protects an Environment secret.
Before COWORK_TEST_API_KEY is stored or used, or any production evidence run starts, the prod Environment must have a nonempty required-reviewer rule with prevent_self_review: true , can_admins_bypass: false , and a selected-branches deployment policy whose only entry is the main branch, created as an exact Branch rule (no tag, wildcard, or second branch rule). Verify the live settings without reading any secret value:
The first command must show exactly one required-reviewer rule with at least one named reviewer and prevent_self_review: true , plus can_admins_bypass: false , protected_branches: false , and custom_branch_policies: true . The second must print exactly [{"name":"main","type":"branch"}] . Only after both checks pass may an operator store COWORK_TEST_API_KEY , COWORK_TEST_USER_EMAIL , and COWORK_TEST_ORG_ID on that Environment. Evidence must come from a fresh main-branch run started after the protection was active, with run_attempt: 1 ; an eligible reviewer other than the run's actor and triggering_actor must approve its prod Environment gate. A rerun of an attempt that began before protection does not count. Keeping the values at Environment scope prevents non-prod jobs from receiving them, but that scope is safe only when these Environment controls are active.
Nightly production read-only smoke
The production nightly reads production on mdb-prod at 43 7 * * * once its schedule is live. It is held today; the Environment prerequisites below say what turns it on. It uses the same guarded standing identity, but selects only tests/integration/test_production_read_only.py . That selection is GET-only: it reads health, conversations, schedules, files, and pins. It never provisions an identity and does not create conversations, schedules, files, artifacts, or model turns. The broad integration target excludes the production_read_only marker, so release and staging callers cannot include this production-only selection by accident.
Failures and the recovery use the shared engineering-channel notifier. The nightly is an alert, not a release gate. Review any new endpoint in READ_ONLY_ENDPOINTS together with tests/test_production_read_only_workflow.py , which rejects mutating HTTP calls and pins the complete request list.
The unattended nightly cannot reference the existing prod Environment. That Environment must retain its required-reviewer gate for production deploys, and GitHub pauses every job that references such an Environment until a reviewer approves it. The monitor instead uses a dedicated prod-read-only Environment with unique COWORK_PROD_READ_ONLY_API_KEY , COWORK_PROD_READ_ONLY_USER_EMAIL , and COWORK_PROD_READ_ONLY_ORG_ID inputs. Unique names prevent a missing Environment value from falling back to a repository or organization credential.
Before promoting this workflow to main , an operator must create prod-read-only with no required-reviewer or wait-timer rule and a custom deployment policy whose only entry is the exact main branch. The repository's main protection must continue to require a pull-request approval, resolve review conversations, and apply to administrators. These controls let the scheduled job start without weakening the separately protected prod Environment:
Only after those controls exist may the operator copy the already reviewed standing identity into the dedicated names. The commands prompt for the secret and variable values and do not print them:
Verify policy and names without reading credential values:
The Environment response must have no required_reviewers or wait_timer entry and must enable only custom branch policies. The branch-policy response must be exactly [{"name":"main","type":"branch"}] . The branch-protection response must show at least one required approval, administrator enforcement, and required conversation resolution. Do not dispatch until every check passes and the cowork-server#472 prerequisite has landed.
The nightly schedule is held out of the workflow until those checks pass. GitHub arms a schedule: trigger as soon as the file reaches the default branch, so shipping one before the Environment exists does not buy a monitor, it buys a nightly page that reports a missing credential in the same shape as a production outage. workflow_dispatch is the only trigger until an operator has provisioned prod-read-only and watched one dispatched run go green. Restore the schedule: block with - cron: "43 7 * * *" and delete this paragraph in the same change; a contract test fails if only one of the two happens.
Set LOG_LEVEL (default WARNING ) to control verbosity. Enable file logging with ENABLE_FILE_LOGGING=true (writes to LOG_DIR , defaults to ~/.cowork/logs/ ).
Database exception records omit SQL, parameter values, driver details and tracebacks, in the owned console and file handlers and in everything Uvicorn logs. setup_logging() attaches the database and provider filters to the uvicorn , uvicorn.error , uvicorn.access and uvicorn.asgi loggers, and to any handler a launcher already installed on them, so the policy holds under every launcher: the cowork-server CLI, python -m uvicorn cowork.server:app , or uvicorn spa_wrapper:app with Uvicorn's default log config. Uvicorn's levels stay as the launcher set them, so lifecycle lines such as Finished server process still print. The shared filter replaces each such record with Database operation failed: error_type= sqlstate= site= . : , keeping only valid driver SQLSTATE codes. site names the logging call. When that call only relays the error, as Uvicorn's request runner and the server's lifespan guard do, site names the deepest Cowork frame the error passed through outside the session wrappers ( cowork.db.scoped , cowork.db.session and cowork.db.units ), such as the service line that ran a route's failing statement. Session logs retain error types and client HTTP status, including the 503 for a full pool. A 5xx HTTPException logs its status. Its own detail is not logged, but its cause's class, message and traceback are, unless the cause chain holds a database or provider error, which the filters replace. Any other error, including one that carries a status_code without being an HTTPException , logs only its type in the session line, then reaches Uvicorn, which logs it through the same filters. Exceptions and HTTP errors returned to callers stay unchanged.
A database error while the server starts or stops (a migration, the seed rows, or Postgres not yet reachable after a reboot) logs that safe line through the owned handlers. Uvicorn then prints only RuntimeError: Database operation failed during server startup (or shutdown ), because Starlette hands it the failure as plain traceback text, which no filter can read. Other startup errors keep their traceback.
A call site passes the ids that locate a failure as extra=log_context(...) from cowork.common.logger , which sets record attributes: request_id , project_id , schedule_id , conversation_id , and artifact_slug for one artifact or artifact_slugs for several. The filters never change them, and the console and file formatters render them before the message, for example [Req: ][Project: ][Schedule: ][Conversation: ][Artifact:' '] or [Artifacts:' ', ' '] . Artifact slugs are folder names, so they render quoted. A site that carries only a request id passes extra={"request_id": ...} directly.
OpenAI and Anthropic SDK errors (any OpenAIError or AnthropicError ) and Anton's typed provider errors are found, in the same handlers and Uvicorn loggers, through each exception's cause, then its context (even a suppressed one), then its exception group members. The record becomes Provider operation failed: error_type= provider_error= status= ; a wrapper's own status is never used. Cowork's request ID ( [Req: ] ) stays on the line; the provider's own request ID is not logged. Provider messages, bodies, requests and tracebacks are omitted. Routing failure warnings also omit body-derived type, code and parameter fields. Original exceptions, probe verdicts and client HTTP/SSE errors stay unchanged.
Uvicorn's access line keeps each request's method, path and status, and setup_logging() replaces its query with ?[redacted] , because a query can carry an OAuth callback's code or a webhook's verify token.
SQLAlchemy query and connection diagnostics stay at WARNING , even when application logging is set to DEBUG . SDK request diagnostics and HTTP client logging stay at ERROR , including Anthropic, httpx2 and the whole httpcore and httpcore2 namespaces, because they can include request bodies, URLs or response headers such as set-cookie .
Releases are automatic on merge; there is no version to bump by hand (the package version comes from the tag).
Push to main : publish.yml runs the unit tests, cuts a CalVer tag and GitHub release ( v0. . . . ), then builds and publishes to PyPI via OIDC trusted publishing.
Push to staging : publish-staging.yml does the same on the rc pre-release stream ( v0. . . . rc , GitHub and PyPI pre-release). When PyPI's newest anton-agent upload is an rc, it pins that rc into the wheel so the pair installs exactly. When the newest upload is a stable release, the wheel keeps the anton-agent range from pyproject.toml .
Both take their version, tag, and release from the shared calver-release.yml reusable in mindsdb/github-actions ( prerelease: true selects the rc stream). The publish jobs stay in these two workflows: PyPI trusted publishing matches the OIDC claim on the workflow filename and does not support reusable workflows.
Nightly staging integration
The cowork-server maintainers own the deployed integration signal and its staging prerequisites. nightly-staging-integration.yml runs every day at 06:41 UTC and can also be dispatched by hand. It calls the same tests-integration.yml reusable workflow as a deployment on mdb-dev , then reports a failure or the first recovery through the shared engineering-channel notifier. It is a standalone monitor and never gates a publish, release, or deployment.
The nightly runs staging's copy of the tests, not main's. GitHub starts every scheduled run on the default branch, so the checkout would otherwise take main . main trails staging by every commit waiting for the weekly release. Any behavior change among those commits fails main 's tests against staging's pods, even though staging works as intended. So the job passes ref: staging , and tests-integration.yml hands that input to actions/checkout . The deploy callers leave ref empty and keep testing the commit they just deployed. test_nightly_integration_workflow.py fails if a scheduled caller's ref differs from its deploy-env .
codeql.yml runs CodeQL on every pull request and push to staging and main , and weekly on main . Each event's pipeline calls it as a job ( dev-build-deploy.yml , publish-staging.yml , publish.yml ), so its results sit in that event's one run. It scans Python, JavaScript/TypeScript and the workflows themselves with the default query suite, and needs no build. It skips tests/ , which never ships and whose fixtures plant fake secrets on purpose. It replaces CodeQL's default setup, which scans only the default branch and branches under classic branch protection. staging is protected by rulesets, so default setup never scanned a pull request onto it. Default setup must stay off in the repository's code scanning settings, since GitHub refuses a workflow's results while it is on.
The suite may create and delete test conversations, schedules, files, and agent turns in staging. The fixed test tenant is reserved for the cowork suite, and the workflow sets COWORK_REQUIRE_INTEGRATION=true for staging so a missing target, identity source, replica, or port-forward fails instead of becoming a green skip.
In the packaged Electron app, a background updater checks PyPI on every launch and upgrades automatically (with rollback on failure). See server-updater.ts in the frontend repo.
The server is designed to be agent-agnostic — core features (projects, conversations, files) are shared across agents, while agent-specific behavior lives in harness adapters. See docs/DESIGN.md for the full architectural rationale.
Server modes and terms
The server runs in one of three modes, set by two settings ( Configuration ):
The code names MindsHub mode TenantScope.org_mode , and the app learns it from /health 's org_mode .
MindsHub : the MindsDB platform service this server asks organizations, people, teams, permissions and artifact rules. Its public reads go out with the caller's own credential ( cowork/services/mindshub_client.py ); its internal artifact-access routes take a shared secret ( cowork/services/artifact_access.py ).
MindsHub UI : the web app's build flag VITE_PLATFORM_UI , which shows MindsHub's model, provider and workspace controls. It is set in the app's build, not here, and it is separate from the server's mode: the cloud build turns both on, and neither implies the other.
Audience : who a skill or an artifact is shared with, under MindsHub's artifact rule names: org_allowed (Everyone at ‹org›), allowed_team_ids (Specific teams), allowed_user_ids (Specific people in the organization) and, for an artifact only, allowed_emails (anyone else, by address). Nothing set is "Only me".
Default team : the organization's team MindsHub marks is_default , whose members are everyone in it. Naming it is stored as org_allowed , never as a team.
Always on : a skill shared with everyone or with a team that the agent applies on every task in the turns of the organization or the team, instead of recalling it when a task needs it. It stays on demand for people a skill is shared with personally ( Always-on skills ).
Off for me : a person's own switch for one skill ( PUT /api/v1/skills/{skill_id}/me ), which leaves it out of their turns only. A skill's enabled turns it off for everyone who reads it; a turn uses a skill only when both are on.
A harness adapts an external agent library (Anton today) to the cowork-server interface. All harnesses implement the HarnessProvider protocol ( harnesses/base.py ), which exposes streaming responses, skill sync, and memory operations. The active harness is selected via the harness user setting. To add a new agent, implement the protocol and register it with the @register decorator.
Each turn's scratchpads exit when the turn ends. The Anton harness builds a fresh ChatSession for every turn, and each scratchpad that session starts is a child process of the server. When the turn completes, fails or is stopped, close_session_scratchpads ( cowork/common/chat_session.py ) kills those processes. A Stop or an opted-in client disconnect also interrupts a running cell and ends its turn; the harness does not start another model step. The turn starts a new process, which reloads the variables the old one saved to the conversation's namespace snapshot after every cell. Only the scratchpads close: full-stack backends the agent launched keep running. Anything a cell starts in the scratchpad's process group, such as a default subprocess.Popen child or a thread, dies with it, so a long-lived service belongs in launch_backend . A child started with start_new_session=True or setsid escapes: it keeps running and holds two of the server's pipe descriptors until it exits. The connector probe closes its scratchpads the same way, and shutdown waits up to 5 seconds for closes still running. A scratchpad runs as python /anton_scratchpad_ .py , so pgrep -f anton_scratchpad_ counts the live ones; it should drop to 0 once no turn is running.
Streaming & scheduling
Agent responses stream to clients via Server-Sent Events (SSE) on POST /responses/ . The server tracks in-flight streams and supports cancellation ( /responses/cancel ) and late-join tailing ( /responses/tail ).
A streaming API question can set "cancel_on_disconnect": true to stop its own run when the originating POST connection closes before the answer finishes. The option is a strict boolean, defaults to false , and requires "stream": true . Browser questions leave it off, so a reload still reconnects to the detached answer. Closing a /responses/tail observer never cancels a run. If a client leaves during routing or setup, that request's cleanup prevents it from leaving a live producer behind. Completion and server shutdown retain their existing outcomes.
A question can set "memory": "off" to read no learned memory and learn nothing, while other questions keep memory, for example a scored evaluation run on a deployment whose testers have it on. The turn runs as every turn does with MEMORY_ENABLED=false : two empty memory tiers in its scratch folder, no background memory passes, and the operator's managed rules still read. A later turn sent without the key in the same conversation learns from the whole conversation, its earlier memory-off turns included, so send the key on every turn of the conversation. The field takes "on" (the default) or "off" . A deployment that doesn't trust identity headers, such as the desktop app, still reads stored memory with memory off, so it refuses the question with 501.
Each answer also gets one response.memory_read event, before its response.figure_sources , if any, and its response.completed . read says whether the turn read learned memory, the person's own or the shared store, and entries counts the rules, lessons, profile lines and scratchpad tips anton put in front of the model ( ChatSession.memory_read ). The operator's managed rules aren't counted. A turn on two empty tiers, as every question with "memory": "off" runs, reads nobody's learned memory, so it gets "read": false and "entries": 0 whether or not the deployment sets COWORK_DEPLOYMENT_KIND . So does a direct answer from the routing gate, which runs no agent. The harness sends the event with the first event anton streams after building the turn's prompt, which anton does before its first model call, or as the turn fails, is stopped or ends, if anton streams nothing after it. So a turn that fails after building its prompt carries it, and so does a turn the user stops after that. The event is saved with the answer's events. An answer that ended before anton built its prompt gets none, and so do a turn on the remote worker and a turn on an anton without ChatSession.memory_read .
The root of response.created carries a run_id UUID for that execution. An API client or proxy can send {"conversation_id": "...", "expected_run_id": "...", "reason": "client_gone"} to POST /api/v1/responses/cancel . The guard must match the authorized run; a stale or foreign ID returns 404 and cannot stop a successor. Turn numbers can repeat, so they are not cancellation guards. Existing Stop calls without expected_run_id still cancel the conversation's current authorized run. A 200 response reports whether cancellation was requested; the stream's terminal event and persisted answer determine the final outcome. Database or worker failures can prevent successful finalization.
A proxy that keeps reading upstream after its client leaves must relay the disconnect explicitly. The self-hosted recording proxy consumes the option, keeps its upstream connection detached for audit records, and sends an exact-run cancel. Its final record comes from the answer's events. See Disconnect ownership and exact-run cancellation .
tests/test_disconnect_transport.py covers real sockets and a local executing scratchpad. For the deployed remote-worker check, use the standard post-deploy identity and COWORK_BASE_URL , then set COWORK_RUN_DISCONNECT_WORKER_TEST=true and COWORK_DISCONNECT_NAMESPACE before running uv run pytest -q tests/integration/test_disconnect_worker.py . COWORK_DISCONNECT_CONTEXT optionally selects the Kubernetes context. The runner needs read access to pods and permission to exec the observer in the worker container. The check starts its own bounded cell and observes process/container identity and heartbeat cessation; a cancelled SSE event alone cannot pass it. It skips unless explicitly enabled.
/responses/cancel takes an optional reason . The UI sends "stalled" when it heard nothing for its idle window, and the turn then saves as a response.failed with code stalled , so a reload shows the stall card. Without a reason, or with any other value, the cancel is a Stop and keeps the partial answer with no error row. While anton waits on a model call that sends no output, the server (in cloud, the anton pod) writes a model_wait progress frame every 20 to 25 seconds so the turn's idle bounds do not end it. A model call that sends no output for 600 seconds ends the turn with code model_timeout ; anton's ANTON_MODEL_CALL_IDLE_TIMEOUT_S sets that limit, and 0 or less turns it off. Turn liveness and idle bounds lists every bound a quiet turn meets and what happens when each one fires.
POST /responses/ reads what it needs (the turn's settings, its attachments, the conversation, whether an always-on skill reaches the turn and the routing gate's history) as one short database unit in a worker thread ( run_db in cowork/db/units.py ). A turn that carries attachments, or names no project by id and so may start its conversation in the general project, whose folder is checked, runs that unit on the file store's threads instead ( run_efs_unit ). Deciding whether an always-on skill reaches the turn can take its skill file, which that unit doesn't read: when one of the organization's skills is always on, the file is read in a unit of its own on the file store's threads ( run_efs_unit ), and when none reaches the turn, the gate's history is read in one more database unit after it. The request holds no pooled connection while the gate or the stream runs, and a wait for one never stalls the event loop. When no connection frees within POOL_TIMEOUT (5 s by default), the request is refused with 503 , a Retry-After header and {"detail": "Cowork is busy. Try again in 5 seconds.", "code": "server_busy"} . An answer that meets the same wait after its stream started ends with one response.failed frame with code server_busy and the retry_after and retry_at fields rate_limited carries. The question sent again after that frame gets a stream of its own.
That unit also saves the turn's model and reasoning_effort onto the conversation ( ConversationService.record_turn_picks ), so GET /api/v1/conversations/ and GET /api/v1/conversations/{id} return the latest picks as model and reasoningEffort , and a reopened chat comes back on them. A turn that sends no model or no effort keeps the saved one: Cowork sends no model for a pinned model its picker no longer offers, such as one the wallet locks, so that pin comes back after a top-up. A turn that goes back to the default names the pick in reset_picks ( "model" for Model Router or the operator's default model, "reasoning_effort" for the default effort), and that clears the saved one, so a reopened chat comes back on the default. A model or effort the turn sends wins over its own reset. A comparison side keeps the model and effort it was set up with, since its turns run on those whatever the request says.
In a turn this process runs ( COWORK_TURN_BACKEND=inprocess ), scratchpad call-end events retain their complete input in the stream and saved conversation, including code longer than 65,536 characters. The turn's write check can therefore read bindings from a long earlier cell. Results and every other tool's input retain their 65,536-character cap. cowork-server adds no cap of its own to a remote pod's scratchpad call input: the pod's own 65,536-character cap ( MAX_STEP_CHARS in anton's anton/cloud_turn/__main__.py ) is the only one, so a remote turn's saved call-end event can hold a cut call. Remote turns replay no cells and refuse ANTON_WRITE_APPROVAL , so no write check reads it. Replay preserves an explicit cell error; when a truncated result loses that field, only its saved cell_status="ok" establishes success, and the cell otherwise says it failed, timed out or has an unknown outcome. The agent reads that outcome too: its notebook view and compaction summary show such a cell as failed, and anton's end-of-turn memory pass counts it as one. A failed or unconfirmed cell keeps its code for binding analysis but cannot establish ownership of a file while it stays in the pad. A cell that compaction folds into a summary keeps that flag, so an earlier failed write there can't make its file the agent's own either. Plain-text refusals are never replayed as executed cells. Old events whose call and result both lost their code cannot be recovered.
An answer produced in this process ( COWORK_TURN_BACKEND=inprocess , the default) runs its own database work as units too. One at the start saves the question (pending) and loads the conversation. The harness reads the history, the attachments and each recall_history lookup in units of its own. One at the end saves the answer and clears the question's pending flag in one commit. Both hold a per-conversation lock that keeps a conversation's message writes in order. So such an answer holds no pooled connection while the model answers or the stream runs. A save that fails at the end of a finished or stopped answer ends the stream with response.failed ( server_busy when no connection freed in time), never response.completed . An interrupted or failed answer whose save fails keeps its own response.failed frame, and the boot's recovery seals an interrupted one into history. A Stop, a second Stop or a shutdown that arrives while a turn saves its question or its answer waits for that save, so the stream's last frame always matches what the database holds. The compacted history summary and new artifact index are database units too. The harness waits for its cleanup through run_to_completion , so a Stop cannot abandon these writes, and a full pool never blocks the event loop. A shutdown can still lose one that has not started when the event loop closes ("Work on the shared file store" below). When the pool stays full, a Stop waits up to POOL_TIMEOUT for each pending write (the answer, a compacted summary and a new artifact's row), so /responses/cancel can take up to three times POOL_TIMEOUT . A Stop during a running cell returns within 5 s only while the pool frees connections. An answer produced by the remote backend ( COWORK_TURN_BACKEND=remote ) works the same way. Saving the question, saving the compacted summary the pod reports, indexing the artifacts it created and saving the answer are each a unit, and the artifacts' owners are looked up in a unit before they are published. Staging the pod's workspace, reading what the pod is seeded with (its history and the project's memory), building the skills it gets and saving the memory it reports work on the file store, so each runs as one unit on the file store's threads ( run_efs_unit , "Work on the shared file store" below). So it holds no pooled connection while the pod answers, and its settings come from the snapshot the request loaded. The turn indexes the artifacts the pod created once, however it ends. A shutdown waits up to 8 s at the end of its teardown for that write, and loses it if it is still running then ("Work on the shared file store" below). A Stop waits for that write and then for the answer's save, so with the pool full /responses/cancel can take up to twice POOL_TIMEOUT . A memory or summary save that is still waiting for a connection when a Stop lands is dropped.
The connector form's stream ( POST /api/v1/connectors/submissions/ ) reads its conversation and the settings that build the probe's model client, and saves the probe's narrative, as units too. So it holds no connection while the credential probe waits on the model, and it never waits for one on the event loop. When no connection frees in time for the conversation read or the settings read, the form shows Cowork is busy. Try again in 5 seconds. and the probe does not start. The stream ends at that refusal and saves nothing to the conversation. A save of the probe's narrative that fails still ends the stream with response.completed , because the form carries the probe's outcome.
Every other coroutine route reads and writes through database units as well, and takes the caller's tenant scope ( get_tenant_scope ) instead of the request's session. , settings, the MindsHub workspace selector, the channel configuration routes, a model comparison's usage, delete and continue routes, and the read of a skill's stored rule before its sharing save therefore wait for a connection in a worker thread, and a full pool refuses them with the same 503 . tests/test_coroutine_routes_hold_no_session.py fails when a coroutine route takes the request's session, and when a coroutine dependency of any route does, since that dependency runs on the event loop even under a sync route. The routes still allowed to are listed there with their reasons, and all four are desktop-only. A channel turn, an inbound Slack, Discord or Telegram message, runs the same way. Its binding, its conversation, its harness, its question, its answer and the artifacts it created are each read or written in a unit, so it holds no pooled connection while the agent answers. The turn's first unit reads its harness and loads its settings. The rest of the turn runs with that snapshot bound, as a browser turn does ( use_turn_settings ). The pod's seed is read in one unit by the same reader a browser turn uses ( ResponsesHandler._read_remote_turn_inputs ), less the project memory. That read and each memory save the pod reports take their settings from the snapshot, so no unit waits for a second connection while it holds the first. The workspace staging before the pod starts, and the memory and compaction the pod reports, go through the same helpers a browser turn uses ( stage_remote_workspace , save_turn_memory and save_turn_compaction in cowork/handlers/responses.py ). The staging, the skills block the pod gets and each memory save work on the file store, so each runs as one unit on the file store's threads ( run_efs_unit ). A full pool or a busy file store refuses the turn at its staging or its skills block, but a memory or compaction write it refuses is dropped with a WARNING, and the turn goes on to its . When the pool or the file store refuses a channel message before the agent answers it, the sender gets one short , "I'm overloaded right now and couldn't start on that. Please send it again in a minute.", and the event is still recorded failed . A refusal while the binding is read or made answers only a direct message or a message that mentions the bot, since the channel's trigger rule is not read yet. Once the agent has answered, a full pool never costs the sender the : the saves of the question and the answer each try 3 times, 1 and then 2 seconds apart, and a save still refused is dropped with a WARNING naming the conversation, and the is delivered anyway. The turn then sends the files of the artifacts it created or touched, as its own artifact cards name them, never another conversation's from the project's shared artifacts folder: at most 3, each a regular file inside the project's .anton/artifacts , read in one run_efs call through descriptors that do not follow a link. A file larger than the adapter's own upload cap ( max_attachment_bytes : 10 MiB for Discord, 50 MiB for Slack and Telegram, 100 MiB for WhatsApp, and 100 MiB for an adapter that states none) is skipped on its size before any of it is read. A file store that frees no slot in time sends no files, with a WARNING, and the turn still counts as delivered. Each adapter's send_attachment takes the bytes and the file name, and refuses a file past its own platform's cap. A channel attachment keeps only the last component of its platform file name, as an upload does ( upload_basename in cowork/services/files.py ); a name that is empty, . or .. is stored as file . In org tenancy a channel turn saves no memory at all: it runs for its organization with no member, and neither memory tier takes an entry without one, so the turn logs one INFO line instead. The webhook records each inbound event in a unit before it schedules the event. A cancel of the intake, such as a credentials change, a lost lease or a shutdown, waits for the event in hand to be both recorded and scheduled, so a recorded event is never left for its redelivery to be dropped as a duplicate. Telegram's poll loop polls a batch again when its intake fails, so a full pool delays those messages and the loop keeps running. A stream (the Discord gateway, Slack Socket Mode) has no offset to resend, and a new connection does not bring a message back, so a batch the pool refuses is taken in again on the same connection, 3 seconds after each refusal, until it is recorded; dedupe drops the events of it already recorded. An event is marked failed only when the runtime itself fails on it. Its status is a record for operators that dedupe does not read, so a status write the pool refuses is dropped with a WARNING. The ingress reconcile, which runs every 30 seconds on every replica, reads every organization's installations in one unit.
A question sent into a conversation whose streamed turn is still answering is refused with 409 and {"detail": "Another question is still being answered in this conversation. Wait for it to finish, then send yours again.", "code": "turn_in_progress"} . It is refused before anything reads or saves it, and the running answer goes on. A turn whose stream has already ended counts as finished, so a question queued behind it is accepted. The check runs before any database read, and RunRegistry.start repeats it under a lock for that conversation before it opens the new turn's buffer. Two questions racing through the gate read the same history, so both compute the same turn number, which names the turn's buffer and which boot recovery reads as the question's position in the history. Once a turn saves its question, the registry refuses a later start at that turn's number or an earlier one, even after that turn has ended. So the second of two racing questions is refused with the same 409 whether it reaches the registry before or after the first turn ends, and two questions never a buffer. A question that follows a turn that saved nothing (refused for a full pool, say) keeps that turn's number and is accepted. A queued follow-up waits for the preceding turn's internal terminal record once its final client frame is being written; slow buffer creation for one conversation does not hold up other conversations.
With several replicas ( COWORK_STREAM_BACKEND=redis ), a send that reaches another replica than the one running the conversation's turn gets the same 409 . Each turn takes its conversation's turn claim in Redis before it opens its buffer, renews it every 10 s, and releases it once its stream has a terminal record. Only the run that holds the claim writes the conversation's turn index entry, and a channel turn writes it only while no run holds the claim, so Stop and answers keep reaching the run that is answering. A turn also notes there that it saved its question as soon as it saves it, so the second of two racing questions is refused with 409 on every replica, also when it arrives after the first turn ended. A claim that is not renewed lapses 90 s after its last renewal, longer than the stall the liveness probe forgives (up to 65 s) plus the time a claim can have run down when that stall starts. A send that arrives while another replica's turn writes its final frame waits up to 10 s for that turn to release its claim, as a follow-up on the same replica does. When Redis cannot say whether another run holds the conversation, the send is refused with 503 , Retry-After: 2 and {"detail": "Cowork is busy. Try again in 2 seconds.", "code": "server_busy"} . A claim that a refused send may have taken, or that a finished turn could not release, is released again every second until Redis answers, so it is gone a second after Redis is back. A process that starts in a pod releases the claims an earlier process in that pod left, and writes the controller's cancel flag for each of their turns, which relies on one server process per pod. That covers a container restarted in place, after an OOM kill or a crash, that starts again within 90 s of its last renewal. A liveness restart kills a stalled process only after its claims have lapsed, so it counts as a force-kill here. A pod that is force-killed or lost releases nothing, so a send into a conversation whose turn it was relaying is refused with 409 until that turn's claim lapses, up to 90 s, and is admitted after that. Nothing ends that dead turn's stream or saves it yet: a reader that stays attached ends the stream after its idle cut, and its question stays pending. Where turns run in a sandbox, the dead turn's sandbox turn runs on until it ends or reaches the controller's turn limit, and the send in that conversation waits behind it, unless a Stop on the dead turn, sent before that send, cancels it. A conversation delete stops the turn it finds running, on whichever replica it lands. The replica running the turn cancels it and releases its claim. Another replica reads the claim and writes the turn's cancel flag with the cause discarded , so the turn stops without saving into the deleted history or writing to its deleted stream, and releases its claim; the send is admitted once it has stopped. A delete that cannot write that flag logs turn_discard_cancel_failed , and the send is then refused with 409 until the turn ends. A conversation delete that cannot reach Redis to forget the conversation's turn index entry logs turn_index_forget_failed , and a send at or below the deleted turn's number is then refused with 409 on every replica until 5 minutes after that turn released its claim. A turn whose process died before its release left no release time, so such a send is refused until the entry expires, an hour after the turn started. That is how long a turn's saved question goes on refusing a send at its number that read the history before the save, far longer than a request spends between reading the history and starting its turn. The claim does not order database writes either: a save that outlives its turn at shutdown can still be writing when a turn on another replica starts. cowork/streaming/turn_claim.py describes the keys. The file backend never reads or writes them.
Where turns run remotely ( COWORK_TURN_BACKEND=remote ), a replica that has begun ending its turns for a shutdown refuses a new one with 503 , Retry-After: 1 and {"detail": "Cowork is busy. Try again in 1 second.", "code": "server_busy"} , the refusal a full database pool gives. The retry reaches another replica. deployment/cowork-server/README.md describes what a shutdown does to the answers in progress.
A turn that fails ends with one response.failed frame carrying a stable code and the user-facing error ( cowork/handlers/turn_errors.py ), and the conversation's saved events keep the same payload, so a reload shows the same card. For included_allowance_exhausted , window_allowance_exhausted and free_serving_paused the frame also carries reset_at , the instant the free way forward comes back. An in-process turn passes the gate's X-MindsHub-Reset-At header through as sent. A hosted turn takes it from the anton worker's turn_failed , which scratchpad-controller forwards beside error . The producer keeps it only for those three codes and only when it parses as an ISO-8601 instant with a UTC offset. An older worker sends none, and its frame has no reset_at . For budget_exceeded the frame also carries budget_scope ( org , workspace , api_key , team , user , all_members , or a newer scope), budget_period ( day , month or year ) and, for a per-model budget, budget_model (the model's alias; the app shows its catalog label), taken the same way from the gate or the worker's turn_failed , each only when a well-formed value was sent. For window_allowance_exhausted (a Plus or Pro window is spent and the wallet cannot pay) the frame also carries window ( 5h or 7d ), and for model_not_in_tier (the plan's allowance does not cover the model and the wallet cannot pay) it carries required_tier ( plus or pro ). The gateway sends both fields at the top level of its error body, so an in-process turn reads them back off the response; a hosted turn takes them from the worker's turn_failed , and the producer keeps each for its own code only and only when it is one of those values. Neither has a typed anton stop yet, so an in-process turn recognizes them by the X-MindsHub-Reason header or body code alone, and a hosted turn maps the type names WindowAllowanceExhaustedError and ModelNotInTierError once the worker raises them.
In-process turns pick the billing code from anton's exception type, the same way hosted turns do: WalletEmptyError gives token_limit , AllowanceExhaustedError gives included_allowance_exhausted , FreeServingPausedError gives free_serving_paused , and BudgetExceededError gives budget_exceeded . The locked anton (2.26.11.9.1) predates Bud...
