mirror of
https://github.com/bytedance/deer-flow.git
synced 2026-07-27 08:28:00 +00:00
* feat(checkpoint): dual-mode checkpoint storage with LangGraph DeltaChannel
Add a restart-required database.checkpoint_channel_mode ("full" default,
"delta") that stores the messages channel via LangGraph 1.2 DeltaChannel,
cutting checkpoint storage from O(n^2) to O(n) for append-only history.
Existing full checkpoints seed delta state transparently; no data migration.
- config: mode schema + freeze-on-first-use with
CheckpointModeReconfigurationError; mode marker persisted in checkpoint
metadata; unsafe delta->full downgrade rejected fail-closed with
CheckpointModeMismatchError (run-level error, failed state read)
- state: delta message state schema; CheckpointStateAccessor centralizes
materialized reads for all consumers (threads API, branches,
regeneration, compaction, state updates, memory, goal workers)
- runtime: raw writers (run durations, interrupted title, thread goal)
parent their checkpoints to the checkpoint they derive from, preserving
delta ancestry; rollback forks the pre-run lineage through a state
mutation graph with Overwrite restores; InMemorySaver delta-history
override delegates to the base walk (fixes dropped first write after
migration, also present upstream)
- tests: conformance suite over {memory, sqlite, postgres} covering
migration replay, stable message IDs, storage shape and writer
preservation; conftest fixture isolates the frozen mode between tests;
stale config fakes refreshed
- ci: backend unit tests gain a postgres service
* fix(checkpoint): close materialization gaps in goal flow, guard public factory
- Route goal-continuation message reads through CheckpointStateAccessor:
raw channel_values reads see the delta sentinel in delta mode, which
disabled goal continuation (stand_down=no_durable_end_of_turn) after
durable assistant turns. Raw tuples remain for tuple-only metadata
(checkpoint id, pending_writes).
- Reject checkpoint_channel_mode='delta' + checkpointer in
create_deerflow_agent at construction: factory-built persisted graphs
bypass mode-marker injection and the fail-closed gate, reproducing
silent mixed-mode state loss. Delta without persistence stays allowed.
- Import the postgres saver lazily (pytest.importorskip in the fixture)
so the documented default install collects the suite; add a CI job
running pytest --collect-only on uv sync --group dev without extras.
- Fix test_checkpointer fallback test to patch get_app_config at its
use site (provider module), making it deterministic when a local
config.yaml selects a persistent backend.
* fix(gateway): preserve extension-owned channels in state mutations, bump config version
- build_state_mutation_graph / build_checkpoint_state_mutation_accessor
accept an explicit state_schema; branch and POST /state now compile the
mutation graph from the thread's effective schema
(graph_state_schema on the assistant graph). The base-ThreadState
fallback silently discarded channels contributed by custom
AgentMiddleware.state_schema on branch (data loss) and returned a
false-success 200 on POST /state.
- POST /state validates values keys against the mutation graph's
channels and rejects unknown fields with 422 instead of ignoring
them; reducer detection covers extension channels
(BinaryOperatorAggregate or DeltaChannel) so Overwrite replace
semantics work for middleware reducers in both modes.
- Endpoint regression: custom AgentMiddleware.state_schema value
survives branch, updates through POST /state, and an unknown field
receives 422.
- config_version 26 -> 27 for the new database.checkpoint_channel_mode
(example, Helm chart values + README, support-bundle fixture), so
existing installs get the outdated-config warning and
make config-upgrade merges the field; covered by a test driving the
real example file and the real config-upgrade script.
* fix(gateway): resolve assistant schema via one boundary, copy branch reducer values with Overwrite
GET /threads/{id}/state now resolves the thread's assistant_id through a
single reusable boundary (thread metadata -> assistant_id -> effective
graph), so channels contributed by a custom AgentMiddleware.state_schema
are materialized instead of dropped by the default lead schema. POST
/state uses the same boundary instead of resolving the schema ad hoc.
Branch writes wrap every copied reducer channel in Overwrite (derived
from the effective mutation graph: BinaryOperatorAggregate + DeltaChannel),
not just messages, so already-aggregated values are never re-merged.
Regression tests use a real AgentMiddleware.state_schema with a
non-identity reducer in both full and delta modes: GET /state returns the
extension value, POST /state replaces it, branch preserves it
byte-for-byte; the unknown-field 422 is a separate assertion.
* refactor(checkpoint): collapse read-path round-trips and ship dual-mode parity tests
Address review round 4 on PR #4292:
- Push ahistory/history limit through Pregel into checkpointer.alist
(SQL LIMIT) instead of materializing all rows and breaking in Python
- Fold the read-side mode-compat gate onto the returned snapshot's
metadata; only writes keep the pre-write tuple fetch (fail-closed)
- Cache factory-built accessor graphs per (assistant_id, mode) with
factory-identity revalidation; state reads no longer build a lead
agent per request
- get_thread: one snapshot fetch + one raw pending_writes fetch on the
resolved checkpoint (post-checkpoint __error__ writes never surface
in snapshot.tasks; verified empirically)
- DeerFlowClient.get_thread: single checkpointer.list walk collects
pending_writes per checkpoint instead of N get_tuple calls
- InMemorySaver delta-history patch: stand-down when the upstream
override disappears, try/except guard, validated-version warning,
guard tests
- make_lead_agent mode precedence: first freeze is owned by app_config
(client-supplied configurable key ignored); once frozen, injected
key/app_config must match or fail closed
- Rollback: lock in non-message channel restoration via fork
inheritance with a dedicated reducer-channel test
- Add tests/test_threads_checkpoint_mode.py and
tests/test_gateway_checkpoint_mode.py referenced by AGENTS.md and
the PR validation section: lifecycle parity (memory + sqlite),
per-step blob-count storage guard, gateway endpoint parity
Counted-saver tests pin checkpoint round-trips for aget/ahistory so
these regressions cannot silently return.
* fix(checkpoint): precise mode-mismatch HTTP mapping, gate E2E, and accessor resilience
- threads router: map CheckpointModeMismatchError to 409 (with cause and
thread id) and CheckpointModeReconfigurationError to 503 across all state
endpoints instead of swallowing both into a generic 500
- gate coverage: seed a real delta checkpoint into AsyncSqliteSaver and
assert aget/aupdate/ahistory fail closed; assert 409 at the HTTP boundary
through the real route stack
- rollback: compile the restore mutation graph with the thread's effective
state schema per the build_state_mutation_graph contract
- inheritance contract locks: rollback and manual compaction preserve
middleware-contributed channels via checkpoint fork cloning
- services: revalidate the accessor-graph cache against app_config identity
so config.yaml hot-reloads never serve a stale compiled graph
- services: degrade full-mode state reads to raw checkpointer reads when the
agent factory is unavailable (delta gate still applies; delta mode has no
fallback)
- deps: override websockets==16.0 (langgraph-sdk 0.4.2's <16 pin silently
downgraded 16.0 -> 15.0.1; pin is not grounded in any API incompatibility)
and bump the langchain lower bound to what the lockfile actually resolves
* fix(checkpoint): include anchor checkpoint in degraded history walk + cover get_thread
- _RawCheckpointReadAccessor.ahistory: alist(before=...) is exclusive while
pregel's get_state_history treats config.checkpoint_id as the inclusive
start; fetch the anchor explicitly so both read paths paginate identically
- extend the degraded-path gateway test: GET /thread returns raw values, and
POST /history with before starts at the anchor checkpoint
* fix(gateway): preserve degraded checkpoint timestamps
* fix(gateway): harden degraded checkpoint access
* fix(gateway): resolve assistants for checkpoint reads
---------
Co-authored-by: Willem Jiang <willem.jiang@gmail.com>
568 lines
22 KiB
Python
568 lines
22 KiB
Python
"""Thread-scoped goal state and evaluator helpers.
|
|
|
|
This module implements the Claude Code-style goal loop primitives used by
|
|
Gateway runs and thin API surfaces. It intentionally lives in ``deerflow`` so
|
|
the harness can evaluate and continue runs without importing the FastAPI app.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import copy
|
|
import hashlib
|
|
import inspect
|
|
import json
|
|
import logging
|
|
import os
|
|
import threading
|
|
import weakref
|
|
from collections.abc import AsyncIterator
|
|
from contextlib import asynccontextmanager
|
|
from typing import Any, Literal, NamedTuple
|
|
|
|
from langchain_core.messages import HumanMessage, SystemMessage
|
|
from langgraph.checkpoint.base import empty_checkpoint, uuid6
|
|
|
|
import deerflow.utils.llm_text as llm_text
|
|
from deerflow.agents.goal_state import GoalBlocker, GoalEvaluation, GoalState
|
|
from deerflow.models import create_chat_model
|
|
from deerflow.tracing import inject_langfuse_metadata
|
|
from deerflow.utils.messages import message_to_text
|
|
from deerflow.utils.time import now_iso
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
DEFAULT_MAX_GOAL_CONTINUATIONS = 8
|
|
DEFAULT_MAX_NO_PROGRESS_CONTINUATIONS = 2
|
|
MAX_GOAL_OBJECTIVE_CHARS = 4000
|
|
MAX_GOAL_REASON_CHARS = 1000
|
|
MAX_GOAL_EVIDENCE_CHARS = 1000
|
|
MAX_GOAL_CONVERSATION_CHARS = 12000
|
|
MAX_GOAL_CONVERSATION_MESSAGES = 30
|
|
|
|
GOAL_BLOCKERS: set[GoalBlocker] = {
|
|
"none",
|
|
"missing_evidence",
|
|
"needs_user_input",
|
|
"run_failed",
|
|
"external_wait",
|
|
"goal_not_met_yet",
|
|
}
|
|
CONTINUABLE_GOAL_BLOCKERS: set[GoalBlocker] = {"goal_not_met_yet"}
|
|
|
|
GOAL_CLEAR_ALIASES = frozenset({"clear", "reset", "off"})
|
|
|
|
_extract_response_text = llm_text.extract_response_text
|
|
_strip_markdown_code_fence = llm_text.strip_markdown_code_fence
|
|
_strip_think_blocks = llm_text.strip_think_blocks
|
|
|
|
_goal_locks_guard = threading.Lock()
|
|
_goal_locks_by_loop: weakref.WeakKeyDictionary[asyncio.AbstractEventLoop, dict[str, asyncio.Lock]] = weakref.WeakKeyDictionary()
|
|
|
|
|
|
class GoalWriteConflict(RuntimeError):
|
|
"""Raised when a goal write is based on a stale checkpoint."""
|
|
|
|
|
|
@asynccontextmanager
|
|
async def goal_thread_lock(thread_id: str) -> AsyncIterator[None]:
|
|
"""Serialize goal read-modify-write sequences within the current event loop."""
|
|
loop = asyncio.get_running_loop()
|
|
with _goal_locks_guard:
|
|
locks = _goal_locks_by_loop.get(loop)
|
|
if locks is None:
|
|
locks = {}
|
|
_goal_locks_by_loop[loop] = locks
|
|
lock = locks.get(thread_id)
|
|
if lock is None:
|
|
lock = asyncio.Lock()
|
|
locks[thread_id] = lock
|
|
|
|
async with lock:
|
|
yield
|
|
|
|
|
|
class GoalCommand(NamedTuple):
|
|
"""Parsed intent of a ``/goal`` slash command argument string."""
|
|
|
|
kind: Literal["status", "clear", "set"]
|
|
objective: str = ""
|
|
|
|
|
|
def parse_goal_command(args: str) -> GoalCommand:
|
|
"""Parse the argument string of a ``/goal`` command into an intent.
|
|
|
|
Shared by the TUI and IM-channel surfaces so the three-way semantics stay in
|
|
one place: empty shows the active goal, ``clear``/``reset``/``off`` clears it,
|
|
and anything else sets the goal to that (trimmed) objective. The frontend
|
|
keeps a parallel TypeScript copy in ``input-box-helpers.ts``.
|
|
"""
|
|
stripped = args.strip()
|
|
if not stripped:
|
|
return GoalCommand("status")
|
|
if stripped.lower() in GOAL_CLEAR_ALIASES:
|
|
return GoalCommand("clear")
|
|
return GoalCommand("set", stripped)
|
|
|
|
|
|
def normalize_goal_objective(objective: str) -> str:
|
|
"""Normalize and validate user-provided goal text."""
|
|
normalized = " ".join(objective.strip().split())
|
|
if not normalized:
|
|
raise ValueError("Goal objective must not be empty.")
|
|
if len(normalized) > MAX_GOAL_OBJECTIVE_CHARS:
|
|
raise ValueError(f"Goal objective must be at most {MAX_GOAL_OBJECTIVE_CHARS} characters.")
|
|
return normalized
|
|
|
|
|
|
def build_goal_state(
|
|
objective: str,
|
|
*,
|
|
max_continuations: int = DEFAULT_MAX_GOAL_CONTINUATIONS,
|
|
max_no_progress_continuations: int = DEFAULT_MAX_NO_PROGRESS_CONTINUATIONS,
|
|
now: str | None = None,
|
|
) -> GoalState:
|
|
"""Create a fresh active goal state for a thread."""
|
|
objective = normalize_goal_objective(objective)
|
|
capped_max = max(0, min(int(max_continuations), DEFAULT_MAX_GOAL_CONTINUATIONS))
|
|
timestamp = now or now_iso()
|
|
return GoalState(
|
|
objective=objective,
|
|
status="active",
|
|
created_at=timestamp,
|
|
updated_at=timestamp,
|
|
continuation_count=0,
|
|
max_continuations=capped_max,
|
|
no_progress_count=0,
|
|
max_no_progress_continuations=max(0, int(max_no_progress_continuations)),
|
|
)
|
|
|
|
|
|
def parse_goal_evaluation_response(text: str) -> GoalEvaluation:
|
|
"""Parse the evaluator's JSON object response."""
|
|
candidate = _strip_markdown_code_fence(_strip_think_blocks(text))
|
|
start = candidate.find("{")
|
|
end = candidate.rfind("}")
|
|
if start == -1 or end == -1 or end <= start:
|
|
raise ValueError("Goal evaluator response did not contain a JSON object.")
|
|
try:
|
|
payload = json.loads(candidate[start : end + 1])
|
|
except Exception as exc:
|
|
raise ValueError("Goal evaluator response was not valid JSON.") from exc
|
|
if not isinstance(payload, dict):
|
|
raise ValueError("Goal evaluator JSON must be an object.")
|
|
satisfied = payload.get("satisfied")
|
|
if not isinstance(satisfied, bool):
|
|
raise ValueError("Goal evaluator JSON must include boolean 'satisfied'.")
|
|
reason = _normalize_evaluation_text(payload.get("reason"), max_chars=MAX_GOAL_REASON_CHARS)
|
|
evidence_summary = _normalize_evaluation_text(payload.get("evidence_summary"), max_chars=MAX_GOAL_EVIDENCE_CHARS)
|
|
blocker = _normalize_goal_blocker(payload.get("blocker"), satisfied=satisfied)
|
|
return GoalEvaluation(
|
|
satisfied=satisfied,
|
|
blocker=blocker,
|
|
reason=reason,
|
|
evidence_summary=evidence_summary,
|
|
)
|
|
|
|
|
|
def _normalize_evaluation_text(value: object, *, max_chars: int) -> str:
|
|
if not isinstance(value, str):
|
|
return ""
|
|
return " ".join(value.strip().split())[:max_chars]
|
|
|
|
|
|
def _normalize_goal_blocker(value: object, *, satisfied: bool) -> GoalBlocker:
|
|
if satisfied:
|
|
return "none"
|
|
if isinstance(value, str) and value in GOAL_BLOCKERS and value != "none":
|
|
return value
|
|
return "missing_evidence"
|
|
|
|
|
|
def _message_type(message: Any) -> str | None:
|
|
value = getattr(message, "type", None)
|
|
if value is None and isinstance(message, dict):
|
|
value = message.get("type") or message.get("role")
|
|
if value == "assistant":
|
|
return "ai"
|
|
if value == "user":
|
|
return "human"
|
|
return str(value) if value else None
|
|
|
|
|
|
def _additional_kwargs(message: Any) -> dict[str, Any]:
|
|
value = getattr(message, "additional_kwargs", None)
|
|
if value is None and isinstance(message, dict):
|
|
value = message.get("additional_kwargs")
|
|
return dict(value) if isinstance(value, dict) else {}
|
|
|
|
|
|
def _is_visible_message(message: Any) -> bool:
|
|
if _additional_kwargs(message).get("hide_from_ui") is True:
|
|
return False
|
|
return _message_type(message) in {"human", "ai"}
|
|
|
|
|
|
def has_visible_assistant_evidence(messages: list[Any]) -> bool:
|
|
"""Return true when the evaluator can inspect at least one visible AI reply."""
|
|
return any(_is_visible_message(message) and _message_type(message) == "ai" and bool(message_to_text(message).strip()) for message in messages)
|
|
|
|
|
|
def visible_conversation_signature(messages: list[Any]) -> str:
|
|
"""Return a stable lightweight signature for the visible evaluator evidence."""
|
|
visible = []
|
|
for message in messages:
|
|
if not _is_visible_message(message):
|
|
continue
|
|
visible.append(
|
|
{
|
|
"role": _message_type(message),
|
|
"text": message_to_text(message).strip(),
|
|
}
|
|
)
|
|
return json.dumps(visible[-MAX_GOAL_CONVERSATION_MESSAGES:], ensure_ascii=False, sort_keys=True)
|
|
|
|
|
|
def format_visible_conversation(messages: list[Any]) -> str:
|
|
"""Return the user-visible conversation evidence for goal evaluation."""
|
|
lines: list[str] = []
|
|
visible = [message for message in messages if _is_visible_message(message)]
|
|
for message in visible[-MAX_GOAL_CONVERSATION_MESSAGES:]:
|
|
text = message_to_text(message).strip()
|
|
if not text:
|
|
continue
|
|
role = "User" if _message_type(message) == "human" else "Assistant"
|
|
lines.append(f"{role}: {text}")
|
|
conversation = "\n\n".join(lines)
|
|
if len(conversation) > MAX_GOAL_CONVERSATION_CHARS:
|
|
conversation = conversation[-MAX_GOAL_CONVERSATION_CHARS:]
|
|
return conversation
|
|
|
|
|
|
def create_goal_evaluator_model(
|
|
*,
|
|
model_name: str | None = None,
|
|
app_config: Any | None = None,
|
|
) -> Any:
|
|
"""Create the non-thinking chat model used by the goal evaluator.
|
|
|
|
The evaluator runs from ``runtime/runs/worker.py`` after the main graph
|
|
run has already completed, so — unlike ``make_lead_agent``/
|
|
``DeerFlowClient.stream``, which attach ``build_tracing_callbacks()`` at
|
|
the graph root and correctly pass ``attach_tracing=False`` to avoid
|
|
double-attaching — there is no graph root here for the evaluator's model
|
|
call to inherit tracing from. It must attach its own model-level tracing
|
|
callbacks, same as the other standalone, non-graph callers
|
|
(``oneshot_llm.run_oneshot_llm``, ``MemoryUpdater``).
|
|
"""
|
|
return create_chat_model(
|
|
name=model_name,
|
|
thinking_enabled=False,
|
|
app_config=app_config,
|
|
attach_tracing=True,
|
|
)
|
|
|
|
|
|
def _resolve_environment() -> str | None:
|
|
return os.environ.get("DEER_FLOW_ENV") or os.environ.get("ENVIRONMENT")
|
|
|
|
|
|
async def evaluate_goal_completion(
|
|
goal: GoalState,
|
|
messages: list[Any],
|
|
*,
|
|
model: Any | None = None,
|
|
model_name: str | None = None,
|
|
app_config: Any | None = None,
|
|
thread_id: str | None = None,
|
|
user_id: str | None = None,
|
|
deerflow_trace_id: str | None = None,
|
|
) -> GoalEvaluation:
|
|
"""Ask a small non-thinking model whether the active goal is satisfied.
|
|
|
|
``thread_id``/``user_id``/``deerflow_trace_id`` are forwarded to Langfuse
|
|
trace metadata only (mirrors ``oneshot_llm.run_oneshot_llm``): this is a
|
|
standalone model call outside the main graph, so it must inject its own
|
|
Langfuse session/user attribution instead of relying on graph-root
|
|
callbacks to lift it — same fix as PR #2944 (main graph) and PR #3902
|
|
(memory_agent/suggest_agent).
|
|
"""
|
|
conversation = format_visible_conversation(messages)
|
|
if not conversation or not has_visible_assistant_evidence(messages):
|
|
return GoalEvaluation(
|
|
satisfied=False,
|
|
blocker="missing_evidence",
|
|
reason="No visible assistant evidence is available yet.",
|
|
evidence_summary="",
|
|
)
|
|
|
|
system_instruction = (
|
|
"You are a strict completion evaluator for an AI coding assistant.\n"
|
|
"Decide whether the active goal is fully satisfied using ONLY the visible conversation evidence.\n"
|
|
"Do not assume files, commands, tests, or external state changed unless the conversation explicitly shows it.\n"
|
|
"If the visible evidence is too weak to prove progress, fail closed with blocker missing_evidence.\n"
|
|
"Use blocker needs_user_input when the assistant is waiting on the user, run_failed when the turn failed, "
|
|
"external_wait when work is waiting on an outside system, goal_not_met_yet when useful autonomous work can continue, "
|
|
"and none only when satisfied is true.\n"
|
|
'Output exactly one JSON object: {"satisfied": boolean, "blocker": string, "reason": string, "evidence_summary": string}.'
|
|
)
|
|
user_content = f"Active goal:\n{goal['objective']}\n\nVisible conversation evidence:\n{conversation}\n\nIs the active goal fully satisfied?"
|
|
|
|
if model is None:
|
|
model = create_goal_evaluator_model(model_name=model_name, app_config=app_config)
|
|
invoke_config: dict[str, Any] = {"run_name": "goal_evaluator"}
|
|
inject_langfuse_metadata(
|
|
invoke_config,
|
|
thread_id=thread_id,
|
|
user_id=user_id,
|
|
assistant_id="goal_evaluator",
|
|
model_name=model_name,
|
|
environment=_resolve_environment(),
|
|
deerflow_trace_id=deerflow_trace_id,
|
|
)
|
|
response = await model.ainvoke(
|
|
[SystemMessage(content=system_instruction), HumanMessage(content=user_content)],
|
|
config=invoke_config,
|
|
)
|
|
return parse_goal_evaluation_response(_extract_response_text(response.content))
|
|
|
|
|
|
def should_continue_goal(goal: GoalState, evaluation: GoalEvaluation, *, no_progress_count: int | None = None) -> bool:
|
|
"""Return whether another hidden continuation turn should run."""
|
|
if evaluation["satisfied"]:
|
|
return False
|
|
if evaluation["blocker"] not in CONTINUABLE_GOAL_BLOCKERS:
|
|
return False
|
|
if int(goal.get("continuation_count", 0)) >= int(goal.get("max_continuations", DEFAULT_MAX_GOAL_CONTINUATIONS)):
|
|
return False
|
|
current_no_progress = int(goal.get("no_progress_count", 0) if no_progress_count is None else no_progress_count)
|
|
max_no_progress = int(goal.get("max_no_progress_continuations", DEFAULT_MAX_NO_PROGRESS_CONTINUATIONS))
|
|
return current_no_progress < max_no_progress
|
|
|
|
|
|
def latest_visible_assistant_signature(messages: list[Any]) -> str:
|
|
"""Return a stable signature of the latest visible assistant evidence.
|
|
|
|
The "no progress" breaker keys on what the agent actually produced — the
|
|
text of the most recent user-visible assistant message — not on the
|
|
evaluator's free-text ``reason``/``evidence_summary`` (which an LLM rewords
|
|
on every turn, so it almost never repeats byte-for-byte). When a
|
|
continuation adds no new visible assistant output, the signature is
|
|
unchanged and the breaker can recognise the stalled turn.
|
|
"""
|
|
for message in reversed(messages):
|
|
if not _is_visible_message(message) or _message_type(message) != "ai":
|
|
continue
|
|
text = message_to_text(message).strip()
|
|
if text:
|
|
return hashlib.sha256(text.encode("utf-8")).hexdigest()
|
|
return ""
|
|
|
|
|
|
def compute_goal_progress_key(evaluation: GoalEvaluation, *, evidence_signature: str = "") -> str:
|
|
"""Return a stable key used to detect repeated non-progress evaluations.
|
|
|
|
Keyed on the typed ``blocker`` plus a signature of the visible assistant
|
|
evidence, so a stalled goal is detected even when the evaluator rewords its
|
|
free-text ``reason``/``evidence_summary``.
|
|
"""
|
|
return json.dumps(
|
|
{
|
|
"satisfied": evaluation["satisfied"],
|
|
"blocker": evaluation["blocker"],
|
|
"evidence_signature": evidence_signature,
|
|
},
|
|
ensure_ascii=False,
|
|
sort_keys=True,
|
|
)
|
|
|
|
|
|
def compute_no_progress_count(goal: GoalState, evaluation: GoalEvaluation, *, evidence_signature: str = "") -> int:
|
|
"""Increment repeated-progress count when visible evidence has not advanced."""
|
|
if evaluation["satisfied"]:
|
|
return 0
|
|
progress_key = compute_goal_progress_key(evaluation, evidence_signature=evidence_signature)
|
|
previous = goal.get("last_evaluation", {})
|
|
if isinstance(previous, dict) and previous.get("progress_key") == progress_key:
|
|
return int(goal.get("no_progress_count", 0)) + 1
|
|
return 0
|
|
|
|
|
|
def make_goal_continuation_message(goal: GoalState, evaluation: GoalEvaluation) -> HumanMessage:
|
|
"""Build the hidden user message that asks the agent to keep working."""
|
|
content = (
|
|
"<goal_continuation>\n"
|
|
f"Active goal: {goal['objective']}\n"
|
|
f"Evaluator result: not satisfied. Blocker: {evaluation['blocker']}. Reason: {evaluation['reason'] or 'No reason provided.'}\n"
|
|
f"Visible evidence: {evaluation.get('evidence_summary') or 'No evidence summary provided.'}\n"
|
|
"Continue working toward the active goal. Use the available tools and conversation context. "
|
|
"Do not ask the user to continue unless you are genuinely blocked.\n"
|
|
"</goal_continuation>"
|
|
)
|
|
return HumanMessage(
|
|
content=content,
|
|
additional_kwargs={
|
|
"hide_from_ui": True,
|
|
"deerflow_goal_continuation": True,
|
|
},
|
|
)
|
|
|
|
|
|
async def _call_checkpointer_method(checkpointer: Any, async_name: str, sync_name: str, *args: Any, **kwargs: Any) -> Any:
|
|
async_method = getattr(checkpointer, async_name, None)
|
|
if async_method is not None:
|
|
result = async_method(*args, **kwargs)
|
|
return await result if inspect.isawaitable(result) else result
|
|
sync_method = getattr(checkpointer, sync_name, None)
|
|
if sync_method is None:
|
|
raise AttributeError(f"Missing checkpointer method: {async_name}/{sync_name}")
|
|
# Offload the synchronous checkpointer call so its blocking IO never runs on
|
|
# the event loop (backend/AGENTS.md blocking-IO gate).
|
|
result = await asyncio.to_thread(sync_method, *args, **kwargs)
|
|
return await result if inspect.isawaitable(result) else result
|
|
|
|
|
|
def _next_channel_version(checkpointer: Any, current_version: Any) -> Any:
|
|
get_next_version = getattr(checkpointer, "get_next_version", None)
|
|
if callable(get_next_version):
|
|
return get_next_version(current_version, None)
|
|
if isinstance(current_version, int):
|
|
return current_version + 1
|
|
return 1
|
|
|
|
|
|
async def ensure_thread_checkpoint(checkpointer: Any, thread_id: str) -> None:
|
|
"""Create an empty root checkpoint for *thread_id* when none exists."""
|
|
config = {"configurable": {"thread_id": thread_id, "checkpoint_ns": ""}}
|
|
checkpoint_tuple = await _call_checkpointer_method(checkpointer, "aget_tuple", "get_tuple", config)
|
|
if checkpoint_tuple is not None:
|
|
return
|
|
metadata = {
|
|
"step": -1,
|
|
"source": "input",
|
|
"writes": None,
|
|
"parents": {},
|
|
"created_at": now_iso(),
|
|
}
|
|
await _call_checkpointer_method(checkpointer, "aput", "put", config, empty_checkpoint(), metadata, {})
|
|
|
|
|
|
def _checkpoint_id_from_tuple(checkpoint_tuple: Any) -> str | None:
|
|
config = getattr(checkpoint_tuple, "config", {}) or {}
|
|
configurable = config.get("configurable", {}) if isinstance(config, dict) else {}
|
|
checkpoint_id = configurable.get("checkpoint_id") if isinstance(configurable, dict) else None
|
|
if isinstance(checkpoint_id, str):
|
|
return checkpoint_id
|
|
checkpoint = getattr(checkpoint_tuple, "checkpoint", {}) or {}
|
|
if isinstance(checkpoint, dict) and isinstance(checkpoint.get("id"), str):
|
|
return checkpoint["id"]
|
|
return None
|
|
|
|
|
|
async def read_thread_goal(checkpointer: Any, thread_id: str) -> GoalState | None:
|
|
"""Read the latest thread goal from checkpoint state."""
|
|
config = {"configurable": {"thread_id": thread_id, "checkpoint_ns": ""}}
|
|
checkpoint_tuple = await _call_checkpointer_method(checkpointer, "aget_tuple", "get_tuple", config)
|
|
if checkpoint_tuple is None:
|
|
return None
|
|
checkpoint = getattr(checkpoint_tuple, "checkpoint", {}) or {}
|
|
channel_values = checkpoint.get("channel_values", {}) if isinstance(checkpoint, dict) else {}
|
|
raw_goal = channel_values.get("goal") if isinstance(channel_values, dict) else None
|
|
return copy.deepcopy(raw_goal) if isinstance(raw_goal, dict) else None
|
|
|
|
|
|
async def write_thread_goal(
|
|
checkpointer: Any,
|
|
thread_id: str,
|
|
goal: GoalState | None,
|
|
*,
|
|
as_node: str = "goal",
|
|
create_if_missing: bool = False,
|
|
expected_checkpoint_id: str | None = None,
|
|
) -> dict[str, Any]:
|
|
"""Write a new checkpoint with the thread goal set or cleared.
|
|
|
|
Returns the updated channel values.
|
|
"""
|
|
if create_if_missing:
|
|
await ensure_thread_checkpoint(checkpointer, thread_id)
|
|
|
|
read_config: dict[str, Any] = {
|
|
"configurable": {
|
|
"thread_id": thread_id,
|
|
"checkpoint_ns": "",
|
|
}
|
|
}
|
|
checkpoint_tuple = await _call_checkpointer_method(checkpointer, "aget_tuple", "get_tuple", read_config)
|
|
if checkpoint_tuple is None:
|
|
raise LookupError(f"Thread {thread_id} checkpoint not found")
|
|
if expected_checkpoint_id is not None and _checkpoint_id_from_tuple(checkpoint_tuple) != expected_checkpoint_id:
|
|
raise GoalWriteConflict(f"Thread {thread_id} goal checkpoint changed while preparing write")
|
|
|
|
checkpoint: dict[str, Any] = dict(getattr(checkpoint_tuple, "checkpoint", {}) or {})
|
|
metadata: dict[str, Any] = dict(getattr(checkpoint_tuple, "metadata", {}) or {})
|
|
channel_values: dict[str, Any] = dict(checkpoint.get("channel_values", {}) or {})
|
|
|
|
if goal is None:
|
|
channel_values.pop("goal", None)
|
|
else:
|
|
channel_values["goal"] = copy.deepcopy(goal)
|
|
|
|
channel_versions = dict(checkpoint.get("channel_versions", {}) or {})
|
|
current_version = channel_versions.get("goal")
|
|
next_version = _next_channel_version(checkpointer, current_version)
|
|
channel_versions["goal"] = next_version
|
|
|
|
checkpoint["channel_values"] = channel_values
|
|
checkpoint["channel_versions"] = channel_versions
|
|
checkpoint["id"] = str(uuid6())
|
|
metadata["updated_at"] = now_iso()
|
|
metadata["source"] = "update"
|
|
metadata["step"] = metadata.get("step", 0) + 1
|
|
metadata["writes"] = {as_node: {"goal": goal}}
|
|
|
|
write_config = {
|
|
"configurable": {
|
|
"thread_id": thread_id,
|
|
"checkpoint_ns": "",
|
|
# Parent the new checkpoint to the one it was derived from.
|
|
# Without this the saver stores a parentless checkpoint, which
|
|
# severs Delta-channel replay ancestry (and truncates history
|
|
# walks in full mode too).
|
|
"checkpoint_id": _checkpoint_id_from_tuple(checkpoint_tuple),
|
|
}
|
|
}
|
|
await _call_checkpointer_method(checkpointer, "aput", "put", write_config, checkpoint, metadata, {"goal": next_version})
|
|
return channel_values
|
|
|
|
|
|
def attach_goal_evaluation(
|
|
goal: GoalState,
|
|
evaluation: GoalEvaluation,
|
|
*,
|
|
run_id: str,
|
|
continuation_count: int | None = None,
|
|
no_progress_count: int | None = None,
|
|
stand_down_reason: str | None = None,
|
|
evidence_signature: str = "",
|
|
) -> GoalState:
|
|
"""Return a goal copy with the latest evaluator result attached."""
|
|
next_goal = copy.deepcopy(goal)
|
|
if continuation_count is not None:
|
|
next_goal["continuation_count"] = continuation_count
|
|
if no_progress_count is not None:
|
|
next_goal["no_progress_count"] = no_progress_count
|
|
next_goal["updated_at"] = now_iso()
|
|
next_goal["last_evaluation"] = {
|
|
"satisfied": evaluation["satisfied"],
|
|
"blocker": evaluation["blocker"],
|
|
"reason": evaluation["reason"],
|
|
"evidence_summary": evaluation.get("evidence_summary", ""),
|
|
"run_id": run_id,
|
|
"evaluated_at": next_goal["updated_at"],
|
|
"progress_key": compute_goal_progress_key(evaluation, evidence_signature=evidence_signature),
|
|
}
|
|
if stand_down_reason:
|
|
next_goal["last_evaluation"]["stand_down_reason"] = stand_down_reason
|
|
return next_goal
|