Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions loopx/capabilities/manager_context/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -350,7 +350,10 @@ def evidence_goal_scope(runtime_root: Path, channel: str, *, registry_path: Path
def _require_external_channel(channel: str) -> None:
# Legacy manager connections and native App/source bindings both identify
# one exact audience. Never accept a prefix or a partially specified binding.
if not re.fullmatch(r"manager\.external\.(?:[a-f0-9]{24}|native\.[a-f0-9]{24}\.[a-f0-9]{24})", channel):
if not re.fullmatch(
r"manager\.external\.(?:[a-f0-9]{24}|native\.[a-f0-9]{24}\.[a-f0-9]{24}(?:\.topic\.[a-f0-9]{24})?)",
channel,
):
raise ValueError("an exact external manager channel is required")


Expand Down Expand Up @@ -474,7 +477,10 @@ def configure_delivery_scope(runtime_root: Path, *, channel: str,
local_delivery_scope: str, sender_id: str | None = None,
execute: bool = False, if_absent: bool = False) -> dict:
"""One owner policy for current/future registered recipients, not execution."""
if not re.fullmatch(r"manager\.external\.(?:[a-f0-9]{24}|native\.[a-f0-9]{24}\.[a-f0-9]{24})", channel):
if not re.fullmatch(
r"manager\.external\.(?:[a-f0-9]{24}|native\.[a-f0-9]{24}\.[a-f0-9]{24}(?:\.topic\.[a-f0-9]{24})?)",
channel,
):
raise ValueError("an exact external manager channel is required")
path = _root(runtime_root) / "policy.json"

Expand Down
19 changes: 12 additions & 7 deletions loopx/capabilities/native_chat/conversation_bindings.py
Original file line number Diff line number Diff line change
Expand Up @@ -212,9 +212,11 @@ def _reconcile_steward_executor(self, row: dict[str, Any], defaults: Mapping[str
binding_id = row["binding_id"]
endpoint = defaults["executor_endpoint"]
channel_prefix = f"manager.external.native.{binding_id}."
candidates = [s for s in store.list_sessions()
if s.get("channel_id", "").startswith(channel_prefix) and s.get("status") != "closed"]
if len(candidates) != 1 or candidates[0].get("agent_id") != endpoint or candidates[0].get("status") != "ready":
all_open = [s for s in store.list_sessions()
if s.get("channel_id", "").startswith(channel_prefix) and s.get("status") != "closed"]
candidates = [s for s in all_open if not (s.get("steward_context") or {}).get("topic_ref")]
if (len(candidates) != 1 or candidates[0].get("agent_id") != endpoint or candidates[0].get("status") != "ready"
or any(s.get("status") != "ready" or s.get("active_turn_id") is not None for s in all_open)):
return # Defaults alone do not retarget an existing session.
observation = self.observe(row["transport_ref"])
with exclusive_file_lock(self.path, operation="reconcile_steward_executor"):
Expand Down Expand Up @@ -369,8 +371,9 @@ def resolve(self, *, binding_id: str, source_ref: str, sender_ref: str,
**({"origin": origin} if origin is not None else {}),
**({"session_context": session_context} if session_context is not None else {}),
**({"session": self._session_observation(session)} if session is not None else {}),
**({"group_ref": group_ref, "topic_ref": topic_ref,
"group_human_message": group_human_message} if group_ref is not None or topic_ref is not None or group_human_message else {}),
**({"group_ref": group_ref} if group_ref is not None else {}),
**({"topic_ref": topic_ref} if topic_ref is not None else {}),
**({"group_human_message": group_human_message} if group_ref is not None or group_human_message else {}),
})
# Presentation may need the name from this exact verified read. Keep it
# outside the persisted context and opt-in; it is never a cached grant
Expand All @@ -395,7 +398,8 @@ def input_context(self, saved: dict[str, Any], *, origin: str, session: dict[str
"""
if origin == "web":
source = {"source_ref": saved["source_ref"], "sender_ref": saved["operator_ref"],
"private_human_message": False, "origin": "web", "session_context": saved}
"private_human_message": False, "origin": "web", "session_context": saved,
**({"topic_ref": saved["topic_ref"]} if saved.get("topic_ref") else {})}
elif origin in {"lark", "external"}:
source = self._session_source(saved)
else:
Expand Down Expand Up @@ -539,7 +543,8 @@ def _session_source(saved: dict[str, Any]) -> dict[str, Any]:
"private_human_message": False, "group_ref": saved["group_ref"],
"topic_ref": saved["topic_ref"], "group_human_message": True, "session_context": saved}
return {"source_ref": saved["source_ref"], "sender_ref": saved["operator_ref"],
"private_human_message": True, "session_context": saved}
"private_human_message": True, "session_context": saved,
**({"topic_ref": saved["topic_ref"]} if saved.get("topic_ref") else {})}

def session_context(self, saved: dict[str, Any], *, session: dict[str, Any] | None = None) -> dict[str, Any]:
return self.resolve(binding_id=saved["binding_id"], session=session, **self._session_source(saved))
Expand Down
3 changes: 2 additions & 1 deletion loopx/capabilities/native_chat/external_conversations.py
Original file line number Diff line number Diff line change
Expand Up @@ -1453,6 +1453,7 @@ def capture_native_mention(self, binding: dict[str, Any], source: dict[str, Any]
allocation = session.get("manager_executor_allocation") or {}
if (saved.get("binding_id") == binding["binding_id"]
and saved.get("source_ref") == source["source_ref"]
and (saved.get("topic_ref") or None) == (source.get("topic_ref") or None)
and session.get("status") in RESUMABLE_SESSION_STATES
and (session.get("agent_id") == binding["executor_endpoint_id"]
or binding["context_kind"] == "steward" and allocation.get("selection_policy") == "flexible")):
Expand Down Expand Up @@ -1482,7 +1483,7 @@ def admit(self, *, binding_id: str, source: dict[str, Any], request_ref: str,
# These references enter the lock path before authority is resolved.
# Check path-safe shape here; the typed owner checks current grants
# and provider identity after both fences are acquired.
for ref in (binding_id, source.get("source_ref")):
for ref in (binding_id, source.get("source_ref"), *([source["topic_ref"]] if "topic_ref" in source else ())):
if not isinstance(ref, str) or not _REQUEST_JOURNAL_STEM.fullmatch(ref):
raise ValueError("invalid external conversation source reference")
path = self.root / f"{request_ref}.json"
Expand Down
75 changes: 67 additions & 8 deletions loopx/capabilities/native_chat/session_queue.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,63 @@
"""The existing same-Session FIFO, preparation and recovery consumer."""
from collections.abc import Iterator
from contextlib import contextmanager
import os
from pathlib import Path
from typing import Any
import threading

from ...chat_store import CHAT_SESSION_MODE_ATTACHED, TERMINAL_TURN_STATES

STEWARD_MAX_CONCURRENT_LANES_DEFAULT = 4


def _resolve_steward_max_concurrent_lanes(controller: Any) -> int:
configured = getattr(controller, "max_steward_concurrent_lanes", None)
if isinstance(configured, int) and not isinstance(configured, bool) and 1 <= configured <= 32:
return configured
raw_env = os.environ.get("LOOPX_STEWARD_MAX_CONCURRENT_LANES", "").strip()
if raw_env.isdigit():
parsed = int(raw_env)
if 1 <= parsed <= 32:
return parsed
return STEWARD_MAX_CONCURRENT_LANES_DEFAULT


def _steward_lane_semaphore(controller: Any) -> tuple[threading.BoundedSemaphore, int]:
limit = _resolve_steward_max_concurrent_lanes(controller)
with controller.lock:
current = getattr(controller, "_steward_lane_semaphore_state", None)
if current is None or current[1] != limit:
current = (threading.BoundedSemaphore(limit), limit)
controller._steward_lane_semaphore_state = current
return current


@contextmanager
def _acquire_steward_lane_slot(controller: Any, session: dict[str, Any] | None, turn: dict[str, Any] | None) -> Iterator[None]:
"""Bound concurrent active upstream model Turns across Steward Topic Lanes."""
channel_id = str((session or {}).get("channel_id") or "")
if (
not session
or not isinstance(session.get("steward_context"), dict)
or not channel_id.startswith("manager.external.native.")
or _is_observation_only_monitor_turn(turn)
):
yield
return
semaphore, _ = _steward_lane_semaphore(controller)
acquired = False
while not controller.closed.is_set():
if semaphore.acquire(timeout=0.05):
acquired = True
break
if not acquired:
raise RuntimeError("chat runtime closed before steward lane slot acquisition")
try:
yield
finally:
semaphore.release()


def _is_observation_only_monitor_turn(turn: dict[str, Any] | None) -> bool:
"""Return True only for native no-model monitor turns."""
Expand Down Expand Up @@ -163,14 +216,20 @@ def _drain_session_queue_events(controller: Any, *, session_id: str, work_dir: P
with controller.lock:
controller.turn_done_events[(session_id, turn_id)] = done_event
try:
controller._run_turn(
session_id=session_id,
turn_id=turn_id,
message=str(turn.get("message") or ""),
attachments=turn.get("attachments") or [],
adapter=adapter,
done_event=done_event,
)
with _acquire_steward_lane_slot(controller, current, turn):
controller._run_turn(
session_id=session_id,
turn_id=turn_id,
message=str(turn.get("message") or ""),
attachments=turn.get("attachments") or [],
adapter=adapter,
done_event=done_event,
)
except RuntimeError as exc:
if str(exc) == "chat runtime closed before steward lane slot acquisition":
controller._release_done_event((session_id, turn_id), done_event, drop_event=True)
return
raise
except OSError:
# _run_turn has released its execution fence/done event.
# A failed error checkpoint must not kill this queue worker;
Expand Down
5 changes: 4 additions & 1 deletion loopx/capabilities/native_chat/steward_managed_mode.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,10 @@ def _session(self, binding_id: str, session_id: str | None) -> dict[str, Any]:
session = self.store.load_session(actor["session_id"])
else:
candidates = self.bindings.local_sessions(binding_id)
candidates = [row for row in candidates if row.get("status") != "closed"]
candidates = [
row for row in candidates
if row.get("status") != "closed" and not (row.get("steward_context") or {}).get("topic_ref")
]
channels = {row.get("channel_id") for row in candidates}
if len(channels) != 1 or not candidates:
raise ValueError("select the original private steward conversation first")
Expand Down
20 changes: 13 additions & 7 deletions loopx/control_plane/collaboration/conversation_binding.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,10 @@ const hasConflictingRecoveryKey = (obj: JsonObject, allowed: string): boolean =>
const fieldsMatch = (left: JsonObject, right: JsonObject, keys: readonly string[]): boolean =>
keys.every(key => left[key] === right[key]);
const isStewardEndpoint = (v: unknown): boolean => v === "antigravity" || v === "codex";
const boundChannelId = (steward: boolean, bindingId: unknown, sourceRef: unknown): string =>
`${steward ? "manager.external.native" : "project.external"}.${bindingId}.${sourceRef}`;
const boundChannelId = (steward: boolean, bindingId: unknown, sourceRef: unknown, topicRef?: unknown): string =>
steward && isNonEmptyStr(topicRef)
? `manager.external.native.${bindingId}.${sourceRef}.topic.${topicRef}`
: `${steward ? "manager.external.native" : "project.external"}.${bindingId}.${sourceRef}`;
const recoveryClientBase = (row: JsonObject, version: number): string =>
`external-${ref(row.request_ref, "original request")}-recovery-${version}`;
const reviewClientId = (row: JsonObject, version: number): string => `${recoveryClientBase(row, version)}-review-1`;
Expand Down Expand Up @@ -72,6 +74,7 @@ const matchesAttachedSession = (current: JsonObject | null, target: JsonObject):
const matchesPrivateOwnerSource = (selected: JsonObject, row: JsonObject, source: JsonObject, context: JsonObject): boolean =>
row.binding_id === selected.binding_id && source.private_human_message === true
&& source.sender_ref === selected.operator_ref && context.source_ref === source.source_ref
&& (source.topic_ref ?? null) === (context.topic_ref ?? null)
&& fieldsMatch(context, selected, ["binding_id", "provider_ref", "operator_ref", "project_ref"]);
const matchesNativeProofBase = (proof: JsonObject, current: JsonObject, row: JsonObject, failed: JsonObject): boolean =>
proof.thread_id === current.upstream_thread_id && proof.request_ref === row.request_ref
Expand Down Expand Up @@ -395,8 +398,9 @@ export function resolveBoundConversation(params: JsonObject): JsonObject {
topic = {group_ref: groupRef, topic_ref: topicRef, filesystem_scope: "workspace_only"};
} else {
ensure(params.sender_ref === row.operator_ref && params.private_human_message === !local
&& params.group_ref === undefined && params.topic_ref === undefined && params.group_human_message !== true,
&& params.group_ref === undefined && (steward || params.topic_ref === undefined) && params.group_human_message !== true,
"message audience is outside the binding grant");
if (steward && params.topic_ref !== undefined) topic = {topic_ref: ref(params.topic_ref, "topic reference")};
}
const project = boundProject(params, row);
const goals = steward && row.goal_scope === "all_registered"
Expand All @@ -414,7 +418,7 @@ export function resolveBoundConversation(params: JsonObject): JsonObject {
const matches = steward ? matchesStewardContext(saved, context, row) : isDeepStrictEqual(saved, context);
ensure(matches, "bound Session context changed");
}
const channel = boundChannelId(steward, id, source);
const channel = boundChannelId(steward, id, source, steward ? topic.topic_ref : undefined);
if (params.session !== undefined) {
const session = requireJsonObject(params.session, "canonical bound Session");
sessionIdentity(session.session_id, "bound Session identity");
Expand Down Expand Up @@ -453,7 +457,9 @@ export function listLocalBoundSessions(params: JsonObject): JsonObject {
if (![session.project_context, session.steward_context].some(v => jsonObject(v)?.binding_id === id)
|| session.status === "closed") continue;
const saved = requireJsonObject(steward ? session.steward_context : session.project_context, "bound Session context");
if (params.app_steward_entry === true && steward && saved.topic_ref !== undefined) continue;
resolveBoundConversation({...params, source_ref: saved.source_ref, session,
...(steward && saved.topic_ref !== undefined ? {topic_ref: saved.topic_ref} : {}),
sender_ref: row.operator_ref, private_human_message: false, origin: "web", session_context: saved});
ids.push(sessionIdentity(session.session_id, "bound Session identity"));
}
Expand Down Expand Up @@ -671,7 +677,7 @@ function planStewardBindingAdoptionHold(params: JsonObject, request: JsonObject)
ensure(matchesPrivateOwnerSource(row, request, source, context)
&& context.audience === "bound_owner" && context.grant === "portfolio_read"
&& original.goal_id === "loopx-manager" && original.session_mode === "managed_runtime"
&& original.project_context == null && original.channel_id === boundChannelId(true, row.binding_id, source.source_ref)
&& original.project_context == null && original.channel_id === boundChannelId(true, row.binding_id, source.source_ref, context.topic_ref)
&& matchesStewardContext(saved, context, row), "the original steward Session belongs to another source");
return {operation: "hold_steward_binding", session_id: sessionIdentity(original.session_id, "original steward Session")};
}
Expand Down Expand Up @@ -823,7 +829,7 @@ function planContextRecovery(params: JsonObject, row: JsonObject, current: JsonO
const source = requireJsonObject(row.source, "original conversation source");
if (!matchesPrivateOwnerSource(selected, row, source, saved)
|| (!steward && saved.grant !== selected.grant)
|| current.channel_id !== boundChannelId(steward, selected.binding_id, saved.source_ref)) return NO_RECOVERY;
|| current.channel_id !== boundChannelId(steward, selected.binding_id, saved.source_ref, saved.topic_ref)) return NO_RECOVERY;
const failed = requireJsonObject(recovery.failed_turn, "original failed Turn");
if (recovery.retained_result_review != null) {
return (row.context_recovery as JsonObject | undefined)?.legacy_result_review === true
Expand Down Expand Up @@ -1679,7 +1685,7 @@ function boundConversationStatus(params: JsonObject, current: JsonObject | null)
ensure(fieldsMatch(context, selected, ["binding_id", "project_ref", "provider_ref", "operator_ref"]),
"status context belongs to another binding");
const source = ref(context.source_ref, "status source identity");
const channel = boundChannelId(steward, selected.binding_id, source);
const channel = boundChannelId(steward, selected.binding_id, source, context.topic_ref);
const recipient = params.agent_target ? agentTarget(params.agent_target) : null;
if (recipient) {
ensure(matchesAttachedSession(current, recipient), "status Agent Session changed");
Expand Down
Loading