openforma 0.4.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- forma_cli/__init__.py +5 -0
- forma_cli/app.py +1139 -0
- forma_cli/config.py +112 -0
- forma_cli/credentials.py +141 -0
- forma_cli/local.py +562 -0
- forma_cli/metadata_api.py +138 -0
- forma_cli/project_artifacts.py +182 -0
- forma_cli/sdk.py +571 -0
- forma_core/__init__.py +9 -0
- forma_core/__main__.py +4 -0
- forma_core/_version.py +3 -0
- forma_core/agents/__init__.py +50 -0
- forma_core/agents/clarification.py +194 -0
- forma_core/agents/component_reconciliation.py +99 -0
- forma_core/agents/context_gathering.py +115 -0
- forma_core/agents/continuous.py +537 -0
- forma_core/agents/contracts.py +247 -0
- forma_core/agents/firecrawl_mcp.py +484 -0
- forma_core/agents/lattice.py +239 -0
- forma_core/agents/orchestrator.py +3724 -0
- forma_core/agents/pipeline.py +843 -0
- forma_core/agents/project_correction.py +83 -0
- forma_core/agents/prompt_compaction.py +428 -0
- forma_core/agents/system_architecture.py +345 -0
- forma_core/agents/video_correction.py +119 -0
- forma_core/agents/web_research_workflow.py +1256 -0
- forma_core/agents/workflows.py +176 -0
- forma_core/assets/__init__.py +1 -0
- forma_core/assets/models.py +156 -0
- forma_core/assets/project.py +17 -0
- forma_core/assets/repository.py +48 -0
- forma_core/assets/service.py +142 -0
- forma_core/assets/validation.py +35 -0
- forma_core/benchmarks/__init__.py +5 -0
- forma_core/benchmarks/ir_triad_v1.py +477 -0
- forma_core/biology/__init__.py +28 -0
- forma_core/biology/benchmark.py +80 -0
- forma_core/biology/ewart_liverchip.py +279 -0
- forma_core/biology/ir.py +25 -0
- forma_core/biology/liverbench.py +416 -0
- forma_core/biology/liverbench_assay.py +251 -0
- forma_core/biology/liverbench_baselines.py +133 -0
- forma_core/biology/liverbench_independent.py +229 -0
- forma_core/biology/liverchip_demo.py +154 -0
- forma_core/biology/liverchip_evidence.py +149 -0
- forma_core/biology/models.py +247 -0
- forma_core/biology/validation.py +72 -0
- forma_core/cad_migrations/__init__.py +6 -0
- forma_core/cad_migrations/cli.py +101 -0
- forma_core/cad_migrations/emitters.py +227 -0
- forma_core/cad_migrations/models.py +121 -0
- forma_core/cad_migrations/planner.py +68 -0
- forma_core/chemistry/__init__.py +5 -0
- forma_core/chemistry/models.py +215 -0
- forma_core/chemistry/stoichiometry.py +272 -0
- forma_core/chemistry/validation.py +179 -0
- forma_core/cli/__init__.py +1 -0
- forma_core/cli/__main__.py +4 -0
- forma_core/cli/main.py +370 -0
- forma_core/config/__init__.py +28 -0
- forma_core/config/compatibility.py +282 -0
- forma_core/config/contract.py +184 -0
- forma_core/config/environment.py +129 -0
- forma_core/config/parti.py +34 -0
- forma_core/config/runtime.py +303 -0
- forma_core/control/__init__.py +10 -0
- forma_core/control/actions.py +136 -0
- forma_core/control/adapters.py +36 -0
- forma_core/control/cli.py +49 -0
- forma_core/control/client.py +124 -0
- forma_core/control/models.py +168 -0
- forma_core/control/opencode_worker.py +80 -0
- forma_core/control/package.py +318 -0
- forma_core/control/rover_scene/__init__.py +1 -0
- forma_core/control/rover_scene/__main__.py +34 -0
- forma_core/control/rover_scene/assets.py +65 -0
- forma_core/control/rover_scene/fleet.py +214 -0
- forma_core/control/rover_scene/host.py +258 -0
- forma_core/control/rover_scene/kinematics.py +35 -0
- forma_core/control/rover_scene/machine.py +347 -0
- forma_core/control/rover_scene/robot.py +166 -0
- forma_core/control/rover_scene/scene.py +206 -0
- forma_core/control/rover_scene/view.py +80 -0
- forma_core/control/rover_scene/web/index.html +25 -0
- forma_core/control/rover_scene/web/viewer.js +148 -0
- forma_core/control/runtime.py +356 -0
- forma_core/control/so101.py +235 -0
- forma_core/control/tasks.py +287 -0
- forma_core/database.py +2362 -0
- forma_core/debug.py +314 -0
- forma_core/domains/__init__.py +7 -0
- forma_core/domains/agents.py +85 -0
- forma_core/domains/base.py +69 -0
- forma_core/domains/benchmark.py +87 -0
- forma_core/domains/cli.py +48 -0
- forma_core/domains/compatibility.py +234 -0
- forma_core/domains/composition.py +372 -0
- forma_core/domains/diagnostics.py +15 -0
- forma_core/domains/generation.py +479 -0
- forma_core/domains/interaction.py +301 -0
- forma_core/domains/planning.py +140 -0
- forma_core/domains/providers.py +214 -0
- forma_core/domains/registry.py +267 -0
- forma_core/domains/selection.py +75 -0
- forma_core/domains/storage.py +60 -0
- forma_core/domains/tools.py +180 -0
- forma_core/electronics/__init__.py +1 -0
- forma_core/electronics/models.py +84 -0
- forma_core/electronics/primitives.py +43 -0
- forma_core/electronics/rules.py +340 -0
- forma_core/external_sources.py +497 -0
- forma_core/fabricator/__init__.py +33 -0
- forma_core/fabricator/__main__.py +7 -0
- forma_core/fabricator/main.py +578 -0
- forma_core/firmware/__init__.py +60 -0
- forma_core/firmware/drivers.py +140 -0
- forma_core/firmware/examples.py +503 -0
- forma_core/firmware/generate.py +520 -0
- forma_core/firmware/models.py +34 -0
- forma_core/firmware/sil/__init__.py +5 -0
- forma_core/firmware/sil/adapter.py +71 -0
- forma_core/firmware/sil/build.py +49 -0
- forma_core/firmware/sil/native/CMakeLists.txt +9 -0
- forma_core/firmware/sil/native/bridge.cpp +112 -0
- forma_core/firmware/sil/native/controller.cpp +123 -0
- forma_core/firmware/sil/native/controller.h +49 -0
- forma_core/firmware/sil/simulator.py +139 -0
- forma_core/firmware/targets.py +111 -0
- forma_core/firmware/validation.py +130 -0
- forma_core/fluidics/__init__.py +6 -0
- forma_core/fluidics/benchmark.py +217 -0
- forma_core/fluidics/calculations.py +79 -0
- forma_core/fluidics/examples.py +54 -0
- forma_core/fluidics/ir.py +25 -0
- forma_core/fluidics/models.py +132 -0
- forma_core/fluidics/topology.py +47 -0
- forma_core/fluidics/validation.py +134 -0
- forma_core/generation.py +32 -0
- forma_core/geometry_bindings/__init__.py +20 -0
- forma_core/geometry_bindings/cad_adapter.py +80 -0
- forma_core/geometry_bindings/models.py +163 -0
- forma_core/geometry_bindings/resolution.py +340 -0
- forma_core/geometry_bindings/tools.py +125 -0
- forma_core/image_providers.py +3049 -0
- forma_core/images.py +3 -0
- forma_core/integrations/__init__.py +1 -0
- forma_core/integrations/huggingface/__init__.py +29 -0
- forma_core/integrations/huggingface/huggingface_artifacts.py +272 -0
- forma_core/jobs/__init__.py +1 -0
- forma_core/jobs/context.py +277 -0
- forma_core/jobs/continuous.py +719 -0
- forma_core/jobs/metrics.py +124 -0
- forma_core/jobs/migrations.py +161 -0
- forma_core/jobs/persistence.py +28 -0
- forma_core/jobs/repositories.py +422 -0
- forma_core/jobs/schema.py +28 -0
- forma_core/jobs/source_usage.py +230 -0
- forma_core/jobs/store.py +476 -0
- forma_core/llm.py +3 -0
- forma_core/llm_providers.py +2682 -0
- forma_core/logs.py +107 -0
- forma_core/mechanics/__init__.py +1 -0
- forma_core/mechanics/gear_benchmark.py +85 -0
- forma_core/mechanics/mechanism_benchmarks.py +345 -0
- forma_core/mechanics/models.py +72 -0
- forma_core/mechanics/primitives.py +109 -0
- forma_core/mechanics/solid_cad.py +83 -0
- forma_core/observability.py +237 -0
- forma_core/openai_streams.py +780 -0
- forma_core/opencode/__init__.py +25 -0
- forma_core/opencode/architecture.py +82 -0
- forma_core/opencode/capabilities.py +130 -0
- forma_core/opencode/models.py +419 -0
- forma_core/opencode/persistence.py +62 -0
- forma_core/opencode/public_events.py +91 -0
- forma_core/opencode/schema.py +28 -0
- forma_core/opencode/store.py +874 -0
- forma_core/persistence/__init__.py +16 -0
- forma_core/persistence/base.py +38 -0
- forma_core/persistence/images.py +598 -0
- forma_core/persistence/migrations.py +200 -0
- forma_core/persistence/models.py +439 -0
- forma_core/persistence/project_artifacts.py +341 -0
- forma_core/persistence/project_reconciliation.py +1094 -0
- forma_core/persistence/providers/__init__.py +4 -0
- forma_core/persistence/providers/sqlite.py +114 -0
- forma_core/persistence/providers/supabase.py +31 -0
- forma_core/persistence/repositories/__init__.py +9 -0
- forma_core/persistence/repositories/base.py +335 -0
- forma_core/persistence/repositories/sqlite.py +1571 -0
- forma_core/persistence/repositories/supabase.py +1576 -0
- forma_core/persistence/schema.py +176 -0
- forma_core/processes/__init__.py +5 -0
- forma_core/processes/models.py +338 -0
- forma_core/processes/validation.py +141 -0
- forma_core/project_list_cache.py +316 -0
- forma_core/prompt_continuity.py +387 -0
- forma_core/providers/__init__.py +39 -0
- forma_core/providers/base.py +28 -0
- forma_core/providers/models.py +138 -0
- forma_core/providers/openai.py +92 -0
- forma_core/providers/openai_compatible.py +190 -0
- forma_core/providers/registry.py +68 -0
- forma_core/providers/registry_utils.py +46 -0
- forma_core/py.typed +1 -0
- forma_core/runtime.py +3 -0
- forma_core/selectors.py +36 -0
- forma_core/signups/__init__.py +5 -0
- forma_core/signups/models.py +49 -0
- forma_core/terminal/__init__.py +1 -0
- forma_core/terminal/dashboard.py +475 -0
- forma_core/terminal/images.py +156 -0
- forma_core/thermal/__init__.py +5 -0
- forma_core/thermal/models.py +361 -0
- forma_core/thermal/validation.py +175 -0
- forma_core/user_integrations.py +2069 -0
- forma_core/utils.py +291 -0
- forma_core/validation.py +83 -0
- forma_core/vertex_auth.py +92 -0
- forma_core/video_prompts.py +193 -0
- forma_core/video_review.py +1006 -0
- forma_core/wiring.py +356 -0
- forma_core/workers/__init__.py +120 -0
- forma_core/workers/contracts.py +183 -0
- forma_core/workers/generation.py +753 -0
- forma_core/workers/orchestration.py +805 -0
- forma_core/workers/registry.py +222 -0
- forma_core/workers/reverse_engineering.py +272 -0
- forma_core/workers/validation.py +291 -0
- forma_core/workspaces/__init__.py +5 -0
- forma_core/workspaces/chats/__init__.py +11 -0
- forma_core/workspaces/chats/models.py +48 -0
- forma_core/workspaces/context/__init__.py +15 -0
- forma_core/workspaces/context/agent.py +260 -0
- forma_core/workspaces/context/models.py +117 -0
- forma_core/workspaces/context/pdf.py +418 -0
- forma_core/workspaces/design_briefs/__init__.py +25 -0
- forma_core/workspaces/design_briefs/models.py +85 -0
- forma_core/workspaces/design_briefs/references.py +56 -0
- forma_core/workspaces/models.py +41 -0
- forma_core/workspaces/projects/__init__.py +88 -0
- forma_core/workspaces/projects/cad_generation.py +1016 -0
- forma_core/workspaces/projects/context_governance.py +365 -0
- forma_core/workspaces/projects/design_lifecycle.py +668 -0
- forma_core/workspaces/projects/fabrication/__init__.py +54 -0
- forma_core/workspaces/projects/fabrication/demo_printers.py +236 -0
- forma_core/workspaces/projects/fabrication/models.py +120 -0
- forma_core/workspaces/projects/fabrication/printer_config.py +205 -0
- forma_core/workspaces/projects/fabrication/slicers/__init__.py +7 -0
- forma_core/workspaces/projects/fabrication/slicers/base.py +25 -0
- forma_core/workspaces/projects/fabrication/slicers/cura.py +125 -0
- forma_core/workspaces/projects/fabrication/slicers/orca.py +208 -0
- forma_core/workspaces/projects/fabrication/slicing.py +202 -0
- forma_core/workspaces/projects/fabrication/validation.py +103 -0
- forma_core/workspaces/projects/gear_benchmark.py +6 -0
- forma_core/workspaces/projects/generation_mode.py +70 -0
- forma_core/workspaces/projects/identity.py +28 -0
- forma_core/workspaces/projects/iteration.py +680 -0
- forma_core/workspaces/projects/manifest.py +362 -0
- forma_core/workspaces/projects/mechanism_benchmarks.py +12 -0
- forma_core/workspaces/projects/models.py +913 -0
- forma_core/workspaces/projects/objects.py +731 -0
- forma_core/workspaces/projects/outcomes.py +47 -0
- forma_core/workspaces/projects/output.py +735 -0
- forma_core/workspaces/projects/resolver.py +397 -0
- forma_core/workspaces/projects/solid_cad.py +8 -0
- forma_core/workspaces/projects/state.py +622 -0
- forma_core/workspaces/readiness/__init__.py +28 -0
- forma_core/workspaces/readiness/evaluator.py +103 -0
- forma_core/workspaces/readiness/models.py +97 -0
- forma_core/workspaces/readiness/service.py +225 -0
- forma_core/workspaces/reverse_engineering/__init__.py +37 -0
- forma_core/workspaces/reverse_engineering/analyzer.py +246 -0
- forma_core/workspaces/reverse_engineering/models.py +128 -0
- forma_core/workspaces/validation/__init__.py +37 -0
- forma_core/workspaces/validation/evaluator.py +327 -0
- forma_core/workspaces/validation/models.py +146 -0
- forma_core/workspaces/validation/service.py +212 -0
- forma_core/workspaces/workflow/__init__.py +29 -0
- forma_core/workspaces/workflow/guard.py +33 -0
- forma_core/workspaces/workflow/models.py +77 -0
- forma_core/workspaces/workflow/service.py +287 -0
- openforma-0.4.0.dist-info/METADATA +247 -0
- openforma-0.4.0.dist-info/RECORD +288 -0
- openforma-0.4.0.dist-info/WHEEL +5 -0
- openforma-0.4.0.dist-info/entry_points.txt +4 -0
- openforma-0.4.0.dist-info/licenses/LICENSE +373 -0
- openforma-0.4.0.dist-info/top_level.txt +2 -0
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
"""Persistent, feedback-backed machine tasks. Host calls on its control event loop.
|
|
2
|
+
|
|
3
|
+
The injected agent decides actions; this runner owns leases, heartbeats, evidence
|
|
4
|
+
and cancellation. It never substitutes a scripted policy for a failed agent.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import asyncio
|
|
9
|
+
from copy import deepcopy
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
from datetime import datetime, timezone
|
|
12
|
+
import json
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Protocol
|
|
15
|
+
import uuid
|
|
16
|
+
|
|
17
|
+
from .runtime import ControlError, MachineRegistry
|
|
18
|
+
|
|
19
|
+
TERMINAL = {"completed", "failed", "cancelled", "interrupted"}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class TaskAgent(Protocol):
|
|
23
|
+
async def run(self, task: dict, invoke, progress) -> None: ...
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def timestamp():
|
|
27
|
+
return datetime.now(timezone.utc).isoformat()
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass
|
|
31
|
+
class Task:
|
|
32
|
+
record: dict
|
|
33
|
+
session: str | None = None
|
|
34
|
+
sequence: int = 0
|
|
35
|
+
job: asyncio.Task | None = None
|
|
36
|
+
action_lock: asyncio.Lock = field(default_factory=asyncio.Lock)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class MachineTaskRunner:
|
|
40
|
+
def __init__(self, registry: MachineRegistry, agent: TaskAgent, directory: Path, *, timeout_s=300):
|
|
41
|
+
self.registry, self.agent, self.directory = registry, agent, Path(directory)
|
|
42
|
+
self.timeout_s = timeout_s
|
|
43
|
+
self.tasks: dict[str, Task] = {}
|
|
44
|
+
self.latest: dict[str, str] = {}
|
|
45
|
+
self.directory.mkdir(parents=True, exist_ok=True)
|
|
46
|
+
for path in sorted(self.directory.glob("*.json"), key=lambda p: p.stat().st_mtime):
|
|
47
|
+
record = json.loads(path.read_text(encoding="utf-8"))
|
|
48
|
+
task = Task(record)
|
|
49
|
+
self.tasks[record["task_id"]] = task
|
|
50
|
+
self.latest[record["machine_id"]] = record["task_id"]
|
|
51
|
+
if record["status"] not in TERMINAL:
|
|
52
|
+
record.update(status="interrupted", reason="host_restarted", finished_at=timestamp())
|
|
53
|
+
self._event(task, "interrupted", "Host restarted; execution was not resumed.")
|
|
54
|
+
|
|
55
|
+
def _save(self, task):
|
|
56
|
+
path = self.directory/(task.record["task_id"]+".json")
|
|
57
|
+
temp = path.with_suffix(".tmp")
|
|
58
|
+
temp.write_text(json.dumps(task.record, indent=2, allow_nan=False)+"\n", encoding="utf-8")
|
|
59
|
+
temp.replace(path)
|
|
60
|
+
|
|
61
|
+
def _event(self, task, kind, message, **fields):
|
|
62
|
+
record = task.record
|
|
63
|
+
record["revision"] += 1
|
|
64
|
+
record["events"].append(dict(id=record["revision"], time=timestamp(), kind=kind, message=message, **fields))
|
|
65
|
+
record["events"] = record["events"][-500:]
|
|
66
|
+
self._save(task)
|
|
67
|
+
|
|
68
|
+
def snapshot(self, machine_id, *, full=False):
|
|
69
|
+
task_id = self.latest.get(machine_id)
|
|
70
|
+
return self.get(task_id, full=full) if task_id else None
|
|
71
|
+
|
|
72
|
+
def get(self, task_id, *, full=True):
|
|
73
|
+
if task_id not in self.tasks:
|
|
74
|
+
raise ControlError("unknown_task")
|
|
75
|
+
record = self.tasks[task_id].record
|
|
76
|
+
if full:
|
|
77
|
+
return deepcopy(record)
|
|
78
|
+
result = {k: v for k, v in record.items() if k not in {"package", "actions", "initial_observation", "final_observation", "events"}}
|
|
79
|
+
result["events"] = [{k: v for k, v in event.items() if k not in {"observation", "evidence"}} for event in record["events"][-50:]]
|
|
80
|
+
return deepcopy(result)
|
|
81
|
+
|
|
82
|
+
def _machine(self, task):
|
|
83
|
+
return self.registry.get(task.record["machine_id"])
|
|
84
|
+
|
|
85
|
+
def _require_active(self, task):
|
|
86
|
+
if task.record["status"] in TERMINAL:
|
|
87
|
+
raise ControlError("task_not_active")
|
|
88
|
+
machine = self._machine(task)
|
|
89
|
+
if not machine.owner or machine.owner["session_id"] != task.session:
|
|
90
|
+
raise ControlError("task_ownership_lost")
|
|
91
|
+
return machine
|
|
92
|
+
|
|
93
|
+
def _command(self, task, op, **values):
|
|
94
|
+
machine = self._require_active(task)
|
|
95
|
+
lease = machine.lease(task.session)
|
|
96
|
+
task.sequence += 1
|
|
97
|
+
return machine.command(dict(protocol_version=2, session_id=task.session,
|
|
98
|
+
lease_id=lease["lease_id"], seq=task.sequence, op=op, **values))
|
|
99
|
+
|
|
100
|
+
def observe(self, task):
|
|
101
|
+
state = self._machine(task).snapshot()
|
|
102
|
+
execution = state["execution"]
|
|
103
|
+
return dict(machine_id=state["machine_id"], state=state["state"], uptime_ms=state["uptime_ms"],
|
|
104
|
+
axes=state["axes"], execution_fault=state["execution_fault"],
|
|
105
|
+
provenance=task.record["provenance"],
|
|
106
|
+
observations={k: v for k, v in (execution["details"] if execution else {}).items() if k != "bodies"})
|
|
107
|
+
|
|
108
|
+
def start(self, machine_id, goal, *, session_id=None, reset=False, model=None):
|
|
109
|
+
if not isinstance(goal, str) or not 1 <= len(goal.strip()) <= 2000:
|
|
110
|
+
raise ControlError("invalid_task_goal")
|
|
111
|
+
machine = self.registry.get(machine_id)
|
|
112
|
+
previous = self.snapshot(machine_id)
|
|
113
|
+
if previous and previous["status"] not in TERMINAL:
|
|
114
|
+
raise ControlError("task_already_running")
|
|
115
|
+
if machine.action_execution is None:
|
|
116
|
+
raise ControlError("machine_has_no_action_contract")
|
|
117
|
+
if machine.owner:
|
|
118
|
+
if session_id is None:
|
|
119
|
+
raise ControlError("control_busy")
|
|
120
|
+
machine._require_owner(session_id)
|
|
121
|
+
if reset and (machine.definition.backend != "virtual" or not callable(getattr(machine.adapter, "fresh", None))):
|
|
122
|
+
raise ControlError("task_reset_unavailable")
|
|
123
|
+
if machine.state == "FAULT" and not reset:
|
|
124
|
+
raise ControlError("adapter_fault")
|
|
125
|
+
# Validate a replacement before relinquishing the existing owner.
|
|
126
|
+
fresh = machine.adapter.fresh() if reset else None
|
|
127
|
+
if fresh is not None:
|
|
128
|
+
try:
|
|
129
|
+
machine.action_execution.bind(fresh)
|
|
130
|
+
except Exception:
|
|
131
|
+
if hasattr(fresh, "close"):
|
|
132
|
+
fresh.close()
|
|
133
|
+
raise
|
|
134
|
+
if machine.owner:
|
|
135
|
+
machine.release(session_id)
|
|
136
|
+
if fresh is not None:
|
|
137
|
+
old = machine.adapter
|
|
138
|
+
machine.replace_adapter(fresh)
|
|
139
|
+
if hasattr(old, "close"):
|
|
140
|
+
old.close()
|
|
141
|
+
owner = machine.claim("Task agent", kind="agent")
|
|
142
|
+
package = machine.action_execution.package
|
|
143
|
+
record = dict(format="forma.machine-task", version=1, task_id=uuid.uuid4().hex,
|
|
144
|
+
machine_id=machine_id, goal=goal.strip(), status="starting", reason=None, summary=None,
|
|
145
|
+
created_at=timestamp(), finished_at=None, revision=0, events=[], actions=[],
|
|
146
|
+
action_count=0, heartbeat_count=0, model=model, agent_session_id=None,
|
|
147
|
+
package_sha256=package.sha256, package=package.model_dump(mode="json"),
|
|
148
|
+
provenance=package.adapter.evidence, reset_fixture=reset)
|
|
149
|
+
task = Task(record, session=owner["session_id"])
|
|
150
|
+
self.tasks[record["task_id"]] = task
|
|
151
|
+
self.latest[machine_id] = record["task_id"]
|
|
152
|
+
record["initial_observation"] = self.observe(task)
|
|
153
|
+
try:
|
|
154
|
+
self._event(task, "starting", "Starting task worker; machine control acquired.")
|
|
155
|
+
task.job = asyncio.create_task(self._run(task))
|
|
156
|
+
except Exception:
|
|
157
|
+
machine.release(task.session)
|
|
158
|
+
task.session = None
|
|
159
|
+
raise
|
|
160
|
+
return self.get(record["task_id"], full=False)
|
|
161
|
+
|
|
162
|
+
def _finish(self, task, status, reason, summary=None):
|
|
163
|
+
if task.record["status"] in TERMINAL:
|
|
164
|
+
return
|
|
165
|
+
machine = self._machine(task)
|
|
166
|
+
if machine.owner and machine.owner["session_id"] == task.session:
|
|
167
|
+
machine.release(task.session)
|
|
168
|
+
task.session = None
|
|
169
|
+
# Capture an interrupted in-flight action before its coroutine is cancelled.
|
|
170
|
+
current = machine.action_execution.snapshot()
|
|
171
|
+
if current and any(a.get("run_id") == current["run_id"] for a in task.record["actions"]):
|
|
172
|
+
for action in task.record["actions"]:
|
|
173
|
+
if action.get("run_id") == current["run_id"]:
|
|
174
|
+
action["evidence"] = current
|
|
175
|
+
task.record.update(status=status, reason=reason, summary=summary, finished_at=timestamp(), final_observation=self.observe(task))
|
|
176
|
+
self._event(task, status, summary or reason)
|
|
177
|
+
|
|
178
|
+
def cancel(self, machine_id, *, reason="stopped_by_user"):
|
|
179
|
+
task_id = self.latest.get(machine_id)
|
|
180
|
+
if task_id:
|
|
181
|
+
task = self.tasks[task_id]
|
|
182
|
+
if task.record["status"] not in TERMINAL:
|
|
183
|
+
self._finish(task, "cancelled" if reason == "stopped_by_user" else "interrupted", reason)
|
|
184
|
+
if task.job:
|
|
185
|
+
task.job.cancel()
|
|
186
|
+
return self.snapshot(machine_id)
|
|
187
|
+
|
|
188
|
+
async def close(self):
|
|
189
|
+
for machine_id in list(self.latest):
|
|
190
|
+
self.cancel(machine_id, reason="host_shutdown")
|
|
191
|
+
await asyncio.gather(*(t.job for t in self.tasks.values() if t.job), return_exceptions=True)
|
|
192
|
+
|
|
193
|
+
async def _heartbeat(self, task):
|
|
194
|
+
interval = self._machine(task).definition.timing.heartbeat_ms / 1000 * .75
|
|
195
|
+
while True:
|
|
196
|
+
await asyncio.sleep(interval)
|
|
197
|
+
if task.record["status"] in TERMINAL:
|
|
198
|
+
return
|
|
199
|
+
try:
|
|
200
|
+
self._command(task, "heartbeat")
|
|
201
|
+
task.record["heartbeat_count"] += 1
|
|
202
|
+
except Exception as error:
|
|
203
|
+
self._finish(task, "interrupted", str(error))
|
|
204
|
+
task.job.cancel()
|
|
205
|
+
return
|
|
206
|
+
|
|
207
|
+
async def _run(self, task):
|
|
208
|
+
heartbeat = asyncio.create_task(self._heartbeat(task))
|
|
209
|
+
try:
|
|
210
|
+
async with asyncio.timeout(self.timeout_s):
|
|
211
|
+
await self.agent.run(deepcopy(task.record),
|
|
212
|
+
lambda name, inputs: self.tool(task, name, inputs),
|
|
213
|
+
lambda kind, data: self.progress(task, kind, data))
|
|
214
|
+
if task.record["status"] not in TERMINAL:
|
|
215
|
+
self._finish(task, "failed", "agent_ended_without_verified_result")
|
|
216
|
+
except asyncio.CancelledError:
|
|
217
|
+
self._finish(task, "interrupted", "worker_cancelled")
|
|
218
|
+
except TimeoutError:
|
|
219
|
+
self._finish(task, "failed", "task_timeout")
|
|
220
|
+
except Exception as error:
|
|
221
|
+
self._finish(task, "failed", str(error))
|
|
222
|
+
finally:
|
|
223
|
+
heartbeat.cancel()
|
|
224
|
+
await asyncio.gather(heartbeat, return_exceptions=True)
|
|
225
|
+
|
|
226
|
+
def progress(self, task, kind, data):
|
|
227
|
+
self._require_active(task)
|
|
228
|
+
if kind == "ready":
|
|
229
|
+
task.record.update(model=data.get("model"), agent_session_id=data.get("session_id"), status="running")
|
|
230
|
+
self._command(task, "arm")
|
|
231
|
+
self._event(task, "ready", "Agent connected; machine armed.")
|
|
232
|
+
elif kind == "thinking":
|
|
233
|
+
self._event(task, "thinking", "Agent deciding the next step; heartbeat maintained.")
|
|
234
|
+
|
|
235
|
+
async def tool(self, task, name, inputs):
|
|
236
|
+
machine = self._require_active(task)
|
|
237
|
+
if not isinstance(inputs, dict):
|
|
238
|
+
raise ControlError("invalid_task_tool_input")
|
|
239
|
+
if name == "inspect_machine":
|
|
240
|
+
self._event(task, "inspect", "Agent inspected capabilities and observations.")
|
|
241
|
+
return dict(package=task.record["package"], current=self.observe(task))
|
|
242
|
+
if name == "observe":
|
|
243
|
+
observation = self.observe(task)
|
|
244
|
+
self._event(task, "observe", str(inputs.get("note", "Agent checked feedback."))[:1000], observation=observation)
|
|
245
|
+
return observation
|
|
246
|
+
if name == "execute_action":
|
|
247
|
+
async with task.action_lock:
|
|
248
|
+
self._require_active(task)
|
|
249
|
+
if task.record["action_count"] >= 50:
|
|
250
|
+
raise ControlError("task_action_limit")
|
|
251
|
+
entry = dict(action_id=inputs.get("action_id"), parameters=inputs.get("parameters", {}),
|
|
252
|
+
reason=str(inputs.get("reason", ""))[:1000], before=self.observe(task))
|
|
253
|
+
task.record["actions"].append(entry)
|
|
254
|
+
task.record["action_count"] += 1
|
|
255
|
+
try:
|
|
256
|
+
reply = self._command(task, "action", action_id=entry["action_id"], parameters=entry["parameters"])
|
|
257
|
+
entry["run_id"] = reply["run_id"]
|
|
258
|
+
self._event(task, "action_started", entry["reason"] or entry["action_id"],
|
|
259
|
+
action_id=entry["action_id"], parameters=entry["parameters"], run_id=entry["run_id"])
|
|
260
|
+
while True:
|
|
261
|
+
self._require_active(task)
|
|
262
|
+
evidence = machine.action_execution.snapshot(entry["run_id"])
|
|
263
|
+
if evidence["status"] != "running":
|
|
264
|
+
break
|
|
265
|
+
await asyncio.sleep(.05)
|
|
266
|
+
entry.update(evidence=evidence, after=self.observe(task))
|
|
267
|
+
self._event(task, "action_"+evidence["status"], f"{entry['action_id']}: {evidence['status']}",
|
|
268
|
+
evidence=evidence, observation=entry["after"])
|
|
269
|
+
return dict(evidence=evidence, current=entry["after"])
|
|
270
|
+
except ControlError as error:
|
|
271
|
+
entry["error"] = error.reason
|
|
272
|
+
self._event(task, "action_rejected", error.reason, action_id=entry["action_id"])
|
|
273
|
+
raise
|
|
274
|
+
if name == "finish_task":
|
|
275
|
+
outcome, summary = inputs.get("outcome"), inputs.get("summary")
|
|
276
|
+
ids = inputs.get("evidence_run_ids")
|
|
277
|
+
if outcome not in {"completed", "failed"} or not isinstance(summary, str) or not summary.strip() or len(summary) > 4000:
|
|
278
|
+
raise ControlError("invalid_task_result")
|
|
279
|
+
completed = {a["run_id"] for a in task.record["actions"] if a.get("evidence", {}).get("status") == "completed"}
|
|
280
|
+
if not isinstance(ids, list) or any(not isinstance(i, str) for i in ids) or not set(ids) <= completed:
|
|
281
|
+
raise ControlError("unknown_task_evidence")
|
|
282
|
+
if outcome == "completed" and (not ids or task.action_lock.locked()):
|
|
283
|
+
raise ControlError("task_completion_needs_evidence")
|
|
284
|
+
task.record["evidence_run_ids"] = ids
|
|
285
|
+
self._finish(task, outcome, "agent_verified_from_action_evidence" if outcome == "completed" else "agent_reported_failure", summary)
|
|
286
|
+
return self.get(task.record["task_id"], full=False)
|
|
287
|
+
raise ControlError("unsupported_task_tool")
|