The platform for continuously improving AI agents.
Run the assistant's workspaces on Modal and remove Daytona (#359)
Freyam Mehta482535319e54
diff --git a/.agents/skills/backend-architecture/references/assistant.md b/.agents/skills/backend-architecture/references/assistant.mdindex f10f4a52..44a0b12e 100644--- a/.agents/skills/backend-architecture/references/assistant.md+++ b/.agents/skills/backend-architecture/references/assistant.md@@ -12,7 +12,7 @@ The Console's assistant is a second author beside a customer's coding agent, sco- A message is delivered with `threads.brief`: what the dataset holds now: its intent, the linked capability's contract, the split sibling, its pipeline, and for the source and latest versions their `data/<cell>.parquet` path, `fit`, exact `duplicate_rows` and a column profile (`store.frame_profile`, cached per frame). It is attached again only when it changed or a summary replaced the message that carried it.- When a reply's prompt passes `ASSISTANT_COMPACT_TOKENS`, the turn appends a `summary` of all but the last `COMPACT_KEEP` events. A model call reads the newest summary and the events after it; the transcript keeps everything. The cut never separates a tool call from its result.- Stop sets `stop_requested`, drops queued messages and stops the conversation's kernel at once (`tasks/assistant.stop_kernel`), so a cell that runs answers. The turn sees the flag at its next step. Jobs the turn started continue.-- The sender of the newest message pays for the model calls (`BillingService.DATA_WORKSHOP`, idempotency key `assistant:<thread>:<sequence>`), and tools run with that sender's project access, checked before each model call. A reply and its charge are saved in one transaction. A reply stopped in the middle is not charged: the provider reports no usage for it.+- Tools run with the project access of the newest message's sender, checked before each model call. The project's `owner` pays (gate and charges): a turn of a project without one fails. A reply and its charge are saved in one transaction; billing details are under Workspaces.## Tools@@ -25,14 +25,15 @@ The Console's assistant is a second author beside a customer's coding agent, sco## Workspaces-- `services/workspaces/` is one contract: `put_data`, `has_data`, `run`, `read_file`, `stop`, `forget`, `remove`. A provider is one module and one entry in `PROVIDERS`; `WORKSPACE_PROVIDER` selects it. Production uses `daytona`; `native` is for local and self-hosted installs with one sandbox server.-- A project has one workspace. Its `data/` holds each dataset version once, as `<cell>.parquet`, read-only to cells. A conversation has its own kernel and working folder with a `data` link. Variables live in the kernel; files live in the folder.-- Every provider runs `sandbox/kernel.py:run` around a cell: output bounded at 60k characters, the last expression's value, the traceback. A cell runs `DEFAULT_SECONDS` (120) and at most `MAX_SECONDS` (600). A kernel idle for 15 minutes stops; the next cell starts a new one, and `Execution.restarted` tells the model that variables are gone and files remain.-- `native` runs the workspaces in the `sandbox` service (`sandbox/workspaces.py`) on the `workspaces` volume, under the uid and memory admission of a pipeline run, from the same memory budget. Copies are removed oldest first above `DATA_BUDGET_BYTES` (20 GiB).+- `services/workspaces/` is one contract: `warm`, `projects`, `bill`, `put_data`, `has_data`, `run`, `read_file`, `stop`, `forget`, `remove`. A provider is one module and one entry in `PROVIDERS`; `WORKSPACE_PROVIDER` selects it. `modal` is the default and runs on our cloud; `native` is a fallback for offline installs with one sandbox server.+- A project has one workspace. Its `data/` holds each dataset version once, as `<cell>.parquet`, read-only to cells. A conversation has its own kernel and working folder with a `data` link, closed to the project's other kernels. Variables live in the kernel; files live in the folder.+- Every provider runs `sandbox/kernel.py:run` around a cell: output bounded at 60k characters, the last expression's value, the traceback. A cell runs `DEFAULT_SECONDS` (120) and at most `MAX_SECONDS` (600); `kernel.exchange` holds a reply to 1 MiB for both providers. A new kernel sets `Execution.restarted`, which tells the model that variables are gone and files remain. A version over the provider's cap (Modal 4 GiB, native 1 GiB) raises `DataTooLargeError`, which the model reads as a tool error.+- `modal` (`modal_sandbox.py`) gives each project one sandbox `overmind-ws-<project>` in app `overmind-workspaces` of `MODAL_ENVIRONMENT`, with two v2 Volumes: `-data` at `/workspace/data` and `-work` at `/workspace/conversations`. It is network-blocked, requests 0.25 core and 1 GiB with limits of 8 cores and 16 GiB (billed at the greater of request and use), stops after 60 idle minutes and at Modal's 24-hour limit. It starts in `MODAL_WORKSPACE_REGION` and, if not ready in 20 s, in any region. A turn calls `warm`, which starts it in a thread while the model writes. The image is built from the code; its tag hashes the kernel and the library pins, and a sandbox of another tag is replaced at its next use, files kept. A cell is one `exec` of `kernel.py cell`, which starts a detached `serve` under the conversation's own uid (a root-only registry on the work Volume keeps it the same in every sandbox), with folders `0700` and versions `root 0444`: gVisor has no Landlock, so the uid keeps conversations apart and seccomp still refuses every socket family but `AF_UNIX`. A Volume a running sandbox mounts refuses outside reads and writes, and the sandbox keeps a stale view of outside changes: while it runs, versions go in (temporary name, then rename and `sync`) and files come out (a no-follow copy) through it; with none running, `has_data`, `read_file` and `forget` use the Volume API. Mounts are links to `/__modal/volumes/vo-…`, so the `data` link is absolute. Only `warm`, `put_data` and `run` start a sandbox.+- `bill` charges each `WorkspaceSandbox` row: Modal's `_experimental_stats().cost` for the window from `billed_until` to 10 minutes ago (usage arrives late), to the project's owner as `workspace`, keyed `modal-sandbox:<id>:<window start>`. An unmeasured window waits; a row finishes once its sandbox ended and a window holds no time. `tasks/assistant.bill_workspaces` runs it every 15 minutes. Model calls charge the owner as `assistant` at OpenRouter's `usage.cost`, keyed `openrouter:<generation>`; a call without a cost, or a stream cut off after it started, is charged by `charge_generation` from `/api/v1/generation`.+- `native` runs the workspaces in the `sandbox` service (`sandbox/workspaces.py`) on the `workspaces` volume, under the uid and memory admission of a pipeline run, from the same memory budget. Copies are removed oldest first above `DATA_BUDGET_BYTES` (20 GiB). Its kernels stop after 15 idle minutes.- Native kernels, pipeline package runs and document extraction share one container and one Linux kernel. A uid keeps a run out of another's files, and `kernel.py:confine` closes the rest without any privilege (Fargate cannot grant `CAP_SYS_ADMIN`): Landlock limits the process and its children to its own folders, the libraries and its own `/proc` entry, denies TCP and scopes signals and abstract sockets; a seccomp filter refuses every socket family but `AF_UNIX`. Landlock applies as far as the host's Linux supports it (files 5.13, TCP 6.7, scoping 6.12); `/health` reports its version as `landlock`. A library that cannot reach a file it needs may abort the process instead of raising, so `conformance.LIBRARY_USE` uses every pinned library; a new library or allowed path is checked there.-- `daytona` gives each project one network-blocked sandbox (2 vCPU, 4 GiB, 5 GiB disk) from the snapshot `manage.py build_workspace_snapshot` builds; the snapshot name hashes the kernel and the image recipe, so a release that changes either needs a build first. A conversation is a code-interpreter context whose working folder is under `/workspace`; `confine` runs inside each context. Sandboxes stop after 15 idle minutes, archive after 60 and are deleted after 7 days stopped. Only `put_data` and `run` create a sandbox; reads, `forget` and `stop` never do. A sandbox keeps the snapshot it was created from, with that release's kernel, for up to 7 days unused: a change to how the server calls the kernel (`SETUP`, `_cell`) must still work with the previous one. A version is uploaded under a temporary name and renamed when whole, `read_file` reads a no-follow copy of a regular file, and `forget` and `remove` raise until the files are gone, so their tasks retry. Tier 1 counts the memory of running sandboxes (10 GiB) and the disk of sandboxes not archived (30 GiB).-- A deleted dataset's copies and conversations leave the workspace (`tasks/assistant.forget_workspace_data`), and a deleted project's workspace goes with it (`remove_workspace`); both retry, because a hosted provider holds customer data.-- `conformance.py` holds the contract checks. The test suite runs them on `native`; `manage.py check_workspaces` runs them on the configured provider, the only way to check a hosted one. `.github/workflows/workspaces.yml` runs it on Daytona each day and on a change to the adapter, the kernel or `uv.lock`; it needs the repository secret `DAYTONA_API_KEY`.+- A deleted dataset's copies and conversations leave the workspace (`tasks/assistant.forget_workspace_data`), and a deleted project's workspace goes with it (`remove_workspace`); both retry, because the workspace holds customer data. `sweep_idle_workspaces` removes, each day, every workspace whose project had no assistant activity for 7 days.+- `conformance.py` holds the contract checks. The test suite runs them on `native`, and the Modal provider's edge cases on `tests/fakes/modal.py`; `manage.py check_workspaces` runs them on the configured provider. `.github/workflows/workspaces.yml` runs it on Modal in `overmind-dev`, with the `development` environment's Modal token as `deploy-modal.yml` uses it, each night and after a merge to `main` that changes the provider, the kernel or `uv.lock`. A rollout runs it on staging before prod.## Live updatesdiff --git a/.agents/skills/backend-architecture/references/auth-and-billing.md b/.agents/skills/backend-architecture/references/auth-and-billing.mdindex 52bf5aca..d5aa8b0f 100644--- a/.agents/skills/backend-architecture/references/auth-and-billing.md+++ b/.agents/skills/backend-architecture/references/auth-and-billing.md@@ -15,7 +15,7 @@ Tenancy is project-scoped (`User` ↔ `Project` through `ProjectMembership`), wi## Billing-- Billing is credits only. Ledger charges always run. Remaining-credit 402s, the $50 signup `grant` and Stripe Checkout apply only when `STRIPE_SECRET_KEY` is set (`services/billing_provider.py`); otherwise spend is recorded and shown, and gates and grants are no-ops.+- Billing is credits only. Ledger charges always run. A project's `owner` (its creator; the claiming account for a guest project; never removable as a member) pays for the assistant's model calls (`assistant`) and its workspace sandbox (`workspace`): backend-architecture `references/assistant.md`. Remaining-credit 402s, the $50 signup `grant` and Stripe Checkout apply only when `STRIPE_SECRET_KEY` is set (`services/billing_provider.py`); otherwise spend is recorded and shown, and gates and grants are no-ops.- Money in is a `grant` (free: signup, promotions, `manage.py grant_credits`) or a `purchase` (a paid live Checkout session). A purchase is keyed `topup:<session id>` and lands from whichever comes first: `POST /api/billing/topup/confirm/` when the buyer returns from Checkout, or the webhook for payment methods that settle later (`services/credit_purchases.py`). The webhook endpoint's events live in `WEBHOOK_EVENTS`; `manage.py sync_stripe_webhook --url <endpoint>` applies them to Stripe.- Native-agent model choice and funding belong to the coding-agent environment. Training, evaluation and serving keep their own billing.- Compute estimates use live provider rates with fetch timestamps (`services/provider_pricing.py`: Modal workspace rates, cached 300 s when current and 30 s when unavailable, no static fallback; `compute_costs.py` and the forecasts call it). They never create ledger charges. One quote uses one rate snapshot. Chat-training cost estimates are the exception: they use the fixed `_MODAL_H100_USD_PER_SECOND` in `finetuning_pricing.py`.diff --git a/.agents/skills/backend-architecture/references/celery.md b/.agents/skills/backend-architecture/references/celery.mdindex 97618942..aeca1919 100644--- a/.agents/skills/backend-architecture/references/celery.md+++ b/.agents/skills/backend-architecture/references/celery.md@@ -6,7 +6,7 @@ Seven workers over seven queues. Workers are resource profiles; queues are fairn| ------------- | ------- | ---- | ----------------------------------------------------------------------------------- || `control` | threads | 8 | orchestration, chord callbacks, FSM advances, reconcilers || `io` | threads | 24 | preparation, eval launch, serving, connector polling |-| `assistant` | threads | 24 | assistant turns, kernel stops and workspace cleanup |+| `assistant` | threads | 24 | assistant turns, kernel stops, workspace cleanup and billing || `io_traces` | prefork | 4 | live span and trajectory scoring, signals || `batch` | prefork | 6 | pipeline bindings, evaluation generation and scoring, partitions, native evaluation || `landing` | prefork | 1 | source imports |diff --git a/.env.example b/.env.exampleindex d0e01a4b..f7b7fdd4 100644--- a/.env.example+++ b/.env.example@@ -150,10 +150,11 @@ WORKSHOP_PROJECT_CONCURRENCY=2# Isolated document extraction (required for document uploads).SANDBOX_URL=http://sandbox:8080SANDBOX_TOKEN=change-me-in-production-# Where the assistant runs Python: native (the sandbox service, one server) or daytona.-# Native kernels share one Linux kernel; manage.py check_workspaces shows their isolation.-WORKSPACE_PROVIDER=native-# Required for daytona. Build its snapshot once per release: manage.py build_workspace_snapshot-DAYTONA_API_KEY=+# Where the assistant runs Python: modal (a Modal sandbox for each project, in+# MODAL_ENVIRONMENT) or native (the sandbox service, one server, for offline installs).+# manage.py check_workspaces runs the workspace contract on the selected provider.+WORKSPACE_PROVIDER=modal+# Modal region that workspaces start in; with no room there, they start in any region.+MODAL_WORKSPACE_REGION=eu# Prompt tokens of one assistant reply above which older conversation is summarized.ASSISTANT_COMPACT_TOKENS=120000diff --git a/.github/workflows/workspaces.yml b/.github/workflows/workspaces.ymlindex 67cd7433..cd268e62 100644--- a/.github/workflows/workspaces.yml+++ b/.github/workflows/workspaces.yml@@ -1,6 +1,8 @@name: Workspaces-# The Daytona adapter cannot run in the test suite: it needs the hosted service and a key.+# The test suite runs the workspace contract on the native sandbox and on Modal fakes. This+# job runs it on Modal itself, after a merge and each night, in overmind-dev with the token+# the Modal deploy uses there.on:schedule:- cron: "17 5 * * *"@@ -22,8 +24,9 @@ concurrency:cancel-in-progress: falsejobs:- daytona:+ modal:runs-on: ubuntu-latest+ environment: developmenttimeout-minutes: 30services:postgres:@@ -42,14 +45,15 @@ jobs:env:DJANGO_DEBUG: "True"POSTGRES_HOST: localhost- WORKSPACE_PROVIDER: daytona- DAYTONA_API_KEY: ${{ secrets.DAYTONA_API_KEY }}- # Required by settings; this job reaches only Daytona and Postgres.+ WORKSPACE_PROVIDER: modal+ MODAL_ENVIRONMENT: overmind-dev+ MODAL_WORKSPACE_REGION: eu+ MODAL_TOKEN_ID: ${{ secrets.MODAL_TOKEN_ID }}+ MODAL_TOKEN_SECRET: ${{ secrets.MODAL_TOKEN_SECRET }}+ # Required by settings; this job reaches only Modal and Postgres.SANDBOX_URL: http://unusedSANDBOX_TOKEN: unusedOPENROUTER_API_KEY: unused- MODAL_TOKEN_ID: unused- MODAL_TOKEN_SECRET: unusedINFERENCE_API_URL: http://unusedINFERENCE_API_KEY: unusedAWS_ACCESS_KEY_ID: unused@@ -65,7 +69,6 @@ jobs:python-version: "3.13"- run: uv sync --frozen- run: touch .env- - name: Build the workspace snapshot if this recipe has none- run: uv run python manage.py build_workspace_snapshot- - name: Run the workspace contract on Daytona+ - run: uv run python manage.py migrate --noinput+ - name: Run the workspace contract on Modalrun: uv run python manage.py check_workspacesdiff --git a/docker-compose.yml b/docker-compose.ymlindex 0e5a6585..00353885 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -18,8 +18,8 @@ x-env-common: &env-commonANTHROPIC_API_KEY: ${ANTHROPIC_API_KEY:-}GEMINI_API_KEY: ${GEMINI_API_KEY:-}OPENROUTER_API_KEY: ${OPENROUTER_API_KEY:-}- WORKSPACE_PROVIDER: ${WORKSPACE_PROVIDER:-native}- DAYTONA_API_KEY: ${DAYTONA_API_KEY:-}+ WORKSPACE_PROVIDER: ${WORKSPACE_PROVIDER:-modal}+ MODAL_WORKSPACE_REGION: ${MODAL_WORKSPACE_REGION:-eu}JEV_REQUESTS_PER_MINUTE: ${JEV_REQUESTS_PER_MINUTE:-1200}JEV_TOKENS_PER_SECOND: ${JEV_TOKENS_PER_SECOND:-250000}HF_TOKEN: ${HF_TOKEN:-}diff --git a/frontend/src/openapi/models/Project.ts b/frontend/src/openapi/models/Project.tsindex de3e1a43..c4d06e0e 100644--- a/frontend/src/openapi/models/Project.ts+++ b/frontend/src/openapi/models/Project.ts@@ -87,6 +87,12 @@ export interface Project {* @memberof Project*/readonly updatedAt: Date;+ /**+ *+ * @type {number}+ * @memberof Project+ */+ readonly owner: number | null;}@@ -102,6 +108,7 @@ export function instanceOfProject(value: object): value is Project {if (!('slug' in value) || value['slug'] === undefined) return false;if (!('createdAt' in value) || value['createdAt'] === undefined) return false;if (!('updatedAt' in value) || value['updatedAt'] === undefined) return false;+ if (!('owner' in value) || value['owner'] === undefined) return false;return true;}@@ -125,6 +132,7 @@ export function ProjectFromJSONTyped(json: any, ignoreDiscriminator: boolean): P'settings': json['settings'] == null ? undefined : json['settings'],'createdAt': (new Date(json['created_at'])),'updatedAt': (new Date(json['updated_at'])),+ 'owner': json['owner'],};}@@ -132,7 +140,7 @@ export function ProjectToJSON(json: any): Project {return ProjectToJSONTyped(json, false);}-export function ProjectToJSONTyped(value?: Omit<Project, 'id'|'member_count'|'member_emails'|'created_at'|'updated_at'> | null, ignoreDiscriminator: boolean = false): any {+export function ProjectToJSONTyped(value?: Omit<Project, 'id'|'member_count'|'member_emails'|'created_at'|'updated_at'|'owner'> | null, ignoreDiscriminator: boolean = false): any {if (value == null) {return value;}diff --git a/overbae/api/guest.py b/overbae/api/guest.pyindex a8fedc58..0e75dd57 100644--- a/overbae/api/guest.py+++ b/overbae/api/guest.py@@ -57,6 +57,7 @@ def start_guest_session() -> tuple[User, Project, str, str]:name="My product",slug=f"guest-{suffix[:12]}",integration_type=IntegrationType.SDK,+ owner=user,)ProjectMembership.objects.create(user=user, project=project)UserOnboarding.objects.create(user=user, status="completed")@@ -92,6 +93,7 @@ def claim_guest(*, guest: User, clerk_token: str) -> tuple[User, Project]:raise PermissionDenied("No workspace to claim.")for membership in memberships:ProjectMembership.objects.get_or_create(user=owner, project=membership.project)+ Project.objects.filter(pk=membership.project_id, owner=guest).update(owner=owner)ProjectMembership.objects.filter(user=guest).delete()guest.is_active = Falseguest.save(update_fields=["is_active"])diff --git a/overbae/api/serializers.py b/overbae/api/serializers.pyindex 12825003..57e83cf4 100644--- a/overbae/api/serializers.py+++ b/overbae/api/serializers.py@@ -302,7 +302,7 @@ class ProjectSerializer(serializers.ModelSerializer):class Meta:model = Projectfields = "__all__"- read_only_fields = ["id", "created_at", "updated_at"]+ read_only_fields = ["id", "owner", "created_at", "updated_at"]# ``_unique_project_slug`` resolves collisions; the auto# ``UniqueTogetherValidator`` would hard-400 them first.validators = []diff --git a/overbae/api/views.py b/overbae/api/views.pyindex 00fd4278..b941852b 100644--- a/overbae/api/views.py+++ b/overbae/api/views.py@@ -190,7 +190,7 @@ class ProjectViewSet(viewsets.ModelViewSet):),code="account_key_required",)- project = serializer.save()+ project = serializer.save(owner=self.request.user)ProjectMembership.objects.create(user=self.request.user, project=project)def perform_destroy(self, instance):@@ -265,6 +265,8 @@ class ProjectMembershipViewSet(raise PermissionDenied("You cannot remove yourself from a project. Delete the project instead.")+ if instance.user_id == instance.project.owner_id:+ raise PermissionDenied("The project's owner cannot be removed.")instance.delete()diff --git a/overbae/core/llms.py b/overbae/core/llms.pyindex d078412e..9b5fd063 100644--- a/overbae/core/llms.py+++ b/overbae/core/llms.py@@ -648,8 +648,12 @@ def _tool_completion_kwargs(return completion_kwargs, selected-def _tool_call_stats(usage: Any, served_model: Any, selected: str, response_ms: Any) -> dict:+def _tool_call_stats(+ usage: Any, served_model: Any, selected: str, response_ms: Any, generation: Any+) -> dict:return {+ # OpenRouter's generation id: what the call cost, once usage did not say.+ "provider_request_id": generation,"prompt_tokens": _usage_value(usage, "prompt_tokens"),"completion_tokens": _usage_value(usage, "completion_tokens"),"response_ms": response_ms or 0,@@ -693,6 +697,7 @@ def call_llm_tools(getattr(response, "model", None),selected,getattr(response, "_response_ms", 0),+ getattr(response, "id", None),)stats["finish_reason"] = getattr(response.choices[0], "finish_reason", None)if stats["finish_reason"] in INCOMPLETE_FINISH_REASONS:@@ -730,10 +735,12 @@ def stream_llm_tools(model: str | None = None,fallback_models: list[str] | None = None,on_progress: Callable[[str, list[dict]], None] | None = None,+ on_generation: Callable[[str], None] | None = None,) -> tuple[str, list[dict[str, Any]], dict]:""":func:`call_llm_tools`, streamed. ``on_progress`` receives the text so far and thetool calls as far as they are written; an exception it raises ends the stream and- propagates.+ propagates. ``on_generation`` receives the provider's generation id once the stream+ starts: the provider bills a stream that started, also one cut off later.Never retried: a stream that started may already be billed."""@@ -742,7 +749,7 @@ def stream_llm_tools()completion_kwargs |= {"stream": True, "stream_options": {"include_usage": True}}deadline = RETRY_DEADLINE_BACKGROUND- text, calls, usage, served, finish = "", {}, None, None, None+ text, calls, usage, served, finish, generation = "", {}, None, None, None, Nonereasoning: dict[tuple, dict] = {}started = time.monotonic()expired = threading.Event()@@ -756,6 +763,10 @@ def stream_llm_tools(try:for chunk in stream:usage, served = chunk.usage or usage, chunk.model or served+ if generation is None and chunk.id:+ generation = chunk.id+ if on_generation is not None:+ on_generation(generation)for choice in chunk.choices:finish = choice.finish_reason or finishtext += choice.delta.content or ""@@ -798,7 +809,9 @@ def stream_llm_tools(except openai.OpenAIError as exc:raise RuntimeError(f"Error calling LLM: {exc}") from exctext, tool_calls = text.strip(), [calls[index] for index in sorted(calls)]- stats = _tool_call_stats(usage, served, selected, (time.monotonic() - started) * 1000)+ stats = _tool_call_stats(+ usage, served, selected, (time.monotonic() - started) * 1000, generation+ )stats["finish_reason"] = finish# The provider needs these back unchanged with the reply's tool results.stats["reasoning_details"] = list(reasoning.values())diff --git a/overbae/management/commands/build_workspace_snapshot.py b/overbae/management/commands/build_workspace_snapshot.pydeleted file mode 100644index fb8305e3..00000000--- a/overbae/management/commands/build_workspace_snapshot.py+++ /dev/null@@ -1,10 +0,0 @@-from django.core.management.base import BaseCommand--from overbae.services.workspaces import daytona---class Command(BaseCommand):- help = "Build the Daytona snapshot that project workspaces start from."-- def handle(self, *args, **options):- self.stdout.write(daytona.build_snapshot(self.stdout.write))diff --git a/overbae/management/commands/seed_demo.py b/overbae/management/commands/seed_demo.pyindex 744eacb9..180f710f 100644--- a/overbae/management/commands/seed_demo.py+++ b/overbae/management/commands/seed_demo.py@@ -700,6 +700,7 @@ class Command(BaseCommand):name="Support Copilot",slug=SLUG,integration_type="sdk",+ owner=owner,settings={"default_timezone": "UTC","repo_summary": (@@ -3936,8 +3937,8 @@ class Command(BaseCommand):user=owner,project=project,amount=Decimal("-" + amt),- service=BillingService.DATA_WORKSHOP,- idempotency_key=f"data-workshop:{ds.pk}:seed",+ service=BillingService.ASSISTANT,+ idempotency_key=f"assistant:{ds.pk}:seed",metadata={"dataset_id": str(ds.pk),"engine": "openrouter",diff --git a/overbae/migrations/0069_project_owner_and_assistant_billing.py b/overbae/migrations/0069_project_owner_and_assistant_billing.pynew file mode 100644index 00000000..a5e466a8--- /dev/null+++ b/overbae/migrations/0069_project_owner_and_assistant_billing.py@@ -0,0 +1,90 @@+import django.db.models.deletion+from django.conf import settings+from django.db import migrations, models+++def own_by_first_member(apps, schema_editor):+ Project = apps.get_model("overbae", "Project")+ ProjectMembership = apps.get_model("overbae", "ProjectMembership")+ alias = schema_editor.connection.alias+ first = {}+ for project_id, user_id in (+ ProjectMembership.objects.using(alias)+ .order_by("project_id", "created_at")+ .values_list("project_id", "user_id")+ ):+ first.setdefault(project_id, user_id)+ for project_id, user_id in first.items():+ Project.objects.using(alias).filter(pk=project_id).update(owner_id=user_id)+++class Migration(migrations.Migration):+ dependencies = [+ ("overbae", "0068_credits_only"),+ ]++ operations = [+ migrations.AddField(+ model_name="project",+ name="owner",+ field=models.ForeignKey(+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="owned_projects",+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ migrations.RunPython(own_by_first_member, migrations.RunPython.noop),+ migrations.AlterField(+ model_name="billingtelemetry",+ name="service",+ field=models.CharField(+ choices=[+ ("grant", "Grant"),+ ("purchase", "Purchase"),+ ("finetuning-job", "Finetuning job"),+ ("inference", "Inference"),+ ("inference-ft-model", "Fine-tuned inference"),+ ("dedicated-inference", "Dedicated inference"),+ ("data-workshop", "Data workshop"),+ ("evaluation", "Evaluation"),+ ("assistant", "Assistant"),+ ("workspace", "Assistant workspace"),+ ],+ max_length=32,+ ),+ ),+ migrations.CreateModel(+ name="WorkspaceSandbox",+ fields=[+ (+ "id",+ models.BigAutoField(+ auto_created=True, primary_key=True, serialize=False, verbose_name="ID"+ ),+ ),+ ("sandbox_id", models.CharField(max_length=64, unique=True)),+ ("started_at", models.DateTimeField(auto_now_add=True)),+ ("billed_until", models.DateTimeField()),+ ("finished", models.BooleanField(db_index=True, default=False)),+ (+ "project",+ models.ForeignKey(+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="workspace_sandboxes",+ to="overbae.project",+ ),+ ),+ (+ "user",+ models.ForeignKey(+ null=True,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="workspace_sandboxes",+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ ],+ ),+ ]diff --git a/overbae/models/__init__.py b/overbae/models/__init__.pyindex 395587df..8558fbef 100644--- a/overbae/models/__init__.py+++ b/overbae/models/__init__.py@@ -4,7 +4,7 @@ from .assistant import (AssistantInput,AssistantThread,)-from .billing import BillingService, BillingTelemetry+from .billing import BillingService, BillingTelemetry, WorkspaceSandboxfrom .capabilities import Capability, IdentityAlias, Promptfrom .connectors import ConnectorCredential, ConnectorSyncConfig, ConnectorSyncRunfrom .dataset_admission import DatasetLandingWork@@ -112,6 +112,7 @@ __all__ = ["IdentityAlias","BillingService","BillingTelemetry",+ "WorkspaceSandbox","ConnectorCredential","ConnectorSyncConfig","ConnectorSyncRun",diff --git a/overbae/models/billing.py b/overbae/models/billing.pyindex 302e4ed1..4bc4e4f1 100644--- a/overbae/models/billing.py+++ b/overbae/models/billing.py@@ -13,8 +13,11 @@ class BillingService(models.TextChoices):INFERENCE = "inference", "Inference"INFERENCE_FT_MODEL = "inference-ft-model", "Fine-tuned inference"DEDICATED_INFERENCE = "dedicated-inference", "Dedicated inference"+ # Rows written before the assistant charged as its own service.DATA_WORKSHOP = "data-workshop", "Data workshop"EVALUATION = "evaluation", "Evaluation"+ ASSISTANT = "assistant", "Assistant"+ WORKSPACE = "workspace", "Assistant workspace"class BillingTelemetry(models.Model):@@ -47,3 +50,26 @@ class BillingTelemetry(models.Model):def __str__(self) -> str:return f"BillingTelemetry({self.user_id}, {self.service}, {self.amount})"+++class WorkspaceSandbox(models.Model):+ """A provider sandbox of a project workspace, metered from its start until it ends."""++ sandbox_id = models.CharField(max_length=64, unique=True)+ project = models.ForeignKey(+ "overbae.Project",+ on_delete=models.SET_NULL,+ null=True,+ related_name="workspace_sandboxes",+ )+ # The project's owner when the sandbox started; empty for a sandbox of no project, such+ # as the provider's own checks.+ user = models.ForeignKey(+ settings.AUTH_USER_MODEL,+ on_delete=models.CASCADE,+ null=True,+ related_name="workspace_sandboxes",+ )+ started_at = models.DateTimeField(auto_now_add=True)+ billed_until = models.DateTimeField()+ finished = models.BooleanField(default=False, db_index=True)diff --git a/overbae/models/iam.py b/overbae/models/iam.pyindex cab94bc8..9ba1e8ae 100644--- a/overbae/models/iam.py+++ b/overbae/models/iam.py@@ -99,6 +99,13 @@ class Project(models.Model):)is_active = models.BooleanField(default=True)settings = models.JSONField(default=dict, blank=True)+ # Pays for what the project's work costs. Empty only once the owner's account is gone.+ owner = models.ForeignKey(+ "overbae.User",+ on_delete=models.SET_NULL,+ null=True,+ related_name="owned_projects",+ )created_at = models.DateTimeField(auto_now_add=True)updated_at = models.DateTimeField(auto_now=True)diff --git a/overbae/services/assistant/tools.py b/overbae/services/assistant/tools.pyindex b334b1ef..1f0d0bb4 100644--- a/overbae/services/assistant/tools.py+++ b/overbae/services/assistant/tools.py@@ -199,6 +199,8 @@ def call(turn: Turn, name: str, arguments: dict) -> Outcome:return Outcome(False, {"error": getattr(exc, "detail", str(exc))})except workspaces.WorkspaceUnavailableError as exc:return Outcome(False, {"error": f"The workspace is not available now: {exc}"})+ except workspaces.DataTooLargeError as exc:+ return Outcome(False, {"error": f"{exc} Filter or sample it into a smaller version first."})return Outcome(False, {"error": f"There is no tool named {name}."})diff --git a/overbae/services/assistant/turn.py b/overbae/services/assistant/turn.pyindex 788291ea..6b293015 100644--- a/overbae/services/assistant/turn.py+++ b/overbae/services/assistant/turn.py@@ -25,13 +25,18 @@ from overbae.models import (AssistantEvent,AssistantInput,AssistantThread,- BillingService,Cell,Dataset,)from overbae.models.assistant import STALE+from overbae.services import workspacesfrom overbae.services.assistant import log, presentation, prompt, threads, tools-from overbae.services.billing_ledger import InsufficientCredits, charge_llm_usage, ensure_credits+from overbae.services.billing_ledger import (+ InsufficientCredits,+ charge_assistant_call,+ charge_generation_later,+ ensure_credits,+)from overbae.services.datasets import heartbeatlogger = logging.getLogger(__name__)@@ -262,6 +267,7 @@ def _turn(thread) -> None:def _answer(thread, deadline: float) -> None:"""Model calls and tool calls until the model replies without calls or asks a question."""+ warmed = Falsewhile True:if not _alive(thread):raise _StoppedError@@ -277,13 +283,21 @@ def _answer(thread, deadline: float) -> None:if user is None:_status(thread, "failed", "The sender of the last message is not a project member.")return+ payer = get_user_model().objects.filter(owned_projects__id=thread.project_id).first()+ if payer is None:+ _status(thread, "failed", "The project has no owner to charge.")+ returntry:- ensure_credits(user)+ ensure_credits(payer)except InsufficientCredits:_status(thread, "failed", "Credits are needed to continue.")return- _compact(thread, user)- reply = _model_call(thread, user)+ if not warmed:+ # Ready by the time the model asks for a cell.+ workspaces.provider().warm(str(thread.project_id))+ warmed = True+ _compact(thread, payer)+ reply = _model_call(thread, payer)if reply is None or not reply.payload["calls"]:returnasked = False@@ -297,7 +311,7 @@ def _answer(thread, deadline: float) -> None:def _actor(thread):"""The sender of the newest message, while still a member of the project: the turn acts- with their access and credits."""+ with their access. The project's owner pays for it."""sender = (thread.events.filter(kind=Kind.USER).order_by("-sequence")@@ -368,25 +382,34 @@ def _window(thread) -> list[AssistantEvent]:return list(thread.events.filter(sequence__gt=covered or 0).defer("presentation"))-def _charge(thread, user, stats, sequence) -> None:- charge_llm_usage(- user,+def _charge(thread, payer, stats, sequence) -> None:+ generation = stats.get("provider_request_id")+ charge_assistant_call(+ payer,+ thread.project_id,stats,- service=BillingService.DATA_WORKSHOP,- project_id=thread.project_id,- idempotency_key=f"assistant:{thread.pk}:{sequence}",+ idempotency_key=f"openrouter:{generation}"+ if generation+ else f"assistant:{thread.pk}:{sequence}",)-def _record(thread, user, kind, payload) -> AssistantEvent:- """Save what a model call produced and charge it, both or neither."""- with transaction.atomic():- event = log.append(thread, kind, payload, turn=thread.turn)- _charge(thread, user, payload["usage"], event.sequence)+def _record(thread, payer, kind, payload) -> AssistantEvent:+ """Save what a model call produced and charge it, both or neither. A reply that cannot+ be saved, as when a newer turn took the thread, is still charged: the provider billed it."""+ try:+ with transaction.atomic():+ event = log.append(thread, kind, payload, turn=thread.turn)+ _charge(thread, payer, payload["usage"], event.sequence)+ except BaseException:+ generation = payload["usage"].get("provider_request_id")+ if generation:+ charge_generation_later(payer, thread.project_id, generation)+ raisereturn event-def _compact(thread, user) -> None:+def _compact(thread, payer) -> None:"""Summarize the older conversation once the last reply's prompt grew too large. Thecut falls before a user message or a reply, so no tool call loses its result."""window = _window(thread)@@ -420,7 +443,7 @@ def _compact(thread, user) -> None:logger.warning("assistant summary failed for thread %s: %s", thread.pk, exc)return_record(- thread, user, Kind.SUMMARY, {"text": text, "through": older[-1].sequence, "usage": stats}+ thread, payer, Kind.SUMMARY, {"text": text, "through": older[-1].sequence, "usage": stats})@@ -500,9 +523,14 @@ def messages(thread, events) -> list[dict]:return out-def _model_call(thread, user) -> AssistantEvent | None:+def _model_call(thread, payer) -> AssistantEvent | None:published = time.monotonic()shown = None+ generation = None++ def started(value):+ nonlocal generation+ generation = valuedef progress(text, calls):nonlocal published, shown@@ -523,28 +551,39 @@ def _model_call(thread, user) -> AssistantEvent | None:model=chain[0],fallback_models=chain[1:],on_progress=progress,+ on_generation=started,)except IncompleteCompletionError as exc:# The provider charged for the reply it cut off.- with transaction.atomic():- event = log.append(- thread,- Kind.STATUS,- {- "state": "failed",- "detail": "The model reached its output limit before it finished.",- },- turn=thread.turn,- )- _charge(thread, user, exc.stats, event.sequence)+ try:+ with transaction.atomic():+ event = log.append(+ thread,+ Kind.STATUS,+ {+ "state": "failed",+ "detail": "The model reached its output limit before it finished.",+ },+ turn=thread.turn,+ )+ _charge(thread, payer, exc.stats, event.sequence)+ except BaseException:+ if generation is not None:+ charge_generation_later(payer, thread.project_id, generation)+ raisereturn None- except (RuntimeError, TimeoutError) as exc:+ except BaseException as exc:+ # The provider bills a stream that started, also one cut off by a stop or a failure.+ if generation is not None:+ charge_generation_later(payer, thread.project_id, generation)+ if not isinstance(exc, RuntimeError | TimeoutError):+ raiselogger.warning("assistant model call failed for thread %s: %s", thread.pk, exc)_status(thread, "failed", "The model did not answer. Send a message to continue.")return Nonereturn _record(thread,- user,+ payer,Kind.ASSISTANT,{"text": text,diff --git a/overbae/services/billing_ledger.py b/overbae/services/billing_ledger.pyindex 4426b6dd..0e38edad 100644--- a/overbae/services/billing_ledger.py+++ b/overbae/services/billing_ledger.py@@ -8,11 +8,14 @@ from decimal import Decimalfrom typing import Anyfrom uuid import UUID+import httpx+from django.conf import settingsfrom django.db import IntegrityError, transactionfrom django.db.models import Case, CharField, Count, Q, Sum, Value, Whenfrom django.db.models.fields.json import KeyTextTransformfrom django.utils import timezone+from overbae.core.model_registry import OPENROUTER_BASE_URLfrom overbae.models import BillingService, BillingTelemetry, FinetuningJob, Userfrom overbae.services import model_catalogfrom overbae.services.billing_provider import get_billing@@ -223,6 +226,54 @@ def charge_llm_usage(return None+def charge_assistant_call(+ user: User, project_id: UUID | str, stats: dict[str, Any], *, idempotency_key: str+) -> BillingTelemetry | None:+ """Charge one model call of the assistant at what the provider billed. A failure+ raises: the call's event and its charge are kept together or not at all. A call whose+ usage carried no cost is charged once the provider prices its generation."""+ cost = stats.get("response_cost")+ if cost is None:+ generation = stats.get("provider_request_id")+ if generation:+ charge_generation_later(user, project_id, generation)+ else:+ logger.warning("assistant call has no cost and no generation id: %s", idempotency_key)+ return None+ return charge_credits(+ user,+ Decimal(str(cost)),+ BillingService.ASSISTANT,+ project_id=project_id,+ idempotency_key=idempotency_key,+ metadata={"llm_usage": stats},+ )+++def charge_generation_later(user: User, project_id: UUID | str, generation: str) -> None:+ # Lazy: tasks import services.+ from overbae.tasks.assistant import charge_generation++ transaction.on_commit(+ lambda: charge_generation.delay(str(user.pk), str(project_id), generation)+ )+++def generation_cost(generation: str) -> Decimal | None:+ """What OpenRouter billed for a generation; None while it has not priced it yet."""+ response = httpx.get(+ f"{OPENROUTER_BASE_URL}/generation",+ params={"id": generation},+ headers={"Authorization": f"Bearer {settings.OPENROUTER_API_KEY}"},+ timeout=30,+ )+ if response.status_code == 404:+ return None+ response.raise_for_status()+ cost = response.json()["data"].get("total_cost")+ return None if cost is None else Decimal(str(cost))++def project_credit_report(user,project,diff --git a/overbae/services/workspaces/__init__.py b/overbae/services/workspaces/__init__.pyindex ebbed20c..7e766bbd 100644--- a/overbae/services/workspaces/__init__.py+++ b/overbae/services/workspaces/__init__.py@@ -2,9 +2,9 @@conversation in it. A provider is one module in this package and one entry in``PROVIDERS``; nothing outside this package names a provider.-Every provider gives a kernel the same layout: its working directory is its own and-outlives it, and ``data/<name>`` holds the project's versions, read-only. A kernel is-disposable: a provider may end it at any time, and the next cell starts a new one.+Every provider gives a kernel the same layout: its working directory is its own, closed+to the project's other kernels, and outlives it, and ``data/<name>`` holds the project's+versions, read-only. A kernel is disposable: a provider may end it at any time, and the next cell starts a new one."""from dataclasses import dataclass@@ -35,7 +35,21 @@ class WorkspaceUnavailableError(Exception):"""The provider cannot serve the call now. Nothing ran."""+class DataTooLargeError(Exception):+ """A version is larger than the provider's workspace takes. Nothing was copied."""++class Provider(Protocol):+ def warm(self, project: str) -> None:+ """Prepare the workspace for a cell that may follow soon. Optional to wait for."""++ def projects(self) -> list[str]:+ """The projects that have a workspace."""++ def bill(self) -> int:+ """Charge project owners for the provider's compute measured since it was last+ charged; how many charges were made."""+def put_data(self, project: str, name: str, source: BinaryIO) -> None:"""Copy a version into the project's ``data``, once: a name already there is kept."""@@ -61,8 +75,8 @@ class Provider(Protocol):PROVIDERS = {+ "modal": "overbae.services.workspaces.modal_sandbox.ModalProvider","native": "overbae.services.workspaces.native.NativeProvider",- "daytona": "overbae.services.workspaces.daytona.DaytonaProvider",}diff --git a/overbae/services/workspaces/conformance.py b/overbae/services/workspaces/conformance.pyindex e9dd1fc0..a57cc100 100644--- a/overbae/services/workspaces/conformance.py+++ b/overbae/services/workspaces/conformance.py@@ -90,6 +90,21 @@ def conversations_of_a_project_share_data_and_not_variables(provider):assert alone.output == "False\n", alone+def a_conversation_cannot_reach_another_conversations_folder(provider):+ with _kernel(provider) as first, _kernel(provider, first.project) as second:+ made = first("import os\nopen('own.txt', 'w').write('mine')\nos.getcwd()")+ assert made.ok, made+ folder = made.output.strip().strip("'")+ result = second(+ "try:\n"+ f" seen = open({folder + '/own.txt'!r}).read()\n"+ "except OSError as error:\n"+ " seen = type(error).__name__\n"+ "seen"+ )+ assert result.ok and "mine" not in result.output, result++# Every pinned library, used the way a kernel uses it: a library that cannot reach a file it# needs under the kernel's confinement may abort the whole process, not raise.LIBRARY_USE = """\@@ -193,7 +208,11 @@ def a_project_sees_no_data_or_process_of_another(provider):f"any('{marker}' in line for line in found)")assert seen.ok and seen.output == "False\n", seen- files = second(f"import glob\nbool(glob.glob('/**/{marker}.txt', recursive=True))")+ # Not a recursive glob: it follows links, and /proc/self/root leads back to /.+ files = second(+ f"import os\nany('{marker}.txt' in names for _r, _d, names in os.walk('/'))",+ timeout=300,+ )assert files.ok and files.output == "False\n", files@@ -234,7 +253,8 @@ def the_kernel_holds_no_secret_and_tokenizes_offline(provider):with _kernel(provider) as run:result = run("import os, tiktoken\n"- "assert not any(name in os.environ for name in ('SANDBOX_TOKEN', 'DAYTONA_API_KEY'))\n"+ "secrets = ('SANDBOX_TOKEN', 'MODAL_TOKEN_ID', 'MODAL_TOKEN_SECRET', 'OPENROUTER_API_KEY')\n"+ "assert not any(name in os.environ for name in secrets)\n""len(tiktoken.get_encoding('o200k_base').encode('offline'))",timeout=120,)@@ -284,6 +304,7 @@ CHECKS = (an_exception_returns_its_traceback_and_keeps_the_variables,data_is_copied_once_and_read_only,conversations_of_a_project_share_data_and_not_variables,+ a_conversation_cannot_reach_another_conversations_folder,the_pinned_libraries_work,a_cell_past_its_deadline_is_interrupted_and_the_variables_stay,long_output_is_bounded_and_says_so,diff --git a/overbae/services/workspaces/daytona.py b/overbae/services/workspaces/daytona.pydeleted file mode 100644index 4738bee5..00000000--- a/overbae/services/workspaces/daytona.py+++ /dev/null@@ -1,488 +0,0 @@-import contextlib-import hashlib-import json-import logging-import shutil-import tempfile-import threading-import time-import tomllib-import uuid-from functools import cache-from pathlib import Path-from typing import BinaryIO--from daytona import (- CreateSandboxFromSnapshotParams,- CreateSnapshotParams,- Daytona,- DaytonaConfig,- DaytonaError,- DaytonaNotFoundError,- DaytonaTimeoutError,- Image,- ListSandboxesQuery,- Resources,- Sandbox,-)-from django.conf import settings-from django.db import connection, transaction--from overbae.services.workspaces import (- MAX_FILE_BYTES,- Execution,- WorkspaceUnavailableError,-)-from sandbox.kernel import __file__ as kernel_file-from sandbox.workspaces import NAME, RESTARTED--logger = logging.getLogger(__name__)--# The libraries the native sandbox promises a package, at the versions the app locks.-LIBRARIES = (- "beautifulsoup4",- "datasketch",- "duckdb",- "emoji",- "ftfy",- "jellyfish",- "jsonschema",- "langcodes",- "langdetect",- "levenshtein",- "lxml",- "markdownify",- "matplotlib",- "numpy",- "pandas",- "pillow",- "pyarrow",- "python-dateutil",- "pytz",- "pyyaml",- "rapidfuzz",- "regex",- "scikit-learn",- "scipy",- "simhash",- "tiktoken",- "unidecode",- "wordfreq",-)-FAILED_BUILD = ("error", "build_failed")-GONE = ("destroying", "destroyed")-PYTHON = "3.13"-TOKENIZER_ENCODINGS = ("cl100k_base", "o200k_base")-KERNEL_PATH = "/opt/overmind/kernel.py"-TOKENIZERS = "/opt/overmind/tiktoken"-RESOURCES = Resources(cpu=2, memory=4, disk=5)-KERNEL = Path(kernel_file)-WORKSPACE = "/workspace"-STOP_MINUTES = 15-ARCHIVE_MINUTES = 60-# A workspace holds copies of customer data: one unused for this long is deleted, files-# and all. The next cell creates it again and copies in what it reads.-DELETE_MINUTES = 7 * 24 * 60-START_SECONDS = 120-# A cell's own deadline is the kernel's; this one catches a kernel stuck outside Python.-GRACE_SECONDS = 30-# A known sandbox is not asked for its state again within this time.-FRESH_SECONDS = 60-# Loads the kernel's cell runner into a new context, from the snapshot.-SETUP = (- "import importlib.util as _overmind_util, json as _overmind_json, signal as _overmind_signal\n"- f"_overmind_spec = _overmind_util.spec_from_file_location('_overmind_kernel', {KERNEL_PATH!r})\n"- "_overmind = _overmind_util.module_from_spec(_overmind_spec)\n"- "_overmind_spec.loader.exec_module(_overmind)\n"- "_overmind_signal.signal(_overmind_signal.SIGALRM, _overmind._interrupt)\n"- # The same limits as a native kernel: its own folder writable, the project's data- # read-only, and no socket but a Unix one.- "import os as _overmind_os, tempfile as _overmind_tempfile\n"- "for _overmind_name in ('HOME', 'TMPDIR', 'MPLCONFIGDIR'):\n"- " _overmind_os.environ[_overmind_name] = _overmind_os.getcwd()\n"- "_overmind_tempfile.tempdir = None\n"- f"_overmind.confine(_overmind_os.getcwd(), readable=({WORKSPACE + '/data'!r},))\n"- "import matplotlib\n"- "matplotlib.use('Agg')\n"- # Last: a cell needs the counter, so a context whose setup stopped early runs nothing.- "_overmind_cells = 0"-)-LOST = (- "The kernel ended during the cell: it ran out of memory or stopped answering. "- "Variables are gone, files remain."-)-# Marks the runner's reply in the context's output, which a cell can also write to directly.-REPLY = "__overmind_reply__:"-UNREAD = "The cell ran, but its result did not come back. Variables remain."-REPLY_KEYS = {"ok", "output", "error", "truncated", "seconds"}---@cache-def _requirements() -> tuple[str, ...]:- lock = tomllib.loads((KERNEL.parent.parent / "uv.lock").read_text())- versions = {package["name"]: package["version"] for package in lock["package"]}- return tuple(f"{name}=={versions[name]}" for name in LIBRARIES)---def _recipe() -> tuple[Image, str]:- """The snapshot's image, and everything that decides what is in it."""- cache_tokenizers = (- 'python -c "import tiktoken; [tiktoken.get_encoding(name) for name in '- f'{TOKENIZER_ENCODINGS!r}]"'- )- image = (- Image.debian_slim(PYTHON)- .pip_install(*_requirements())- .env({"TIKTOKEN_CACHE_DIR": TOKENIZERS})- .run_commands(cache_tokenizers)- .add_local_file(KERNEL, KERNEL_PATH)- )- parts = (PYTHON, *_requirements(), TOKENIZERS, cache_tokenizers, KERNEL_PATH, repr(RESOURCES))- return image, "\n".join(parts)---@cache-def snapshot_name() -> str:- """Names the kernel and the whole recipe, so a change to either selects a new snapshot."""- digest = hashlib.sha256(KERNEL.read_bytes() + _recipe()[1].encode())- return f"overmind-workspace-{digest.hexdigest()[:12]}"---def _client() -> Daytona:- return Daytona(DaytonaConfig(api_key=settings.DAYTONA_API_KEY, otel_enabled=False))---def build_snapshot(on_logs) -> str:- """Build the snapshot sessions start from, unless this recipe already has a usable one."""- client, name = _client(), snapshot_name()- with contextlib.suppress(DaytonaNotFoundError):- existing = client.snapshot.get(name)- if getattr(existing.state, "value", existing.state) not in FAILED_BUILD:- return name- # A build that failed keeps the name: remove it and build again.- client.snapshot.delete(existing)- client.snapshot.create(- CreateSnapshotParams(name=name, image=_recipe()[0], resources=RESOURCES),- on_logs=on_logs,- )- return name---def _cell(code: str, timeout: int) -> str:- """The call that runs ``code`` through the kernel's own runner: its output bound, its- deadline and its reply are the same as in the native sandbox."""- return (- "_overmind_cells += 1\n"- f"print({REPLY!r} + _overmind_json.dumps(_overmind.run("- f"{code!r}, globals(), {timeout}, f'<cell {{_overmind_cells}}>')))"- )---class DaytonaProvider:- """A Daytona sandbox for each project, stopped when idle and archived later; its files- survive both. A conversation's kernel is an interpreter context in it, which a stop- ends."""-- _lock = threading.Lock()- # Sandbox of each project, and when its state was last read.- _sandboxes: dict[str, tuple[Sandbox, float]] = {}- _contexts: dict[tuple[str, str], object] = {}-- def __init__(self):- self.client = _client()-- def _create(self, project: str) -> Sandbox:- # One sandbox for each project, whichever worker asks first.- with transaction.atomic(), connection.cursor() as cursor:- cursor.execute("SELECT pg_advisory_xact_lock(hashtext(%s))", [f"workspace:{project}"])- found = self._find(project)- if found is not None:- return found- return self.client.create(- CreateSandboxFromSnapshotParams(- snapshot=snapshot_name(),- labels=_labels(project),- network_block_all=True,- public=False,- ephemeral=False,- auto_stop_interval=STOP_MINUTES,- auto_archive_interval=ARCHIVE_MINUTES,- auto_delete_interval=DELETE_MINUTES,- ),- timeout=START_SECONDS,- )-- def _find(self, project: str) -> Sandbox | None:- found = self.client.list(ListSandboxesQuery(labels=_labels(project)))- live = next((item for item in found if _state(item) not in GONE), None)- return None if live is None else self.client.get(live.id)-- def _sandbox(self, project: str, *, start: bool = True, create: bool = True) -> Sandbox | None:- """The project's started sandbox. Without ``create`` a project that has none gets- none; without ``start`` one that is not running is not started either."""- with self._lock:- known = self._sandboxes.get(project)- if known is not None and time.monotonic() - known[1] < FRESH_SECONDS:- return known[0]- try:- sandbox = None- if known is not None:- sandbox = known[0]- try:- sandbox.refresh_data()- except DaytonaNotFoundError:- # Deleted since: by its project's removal, or unused for a week.- self._forget(project)- sandbox = None- if sandbox is None:- sandbox = self._find(project)- if sandbox is not None and _state(sandbox) in FAILED_BUILD:- if sandbox.recoverable:- if not start:- return None- # It comes back with its files.- sandbox.recover(timeout=START_SECONDS)- else:- # Its files are lost with it: the next cells copy versions in again.- self.client.delete(sandbox)- self._forget(project)- sandbox = None- if sandbox is None:- if not (start and create):- return None- sandbox = self._create(project)- elif _state(sandbox) != "started":- if not start:- return None- sandbox.start(timeout=START_SECONDS)- except DaytonaError as exc:- self._forget(project)- logger.warning("Daytona workspace for %s is not available: %s", project, exc)- raise WorkspaceUnavailableError("The workspace provider has no room now.") from exc- with self._lock:- self._sandboxes[project] = (sandbox, time.monotonic())- return sandbox-- def _forget(self, project: str) -> None:- with self._lock:- self._sandboxes.pop(project, None)- for key in [key for key in self._contexts if key[0] == project]:- del self._contexts[key]-- def has_data(self, project: str, name: str) -> bool:- sandbox = self._sandbox(project, create=False)- if sandbox is None:- return False- try:- sandbox.fs.get_file_info(f"{WORKSPACE}/data/{name}")- except DaytonaNotFoundError:- return False- except DaytonaError as exc:- raise WorkspaceUnavailableError(str(exc)) from exc- return True-- def put_data(self, project: str, name: str, source: BinaryIO) -> None:- if not NAME.fullmatch(name):- raise ValueError("Invalid file name.")- if self.has_data(project, name):- return- sandbox = self._sandbox(project)- path = f"{WORKSPACE}/data/{name}"- # Under its name only when whole: has_data takes a name that is there as copied.- partial = f"{WORKSPACE}/data/.{uuid.uuid4().hex}"- with tempfile.NamedTemporaryFile() as local:- shutil.copyfileobj(source, local)- local.flush()- try:- sandbox.fs.create_folder(f"{WORKSPACE}/data", "755")- sandbox.fs.upload_file(local.name, partial)- sandbox.fs.set_file_permissions(partial, mode="444")- sandbox.fs.move_files(partial, path)- except DaytonaError as exc:- self._forget(project)- with contextlib.suppress(DaytonaError):- sandbox.fs.delete_file(partial)- raise WorkspaceUnavailableError(str(exc)) from exc-- def _context(self, project: str, conversation: str, sandbox: Sandbox):- """The conversation's context, and why its variables are gone when a new one- replaced an earlier one."""- with self._lock:- known = self._contexts.get((project, conversation))- if known is not None:- return known, None- work = f"{WORKSPACE}/conversations/{conversation}"- found = next((c for c in sandbox.code_interpreter.list_contexts() if c.cwd == work), None)- restarted = None- if found is None:- existed = sandbox.process.exec(f"test -d {work}", timeout=30).exit_code == 0- restarted = RESTARTED if existed else None- sandbox.process.exec(- f"mkdir -p {WORKSPACE}/data {work} && ln -sfn ../../data {work}/data",- timeout=30,- )- found = sandbox.code_interpreter.create_context(cwd=work)- setup = sandbox.code_interpreter.run_code(SETUP, context=found, timeout=60)- if setup.error:- with contextlib.suppress(DaytonaError):- sandbox.code_interpreter.delete_context(found)- raise WorkspaceUnavailableError(f"The kernel did not start: {setup.error.value}")- with self._lock:- self._contexts[(project, conversation)] = found- return found, restarted-- def _end(self, project: str, conversation: str, sandbox: Sandbox, context) -> None:- with self._lock:- self._contexts.pop((project, conversation), None)- if context is None:- return- with contextlib.suppress(DaytonaError):- sandbox.code_interpreter.delete_context(context)-- def run(self, project: str, conversation: str, code: str, timeout: int) -> Execution:- for attempt in range(2):- sandbox, context = self._sandbox(project), None- try:- context, restarted = self._context(project, conversation, sandbox)- result = sandbox.code_interpreter.run_code(- _cell(code, timeout), context=context, timeout=timeout + GRACE_SECONDS- )- except DaytonaTimeoutError:- self._end(project, conversation, sandbox, context)- return Execution(False, "", LOST, False, float(timeout))- except DaytonaError as exc:- text = str(exc)- if "worker process ended" in text:- self._end(project, conversation, sandbox, context)- return Execution(False, "", LOST, False, 0.0)- # A stopped sandbox, or a context its stop ended: look again, once.- self._forget(project)- if attempt:- raise WorkspaceUnavailableError(text) from exc- continue- if result.error:- # Raised by the runner itself, not the cell: the context is not usable.- self._end(project, conversation, sandbox, context)- return Execution(- False, "", f"{result.error.name}: {result.error.value}", False, 0.0- )- reply = _reply(result.stdout)- if reply is None:- return Execution(False, "", UNREAD, False, 0.0, restarted)- return Execution(**reply, restarted=restarted)- raise WorkspaceUnavailableError("The workspace did not answer.")-- def read_file(self, project: str, conversation: str, name: str) -> bytes:- if not NAME.fullmatch(name):- raise FileNotFoundError(name)- sandbox = self._sandbox(project, create=False)- if sandbox is None:- raise FileNotFoundError(name)- # The kernel controls the name: it can be a link out of its folder, which the- # sandbox's own process would follow. A copy that does not follow it is read.- copy = f"/tmp/overmind-read-{uuid.uuid4().hex}"- try:- checked = sandbox.process.exec(- _copy_command(f"{WORKSPACE}/conversations/{conversation}/{name}", copy),- timeout=60,- )- if checked.exit_code != 0:- raise FileNotFoundError(name)- # And while it is read: the cell may still write it.- received = bytearray()- for chunk in sandbox.fs.download_file_stream(copy):- received += chunk- if len(received) > MAX_FILE_BYTES:- raise FileNotFoundError(name)- return bytes(received)- except DaytonaNotFoundError:- raise FileNotFoundError(name) from None- except DaytonaError as exc:- raise WorkspaceUnavailableError(str(exc)) from exc- finally:- with contextlib.suppress(DaytonaError):- sandbox.process.exec(f"rm -f {copy}", timeout=30)-- def forget(self, project: str, data: list[str], conversations: list[str]) -> None:- command = _forget_command(data, conversations)- # A stopped or archived workspace still holds the files: it starts to delete them.- sandbox = self._sandbox(project, create=False) if command else None- if sandbox is None:- return- for conversation in conversations:- self.stop(project, conversation)- try:- deleted = sandbox.process.exec(command, timeout=60)- except DaytonaError as exc:- raise WorkspaceUnavailableError(str(exc)) from exc- if deleted.exit_code != 0:- raise WorkspaceUnavailableError(f"The files were not deleted: {deleted.result}")-- def remove(self, project: str) -> None:- self._forget(project)- try:- for found in self.client.list(ListSandboxesQuery(labels=_labels(project))):- with contextlib.suppress(DaytonaNotFoundError):- self.client.delete(self.client.get(found.id))- for _ in range(START_SECONDS // 2):- if not any(- True for _ in self.client.list(ListSandboxesQuery(labels=_labels(project)))- ):- return- time.sleep(2)- except DaytonaError as exc:- raise WorkspaceUnavailableError(str(exc)) from exc- raise WorkspaceUnavailableError("The workspace is not deleted yet.")-- def stop(self, project: str, conversation: str) -> None:- sandbox = self._sandbox(project, start=False)- if sandbox is None:- return- work = f"{WORKSPACE}/conversations/{conversation}"- with contextlib.suppress(DaytonaError):- for context in sandbox.code_interpreter.list_contexts():- if context.cwd == work:- self._end(project, conversation, sandbox, context)---def _forget_command(data: list[str], conversations: list[str]) -> str:- paths = [f"{WORKSPACE}/data/{name}" for name in data if NAME.fullmatch(name)]- paths += [- f"{WORKSPACE}/conversations/{c}" for c in conversations if c.isalnum() and len(c) <= 64- ]- return "rm -rf " + " ".join(paths) if paths else ""---def _labels(project: str) -> dict[str, str]:- return {"overmind": "workspace", "project": project}---def _state(sandbox) -> str:- return str(getattr(sandbox.state, "value", sandbox.state))---def _reply(stdout: str) -> dict | None:- """The runner's reply: the last marker followed by a whole reply object. The cell's- own output may hold the marker too, inside the reply or written before it."""- decoder = json.JSONDecoder()- for line in reversed(stdout.splitlines()):- start = line.rfind(REPLY)- while start >= 0:- try:- reply, _ = decoder.raw_decode(line, start + len(REPLY))- except ValueError:- reply = None- if isinstance(reply, dict) and reply.keys() == REPLY_KEYS:- return reply- start = line.rfind(REPLY, 0, start)- return None---def _copy_command(path: str, copy: str) -> str:- """Copies a regular file with one link and at most MAX_FILE_BYTES, never a link's- target: ``cp -P`` opens the source without following it."""- return (- f'[ ! -L {path} ] && [ -f {path} ] && [ "$(stat -c %h {path})" = 1 ] '- f'&& [ "$(stat -c %s {path})" -le {MAX_FILE_BYTES} ] '- f"&& cp -P {path} {copy} && [ ! -L {copy} ] && [ -f {copy} ]"- )diff --git a/overbae/services/workspaces/modal_sandbox.py b/overbae/services/workspaces/modal_sandbox.pynew file mode 100644index 00000000..ab71eb0e--- /dev/null+++ b/overbae/services/workspaces/modal_sandbox.py@@ -0,0 +1,540 @@+"""Workspaces in Modal sandboxes: one sandbox for each project, one kernel for each+conversation in it. The project's files live on two Volumes, so they outlive the sandbox,+which ends after an idle hour or at Modal's 24-hour limit, and its kernels with it.++ /workspace/data/<name> the project's versions: root's, read-only to kernels+ /workspace/conversations/<c>/ a kernel's folder, under the conversation's own uid++A version goes in and a file comes out through the running sandbox: a Volume that a+sandbox mounts refuses outside reads and writes. With no sandbox running, the Volume API+serves them directly.+"""++import contextlib+import hashlib+import json+import logging+import os+import shlex+import tempfile+import threading+import time+import tomllib+import uuid+from datetime import timedelta+from functools import cache+from pathlib import Path+from typing import BinaryIO++import modal+from django.conf import settings+from django.db import connection, transaction+from django.utils import timezone+from modal.exception import AlreadyExistsError, NotFoundError+from modal.volume import FileEntryType++from overbae.models import BillingService, Project, WorkspaceSandbox+from overbae.services.billing_ledger import charge_credits+from overbae.services.workspaces import (+ MAX_FILE_BYTES,+ DataTooLargeError,+ Execution,+ WorkspaceUnavailableError,+)+from sandbox import execute+from sandbox.kernel import __file__ as kernel_file+from sandbox.workspaces import ID, NAME, RESTARTED++logger = logging.getLogger(__name__)++APP = "overmind-workspaces"+PREFIX = "overmind-ws-"+# The libraries a kernel imports, at the versions the app locks.+LIBRARIES = (+ "beautifulsoup4",+ "datasketch",+ "duckdb",+ "emoji",+ "ftfy",+ "jellyfish",+ "jsonschema",+ "langcodes",+ "langdetect",+ "levenshtein",+ "lxml",+ "markdownify",+ "matplotlib",+ "numpy",+ "pandas",+ "pillow",+ "pyarrow",+ "python-dateutil",+ "pytz",+ "pyyaml",+ "rapidfuzz",+ "regex",+ "scikit-learn",+ "scipy",+ "simhash",+ "tiktoken",+ "unidecode",+ "wordfreq",+)+PYTHON = "3.13"+TOKENIZER_ENCODINGS = ("cl100k_base", "o200k_base")+TOKENIZERS = "/opt/overmind/tiktoken"+KERNEL = Path(kernel_file)+KERNEL_PATH = "/opt/overmind/kernel.py"+WORKSPACE = "/workspace"+DATA = f"{WORKSPACE}/data"+CONVERSATIONS = f"{WORKSPACE}/conversations"+# Billed at the greater of request and use: an idle kernel costs its request, a cell may+# burst to the limit.+CPU = (0.25, 8.0)+MEMORY = (1024, 16 * 1024)+IDLE_SECONDS = 60 * 60+LIFE_SECONDS = 24 * 60 * 60+MAX_DATA_BYTES = 4 * execute.GIB+# A sandbox in the preferred region that is not ready in this time starts in any region.+REGION_SECONDS = 20+# A cell's own deadline is the kernel's; this one catches a kernel stuck outside Python.+GRACE_SECONDS = 30+# A known sandbox is not looked up again within this time.+FRESH_SECONDS = 60+# Modal reports a sandbox's usage a few minutes late: a window is charged once this old.+BILLING_LAG = timedelta(minutes=10)+LIMITS = {+ "readable": [DATA],+ "rlimits": {+ "RLIMIT_NPROC": execute.PROCESSES,+ "RLIMIT_NOFILE": execute.FILE_DESCRIPTORS,+ },+}+LOST = (+ "The kernel ended during the cell: it ran out of memory or stopped answering. "+ "Variables are gone, files remain."+)+UNKNOWN = (+ "The workspace stopped during the cell: it may have run. Variables may be gone, files remain."+)+++@cache+def image() -> tuple[modal.Image, str]:+ """The sandbox image, and a digest of everything a kernel runs on: a sandbox of another+ digest is replaced at its next use."""+ lock = tomllib.loads((KERNEL.parent.parent / "uv.lock").read_text())+ versions = {package["name"]: package["version"] for package in lock["package"]}+ requirements = [f"{name}=={versions[name]}" for name in LIBRARIES]+ cache_tokenizers = (+ 'python -c "import tiktoken; [tiktoken.get_encoding(name) for name in '+ f'{TOKENIZER_ENCODINGS!r}]"'+ )+ built = (+ modal.Image.debian_slim(PYTHON)+ .uv_pip_install(*requirements)+ .env({"TIKTOKEN_CACHE_DIR": TOKENIZERS})+ .run_commands(cache_tokenizers)+ .add_local_file(KERNEL, KERNEL_PATH)+ )+ recipe = "\n".join((PYTHON, *requirements, cache_tokenizers)).encode()+ return built, hashlib.sha256(recipe + KERNEL.read_bytes()).hexdigest()[:12]+++def _environment() -> str:+ return os.environ["MODAL_ENVIRONMENT"]+++@cache+def _app() -> modal.App:+ return modal.App.lookup(APP, environment_name=_environment(), create_if_missing=True)+++def _key(project: str) -> str:+ return uuid.UUID(project).hex+++def _name(project: str) -> str:+ return PREFIX + _key(project)+++def _volume(project: str, part: str, *, create: bool) -> modal.Volume | None:+ volume = modal.Volume.from_name(+ f"{_name(project)}-{part}",+ environment_name=_environment(),+ create_if_missing=create,+ version=2,+ )+ if not create:+ try:+ volume.hydrate()+ except NotFoundError:+ return None+ return volume+++def _exec(sandbox: modal.Sandbox, command, *, timeout: int, stdin: str | None = None):+ args = ["sh", "-c", command] if isinstance(command, str) else command+ process = sandbox.exec(*args, timeout=timeout)+ if stdin is not None:+ process.stdin.write(stdin)+ process.stdin.write_eof()+ process.stdin.drain()+ out, err = process.stdout.read(), process.stderr.read()+ return process.wait(), out, err+++class ModalProvider:+ _lock = threading.Lock()+ # Sandbox of each project, and when it was last looked up.+ _sandboxes: dict[str, tuple[modal.Sandbox, float]] = {}++ def _remember(self, project: str, sandbox: modal.Sandbox | None) -> None:+ with self._lock:+ if sandbox is None:+ self._sandboxes.pop(project, None)+ else:+ self._sandboxes[project] = (sandbox, time.monotonic())++ def _find(self, project: str) -> modal.Sandbox | None:+ with self._lock:+ known = self._sandboxes.get(project)+ if known is not None and time.monotonic() - known[1] < FRESH_SECONDS:+ return known[0]+ try:+ sandbox = modal.Sandbox.from_name(APP, _name(project), environment_name=_environment())+ except NotFoundError:+ sandbox = None+ if sandbox is not None and sandbox.get_tags().get("image") != image()[1]:+ # Started by an earlier release: its kernels restart in a new one, with the files.+ sandbox.terminate(wait=True)+ sandbox = None+ self._remember(project, sandbox)+ return sandbox++ def _sandbox(self, project: str, *, create: bool = True) -> modal.Sandbox | None:+ try:+ sandbox = self._find(project)+ if sandbox is None and create:+ sandbox = self._create(project)+ self._remember(project, sandbox)+ except modal.exception.Error as exc:+ self._remember(project, None)+ logger.warning("Modal workspace for %s is not available: %s", project, exc)+ raise WorkspaceUnavailableError(f"The workspace did not start: {exc}") from exc+ return sandbox++ def _create(self, project: str) -> modal.Sandbox:+ built, digest = image()+ options = {+ "app": _app(),+ "name": _name(project),+ "tags": {"project": _key(project), "image": digest},+ "image": built,+ "block_network": True,+ "cpu": CPU,+ "memory": MEMORY,+ "timeout": LIFE_SECONDS,+ "idle_timeout": IDLE_SECONDS,+ "workdir": WORKSPACE,+ "readiness_probe": modal.Probe.with_exec("true"),+ "volumes": {+ DATA: _volume(project, "data", create=True),+ CONVERSATIONS: _volume(project, "work", create=True),+ },+ }+ region = settings.MODAL_WORKSPACE_REGION+ sandbox = self._start(project, options | {"region": [region]}) if region else None+ return sandbox or self._start(project, options, wait=False)++ def _start(self, project: str, options: dict, *, wait: bool = True) -> modal.Sandbox | None:+ """The project's sandbox; None when one in the preferred region is not ready in+ time, so that the caller starts it anywhere."""+ try:+ sandbox = modal.Sandbox.create(**options)+ except AlreadyExistsError:+ # Another worker started it first.+ return modal.Sandbox.from_name(APP, options["name"], environment_name=_environment())+ if wait:+ try:+ sandbox.wait_until_ready(timeout=REGION_SECONDS)+ except modal.exception.TimeoutError:+ sandbox.terminate(wait=True)+ return None+ try:+ owner = Project.objects.filter(pk=project).values_list("owner_id", flat=True).first()+ WorkspaceSandbox.objects.create(+ sandbox_id=sandbox.object_id,+ project_id=project if owner is not None else None,+ user_id=owner,+ billed_until=timezone.now(),+ )+ code, _, err = _exec(+ sandbox, f"chmod 755 {DATA} && chmod 711 {CONVERSATIONS}", timeout=60+ )+ if code:+ raise WorkspaceUnavailableError(f"The workspace did not start: {err.strip()}")+ except BaseException:+ # Unregistered or unprepared, it must not serve cells. A registered one is still+ # charged to its end.+ sandbox.terminate()+ raise+ return sandbox++ def warm(self, project: str) -> None:+ """Starts the sandbox while the model writes its reply. A failure is the next+ cell's to report."""++ def start():+ try:+ with contextlib.suppress(WorkspaceUnavailableError):+ self._sandbox(project)+ finally:+ # This thread's own connection, which nothing else closes.+ connection.close()++ threading.Thread(target=start, daemon=True).start()++ def bill(self) -> int:+ """Charge each sandbox's owner for its usage since the last charge, at Modal's cost:+ the greater of request and use, at our rates. A window Modal has not measured yet+ waits for the next charge."""+ until = timezone.now() - BILLING_LAG+ charged = 0+ rows = WorkspaceSandbox.objects.filter(finished=False, billed_until__lt=until)+ for since, pk, sandbox_id in rows.values_list("billed_until", "pk", "sandbox_id"):+ try:+ sandbox = modal.Sandbox.from_id(sandbox_id)+ usage = sandbox._experimental_stats(since=since, until=until)+ ended = sandbox.poll() is not None+ except modal.exception.Error as exc:+ logger.warning("usage of sandbox %s is not available: %s", sandbox_id, exc)+ continue+ if usage.cost is None and not ended:+ continue+ with transaction.atomic():+ row = (+ WorkspaceSandbox.objects.select_for_update(of=("self",))+ .select_related("user")+ .get(pk=pk)+ )+ # Another run charged this window since it was measured.+ if row.billed_until != since:+ continue+ if usage.cost and row.user_id is not None:+ charge_credits(+ row.user,+ usage.cost,+ BillingService.WORKSPACE,+ project_id=row.project_id,+ idempotency_key=f"modal-sandbox:{row.sandbox_id}:{row.billed_until.isoformat()}",+ metadata={+ "sandbox": row.sandbox_id,+ "since": row.billed_until.isoformat(),+ "until": until.isoformat(),+ "cpu_core_seconds": usage.billed_cpu_core_seconds,+ "memory_gib_seconds": usage.billed_memory_gib_seconds,+ "cost_by_resource": {+ k: str(v) for k, v in usage.cost_by_resource.items()+ },+ },+ )+ charged += 1+ row.billed_until = until+ # Its last window had no time left in it: all of it is charged.+ row.finished = ended and not usage.duration+ row.save(update_fields=["billed_until", "finished"])+ return charged++ def projects(self) -> list[str]:+ names = {+ volume.name for volume in modal.Volume.objects.list(environment_name=_environment())+ }+ keys = {name[len(PREFIX) : -5] for name in names if name.startswith(PREFIX)}+ return sorted(str(uuid.UUID(key)) for key in keys)++ def has_data(self, project: str, name: str) -> bool:+ volume = _volume(project, "data", create=False)+ if volume is None:+ return False+ try:+ return any(Path(entry.path).name == name for entry in volume.listdir("/"))+ except modal.exception.Error as exc:+ raise WorkspaceUnavailableError(str(exc)) from exc++ def put_data(self, project: str, name: str, source: BinaryIO) -> None:+ if not NAME.fullmatch(name):+ raise ValueError("Invalid file name.")+ if self.has_data(project, name):+ return+ with tempfile.NamedTemporaryFile() as local:+ copied = 0+ while chunk := source.read(1024**2):+ copied += len(chunk)+ if copied > MAX_DATA_BYTES:+ raise DataTooLargeError(+ f"The version is larger than {MAX_DATA_BYTES // execute.GIB} GiB."+ )+ local.write(chunk)+ local.flush()+ sandbox = self._sandbox(project)+ # Under its name only when whole: has_data takes a name that is there as copied.+ partial = f"{DATA}/.{uuid.uuid4().hex}"+ try:+ sandbox.filesystem.copy_from_local(local.name, partial)+ code, _, err = _exec(+ sandbox,+ f"chown 0:0 {partial} && chmod 444 {partial} "+ f"&& mv {partial} {shlex.quote(f'{DATA}/{name}')} && sync {DATA}",+ timeout=120,+ )+ except modal.exception.Error as exc:+ self._remember(project, None)+ raise WorkspaceUnavailableError(str(exc)) from exc+ if code:+ with contextlib.suppress(modal.exception.Error):+ _exec(sandbox, f"rm -f {partial}", timeout=30)+ raise WorkspaceUnavailableError(f"The version was not copied: {err.strip()}")++ def run(self, project: str, conversation: str, code: str, timeout: int) -> Execution:+ if not ID.fullmatch(conversation):+ raise ValueError("Invalid conversation.")+ sandbox = self._sandbox(project)+ work = f"{CONVERSATIONS}/{conversation}"+ command = ["python", "-I", "-S", KERNEL_PATH, "cell", work, DATA, json.dumps(LIMITS)]+ try:+ status, out, err = _exec(+ sandbox,+ command,+ stdin=json.dumps({"code": code, "timeout": timeout}),+ timeout=timeout + GRACE_SECONDS,+ )+ except modal.exception.ExecTimeoutError:+ self.stop(project, conversation)+ return Execution(False, "", LOST, False, float(timeout))+ except modal.exception.Error:+ # The cell was sent: it may have run, so it is not reported as never run.+ self._remember(project, None)+ return Execution(False, "", UNKNOWN, False, float(timeout))+ if status != 0:+ # The kernel stopped answering past its own deadline: end it.+ self.stop(project, conversation)+ if "did not start" in err:+ raise WorkspaceUnavailableError("The kernel did not start.")+ return Execution(False, "", LOST, False, float(timeout))+ if not out.strip():+ return Execution(False, "", LOST, False, 0.0)+ answer = json.loads(out.strip().splitlines()[-1])+ restarted = RESTARTED if answer["restarted"] else None+ if answer["reply"] is None:+ return Execution(False, "", LOST, False, 0.0, restarted)+ return Execution(**answer["reply"], restarted=restarted)++ def read_file(self, project: str, conversation: str, name: str) -> bytes:+ if not NAME.fullmatch(name) or not ID.fullmatch(conversation):+ raise FileNotFoundError(name)+ try:+ sandbox = self._sandbox(project, create=False)+ if sandbox is None:+ return self._read_volume(project, conversation, name)+ # Copied first: the cell may still write the file while it is read.+ copy = f"/tmp/overmind-read-{uuid.uuid4().hex}"+ try:+ status, _, _ = _exec(+ sandbox,+ [+ "python",+ "-I",+ "-S",+ KERNEL_PATH,+ "copy",+ f"{CONVERSATIONS}/{conversation}/{name}",+ copy,+ str(MAX_FILE_BYTES),+ ],+ timeout=60,+ )+ if status != 0:+ raise FileNotFoundError(name)+ return sandbox.filesystem.read_bytes(copy)+ finally:+ with contextlib.suppress(modal.exception.Error):+ _exec(sandbox, f"rm -f {copy}", timeout=30)+ except modal.exception.Error as exc:+ raise WorkspaceUnavailableError(str(exc)) from exc++ def _read_volume(self, project: str, conversation: str, name: str) -> bytes:+ volume = _volume(project, "work", create=False)+ if volume is None:+ raise FileNotFoundError(name)+ try:+ entries = {Path(entry.path).name: entry for entry in volume.listdir(f"/{conversation}")}+ except NotFoundError:+ raise FileNotFoundError(name) from None+ entry = entries.get(name)+ if entry is None or entry.type != FileEntryType.FILE or entry.size > MAX_FILE_BYTES:+ raise FileNotFoundError(name)+ received = bytearray()+ for chunk in volume.read_file(f"/{conversation}/{name}"):+ received += chunk+ if len(received) > MAX_FILE_BYTES:+ raise FileNotFoundError(name)+ return bytes(received)++ def stop(self, project: str, conversation: str) -> None:+ if not ID.fullmatch(conversation):+ return+ sandbox = self._sandbox(project, create=False)+ if sandbox is None:+ return+ with contextlib.suppress(modal.exception.Error):+ _exec(+ sandbox,+ ["python", "-I", "-S", KERNEL_PATH, "stop", f"{CONVERSATIONS}/{conversation}"],+ timeout=30,+ )++ def forget(self, project: str, data: list[str], conversations: list[str]) -> None:+ data = [name for name in data if NAME.fullmatch(name)]+ conversations = [c for c in conversations if ID.fullmatch(c)]+ if not data and not conversations:+ return+ sandbox = self._sandbox(project, create=False)+ if sandbox is not None:+ # A running sandbox keeps its own view of the Volumes: it deletes the files.+ for conversation in conversations:+ self.stop(project, conversation)+ paths = [f"{DATA}/{name}" for name in data]+ paths += [f"{CONVERSATIONS}/{c}" for c in conversations]+ try:+ status, _, err = _exec(+ sandbox,+ f"rm -rf {' '.join(map(shlex.quote, paths))} "+ f"&& sync {DATA} && sync {CONVERSATIONS}",+ timeout=120,+ )+ except modal.exception.Error as exc:+ raise WorkspaceUnavailableError(str(exc)) from exc+ if status:+ raise WorkspaceUnavailableError(f"The files were not deleted: {err.strip()}")+ return+ for part, names in (("data", data), ("work", conversations)):+ volume = _volume(project, part, create=False) if names else None+ for name in names if volume is not None else ():+ with contextlib.suppress(NotFoundError, FileNotFoundError):+ volume.remove_file(f"/{name}", recursive=True)++ def remove(self, project: str) -> None:+ self._remember(project, None)+ tags = {"project": _key(project)}+ try:+ for sandbox in modal.Sandbox.list(app_id=_app().app_id, tags=tags):+ sandbox.terminate(wait=True)+ for part in ("data", "work"):+ modal.Volume.objects.delete(+ f"{_name(project)}-{part}", environment_name=_environment(), allow_missing=True+ )+ except modal.exception.Error as exc:+ raise WorkspaceUnavailableError(str(exc)) from exc+ if any(True for _ in modal.Sandbox.list(app_id=_app().app_id, tags=tags)):+ raise WorkspaceUnavailableError("The workspace is not deleted yet.")diff --git a/overbae/services/workspaces/native.py b/overbae/services/workspaces/native.pyindex b81fb138..1beb9572 100644--- a/overbae/services/workspaces/native.py+++ b/overbae/services/workspaces/native.py@@ -3,7 +3,7 @@ from typing import BinaryIOimport httpxfrom django.conf import settings-from overbae.services.workspaces import Execution, WorkspaceUnavailableError+from overbae.services.workspaces import DataTooLargeError, Execution, WorkspaceUnavailableErrorCHUNK_BYTES = 1024**2# The sandbox waits for memory before it starts a kernel; a cell may run to its deadline.@@ -48,6 +48,18 @@ class NativeProvider:raise WorkspaceUnavailableError(reason)return response+ def warm(self, project: str) -> None:+ pass++ def bill(self) -> int:+ # The sandbox server is the install's own: nothing is charged.+ return 0++ def projects(self) -> list[str]:+ response = self._request("GET", "", timeout=30)+ response.raise_for_status()+ return response.json()["projects"]+def has_data(self, project: str, name: str) -> bool:response = self._request("HEAD", f"/{project}/data/{name}", timeout=30)return response.status_code == 204@@ -56,9 +68,12 @@ class NativeProvider:if self.has_data(project, name):returnchunks = iter(lambda: source.read(CHUNK_BYTES), b"")- self._request(+ response = self._request("PUT", f"/{project}/data/{name}", content=chunks, timeout=TRANSFER_SECONDS- ).raise_for_status()+ )+ if response.status_code == 413:+ raise DataTooLargeError(_body(response).get("error", "The version is too large."))+ response.raise_for_status()def run(self, project: str, conversation: str, code: str, timeout: int) -> Execution:try:diff --git a/overbae/settings.py b/overbae/settings.pyindex b46bffc5..2c0f808f 100644--- a/overbae/settings.py+++ b/overbae/settings.py@@ -446,6 +446,9 @@ CELERY_TASK_ROUTES = {"overbae.tasks.assistant.stop_kernel": {"queue": "assistant"},"overbae.tasks.assistant.forget_workspace_data": {"queue": "assistant"},"overbae.tasks.assistant.remove_workspace": {"queue": "assistant"},+ "overbae.tasks.assistant.charge_generation": {"queue": "assistant"},+ "overbae.tasks.assistant.bill_workspaces": {"queue": "assistant"},+ "overbae.tasks.assistant.sweep_idle_workspaces": {"queue": "assistant"},"overbae.tasks.innermind.generate_row": {"queue": "batch"},"overbae.tasks.innermind.score_eval_run": {"queue": "batch"},# Model warm-up blocks for minutes; control stays free for reconcilers and metrics.@@ -554,6 +557,14 @@ CELERY_BEAT_SCHEDULE = {"task": "overbae.tasks.guest_cleanup.sweep_guest_workspaces","schedule": 86400.0,},+ "bill-workspaces": {+ "task": "overbae.tasks.assistant.bill_workspaces",+ "schedule": 900.0,+ },+ "sweep-idle-workspaces": {+ "task": "overbae.tasks.assistant.sweep_idle_workspaces",+ "schedule": 86400.0,+ },"reconcile-deployments": {"task": "overbae.tasks.inference_controller.reconcile_deployments","schedule": 15.0,@@ -750,9 +761,12 @@ INFERENCE_API_KEY: str = os.environ.get("INFERENCE_API_KEY", "")SANDBOX_URL = os.environ.get("SANDBOX_URL", "").rstrip("/")SANDBOX_TOKEN = os.environ.get("SANDBOX_TOKEN", "")-# Where the assistant runs Python: native (the sandbox service) or daytona.-WORKSPACE_PROVIDER = os.environ.get("WORKSPACE_PROVIDER", "native")-DAYTONA_API_KEY = os.environ.get("DAYTONA_API_KEY", "")+# Where the assistant runs Python: modal, or native (the sandbox service, one server) for+# installs that run offline.+WORKSPACE_PROVIDER = os.environ.get("WORKSPACE_PROVIDER", "modal")+# A Modal region name such as "eu": workspaces start there and fall back to any region+# when it has no room. Empty lets Modal place them.+MODAL_WORKSPACE_REGION = os.environ.get("MODAL_WORKSPACE_REGION", "")# Prompt tokens of one assistant reply above which the older conversation is summarized.ASSISTANT_COMPACT_TOKENS = int(os.environ.get("ASSISTANT_COMPACT_TOKENS", "120000"))@@ -769,6 +783,10 @@ _REQUIRED_KEYS = {"AWS_BUCKET_NAME": "the fine-tuning checkpoint archive","HF_TOKEN": "gated Hugging Face base models",}+if WORKSPACE_PROVIDER == "modal":+ _REQUIRED_KEYS["MODAL_ENVIRONMENT"] = "the assistant's Modal workspaces"+elif WORKSPACE_PROVIDER != "native":+ raise ImproperlyConfigured("WORKSPACE_PROVIDER must be modal or native.")_missing_keys = [f"{name} ({purpose})"for name, purpose in _REQUIRED_KEYS.items()diff --git a/overbae/tasks/assistant.py b/overbae/tasks/assistant.pyindex b102e478..551c9c8b 100644--- a/overbae/tasks/assistant.py+++ b/overbae/tasks/assistant.py@@ -1,6 +1,22 @@+import logging+from datetime import timedeltafrom uuid import UUID+import httpxfrom celery import shared_task+from django.db import transaction+from django.db.models import Max+from django.utils import timezone++logger = logging.getLogger(__name__)++# A workspace holds copies of customer data: one its project has not used for this long is+# deleted, files and all. The next cell creates it again and copies in what it reads.+IDLE_WORKSPACE = timedelta(days=7)+++class NotPricedError(Exception):+ """The provider has not priced the generation yet."""@shared_task(name="overbae.tasks.assistant.run_turn")@@ -53,3 +69,83 @@ def remove_workspace(project_id):from overbae.services import workspacesworkspaces.provider().remove(project_id)+++@shared_task(+ name="overbae.tasks.assistant.charge_generation",+ autoretry_for=(NotPricedError, httpx.HTTPError),+ retry_backoff=30,+ max_retries=12,+)+def charge_generation(user_id, project_id, generation):+ """Charge a model call of the assistant whose usage carried no cost, at what the provider+ billed for its generation."""+ from overbae.models import BillingService, Project, User+ from overbae.services import billing_ledger++ cost = billing_ledger.generation_cost(generation)+ if cost is None:+ raise NotPricedError(generation)+ with transaction.atomic():+ # The project may be deleted by now; the charge stays its owner's. Its row is held+ # until the charge is written, so a delete waits for it.+ held = (+ Project.objects.select_for_update().filter(pk=project_id).values_list("pk", flat=True)+ )+ billing_ledger.charge_credits(+ User.objects.get(pk=user_id),+ cost,+ BillingService.ASSISTANT,+ project_id=project_id if list(held) else None,+ idempotency_key=f"openrouter:{generation}",+ metadata={"generation": generation},+ )+++@shared_task(name="overbae.tasks.assistant.bill_workspaces")+def bill_workspaces():+ """Charge each project's owner for the workspace compute the provider has measured."""+ from overbae.services import workspaces++ return {"charged": workspaces.provider().bill()}+++@shared_task(name="overbae.tasks.assistant.sweep_idle_workspaces")+def sweep_idle_workspaces():+ from overbae.models import AssistantThread+ from overbae.services import workspaces++ provider = workspaces.provider()+ held = {}+ for project in provider.projects():+ try:+ held[project] = UUID(project)+ except ValueError:+ # Not a project's workspace: nothing uses it.+ held[project] = None+ used = dict(+ AssistantThread.objects.filter(project_id__in=[key for key in held.values() if key])+ .values_list("project_id")+ .annotate(last=Max("updated_at"))+ )+ cutoff = timezone.now() - IDLE_WORKSPACE+ idle = [project for project, key in held.items() if used.get(key, cutoff) <= cutoff]+ removed = 0+ for project in idle:+ # A turn may have started since the read above: it keeps the workspace. One that+ # starts during the removal itself loses what it wrote in those seconds; a lock that+ # every cell holds against the removal would close that.+ if (+ held[project]+ and AssistantThread.objects.filter(+ project_id=held[project], updated_at__gt=timezone.now() - IDLE_WORKSPACE+ ).exists()+ ):+ continue+ try:+ provider.remove(project)+ except workspaces.WorkspaceUnavailableError as exc:+ logger.warning("idle workspace %s is not removed yet: %s", project, exc)+ continue+ removed += 1+ return {"removed": removed}diff --git a/pyproject.toml b/pyproject.tomlindex 9892d5a1..f465a170 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -73,7 +73,6 @@ dependencies = ["wordfreq>=3.1.1","docling-slim[convert-core,format-docx,format-markdown,format-pdf-docling]>=2.131.0,<3","pypdfium2>=5.0,<6",- "daytona==0.231.1","matplotlib>=3.11.2","orjson>=3.13.0",]diff --git a/sandbox/kernel.py b/sandbox/kernel.pyindex 88cfdcb3..ebb68667 100644--- a/sandbox/kernel.py+++ b/sandbox/kernel.py@@ -1,14 +1,20 @@"""A persistent Python namespace, one cell at a time, and the limits untrusted code runsunder. Both workspace providers run cells through ``run``, so this file imports the-standard library only: the native sandbox serves it behind a Unix socket, and a Daytona-interpreter context loads it from the snapshot.+standard library only: the native sandbox serves it behind a Unix socket, and a Modal+sandbox, which has no server, reaches it with one ``cell`` process for each cell.kernel.py serve <socket> [limits-json] hold the namespace and answer requests+ kernel.py cell <work> <data> <limits-json> run the request on stdin in the conversation's+ kernel, starting one when it has none+ kernel.py stop <work> end the conversation's kernel+ kernel.py copy <path> <copy> <max-bytes> copy a regular file the kernel wrote, never+ a link's target, refusing more than max-bytes"""import astimport contextlibimport ctypes+import fcntlimport ioimport jsonimport linecache@@ -16,12 +22,22 @@ import osimport resourceimport signalimport socket+import statimport struct+import subprocessimport sysimport timeimport tracebackOUTPUT_CHARS = 60_000+# What a kernel may answer: its bounded output and error, as JSON. The kernel runs the+# tenant's code, so its caller holds it to this size itself.+MAX_REPLY_BYTES = 1024**2+REPLY_GRACE_SECONDS = 15+START_SECONDS = 20+SOCKET = ".kernel.sock"+# Uids of conversation kernels in a sandbox that has no server to hand them out.+FIRST_UID = 20000# Landlock file rights by ABI version: each version adds rights after the 13 of the first._FS_RIGHTS = {1: 13, 2: 14, 3: 15, 4: 15, 5: 16}@@ -222,5 +238,188 @@ def serve(path, limits):stream.write(json.dumps(reply).encode())+def _text(value) -> str:+ # A lone surrogate is valid in a Python string and in no JSON a caller will send on.+ return str(value).encode("utf-8", "replace").decode()+++def exchange(path: str, request: dict) -> dict:+ """One cell and its reply, within one deadline and one size. The kernel runs the+ tenant's code: nothing it sends is taken on trust."""+ deadline = time.monotonic() + request["timeout"] + REPLY_GRACE_SECONDS+ received = bytearray()+ with socket.socket(socket.AF_UNIX) as connection:+ connection.settimeout(REPLY_GRACE_SECONDS)+ connection.connect(path)+ connection.sendall(json.dumps(request).encode() + b"\n")+ while True:+ connection.settimeout(max(0.01, deadline - time.monotonic()))+ chunk = connection.recv(65536)+ if not chunk:+ break+ received += chunk+ if len(received) > MAX_REPLY_BYTES or time.monotonic() > deadline:+ raise ValueError("The kernel's reply passed its limits.")+ reply = json.loads(received)+ return {+ "ok": reply["ok"] is True,+ "output": _text(reply["output"]),+ "error": _text(reply["error"]),+ "truncated": reply["truncated"] is True,+ "seconds": float(reply["seconds"]),+ }+++def answers(path: str) -> bool:+ with socket.socket(socket.AF_UNIX) as probe:+ try:+ probe.connect(path)+ except OSError:+ return False+ return True+++def _locked(path: str):+ with open(path, "a+") as handle:+ fcntl.flock(handle, fcntl.LOCK_EX)+ yield handle+++def _uid(work: str) -> int:+ """The conversation's own uid, kept beside the conversations: a kernel of another+ sandbox that mounts the same folders runs under the same uid."""+ with _locked(os.path.join(os.path.dirname(work), ".uids")) as registry:+ os.chmod(registry.name, 0o600)+ registry.seek(0)+ uids = json.loads(registry.read() or "{}")+ name = os.path.basename(work)+ if name not in uids:+ uids[name] = FIRST_UID + len(uids)+ registry.seek(0)+ registry.truncate()+ registry.write(json.dumps(uids))+ registry.flush()+ os.fsync(registry.fileno())+ return uids[name]+++def _launch(work: str, data: str, limits: dict) -> bool:+ """Start the conversation's kernel under its own uid; whether an earlier kernel of the+ conversation existed."""+ uid = _uid(work)+ existed = os.path.isdir(work)+ os.makedirs(work, exist_ok=True)+ os.chown(work, uid, uid)+ os.chmod(work, 0o700)+ # A mount is a link to the provider's own path, so a relative link would leave it.+ link = os.path.join(work, "data")+ if not os.path.islink(link) or os.readlink(link) != data:+ with contextlib.suppress(FileNotFoundError, IsADirectoryError):+ os.unlink(link)+ with contextlib.suppress(FileExistsError):+ os.symlink(data, link)+ path = os.path.join(work, SOCKET)+ with contextlib.suppress(FileNotFoundError):+ os.unlink(path)+ name = os.path.basename(work)+ with open(f"/tmp/kernel-{name}.err", "ab") as errors:+ process = subprocess.Popen(+ [sys.executable, "-I", os.path.abspath(__file__), "serve", SOCKET, json.dumps(limits)],+ cwd=work,+ stdin=subprocess.DEVNULL,+ stdout=subprocess.DEVNULL,+ stderr=errors,+ start_new_session=True,+ user=uid,+ group=uid,+ extra_groups=[],+ env={+ "PATH": os.environ.get("PATH", "/usr/local/bin:/usr/bin:/bin"),+ "HOME": work,+ "TMPDIR": work,+ "MPLCONFIGDIR": work,+ **{k: v for k, v in os.environ.items() if k == "TIKTOKEN_CACHE_DIR"},+ },+ )+ with open(f"/tmp/kernel-{name}.pid", "w") as pid:+ pid.write(str(process.pid))+ deadline = time.monotonic() + START_SECONDS+ while not answers(path):+ if process.poll() is not None or time.monotonic() > deadline:+ process.kill()+ raise SystemExit("The kernel did not start.")+ time.sleep(0.05)+ return existed+++def cell(work: str, data: str, limits: dict) -> None:+ """Run the request on stdin and print ``{"reply", "restarted"}``: a reply of null is a+ kernel that ended during the cell."""+ request = json.loads(sys.stdin.read())+ path = os.path.join(work, SOCKET)+ restarted = False+ with _locked(f"/tmp/kernel-{os.path.basename(work)}.lock"):+ if not answers(path):+ restarted = _launch(work, data, limits)+ used = _pid(work)+ try:+ reply = exchange(path, request)+ except (OSError, ValueError, KeyError, TypeError):+ # The kernel's own deadline did not fire: it is stuck outside Python, or dead.+ stop(work, only=used)+ reply = None+ print(json.dumps({"reply": reply, "restarted": restarted}))+++def _pid(work: str) -> int | None:+ with (+ contextlib.suppress(OSError, ValueError),+ open(f"/tmp/kernel-{os.path.basename(work)}.pid") as pid,+ ):+ return int(pid.read())+ return None+++def stop(work: str, *, only: int | None = None) -> None:+ """End the conversation's kernel; with ``only``, that kernel alone, leaving one that+ started since and its names."""+ name = os.path.basename(work)+ # The lock a start holds: a kernel started meanwhile keeps its names.+ with _locked(f"/tmp/kernel-{name}.lock"):+ current = _pid(work)+ target = current if only is None else only+ if target is not None:+ with contextlib.suppress(OSError):+ os.killpg(target, signal.SIGKILL)+ if only is None or current == only:+ for path in (f"/tmp/kernel-{name}.pid", os.path.join(work, SOCKET)):+ with contextlib.suppress(FileNotFoundError):+ os.unlink(path)+++def copy(path: str, target: str, limit: int) -> None:+ """The kernel controls the name, and the file while it is read: open it without+ following a link, as one regular file with one name, and read no more than ``limit``."""+ source = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)+ with os.fdopen(source, "rb") as opened:+ status = os.fstat(opened.fileno())+ if not stat.S_ISREG(status.st_mode) or status.st_nlink != 1:+ raise SystemExit("Not one regular file.")+ content = opened.read(limit + 1)+ if len(content) > limit:+ raise SystemExit("The file is too large.")+ with open(target, "xb") as out:+ out.write(content)++if __name__ == "__main__":- serve(sys.argv[2], json.loads(sys.argv[3]) if len(sys.argv) > 3 else {})+ mode = sys.argv[1]+ if mode == "serve":+ serve(sys.argv[2], json.loads(sys.argv[3]) if len(sys.argv) > 3 else {})+ elif mode == "cell":+ cell(sys.argv[2], sys.argv[3], json.loads(sys.argv[4]))+ elif mode == "stop":+ stop(sys.argv[2])+ elif mode == "copy":+ copy(sys.argv[2], sys.argv[3], int(sys.argv[4]))diff --git a/sandbox/workspaces.py b/sandbox/workspaces.pyindex 2a5afca2..51e23a1d 100644--- a/sandbox/workspaces.py+++ b/sandbox/workspaces.py@@ -16,7 +16,6 @@ import osimport reimport shutilimport signal-import socketimport subprocessimport sysimport threading@@ -30,6 +29,7 @@ from starlette.requests import Requestfrom starlette.responses import JSONResponse, Responsefrom sandbox import execute+from sandbox.kernel import answers, exchangelogger = logging.getLogger(__name__)KERNEL_BYTES = 2 * execute.GIB@@ -41,11 +41,7 @@ MAX_DATA_BYTES = execute.GIBMAX_FILE_BYTES = 64 * 1024**2MAX_EXECUTION_SECONDS = 600DATA_BUDGET_BYTES = 20 * execute.GIB-# What a kernel may answer: its bounded output and error, as JSON. The kernel runs the-# tenant's code, so the server holds it to this size itself.-MAX_REPLY_BYTES = 1024**2START_SECONDS = 20-REPLY_GRACE_SECONDS = 15WATCH_SECONDS = 1FOOTPRINT_EVERY = 5RENEW_EVERY = 60@@ -110,15 +106,6 @@ def project_dir(project: str) -> Path:return path-def _answers(path: str) -> bool:- with socket.socket(socket.AF_UNIX) as probe:- try:- probe.connect(path)- except OSError:- return False- return True--def _start(project: str, conversation: str) -> tuple[Kernel, str | None]:"""A kernel for the conversation, and why its variables are gone when an earlierkernel of the same conversation existed."""@@ -157,7 +144,7 @@ def _start(project: str, conversation: str) -> tuple[Kernel, str | None]:)kernel = Kernel(slot, work, process, directory)deadline = time.monotonic() + START_SECONDS- while not _answers(kernel.socket_path):+ while not answers(kernel.socket_path):code = process.poll()if code is not None or time.monotonic() > deadline:ended = (@@ -213,38 +200,6 @@ def stop(project: str, conversation: str, kernel: Kernel | None = None) -> None:execute.release(held.slot)-def _text(value) -> str:- # A lone surrogate is valid in a Python string and in no response this server sends.- return str(value).encode("utf-8", "replace").decode()---def _exchange(kernel: Kernel, request: dict) -> dict:- """One cell and its reply, within one deadline and one size. The kernel runs the- tenant's code: nothing it sends is taken on trust."""- deadline = time.monotonic() + request["timeout"] + REPLY_GRACE_SECONDS- received = bytearray()- with socket.socket(socket.AF_UNIX) as connection:- connection.settimeout(REPLY_GRACE_SECONDS)- connection.connect(kernel.socket_path)- connection.sendall(json.dumps(request).encode() + b"\n")- while True:- connection.settimeout(max(0.01, deadline - time.monotonic()))- chunk = connection.recv(65536)- if not chunk:- break- received += chunk- if len(received) > MAX_REPLY_BYTES or time.monotonic() > deadline:- raise ValueError("The kernel's reply passed its limits.")- reply = json.loads(received)- return {- "ok": reply["ok"] is True,- "output": _text(reply["output"]),- "error": _text(reply["error"]),- "truncated": reply["truncated"] is True,- "seconds": float(reply["seconds"]),- }--def run(project: str, conversation: str, code: str, timeout: int) -> dict:"""Run a cell in the conversation's kernel, starting one when it has none."""restarted = None@@ -265,7 +220,7 @@ def run(project: str, conversation: str, code: str, timeout: int) -> dict:if not kernel.executing.acquire(blocking=False):raise BusyError("This conversation's kernel already runs a cell.")try:- reply = _exchange(kernel, {"code": code, "timeout": timeout})+ reply = exchange(kernel.socket_path, {"code": code, "timeout": timeout})except (OSError, ValueError, KeyError, TypeError):# The kernel's own deadline did not fire: it is stuck outside Python, or dead.stop(project, conversation, kernel)@@ -368,7 +323,12 @@ async def put_data(request: Request) -> Response:async for chunk in request.stream():written += len(chunk)if written > MAX_DATA_BYTES:- return JSONResponse({"error": "The file is too large."}, status_code=413)+ return JSONResponse(+ {+ "error": f"The version is larger than {MAX_DATA_BYTES // execute.GIB} GiB."+ },+ status_code=413,+ )fh.write(chunk)partial.chmod(0o444)partial.replace(data / name)@@ -447,6 +407,11 @@ async def forget_files(request: Request) -> Response:return Response(status_code=204)+async def list_projects(_request: Request) -> Response:+ found = [path.name for path in root().iterdir() if path.is_dir()] if root().is_dir() else []+ return JSONResponse({"projects": sorted(found)})++async def remove_workspace(request: Request) -> Response:project = request.path_params["project"]if not ID.fullmatch(project):@@ -464,6 +429,7 @@ async def delete(request: Request) -> Response:ROUTES = [+ ("/v1/workspaces", list_projects, ["GET"]),("/v1/workspaces/{project}", remove_workspace, ["DELETE"]),("/v1/workspaces/{project}/forget", forget_files, ["POST"]),("/v1/workspaces/{project}/data/{name}", has_data, ["HEAD"]),diff --git a/tests/factories.py b/tests/factories.pyindex e6364d1d..8cdeca84 100644--- a/tests/factories.py+++ b/tests/factories.py@@ -48,6 +48,8 @@ def api_key_client(user: User, project: Project | None = None) -> APIClient:def make_project(name: str = "P", *, member: User | None = None, **fields: Any) -> Project:fields.setdefault("slug", f"p-{uuid.uuid4().hex[:8]}")+ # Its first member created it, and owns it.+ fields.setdefault("owner", member)project = Project.objects.create(name=name, **fields)if member is not None:make_member(member, project)diff --git a/tests/fakes/llm.py b/tests/fakes/llm.pyindex 6e090aee..9dffd624 100644--- a/tests/fakes/llm.py+++ b/tests/fakes/llm.py@@ -10,6 +10,7 @@ from dataclasses import dataclass, fieldfrom http.server import BaseHTTPRequestHandler, ThreadingHTTPServerfrom typing import Anyfrom unittest import mock+from urllib.parse import parse_qs, urlsplitimport httpximport responses@@ -119,13 +120,15 @@ class FakeLLM:self._scripts.clear()self._failures.clear()- def stream_rounds(self, rounds, *, reasoning: str = "") -> None:- """Script the streamed tool-calling replies of an agent, one ``(calls, text)`` per round."""+ def stream_rounds(self, rounds, *, reasoning: str = "", cost: float | None = 0.01) -> None:+ """Script the streamed tool-calling replies of an agent, one ``(calls, text)`` per round.+ A ``cost`` of None leaves it out of the usage, as a provider may."""replies = iter(rounds)def reply(request: LLMRequest) -> dict[str, Any]:calls, text = next(replies)- message: dict[str, Any] = {"content": None, "usage": {"cost": 0.01}}+ usage = {} if cost is None else {"cost": cost}+ message: dict[str, Any] = {"content": None, "usage": usage}if calls:message["tool_calls"] = callsif isinstance(text, list):@@ -159,6 +162,8 @@ class FakeLLM:output_limits: dict[str, int] = field(default_factory=dict)catalog_payload: list[dict[str, Any]] | None = Nonecatalog_reads: list[dict[str, str]] = field(default_factory=list)+ # What OpenRouter billed for each generation id; one not listed is not priced yet.+ generations: dict[str, float] = field(default_factory=dict)def catalog(self) -> list[dict[str, Any]]:from overbae.core.model_registry import OPENROUTER_MODEL_SLUGS@@ -356,6 +361,12 @@ class FakeLLM:"usage": {"input_tokens": 10, "output_tokens": 1, "cost": self.decision_cost},}return 200, {"content-type": "application/json"}, json.dumps(payload).encode()+ if method == "GET" and "/generation?" in url:+ generation = parse_qs(urlsplit(url).query).get("id", [""])[0]+ if generation not in self.generations:+ return 404, {"content-type": "application/json"}, b'{"error": "not found"}'+ payload = {"data": {"id": generation, "total_cost": self.generations[generation]}}+ return 200, {"content-type": "application/json"}, json.dumps(payload).encode()if method == "GET" and url.rstrip("/").endswith("/models"):with self._lock:self.catalog_reads.append({k.lower(): v for k, v in (headers or {}).items()})@@ -386,7 +397,7 @@ class Network:self.vendors: list[Any] = []self._respx = respx.mock(assert_all_called=False, assert_all_mocked=True)self._responses = responses.RequestsMock(assert_all_requests_are_fired=False)- # Vendor SDKs generated from OpenAPI (Daytona) send through urllib3 directly.+ # SDKs that send through urllib3 directly, such as botocore.self._urllib3 = [mock.patch.object(manager, "urlopen", self._pool(manager.urlopen))for manager in (urllib3.PoolManager, urllib3.ProxyManager)diff --git a/tests/fakes/modal.py b/tests/fakes/modal.pyindex b9739938..bba78da8 100644--- a/tests/fakes/modal.py+++ b/tests/fakes/modal.py@@ -5,10 +5,13 @@ import hashlibimport itertoolsimport jsonimport math+import reimport threadingfrom collections.abc import Callablefrom contextlib import contextmanagerfrom dataclasses import dataclass, field+from datetime import datetime, timedelta+from decimal import Decimalfrom http.server import BaseHTTPRequestHandler, ThreadingHTTPServerfrom pathlib import Pathfrom types import SimpleNamespace@@ -16,7 +19,9 @@ from typing import Anyimport modalfrom asgiref.sync import sync_to_async-from modal.exception import NotFoundError+from django.utils import timezone+from modal.exception import AlreadyExistsError, NotFoundError+from modal.volume import FileEntry, FileEntryTypefrom modal_shared.decisions import DECISION_OBJECTIVES@@ -193,6 +198,99 @@ class _FakeCls:return _FakeInstance(self.cloud, self.app, self.cls)+WORKSPACE_VOLUMES = "overmind-ws-"+# Modal's sandbox price in the fake: what a sandbox costs for each second it runs.+SANDBOX_COST_PER_SECOND = Decimal("0.0001")+++@dataclass+class FakeProcess:+ code: int+ out: str+ err: str++ def __post_init__(self):+ self.stdout = SimpleNamespace(read=lambda: self.out)+ self.stderr = SimpleNamespace(read=lambda: self.err)+ self.stdin = SimpleNamespace(+ write=lambda _data: None, write_eof=lambda: None, drain=lambda: None+ )++ def wait(self) -> int:+ return self.code+++@dataclass+class FakeSandbox:+ """A Modal sandbox: its mounts, the files it holds and the commands it ran. A ``mv``+ into a mount lands in that Volume; every other command answers ``cloud.exec_answer``."""++ cloud: FakeModal+ name: str | None+ tags: dict[str, str]+ region: list[str] | None+ mounts: dict[str, str]+ object_id: str = field(default_factory=lambda: f"sb-fake-{next(_ids)}")+ created_at: datetime = field(default_factory=timezone.now)+ ended_at: datetime | None = None+ files: dict[str, bytes] = field(default_factory=dict)+ commands: list[tuple[str, ...]] = field(default_factory=list)++ def get_tags(self) -> dict[str, str]:+ return dict(self.tags)++ def poll(self) -> int | None:+ return None if self.ended_at is None else 0++ def terminate(self, *, wait: bool = False) -> None:+ self.ended_at = self.ended_at or timezone.now()++ def wait(self, raise_on_termination: bool = True) -> None:+ self.terminate()++ def wait_until_ready(self, *, timeout: int = 300) -> None:+ if set(self.region or ()) & self.cloud.full_regions:+ raise modal.exception.TimeoutError("not ready")++ def exec(self, *args, timeout=None, **_) -> FakeProcess:+ self.commands.append(args)+ command = args[-1]+ moved = re.search(r"mv (\S+) (\S+)", command)+ if moved:+ source, target = moved.groups()+ volume, path = self._mount(target.strip("'"))+ volume[path] = self.files.pop(source)+ return FakeProcess(*self.cloud.exec_answer)++ def _mount(self, path: str) -> tuple[dict[str, bytes], str]:+ for root, name in self.mounts.items():+ if path.startswith(root + "/"):+ return self.cloud.volumes[name], path[len(root) :]+ raise AssertionError(f"{path} is on no mount")++ @property+ def filesystem(self):+ def copy_from_local(local, remote):+ if self.cloud.copy_fails:+ raise modal.exception.ConnectionError("reset")+ self.files[remote] = Path(local).read_bytes()++ return SimpleNamespace(copy_from_local=copy_from_local, read_bytes=self.files.__getitem__)++ def _experimental_stats(self, *, since: datetime, until: datetime):+ end = min(until, self.ended_at or until)+ ran = max(timedelta(0), end - max(since, self.created_at))+ measured = self.object_id not in self.cloud.unmeasured+ cost = SANDBOX_COST_PER_SECOND * int(ran.total_seconds()) if measured and ran else None+ return SimpleNamespace(+ duration=ran,+ cost=cost,+ cost_by_resource={"CPU": cost} if cost else {},+ billed_cpu_core_seconds=ran.total_seconds() * 0.25,+ billed_memory_gib_seconds=ran.total_seconds(),+ )++@dataclassclass FakeModal:handlers: dict[tuple[str, str], tuple[Callable[..., Any], bool]] = field(default_factory=dict)@@ -203,8 +301,18 @@ class FakeModal:dictionaries: dict[tuple[str, str], dict[str, Any]] = field(default_factory=dict)app_logs: list[Any] = field(default_factory=list)worker_stats: dict[str, Any] | BaseException | None = None+ sandboxes: dict[str, FakeSandbox] = field(default_factory=dict)+ # Files of each workspace Volume, by path in the Volume.+ volumes: dict[str, dict[str, bytes]] = field(default_factory=dict)+ full_regions: set[str] = field(default_factory=set)+ unmeasured: set[str] = field(default_factory=set)+ exec_answer: tuple[int, str, str] = (0, "", "")+ copy_fails: bool = False_lock: threading.Lock = field(default_factory=threading.Lock)+ def running(self, name: str) -> list[FakeSandbox]:+ return [s for s in self.sandboxes.values() if s.name == name and s.ended_at is None]+def deploy(self, app: str, name: str, handler: Callable[..., Any], *, held: bool = False) -> None:@@ -256,7 +364,7 @@ class FakeModal:"lookup",_Method(lambda *args, **kwargs: SimpleNamespace(- logs=SimpleNamespace(fetch=_IteratorMethod(fetch_logs))+ app_id="ap-fake", logs=SimpleNamespace(fetch=_IteratorMethod(fetch_logs)))),)@@ -301,9 +409,18 @@ class FakeModal:return _FakeCls(cloud, app, cls)class Volume:+ objects = SimpleNamespace(+ list=lambda **_: [SimpleNamespace(name=name) for name in cloud.volumes],+ delete=lambda name, **_: cloud.volumes.pop(name, None),+ )+@staticmethod- def from_name(*args, **kwargs):- return Volume()+ def from_name(name="", *args, create_if_missing=False, **kwargs):+ if not name.startswith(WORKSPACE_VOLUMES):+ return Volume()+ if create_if_missing:+ cloud.volumes.setdefault(name, {})+ return WorkspaceVolume(name)@contextmanagerdef batch_upload(self, **kwargs):@@ -321,6 +438,65 @@ class FakeModal:def read_file(self):return _IteratorMethod(self._read_file)+ class WorkspaceVolume:+ def __init__(self, name):+ self.name = name++ def read_only(self):+ return self++ def hydrate(self):+ if self.name not in cloud.volumes:+ raise NotFoundError(self.name)+ return self++ def listdir(self, path, **_):+ folder = path.rstrip("/") + "/"+ return [+ FileEntry(path=key, type=FileEntryType.FILE, mtime=0, size=len(content))+ for key, content in cloud.volumes[self.name].items()+ if key.startswith(folder) and "/" not in key[len(folder) :]+ ]++ def read_file(self, path):+ yield cloud.volumes[self.name][path]++ def remove_file(self, path, recursive=False):+ files = cloud.volumes[self.name]+ for key in [k for k in files if k == path or k.startswith(path + "/")]:+ del files[key]++ class Sandbox:+ @staticmethod+ def create(*args, name=None, tags=None, region=None, volumes=None, **_):+ with cloud._lock:+ if name and cloud.running(name):+ raise AlreadyExistsError(name)+ mounts = {root: volume.name for root, volume in (volumes or {}).items()}+ sandbox = FakeSandbox(cloud, name, tags or {}, region, mounts)+ cloud.sandboxes[sandbox.object_id] = sandbox+ return sandbox++ @staticmethod+ def from_name(app_name, name, **_):+ found = cloud.running(name)+ if not found:+ raise NotFoundError(name)+ return found[0]++ @staticmethod+ def from_id(sandbox_id, **_):+ return cloud.sandboxes[sandbox_id]++ @staticmethod+ def list(*, app_id=None, tags=None, **_):+ return [+ s+ for s in cloud.sandboxes.values()+ if s.ended_at is None and (tags or {}).items() <= s.tags.items()+ ]++ monkeypatch.setattr(modal, "Sandbox", Sandbox)monkeypatch.setattr(modal, "Volume", Volume)monkeypatch.setattr(modal, "Function", Function)monkeypatch.setattr(modal, "Cls", Cls)diff --git a/tests/settings.py b/tests/settings.pyindex c21cca36..1a10533b 100644--- a/tests/settings.py+++ b/tests/settings.py@@ -25,6 +25,10 @@ os.environ["AWS_S3_CUSTOM_DOMAIN"] = ""from overbae.settings import * # noqa: E402, F403+# The suite runs workspaces on the native sandbox server it starts; the Modal provider runs+# against tests/fakes here and against Modal itself in the Workspaces workflow.+WORKSPACE_PROVIDER = "native"+DATABASES = {"default": {"ENGINE": "django.db.backends.postgresql",diff --git a/tests/test_assistant_turn.py b/tests/test_assistant_turn.pyindex 4f2cfd75..828af8a7 100644--- a/tests/test_assistant_turn.py+++ b/tests/test_assistant_turn.py@@ -1,6 +1,7 @@import jsonimport timefrom datetime import timedelta+from decimal import Decimalimport pytestfrom conftest import frozen_dataset@@ -12,6 +13,7 @@ from overbae.core.llms import stream_llm_toolsfrom overbae.models import (AssistantInput,AssistantThread,+ BillingService,BillingTelemetry,Dataset,DatasetPipeline,@@ -20,6 +22,7 @@ from overbae.models import (from overbae.services import workspacesfrom overbae.services.assistant import log, threads, tools, turnfrom overbae.services.datasets import land, lifecycle, list_activity+from overbae.services.workspaces.modal_sandbox import ModalProviderfrom overbae.tasks import assistant as assistant_taskspytestmark = [pytest.mark.django_db, pytest.mark.covers("assistant-turn")]@@ -87,13 +90,72 @@ def test_a_turn_runs_code_on_the_datasets_version_and_charges_each_model_call((counted,) = results(thread)assert counted["ok"] and counted["content"]["output"] == "2\n", countedassert thread.state == AssistantThread.State.IDLE- charged = BillingTelemetry.objects.filter(idempotency_key__startswith=f"assistant:{thread.pk}")+ charged = BillingTelemetry.objects.filter(service=BillingService.ASSISTANT)assert charged.count() == 2 and {row.user_id for row in charged} == {user.pk}+ assert all(row.idempotency_key.startswith("openrouter:") for row in charged)# The model read the dataset's facts with the message, once.first = fake_llm.streamed()[0].body["messages"][-1]["content"]assert f"data/{source.pk}.parquet" in first[email protected]("ledger")+def test_a_members_turn_is_charged_to_the_projects_owner(fake_llm, user, thread):+ member = make_user()+ ProjectMembership.objects.create(user=member, project=thread.project)+ fake_llm.stream_rounds([([], "Hello.")])+ say(thread, member, "Hi.")+ (charge,) = BillingTelemetry.objects.filter(service=BillingService.ASSISTANT)+ assert charge.user_id == user.pk == thread.project.owner_id++[email protected]("ledger")+def test_a_call_the_provider_did_not_price_is_charged_at_its_generation_cost(+ fake_llm, user, thread, monkeypatch, django_capture_on_commit_callbacks+):+ later = []+ monkeypatch.setattr(assistant_tasks.charge_generation, "delay", lambda *a: later.append(a))+ fake_llm.stream_rounds([([], "Hello.")], cost=None)+ with django_capture_on_commit_callbacks(execute=True):+ say(thread, user, "Hi.")+ assert not BillingTelemetry.objects.filter(service=BillingService.ASSISTANT).exists()+ ((payer, project, generation),) = later+ with pytest.raises(assistant_tasks.NotPricedError):+ assistant_tasks.charge_generation(payer, project, generation)+ fake_llm.generations[generation] = 0.02+ assistant_tasks.charge_generation(payer, project, generation)+ assistant_tasks.charge_generation(payer, project, generation)+ (charge,) = BillingTelemetry.objects.filter(service=BillingService.ASSISTANT)+ assert charge.amount == Decimal("-0.02") and str(charge.user_id) == payer == str(user.pk)++[email protected]("ledger")+def test_a_generation_of_a_deleted_project_is_still_charged_to_its_owner(fake_llm, user):+ project = make_project(member=user)+ project_id = str(project.pk)+ project.delete()+ fake_llm.generations["gen-gone"] = 0.03+ assistant_tasks.charge_generation(str(user.pk), project_id, "gen-gone")+ (charge,) = BillingTelemetry.objects.filter(service=BillingService.ASSISTANT)+ assert charge.amount == Decimal("-0.03") and charge.project_id is None and charge.user == user+++# The workspace starts in a thread of its own, on its own connection.[email protected]_db(transaction=True)[email protected]("workspaces")+def test_a_turn_starts_the_modal_workspace_while_the_model_replies(fake_llm, fake_modal, settings):+ settings.WORKSPACE_PROVIDER, settings.MODAL_WORKSPACE_REGION = "modal", ""+ ModalProvider._sandboxes.clear()+ user = make_user()+ thread = threads.open_thread(frozen_dataset(make_project(member=user), user=user))+ fake_llm.stream_rounds([([], "Hello.")])+ say(thread, user, "Hi.")+ deadline = time.monotonic() + 5+ while not fake_modal.sandboxes and time.monotonic() < deadline:+ time.sleep(0.05)+ (sandbox,) = fake_modal.sandboxes.values()+ assert sandbox.name == f"overmind-ws-{thread.project_id.hex}"++def test_the_summary_of_a_call_is_for_the_reader_and_no_tool_receives_it(fake_llm, user, thread):query = {"summary": "Counting", "dataset": str(thread.dataset_id), "sql": "select 1 as one"}fake_llm.stream_rounds([([tool_call("query_dataset", query)], ""), ([], "One.")])diff --git a/tests/test_guest_account.py b/tests/test_guest_account.pyindex 24258c39..71c2ec35 100644--- a/tests/test_guest_account.py+++ b/tests/test_guest_account.py@@ -107,6 +107,8 @@ def test_claim_moves_workspace_to_clerk_account(clerk):assert body["user"]["is_guest"] is Falseassert ProjectMembership.objects.filter(user=owner, project=project).exists()assert not ProjectMembership.objects.filter(user=guest).exists()+ project.refresh_from_db()+ assert project.owner == ownerguest.refresh_from_db()assert guest.is_active is Falseassert guest.is_guest is Truediff --git a/tests/test_project_owner_migration.py b/tests/test_project_owner_migration.pynew file mode 100644index 00000000..0563e448--- /dev/null+++ b/tests/test_project_owner_migration.py@@ -0,0 +1,28 @@+import pytest+from django.db.migrations.executor import MigrationExecutor+from migration_replay import scratch_database++pytestmark = pytest.mark.covers("migrations")+++def test_each_project_is_owned_by_its_first_member(django_db_blocker):+ before = [("overbae", "0068_credits_only")]+ after = [("overbae", "0069_project_owner_and_assistant_billing")]+ with scratch_database(django_db_blocker) as database:+ executor = MigrationExecutor(database)+ executor.migrate(before)+ state = executor.loader.project_state(before).apps+ users = state.get_model("overbae", "User").objects+ projects = state.get_model("overbae", "Project").objects+ memberships = state.get_model("overbae", "ProjectMembership").objects+ first, second = (users.create(email=f"{n}@example.com") for n in ("first", "second"))+ shared = projects.create(name="Shared", slug="shared")+ empty = projects.create(name="Empty", slug="empty")+ memberships.create(user=first, project=shared)+ memberships.create(user=second, project=shared)+ executor = MigrationExecutor(database)+ executor.migrate(after)+ new = executor.loader.project_state(after).apps.get_model("overbae", "Project")++ assert new.objects.get(pk=shared.pk).owner_id == first.pk+ assert new.objects.get(pk=empty.pk).owner_id is Nonediff --git a/tests/test_projects.py b/tests/test_projects.pyindex 2f46783b..9173ad67 100644--- a/tests/test_projects.py+++ b/tests/test_projects.py@@ -48,6 +48,7 @@ def test_create_project_creates_owner_membership():assert r.status_code == 201pid = r.data["id"]assert ProjectMembership.objects.filter(user=u, project_id=pid).exists()+ assert r.data["owner"] == u.pk and Project.objects.get(pk=pid).owner == udef test_account_scoped_api_key_can_create_project():@@ -200,3 +201,18 @@ def test_partial_update_project():)assert r.status_code == 200assert r.data["name"] == "Updated"++[email protected]("ledger")+def test_a_member_cannot_remove_the_projects_owner():+ owner = make_user("[email protected]")+ peer = make_user("[email protected]")+ project = Project.objects.create(name="Paid", slug=f"pd-{uuid.uuid4().hex[:6]}", owner=owner)+ held = ProjectMembership.objects.create(user=owner, project=project)+ ProjectMembership.objects.create(user=peer, project=project)++ r = auth_client(peer).delete(+ reverse("project-membership-detail", kwargs={"project_id": project.id, "id": held.id}),+ )+ assert r.status_code == 403+ assert ProjectMembership.objects.filter(id=held.id).exists()diff --git a/tests/test_workspaces.py b/tests/test_workspaces.pyindex b37b5b23..ad4b61fa 100644--- a/tests/test_workspaces.py+++ b/tests/test_workspaces.py@@ -1,15 +1,23 @@import io-import jsonimport osimport sys+import threadingimport uuid+from datetime import timedelta+from decimal import Decimalimport pytest+from conftest import frozen_dataset+from django.utils import timezone+from factories import make_project, make_userfrom starlette.testclient import TestClient+from overbae.models import AssistantThread, BillingService, BillingTelemetry, WorkspaceSandbox+from overbae.services.assistant import threadsfrom overbae.services.workspaces import WorkspaceUnavailableError, conformance-from overbae.services.workspaces.daytona import DaytonaProvider, snapshot_name+from overbae.services.workspaces.modal_sandbox import ModalProviderfrom overbae.services.workspaces.native import NativeProvider+from overbae.tasks import assistant as assistant_tasksfrom sandbox import serverpytestmark = pytest.mark.covers("workspaces")@@ -72,132 +80,181 @@ def test_a_sandbox_without_workspaces_answers_reads_without_creating_them(tmp_paassert client.delete("/v1/workspaces/p1").status_code == 204-JSON = {"content-type": "application/json"}---def sandbox(project, state="started", recoverable=False):- return {- "id": f"s-{project}",- "organizationId": "o1",- "name": f"s-{project}",- "user": "daytona",- "env": {},- "labels": {"overmind": "workspace", "project": project},- "public": False,- "networkBlockAll": True,- "kvm": False,- "target": "eu",- "cpu": 2,- "gpu": 0,- "memory": 4,- "disk": 5,- "state": state,- "recoverable": recoverable,- "snapshot": snapshot_name(),- "toolboxProxyUrl": "https://proxy.app.daytona.io/toolbox",- }---class FakeDaytona:- """Daytona's control plane with the given sandboxes, and the files in their toolbox."""-- def __init__(self, scripted, *boxes):- self.boxes = {box["id"]: box for box in boxes}- self.files: set[str] = set()- self.commands: list[str] = []- self.exit_code = 0- self.upload_fails = False- self.control = scripted("https://app.daytona.io").then(self._control)- scripted("https://proxy.app.daytona.io").then(self._toolbox)-- def _control(self, call):- parts = call.path.rsplit("/", 2)- if parts[-1] == "recover":- self.boxes[parts[-2]]["state"] = "started"- box = self.boxes.get(parts[-1]) or self.boxes.get(parts[-2])- if box is not None:- if call.method == "DELETE":- box["state"] = "destroying"- return 200, JSON, json.dumps(box).encode()- items = list(self.boxes.values())- page = {"items": items, "total": len(items), "page": 1, "totalPages": 1}- return 200, JSON, json.dumps(page).encode()-- def _toolbox(self, call):- action = call.path.split("/toolbox/", 1)[1].split("/", 1)[1]- if action == "files/info":- if call.params["path"] in self.files:- info = {"name": "f", "isDir": False, "size": 1, "mode": "-r--r--r--"}- info |= {"modTime": "", "permissions": "0444", "owner": "d", "group": "d"}- return 200, JSON, json.dumps(info).encode()- return 404, JSON, b'{"message": "not found", "statusCode": 404}'- if action == "files/bulk-upload":- # The bytes that arrived are on disk under the name sent, whole or not.- target = call.body.split(b"\r\n\r\n", 1)[1].split(b"\r\n", 1)[0].decode()- self.files.add(target)- return (500, JSON, b'{"message": "reset"}') if self.upload_fails else (200, JSON, b"{}")- if action == "files/move":- self.files.discard(call.params["source"])- self.files.add(call.params["destination"])- if action == "process/execute":- self.commands.append(call.json["command"])- return 200, JSON, json.dumps({"exitCode": self.exit_code, "result": "denied"}).encode()- return 200, JSON, b"{}"--@pytest.fixture-def daytona(db, settings):- settings.DAYTONA_API_KEY = "test"- return DaytonaProvider()+def modal_workspaces(db, settings, fake_modal):+ settings.MODAL_WORKSPACE_REGION = "eu"+ ModalProvider._sandboxes.clear()+ yield ModalProvider()+ ModalProvider._sandboxes.clear()-def test_a_daytona_read_or_forget_creates_no_workspace(daytona, scripted):- fake = FakeDaytona(scripted)- project = uuid.uuid4().hex- assert not daytona.has_data(project, "a.parquet")- daytona.forget(project, ["a.parquet"], ["c1"])- with pytest.raises(FileNotFoundError):- daytona.read_file(project, "c1", "chart.png")- assert {call.method for call in fake.control.calls} == {"GET"}+def started(provider, fake_modal, project):+ """The project's sandbox, started by copying a version in."""+ provider.put_data(project, f"{uuid.uuid4().hex}.parquet", io.BytesIO(b"rows"))+ (sandbox,) = fake_modal.running(f"overmind-ws-{uuid.UUID(project).hex}")+ return sandbox-def test_a_daytona_workspace_that_outlasts_its_deletion_is_reported(daytona, scripted, slept):- project = uuid.uuid4().hex- fake = FakeDaytona(scripted, sandbox(project))- fake.control.steps[0] = lambda call: (- (200, JSON, json.dumps(sandbox(project)).encode())- if call.method == "DELETE"- else fake._control(call)- )+def test_a_read_forget_or_stop_creates_no_modal_workspace(modal_workspaces, fake_modal):+ project = str(uuid.uuid4())+ assert not modal_workspaces.has_data(project, "a.parquet")+ modal_workspaces.forget(project, ["a.parquet"], ["c1"])+ modal_workspaces.stop(project, "c1")+ with pytest.raises(FileNotFoundError):+ modal_workspaces.read_file(project, "c1", "chart.png")+ assert fake_modal.sandboxes == {} and fake_modal.volumes == {}+++# The workers' threads hold their own connections: their rows commit.[email protected]_db(transaction=True)+def test_workers_that_start_a_project_together_share_one_modal_sandbox(+ modal_workspaces, fake_modal+):+ project = str(uuid.uuid4())+ workers = [+ threading.Thread(+ target=ModalProvider().put_data,+ args=(project, f"{n}.parquet", io.BytesIO(b"rows")),+ )+ for n in range(4)+ ]+ for worker in workers:+ worker.start()+ for worker in workers:+ worker.join()+ (sandbox,) = fake_modal.running(f"overmind-ws-{uuid.UUID(project).hex}")+ assert all(modal_workspaces.has_data(project, f"{n}.parquet") for n in range(4))+ assert WorkspaceSandbox.objects.get().sandbox_id == sandbox.object_id+++def test_a_modal_sandbox_starts_anywhere_when_the_region_has_no_room(modal_workspaces, fake_modal):+ fake_modal.full_regions.add("eu")+ project = str(uuid.uuid4())+ used = started(modal_workspaces, fake_modal, project)+ (tried,) = [s for s in fake_modal.sandboxes.values() if s is not used]+ assert tried.region == ["eu"] and tried.ended_at is not None and used.region is None+ assert WorkspaceSandbox.objects.get().sandbox_id == used.object_id+++def test_a_modal_sandbox_of_an_earlier_release_is_replaced_with_its_files(+ modal_workspaces, fake_modal+):+ project = str(uuid.uuid4())+ old = started(modal_workspaces, fake_modal, project)+ old.tags["image"] = "earlier"+ ModalProvider._sandboxes.clear()+ new = started(modal_workspaces, fake_modal, project)+ assert new is not old and old.ended_at is not None+ assert new.mounts == old.mounts+++def test_a_modal_copy_that_breaks_off_is_not_taken_as_copied(modal_workspaces, fake_modal):+ project = str(uuid.uuid4())+ fake_modal.copy_fails = Truewith pytest.raises(WorkspaceUnavailableError):- daytona.remove(project)- assert any(call.method == "DELETE" for call in fake.control.calls)+ modal_workspaces.put_data(project, "a.parquet", io.BytesIO(b"rows"))+ assert not modal_workspaces.has_data(project, "a.parquet")+ fake_modal.copy_fails = False+ modal_workspaces.put_data(project, "a.parquet", io.BytesIO(b"rows"))+ assert modal_workspaces.has_data(project, "a.parquet")-def test_a_daytona_copy_that_breaks_off_is_not_taken_as_copied(daytona, scripted):- project = uuid.uuid4().hex- fake = FakeDaytona(scripted, sandbox(project))- fake.upload_fails = True+def test_a_modal_workspace_that_outlasts_its_removal_is_reported(modal_workspaces, fake_modal):+ project = str(uuid.uuid4())+ sandbox = started(modal_workspaces, fake_modal, project)+ sandbox.terminate = lambda **_: Nonewith pytest.raises(WorkspaceUnavailableError):- daytona.put_data(project, "a.parquet", io.BytesIO(b"rows"))- assert not daytona.has_data(project, "a.parquet")- fake.upload_fails = False- daytona.put_data(project, "a.parquet", io.BytesIO(b"rows"))- assert daytona.has_data(project, "a.parquet")+ modal_workspaces.remove(project)+ del sandbox.terminate+ modal_workspaces.remove(project)+ assert fake_modal.volumes == {} and modal_workspaces.projects() == []-def test_a_daytona_forget_that_deletes_nothing_is_reported(daytona, scripted):- project = uuid.uuid4().hex- fake = FakeDaytona(scripted, sandbox(project))- fake.exit_code = 1+def test_a_modal_sandbox_that_cannot_be_prepared_serves_no_cell(modal_workspaces, fake_modal):+ project = str(uuid.uuid4())+ fake_modal.exec_answer = (1, "", "denied")with pytest.raises(WorkspaceUnavailableError):- daytona.forget(project, ["a.parquet"], [])---def test_a_daytona_sandbox_that_can_recover_keeps_its_files(daytona, scripted):- project = uuid.uuid4().hex- fake = FakeDaytona(scripted, sandbox(project, "error", recoverable=True))- assert not daytona.has_data(project, "a.parquet")- methods = {(call.method, call.path.rsplit("/", 1)[-1]) for call in fake.control.calls}- assert ("POST", "recover") in methods- assert not any(method == "DELETE" for method, _ in methods)+ modal_workspaces.put_data(project, "a.parquet", io.BytesIO(b"rows"))+ (sandbox,) = fake_modal.sandboxes.values()+ assert sandbox.ended_at is not None+ assert WorkspaceSandbox.objects.get().sandbox_id == sandbox.object_id++[email protected]("ledger")+def test_a_window_another_run_charged_meanwhile_is_not_charged_again(modal_workspaces, fake_modal):+ owner = make_user()+ sandbox = started(modal_workspaces, fake_modal, str(make_project(member=owner).pk))+ start = WorkspaceSandbox.objects.get().billed_until - timedelta(hours=1)+ sandbox.created_at = start+ WorkspaceSandbox.objects.update(billed_until=start)+ measure = sandbox._experimental_stats++ def measured_while_another_run_charges(*, since, until):+ WorkspaceSandbox.objects.update(billed_until=until)+ return measure(since=since, until=until)++ sandbox._experimental_stats = measured_while_another_run_charges+ assert modal_workspaces.bill() == 0+ assert not BillingTelemetry.objects.filter(service=BillingService.WORKSPACE).exists()++[email protected]("ledger")+def test_a_modal_sandbox_is_charged_to_its_owner_once_for_each_window(modal_workspaces, fake_modal):+ owner = make_user()+ project = make_project(member=owner)+ sandbox = started(modal_workspaces, fake_modal, str(project.pk))+ start = WorkspaceSandbox.objects.get().billed_until - timedelta(hours=1)+ sandbox.created_at = start+ WorkspaceSandbox.objects.update(billed_until=start)++ fake_modal.unmeasured.add(sandbox.object_id)+ assert modal_workspaces.bill() == 0+ fake_modal.unmeasured.clear()+ assert modal_workspaces.bill() == 1+ assert modal_workspaces.bill() == 0+ (charge,) = BillingTelemetry.objects.filter(service=BillingService.WORKSPACE)+ seconds = int((WorkspaceSandbox.objects.get().billed_until - start).total_seconds())+ assert charge.user == owner and charge.project_id == project.pk+ assert -charge.amount == Decimal("0.0001") * seconds++ # It ended 20 minutes ago; usage arrives 10 minutes late.+ sandbox.terminate()+ sandbox.ended_at -= timedelta(minutes=20)+ WorkspaceSandbox.objects.update(billed_until=sandbox.ended_at - timedelta(minutes=30))+ assert modal_workspaces.bill() == 1+ assert not WorkspaceSandbox.objects.get().finished+ assert modal_workspaces.bill() == 0+ assert WorkspaceSandbox.objects.get().finished++[email protected]("ledger")+def test_a_modal_sandbox_of_no_project_is_never_charged(modal_workspaces, fake_modal):+ sandbox = started(modal_workspaces, fake_modal, str(uuid.uuid4()))+ sandbox.created_at -= timedelta(hours=1)+ sandbox.terminate()+ sandbox.ended_at -= timedelta(minutes=30)+ WorkspaceSandbox.objects.update(billed_until=sandbox.created_at)+ modal_workspaces.bill()+ modal_workspaces.bill()+ assert WorkspaceSandbox.objects.get().finished and not BillingTelemetry.objects.exists()+++def test_a_workspace_its_project_has_not_used_for_a_week_is_removed(db, provider):+ user = make_user()+ recent, old = (+ threads.open_thread(frozen_dataset(make_project(member=user), user=user)) for _ in range(2)+ )+ AssistantThread.objects.filter(pk=old.pk).update(updated_at=timezone.now() - timedelta(days=8))+ unused = str(uuid.uuid4())+ held = [str(recent.project_id), str(old.project_id), unused]+ try:+ for project in held:+ provider.put_data(project, "a.parquet", io.BytesIO(b"rows"))+ assert set(held) <= set(provider.projects())+ assistant_tasks.sweep_idle_workspaces()+ kept = set(provider.projects())+ assert str(recent.project_id) in kept+ assert str(old.project_id) not in kept and unused not in kept+ finally:+ for project in held:+ provider.remove(project)diff --git a/uv.lock b/uv.lockindex 3daeae86..eb8f5166 100644--- a/uv.lock+++ b/uv.lock@@ -17,15 +17,6 @@ resolution-markers = [constraints = [{ name = "aiohttp", specifier = ">=3.14.3" }]overrides = [{ name = "cryptography", specifier = ">=50.0.0" }]-[[package]]-name = "aiofiles"-version = "25.1.0"-source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/41/c3/534eac40372d8ee36ef40df62ec129bee4fdb5ad9706e58a29be53b2c970/aiofiles-25.1.0.tar.gz", hash = "sha256:a8d728f0a29de45dc521f18f07297428d56992a742f0cd2701ba86e44d23d5b2", size = 46354, upload-time = "2025-10-09T20:51:04.358Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/bc/8a/340a1555ae33d7354dbca4faa54948d76d89a27ceef032c8c3bc661d003e/aiofiles-25.1.0-py3-none-any.whl", hash = "sha256:abe311e527c862958650f9438e859c1fa7568a141b22abcd015e120e86a85695", size = 14668, upload-time = "2025-10-09T20:51:03.174Z" },-]-[[package]]name = "aiohappyeyeballs"version = "2.6.2"@@ -158,18 +149,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/68/30/173960c42b05a6c59f7558e4b12a4b0d9ba376cf6aa9bde7f9e08a30ca8d/aiohttp-3.14.5-py3-none-any.whl", hash = "sha256:efc21a454892828368b11c2c780de0ff8bc991f73f6b99c6b66e56205470929b", size = 279517, upload-time = "2026-10-11T01:05:08.523Z" },]-[[package]]-name = "aiohttp-retry"-version = "2.9.1"-source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "aiohttp" },-]-sdist = { url = "https://files.pythonhosted.org/packages/9d/61/ebda4d8e3d8cfa1fd3db0fb428db2dd7461d5742cea35178277ad180b033/aiohttp_retry-2.9.1.tar.gz", hash = "sha256:8eb75e904ed4ee5c2ec242fefe85bf04240f685391c4879d8f541d6028ff01f1", size = 13608, upload-time = "2024-11-06T10:44:54.574Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/1a/99/84ba7273339d0f3dfa57901b846489d2e5c2cd731470167757f1935fffbd/aiohttp_retry-2.9.1-py3-none-any.whl", hash = "sha256:66d2759d1921838256a05a3f80ad7e724936f083e35be5abb5e16eed6be6dc54", size = 9981, upload-time = "2024-11-06T10:44:52.917Z" },-]-[[package]]name = "aiosignal"version = "1.4.0"@@ -262,7 +241,6 @@ dependencies = [{ name = "clerk-backend-api" },{ name = "cryptography" },{ name = "datasketch" },- { name = "daytona" },{ name = "django" },{ name = "django-celery-beat" },{ name = "django-cors-headers" },@@ -361,7 +339,6 @@ requires-dist = [{ name = "clerk-backend-api", specifier = ">=5.0.6" },{ name = "cryptography", specifier = ">=50.0.0" },{ name = "datasketch", specifier = ">=2.0.0" },- { name = "daytona", specifier = "==0.231.1" },{ name = "django", specifier = ">=6.0.8" },{ name = "django-celery-beat", specifier = ">=2.7.0" },{ name = "django-cors-headers", specifier = ">=4.9.0" },@@ -465,15 +442,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/88/c6/92fcd42f1ba33e1184263f25bfabf3d27c383410470f169e4b8163bf9c17/beautifulsoup4-4.15.0-py3-none-any.whl", hash = "sha256:d6f88de62e1d4e38ecb1077eb9724cd0eff29d2a08ca16a401e9b9e93f117cf9", size = 109924, upload-time = "2026-06-07T16:44:21.566Z" },]-[[package]]-name = "bidict"-version = "0.24.1"-source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/a8/f2/8d2dd8276ca05e1f5157b6a0d34efb2f585f47a0fbed61e8aad04b221f0b/bidict-0.24.1.tar.gz", hash = "sha256:4dca6c17f0b01700e9f24359daa5ebabf7be022d99f4cb2a257b6af2a5076c88", size = 30818, upload-time = "2026-08-25T23:45:52.214Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/97/53/2a3c7d562271ec6b6e38e7216b3104899f8aa4180c0713cb8aaf69e29cd5/bidict-0.24.1-py3-none-any.whl", hash = "sha256:fd3eaa737917d8a14f4baa391670c433c4e3f6f5fd2cd99d4bf436437f432364", size = 36175, upload-time = "2026-08-25T23:45:51.096Z" },-]-[[package]]name = "billiard"version = "4.2.4"@@ -966,134 +934,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/54/df/9e79bf1fb2f660507dbd00d24730d107595a2f599f2524a96344149c95f1/datasketch-2.0.0-py3-none-any.whl", hash = "sha256:aea5ffafcce776e03d085740e78b874e778d779b07ee11ca636ca51b3fef09ed", size = 107247, upload-time = "2026-07-05T06:36:29.222Z" },]-[[package]]-name = "daytona"-version = "0.231.1"-source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "aiofiles" },- { name = "aiohttp" },- { name = "daytona-analytics-api-client" },- { name = "daytona-analytics-api-client-async" },- { name = "daytona-api-client" },- { name = "daytona-api-client-async" },- { name = "daytona-toolbox-api-client" },- { name = "daytona-toolbox-api-client-async" },- { name = "deprecated" },- { name = "httpx" },- { name = "httpx-ws" },- { name = "obstore" },- { name = "opentelemetry-api" },- { name = "opentelemetry-exporter-otlp-proto-http" },- { name = "opentelemetry-instrumentation-aiohttp-client" },- { name = "opentelemetry-sdk" },- { name = "pydantic" },- { name = "python-dotenv" },- { name = "python-multipart" },- { name = "python-socketio", extra = ["asyncio-client", "client"] },- { name = "toml" },- { name = "typing-extensions" },- { name = "urllib3" },- { name = "wsproto" },-]-sdist = { url = "https://files.pythonhosted.org/packages/42/e4/39cb676c3bf24c6b5d00bf16eb3295d62bd9686c9c48fd6d5b38ee6a53ea/daytona-0.231.1.tar.gz", hash = "sha256:eb1ad6236f942d487319c77b137c6739d9a438b04adcb41b8dfeec1b309aac52", size = 208490, upload-time = "2026-11-09T15:45:28.135Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/0d/eb/ddb04f68b6463cbff435e6a09d8fb68ea5f077832c75317cfcbac3896c3f/daytona-0.231.1-py3-none-any.whl", hash = "sha256:14504119e464b92c113c5112138c517cc752c7d570ebf0cf25c16fbb73778adc", size = 246353, upload-time = "2026-11-09T15:45:29.834Z" },-]--[[package]]-name = "daytona-analytics-api-client"-version = "0.231.1"-source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "pydantic" },- { name = "python-dateutil" },- { name = "typing-extensions" },- { name = "urllib3" },-]-sdist = { url = "https://files.pythonhosted.org/packages/89/ca/ff49c537a0dbad4b7094335f11c9a89c6d3c72e9554cb27e4f37c8a28e91/daytona_analytics_api_client-0.231.1.tar.gz", hash = "sha256:824cf70d4dd2516e9bfc9757dc140f3865f06b313e9833358971e26804f34ddf", size = 30169, upload-time = "2026-11-09T15:44:22.379Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/64/94/ae2ec6681e3a4fdea854aa334c5e04a408996f5581743d651619ac6bd785/daytona_analytics_api_client-0.231.1-py3-none-any.whl", hash = "sha256:394370c88ca9a9318e2f084f2be3698003498b926debe09706dbf9e9fa17e25b", size = 45072, upload-time = "2026-11-09T15:44:23.817Z" },-]--[[package]]-name = "daytona-analytics-api-client-async"-version = "0.231.1"-source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "aiohttp" },- { name = "aiohttp-retry" },- { name = "pydantic" },- { name = "python-dateutil" },- { name = "typing-extensions" },-]-sdist = { url = "https://files.pythonhosted.org/packages/32/88/0b01d6b89e28362df2a6a1ae01c681746a2e4309ddad35286b763171237d/daytona_analytics_api_client_async-0.231.1.tar.gz", hash = "sha256:768cdeed6e7dcecfb92c6d1e4cb88e0a685e582dcce4a7e48cc8c5c50ccb411d", size = 30241, upload-time = "2026-11-09T15:44:26.968Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/86/15/524d0013bdd9496d2dc6c7c34147e95e5274010ef13d3609afc448ffc825/daytona_analytics_api_client_async-0.231.1-py3-none-any.whl", hash = "sha256:f651edf03f358fae45503b1eb62a80cd293a74ddb836122d9802aa8695307bbb", size = 45337, upload-time = "2026-11-09T15:44:27.802Z" },-]--[[package]]-name = "daytona-api-client"-version = "0.231.1"-source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "pydantic" },- { name = "python-dateutil" },- { name = "typing-extensions" },- { name = "urllib3" },-]-sdist = { url = "https://files.pythonhosted.org/packages/02/07/4fa7a8aa720393352bf996433d09cedb8e6a86ad8148450d7af59cf4260f/daytona_api_client-0.231.1.tar.gz", hash = "sha256:78dff592f891be08c3ee045a1a64c0d076eeff05f2afa5e3545525394380fa0b", size = 136018, upload-time = "2026-11-09T15:44:21.477Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/0d/ba/81491ee2891a757e98904ae345d0530a2cc98d35f95b5621860cbcb3a6f4/daytona_api_client-0.231.1-py3-none-any.whl", hash = "sha256:872f20d98c6186e2e1affbe18ff24e964aba4282cfbc1ef5d5e79930a5fae963", size = 349577, upload-time = "2026-11-09T15:44:22.518Z" },-]--[[package]]-name = "daytona-api-client-async"-version = "0.231.1"-source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "aiohttp" },- { name = "aiohttp-retry" },- { name = "pydantic" },- { name = "python-dateutil" },- { name = "typing-extensions" },-]-sdist = { url = "https://files.pythonhosted.org/packages/4e/3a/0f99c9141f6d7999ccd3068eea20de4a43e0b9f03b2a283a83457ba651f2/daytona_api_client_async-0.231.1.tar.gz", hash = "sha256:9d33c97ac9821c10e3687c5efa48b1662da4ac87bbbb986dc86f696c8a471cc7", size = 136383, upload-time = "2026-11-09T15:44:25.731Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/cc/ba/2f01b69aa8544bf2247e5abff11444d3632c8fc50f695dca2e1daa9d9315/daytona_api_client_async-0.231.1-py3-none-any.whl", hash = "sha256:fde86d8fa01f101dbb8de840624233ab43d22ea15230aed68f891c7dd5d8bde9", size = 352351, upload-time = "2026-11-09T15:44:27.302Z" },-]--[[package]]-name = "daytona-toolbox-api-client"-version = "0.231.1"-source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "pydantic" },- { name = "python-dateutil" },- { name = "typing-extensions" },- { name = "urllib3" },-]-sdist = { url = "https://files.pythonhosted.org/packages/f0/f1/da88c26d43dcce193c22a96e4cf04a96d14acdc86ac72e9168345c45dbc9/daytona_toolbox_api_client-0.231.1.tar.gz", hash = "sha256:9465dc273f164d74b804af8e67222fc5f5a483d21edfc7fe6962dd61cf742eb3", size = 90482, upload-time = "2026-11-09T15:44:21.457Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/a3/dc/2d5d807bb38292e791da3f816aa70c63270ae2fd941596718cb9ccdefffe/daytona_toolbox_api_client-0.231.1-py3-none-any.whl", hash = "sha256:ae95b0e0613044d1bed91b2c08619ae577effd055b1a52349629c54ebc8fef63", size = 263382, upload-time = "2026-11-09T15:44:23.222Z" },-]--[[package]]-name = "daytona-toolbox-api-client-async"-version = "0.231.1"-source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "aiohttp" },- { name = "aiohttp-retry" },- { name = "pydantic" },- { name = "python-dateutil" },- { name = "typing-extensions" },-]-sdist = { url = "https://files.pythonhosted.org/packages/44/d8/fab0b941ad8e83aa54b9313d4c345795859114fb35b2d7d20a2bcdf7cd80/daytona_toolbox_api_client_async-0.231.1.tar.gz", hash = "sha256:a4c7ed12bb216e931011b3215db5760c243a36a27ad14c5603352a6019da968a", size = 84188, upload-time = "2026-11-09T15:44:26.367Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/cb/40/25a8d69bf0d0224d21a69ceb45a745da67dfbecad85ce966086331e2a523/daytona_toolbox_api_client_async-0.231.1-py3-none-any.whl", hash = "sha256:e854ba948741845a7fe9f66ef4ddecff28ae763acb8c8a2e3dd185e8098c1032", size = 261956, upload-time = "2026-11-09T15:44:28.557Z" },-]-[[package]]name = "defusedxml"version = "0.7.1"@@ -1103,18 +943,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/07/6c/aa3f2f849e01cb6a001cd8554a88d4c77c5c1a31c95bdf1cf9301e6d9ef4/defusedxml-0.7.1-py2.py3-none-any.whl", hash = "sha256:a352e7e428770286cc899e2542b6cdaedb2b4953ff269a210103ec58f6198a61", size = 25604, upload-time = "2021-03-08T10:59:24.45Z" },]-[[package]]-name = "deprecated"-version = "1.3.1"-source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "wrapt" },-]-sdist = { url = "https://files.pythonhosted.org/packages/49/85/12f0a49a7c4ffb70572b6c2ef13c90c88fd190debda93b23f026b25f9634/deprecated-1.3.1.tar.gz", hash = "sha256:b1b50e0ff0c1fddaa5708a2c6b0a6588bb09b892825ab2b214ac9ea9d92a5223", size = 2932523, upload-time = "2025-10-30T08:19:02.757Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/84/d0/205d54408c08b13550c733c4b85429e7ead111c7f0014309637425520a9a/deprecated-1.3.1-py2.py3-none-any.whl", hash = "sha256:597bfef186b6f60181535a29fbe44865ce137a5079f295b479886c82729d5f3f", size = 11298, upload-time = "2025-10-30T08:19:00.758Z" },-]-[[package]]name = "distlib"version = "0.4.3"@@ -1723,8 +1551,8 @@ name = "httpcore2"version = "2.12.0"source = { registry = "https://pypi.org/simple" }dependencies = [- { name = "h11", marker = "sys_platform != 'emscripten'" },- { name = "truststore", marker = "sys_platform != 'emscripten'" },+ { name = "h11" },+ { name = "truststore" },]sdist = { url = "https://files.pythonhosted.org/packages/be/ad/f4f0e57345f1870f3e8cb624e058d7eca6e5a27d33bcc3311d9b618734cd/httpcore2-2.12.0.tar.gz", hash = "sha256:9293522bba0aa7c4c8e9e3f040c16575bd8868e155a77fa30c7a9085a5eae648", size = 67548, upload-time = "2026-08-18T13:22:08.211Z" }wheels = [@@ -1784,21 +1612,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/d2/fd/6668e5aec43ab844de6fc74927e155a3b37bf40d7c3790e49fc0406b6578/httpx_sse-0.4.3-py3-none-any.whl", hash = "sha256:0ac1c9fe3c0afad2e0ebb25a934a59f4c7823b60792691f779fad2c5568830fc", size = 8960, upload-time = "2025-10-10T21:48:21.158Z" },]-[[package]]-name = "httpx-ws"-version = "0.9.0"-source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "anyio" },- { name = "httpcore" },- { name = "httpx" },- { name = "wsproto" },-]-sdist = { url = "https://files.pythonhosted.org/packages/cd/cd/ca91a07ae446451f7476bf3fcc909e98cb942ff032ebfda0e3fe449aca7b/httpx_ws-0.9.0.tar.gz", hash = "sha256:797373326f70eec1ae96f6e43ae9f12002fd7d73aee139a4985eaab964338a08", size = 107105, upload-time = "2026-03-28T14:11:10.781Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/98/f8/a6bc80313a9e93c888fa10534dfce2ad76ff86911b6f485777ce6de6a073/httpx_ws-0.9.0-py3-none-any.whl", hash = "sha256:71640d2fb1bf9a225775015b33cd755cfd4c5f7e21c885192fe3adc4c387b248", size = 15759, upload-time = "2026-03-28T14:11:11.887Z" },-]-[[package]]name = "httpx2"version = "2.12.0"@@ -2800,40 +2613,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/fd/6a/d3a169aaf8536cf228d56a09e04bcb713a2fe4410d4e2105b9419b5a9c89/numpy-2.5.0-cp314-cp314t-win_arm64.whl", hash = "sha256:016623417bb330d719d579daf2d6b9a01ddc52e41a9ed61a47f39fde46dcd865", size = 10686451, upload-time = "2026-06-21T20:57:49.313Z" },]-[[package]]-name = "obstore"-version = "0.11.1"-source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/a2/27/aa7549157a4a681157e315534ba5ab8f167f77662166e792a6e836938f46/obstore-0.11.1.tar.gz", hash = "sha256:a5afe8b99e3b20cdc9133be7a1b381259acf0d470029f6b2fc79c3f9947ad436", size = 130828, upload-time = "2026-08-21T23:57:27.837Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/0d/38/438f85772bfbcd2985845a5d00d1c910e98b15f587dae6cb1e435865eba9/obstore-0.11.1-cp311-abi3-macosx_10_12_x86_64.whl", hash = "sha256:d5c50b755d781efebe4f9c70ee6d00858e44d95f0229b8b5174358f861d9bd7c", size = 5400146, upload-time = "2026-08-21T23:56:29.168Z" },- { url = "https://files.pythonhosted.org/packages/e7/62/edd2613649cb6b4400f5d125223ee094d2da1c4c93636453a5360c61b865/obstore-0.11.1-cp311-abi3-macosx_11_0_arm64.whl", hash = "sha256:093152daa5c32b70a032f231bbc6a7eff76dda4285eed5a81d272b4485032dab", size = 4596203, upload-time = "2026-08-21T23:56:30.7Z" },- { url = "https://files.pythonhosted.org/packages/c1/52/09edd48251a26a65f786bf2def93994ffce501f3aea6724474d8de0a7f4f/obstore-0.11.1-cp311-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:b97ee10456e65f166c030b5fbde8380ca508621e23b84efd77aad83afe99315a", size = 5003021, upload-time = "2026-08-21T23:56:32.085Z" },- { url = "https://files.pythonhosted.org/packages/59/8f/89a28c75d46bbb0552d34a5e84c5bc512526d45f935321f00af2e6275a99/obstore-0.11.1-cp311-abi3-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:48983a143de69b11de49212caa79b5c39acbff7f592f9e85d156a0133a0e5796", size = 5240376, upload-time = "2026-08-21T23:56:33.658Z" },- { url = "https://files.pythonhosted.org/packages/50/c3/b4620899003e2472bec7baf5d2bce12cf6f6f11d02d8f17e03e093717a53/obstore-0.11.1-cp311-abi3-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:3b9cb988e03ff963914cf2176aee293eaaff7dcf4efcb905ce6834264b4b0884", size = 5444946, upload-time = "2026-08-21T23:56:35.093Z" },- { url = "https://files.pythonhosted.org/packages/bd/de/687685ab39ae4a70cc13ac252febfe62a387836a55e046f467c9fb231880/obstore-0.11.1-cp311-abi3-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:97850f68c8417f7167549bdb705c362c825ed470298c6b04faf52258c5e9234e", size = 5304065, upload-time = "2026-08-21T23:56:36.535Z" },- { url = "https://files.pythonhosted.org/packages/b4/36/b962ad52031b5bfdd249923db6151ff2b665b08c017611db96838455f337/obstore-0.11.1-cp311-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2a9f3d66dbf3c073dd6b6033c0787ef14edf78d97bff95595d6f6979692da264", size = 5556770, upload-time = "2026-08-21T23:56:38.377Z" },- { url = "https://files.pythonhosted.org/packages/e0/04/41a0f2917fcaa1e66b754fc98c92441d5a252ff9c619941ac086f9bdb4f6/obstore-0.11.1-cp311-abi3-manylinux_2_24_aarch64.whl", hash = "sha256:2ba3bceec4263b3a70eea873abedb82e03da9599f2326e80d6505cab0c10d401", size = 5337765, upload-time = "2026-08-21T23:56:40.279Z" },- { url = "https://files.pythonhosted.org/packages/f9/39/0b618efe59ee4b58f16d2b9246674a70c390bebf665cd284b439bade9bd3/obstore-0.11.1-cp311-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:e956fa8a953b7eb8580658d68cdf37e410356032c17697a06e44d0e8c4084a0f", size = 5544012, upload-time = "2026-08-21T23:56:41.754Z" },- { url = "https://files.pythonhosted.org/packages/57/3b/1018f6da240f3529d1cb9a836c79a91ce45349ba3cffcd6baa73296c7e6c/obstore-0.11.1-cp311-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:159a50d0f4cc53afe6f5c695313bcaf6e92ac81d7847692c8279153483272bfa", size = 5229851, upload-time = "2026-08-21T23:56:43.367Z" },- { url = "https://files.pythonhosted.org/packages/35/2c/c2fe082816b255159373b15be3f28b2515d0eb954e248e2f65449c456a14/obstore-0.11.1-cp311-abi3-musllinux_1_2_i686.whl", hash = "sha256:128da07f3a1b9c70159e2b2be9e27f458a9d531d57b1856dd7c4ddb73b4c9937", size = 5361812, upload-time = "2026-08-21T23:56:44.871Z" },- { url = "https://files.pythonhosted.org/packages/43/9c/656eb5cce818e7e3985d27f4bd403feb0b6e620494775a55a0943c8d2fff/obstore-0.11.1-cp311-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:67b8acfbbab960c2cb14c34294a96556caa67fcff15ee77c716d5c1bd1558606", size = 5790855, upload-time = "2026-08-21T23:56:46.391Z" },- { url = "https://files.pythonhosted.org/packages/c1/5c/94ece1c902ff5cdbe1140997d1f720221a0d5defa902fdd93715297604f5/obstore-0.11.1-cp311-abi3-win_amd64.whl", hash = "sha256:e23ea15cebe5f5be5d11005043d7b5ff56848e39499681ef52f8227bd385bd51", size = 5308846, upload-time = "2026-08-21T23:56:47.774Z" },- { url = "https://files.pythonhosted.org/packages/c0/af/235730a429e55777f15f9d7fef118a6ecf02f430ed4588deb4b7e13964aa/obstore-0.11.1-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:73284fc8a9804596baf4d80b55c0e71a6007487bfa28d6924acd85264d5be81f", size = 5424585, upload-time = "2026-08-21T23:56:49.532Z" },- { url = "https://files.pythonhosted.org/packages/e3/3c/432ea70c061fc9401fe399391ed4f04dead4a4cf33ea7c9564ce0e299d24/obstore-0.11.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:8a3f93310422b153629af929d9e88d1fc826d5e32a456de4d3a1926a770ae09c", size = 4576791, upload-time = "2026-08-21T23:56:51.014Z" },- { url = "https://files.pythonhosted.org/packages/43/c7/57dbdfa4ba5339b80fc755359bb232bdba7f82e92df6603ef383396b5f16/obstore-0.11.1-cp314-cp314t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:d666690f0a53ae3df4be2c18af6820369a74c9c5b8960e8760f0f8c9a8f15b36", size = 4992141, upload-time = "2026-08-21T23:56:52.46Z" },- { url = "https://files.pythonhosted.org/packages/37/4b/d25a4c129250364b0ca927fbfca5146744fb3bb4de60ae9b302300cbdfef/obstore-0.11.1-cp314-cp314t-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:0844ab75c8413c0af2d0fd2d2f6aa42d166809b6ac4be478151cd946ce7e5d69", size = 5217707, upload-time = "2026-08-21T23:56:53.946Z" },- { url = "https://files.pythonhosted.org/packages/4b/07/0a925c886639d6edce37aafb6eba0c86820cbc9dda42e91ddd784dbe059d/obstore-0.11.1-cp314-cp314t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:307b5f9d64a7c00cd13371e376c05e3914216bd0818a19ff2ae05bc0135e01dc", size = 5429440, upload-time = "2026-08-21T23:56:55.507Z" },- { url = "https://files.pythonhosted.org/packages/5f/c0/38d188a00b9f2de30df26802dd5bc2ecaefdabb882fde786cff800ccf50f/obstore-0.11.1-cp314-cp314t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:6f89647953b4ea50bab3f66591f7f462cd454a5d2fbbeefd885716a2c54e13ce", size = 5308903, upload-time = "2026-08-21T23:56:56.924Z" },- { url = "https://files.pythonhosted.org/packages/60/d3/815e5a7ca59f901b6d24fb01ad3af46de37dfdfd2971c019f914bdb7f65e/obstore-0.11.1-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:50de3116af69b6f1669cb443cc200ccdc1523a790a41f00854331b48f716cf8f", size = 5547007, upload-time = "2026-08-21T23:56:58.508Z" },- { url = "https://files.pythonhosted.org/packages/9c/a1/ec4d2291b7eb15e7ddccb2f0646ce560b8a539df4b0ab94d916e7a15a61c/obstore-0.11.1-cp314-cp314t-manylinux_2_24_aarch64.whl", hash = "sha256:eae71e1c5944ade976ce8cd1e780bed9b5c31d6d4f89cb7263e8dcff78f6cd8e", size = 5330062, upload-time = "2026-08-21T23:56:59.954Z" },- { url = "https://files.pythonhosted.org/packages/0a/09/a4a1301f2474f6569bbc0f2d337108ff2225d0b3d285894ed9a6dc953438/obstore-0.11.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:ff634b5edbbf76c56ae81397aa41500a66ad0aa48b1856dcc0cf31b159172dc0", size = 5539870, upload-time = "2026-08-21T23:57:01.485Z" },- { url = "https://files.pythonhosted.org/packages/9e/8f/7dbbf935a07ff5375c33916307b77aef9d39bded35081530150822898010/obstore-0.11.1-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:cbe509350d66249fc9e65ece4e7b1855d650f18e477721887128452b95c44b24", size = 5222673, upload-time = "2026-08-21T23:57:03.023Z" },- { url = "https://files.pythonhosted.org/packages/d5/89/4932b3dd7963a3a64fd532c30ccc836f0f4ede1a45bea9f12295299398e2/obstore-0.11.1-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:46122e585f48ab3f2e4fed51401a4e866279a3a3d1aee2372d598ab85ba2c539", size = 5335696, upload-time = "2026-08-21T23:57:04.439Z" },- { url = "https://files.pythonhosted.org/packages/aa/ff/f3cf31ac4ebfa648dbd2c69774579fd5da4cf4b05fa1192405dafb6aeb38/obstore-0.11.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:7275e75228059b2b30772b2ba3e41562a4a92ebdd3a96619d300f98ef152119f", size = 5783641, upload-time = "2026-08-21T23:57:05.899Z" },- { url = "https://files.pythonhosted.org/packages/51/31/b352db3450e700c2c51861d139fc92c3284f7e578ca306408b054f6b4a35/obstore-0.11.1-cp314-cp314t-win_amd64.whl", hash = "sha256:13bb0b6a40931ab2da93f93ad843865d483d95acec1bd586df79313daa5a50af", size = 5290060, upload-time = "2026-08-21T23:57:07.632Z" },-]-[[package]]name = "openai"version = "2.44.0"@@ -2996,22 +2775,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/1e/00/b46c6865b481ec0037931468cd97f649663c0b46743812de00644417a171/opentelemetry_instrumentation_agno-0.62.4-py3-none-any.whl", hash = "sha256:04f2aa6486450cd74c427f56136e0eb0d0a4ea1f33977344edfc3d9ef804870d", size = 8881, upload-time = "2026-09-29T10:43:14.201Z" },]-[[package]]-name = "opentelemetry-instrumentation-aiohttp-client"-version = "0.66b2"-source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "opentelemetry-api" },- { name = "opentelemetry-instrumentation" },- { name = "opentelemetry-semantic-conventions" },- { name = "opentelemetry-util-http" },- { name = "wrapt" },-]-sdist = { url = "https://files.pythonhosted.org/packages/44/ac/a65ed79ca7139ad401619ca9d8cc242d0c0b97b338c27805de62cb803b46/opentelemetry_instrumentation_aiohttp_client-0.66b2.tar.gz", hash = "sha256:9b1b3ec682b7b1df3d3c8f7ad1745703be847391bb722c9bd39b661902c667a4", size = 18850, upload-time = "2026-10-29T17:38:13.034Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/19/b2/d37618e84d8340bdc7c780a0b9c6f4f1b12ba4c2298d8765217110fd5a40/opentelemetry_instrumentation_aiohttp_client-0.66b2-py3-none-any.whl", hash = "sha256:33c51743ca225c2405b81b40ac744697804aef44b530f64d1f524c9a9cd3dca2", size = 13610, upload-time = "2026-10-29T17:37:09.117Z" },-]-[[package]]name = "opentelemetry-instrumentation-anthropic"version = "0.62.4"@@ -3985,18 +3748,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/0b/d7/1959b9648791274998a9c3526f6d0ec8fd2233e4d4acce81bbae76b44b2a/python_dotenv-1.2.2-py3-none-any.whl", hash = "sha256:1d8214789a24de455a8b8bd8ae6fe3c6b69a5e3d64aa8a8e5d68e694bbcb285a", size = 22101, upload-time = "2026-03-01T16:00:25.09Z" },]-[[package]]-name = "python-engineio"-version = "4.15.1"-source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "simple-websocket" },-]-sdist = { url = "https://files.pythonhosted.org/packages/dd/91/b565807fa922620ed575b412bf978d032e4c5d79558b400fdbfe1008c95a/python_engineio-4.15.1.tar.gz", hash = "sha256:1a412e798a90c64fabe7b20798939ae6d4a03f34da8a33d5a21a25a8bbbc3612", size = 93104, upload-time = "2026-10-28T23:53:30.846Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/38/5c/552f1dce2443dc33ce6b2ee7f67599ba5c83ef5582e2235a9878ac239049/python_engineio-4.15.1-py3-none-any.whl", hash = "sha256:745cb3c07701c719a2906439a00b67e44ef042904036568530a2c3a8cf18c89a", size = 60775, upload-time = "2026-10-28T23:53:29.304Z" },-]-[[package]]name = "python-json-logger"version = "4.1.0"@@ -4015,28 +3766,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/e1/04/e8135ebd1ad02c56ec633277529b2602ff99ff634be76cdba5744cf554fd/python_multipart-0.0.32-py3-none-any.whl", hash = "sha256:ff6d3f776f16878c894e52e107296ffc890e913c611b1a4ec6c44e2821fe2e23", size = 30042, upload-time = "2026-06-04T16:18:57.319Z" },]-[[package]]-name = "python-socketio"-version = "5.18.1"-source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "bidict" },- { name = "python-engineio" },-]-sdist = { url = "https://files.pythonhosted.org/packages/71/b9/4ab083267c1f8ece9a9e019808412af7c7a03321411a1263cd863321baa2/python_socketio-5.18.1.tar.gz", hash = "sha256:07ab0e7c94a52833a67af1dc05958ad6fb0de69adc87de9198a61b22588c40d4", size = 132106, upload-time = "2026-11-03T12:19:20.723Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/79/e2/cdc630aef7da00698af4ed061ff873297f806cc049cc5c67bf89077cb7e4/python_socketio-5.18.1-py3-none-any.whl", hash = "sha256:e768c473842be811f6dd24bd0a49cd0d4a0c994182e3eba23cc9d1489c7a697e", size = 83022, upload-time = "2026-11-03T12:19:19.136Z" },-]--[package.optional-dependencies]-asyncio-client = [- { name = "aiohttp" },-]-client = [- { name = "requests" },- { name = "websocket-client" },-]-[[package]]name = "pytz"version = "2026.2"@@ -4564,18 +4293,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/2e/86/0f4a39a50fcf510753b7abd98b728e66c14fefe89bad9ef5824745bf7b9f/simhash-2.1.2-py3-none-any.whl", hash = "sha256:968de16c82c227a631aa00e57ab58f9e4ee9e47e8408486199a9eb59c1d6979b", size = 4714, upload-time = "2022-03-03T01:24:22.255Z" },]-[[package]]-name = "simple-websocket"-version = "1.1.0"-source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "wsproto" },-]-sdist = { url = "https://files.pythonhosted.org/packages/b0/d4/bfa032f961103eba93de583b161f0e6a5b63cebb8f2c7d0c6e6efe1e3d2e/simple_websocket-1.1.0.tar.gz", hash = "sha256:7939234e7aa067c534abdab3a9ed933ec9ce4691b0713c78acb195560aa52ae4", size = 17300, upload-time = "2024-10-10T22:39:31.412Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/52/59/0782e51887ac6b07ffd1570e0364cf901ebc36345fea669969d2084baebb/simple_websocket-1.1.0-py3-none-any.whl", hash = "sha256:4af6069630a38ed6c561010f0e11a5bc0d4ca569b36306eb257cd9a192497c8c", size = 13842, upload-time = "2024-10-10T22:39:29.645Z" },-]-[[package]]name = "six"version = "1.17.0"@@ -5170,15 +4887,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/bd/6e/95b0e537de1f4d4301f76f944642c6da50d1511cc7b3d64dc418a66c7509/wcwidth-0.8.1-py3-none-any.whl", hash = "sha256:f453740b1e4a4f3291faa37944c555d71056c4da08d59809b307ef4feba695c8", size = 323092, upload-time = "2026-06-08T05:57:21.413Z" },]-[[package]]-name = "websocket-client"-version = "1.9.2"-source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/d8/cb/a5abcc2891249f393827c650c6296660ce40374ac22d99ab9aea41f9d2a2/websocket_client-1.9.2.tar.gz", hash = "sha256:0fcb57545848be86992e128218fd96dd87a6769ffdb1a968dff79632b85604d0", size = 84110, upload-time = "2026-08-31T14:08:40.964Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/d5/d2/cc4dc1271e464942db7ee278baae2daa99ee77cb2af744025c04da585a3e/websocket_client-1.9.2-py3-none-any.whl", hash = "sha256:e1a673830a9c7bfa47b1cd3d5e4178f4c9651d80a4eab02c9c23a1c3ec6250ce", size = 95786, upload-time = "2026-08-31T14:08:39.899Z" },-]-[[package]]name = "websockets"version = "16.0"@@ -5295,18 +5003,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/87/7d/5ed859fad4b5eddd598a846150aaab2703730ed4886c5c5e03b0df0cfdd5/wrapt-2.5.0-py3-none-any.whl", hash = "sha256:107eea1a511e98a3a5033b0c2cb403fbb37f05dee6ac1fb85c0460d311ec278c", size = 81586, upload-time = "2026-09-27T01:41:55.479Z" },]-[[package]]-name = "wsproto"-version = "1.3.2"-source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "h11" },-]-sdist = { url = "https://files.pythonhosted.org/packages/c7/79/12135bdf8b9c9367b8701c2c19a14c913c120b882d50b014ca0d38083c2c/wsproto-1.3.2.tar.gz", hash = "sha256:b86885dcf294e15204919950f666e06ffc6c7c114ca900b060d6e16293528294", size = 50116, upload-time = "2025-11-20T18:18:01.871Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/a4/f5/10b68b7b1544245097b2a1b8238f66f2fc6dcaeb24ba5d917f52bd2eed4f/wsproto-1.3.2-py3-none-any.whl", hash = "sha256:61eea322cdf56e8cc904bd3ad7573359a242ba65688716b0710a5eb12beab584", size = 24405, upload-time = "2025-11-20T18:18:00.454Z" },-]-[[package]]name = "yarl"version = "1.25.1"