Skip to content
Merged
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
9 changes: 8 additions & 1 deletion loopx/capabilities/native_chat/queue_api.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
"""HTTP transport for original Session Tasks and the existing persisted queue."""

from functools import partial
from typing import Any
from urllib.parse import parse_qs, urlparse

from ...chat_store import CHAT_STORE_SCHEMA_VERSION
from ...status_server import is_loopback_host


class ChatQueueRequestMixin:
Expand Down Expand Up @@ -121,7 +123,12 @@ def _steer_queued_turn(self, session_id: str, queued_turn_id: str) -> None:
for key in body:
if not isinstance(body[key], str) or not body[key] or len(body[key]) > 160:
raise ValueError("invalid queue steering identity")
result = self.server.runtime_controller.steer_queued_turn(session_id=session_id,
controller = self.server.runtime_controller
steer = controller.steer_queued_turn
if is_loopback_host(str(self.server.server_address[0])):
from .queued_admission import steer_queued_web_turn
steer = partial(steer_queued_web_turn, controller)
result = steer(session_id=session_id,
queued_turn_id=queued_turn_id, expected_turn_id=body["target_turn_id"],
client_ingress_id=body["client_ingress_id"])
self._send_json({"ok": True, **result})
Expand Down
123 changes: 120 additions & 3 deletions loopx/capabilities/native_chat/queued_admission.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,20 @@
"""IO admission to the existing same-Session queue; Core owns source authority."""
import hashlib
import json
from collections.abc import Iterator
from contextlib import contextmanager
from pathlib import Path
from typing import Any
from typing import TYPE_CHECKING, Any

from ...chat_attachments import require_text_document_route
from ...attached_session import enqueue_attached_agent_turn
from ...chat_store import CHAT_SESSION_MODE_ATTACHED
from ...control_plane.collaboration import conversation_scope
from . import project_context as project_context_policy

if TYPE_CHECKING:
from ...chat_runtime import ChatRuntimeController


def enqueue_turn(controller: Any, *, session_id: str, client_turn_id: str, message: str,
attachments: list[dict[str, Any]] | None, work_dir: Path | None, objective: str,
Expand Down Expand Up @@ -67,6 +72,119 @@ def enqueue_turn(controller: Any, *, session_id: str, client_turn_id: str, messa
return turn, created


@contextmanager
def bound_steward_web_steering_context(controller: "ChatRuntimeController",
session_id: str) -> Iterator[dict[str, Any] | None]:
"""Authorize steering from the loopback App across the binding fence."""
session = controller.store.load_session(session_id)
if session is None or (session.get("steward_context") or {}).get("audience") != "bound_owner":
yield None
return
saved = session["steward_context"]
contexts = controller.project_contexts
bindings = contexts.conversation_bindings
if bindings is None or controller.registry_path is None:
raise ValueError("bound steward authority is unavailable")

from ...chat_manager_context import manager_authorization_scope_id_for_registry

# Reuse the local Web source grant. Keep its binding fence through the
# exact-Turn receipt and native delivery, including concurrent revocation.
with bindings.input_context(saved, origin="web", session=session, store=controller.store) as selected:
fresh = controller.store.load_session(session_id)
if fresh is None or fresh.get("status") == "closed":
raise KeyError("chat session was not found")
if any(fresh.get(key) != session.get(key) for key in
("steward_context", "project_context", "channel_id", "goal_id", "agent_id", "executor_endpoint_id")):
raise ValueError("bound Session changed before input admission")
contexts.runtime_context(fresh, selected)
scope = manager_authorization_scope_id_for_registry(controller.registry_path,
selected["context"]["goal_ids"], runtime_root=controller.coordination_runtime_root,
channel_id=fresh["channel_id"])
if scope is None or scope != fresh.get("manager_authorization_scope_id"):
raise ValueError("bound steward authorization changed before steering")
yield fresh


def steer_admitted_web_turn(controller: "ChatRuntimeController", session: dict[str, Any], *,
expected_turn_id: str, client_ingress_id: str, message: str,
queued_turn_id: str | None = None) -> tuple[dict[str, Any], bool]:
session_id = session["session_id"]
with controller.store.steering_delivery_lock(session_id, client_ingress_id):
return controller._steer_active_turn(session=session, session_id=session_id, expected_turn_id=expected_turn_id,
client_ingress_id=client_ingress_id, message=message, _queued_turn_id=queued_turn_id, origin="web")


def steer_web_turn(controller: "ChatRuntimeController", *, session_id: str, expected_turn_id: str,
client_ingress_id: str, message: str) -> tuple[dict[str, Any], bool]:
with bound_steward_web_steering_context(controller, session_id) as session:
if session is None:
return controller.steer_active_turn(session_id=session_id, expected_turn_id=expected_turn_id,
client_ingress_id=client_ingress_id, message=message)
return steer_admitted_web_turn(controller, session, expected_turn_id=expected_turn_id,
client_ingress_id=client_ingress_id, message=message)


def steer_queued_web_turn(controller: "ChatRuntimeController", *, session_id: str, queued_turn_id: str,
expected_turn_id: str, client_ingress_id: str) -> dict[str, Any]:
with bound_steward_web_steering_context(controller, session_id) as session:
if session is None:
return controller.steer_queued_turn(session_id=session_id, queued_turn_id=queued_turn_id,
expected_turn_id=expected_turn_id, client_ingress_id=client_ingress_id)
return steer_queued_turn(controller, session_id=session_id, queued_turn_id=queued_turn_id,
expected_turn_id=expected_turn_id, client_ingress_id=client_ingress_id, admitted_steward=session)


def steer_queued_turn(
controller: "ChatRuntimeController", *, session_id: str, queued_turn_id: str, expected_turn_id: str,
client_ingress_id: str, admitted_steward: dict[str, Any] | None = None,
) -> dict[str, Any]:
from ...control_plane.chat_turn_acceptance import plan_queued_chat_steering

ingress_id = "queue-steer-" + hashlib.sha256(
json.dumps([session_id, queued_turn_id, client_ingress_id]).encode()
).hexdigest()[:40]
with controller.store.queue_steering_lock(session_id, queued_turn_id):
session = controller.store.load_session(session_id)
turn = controller.store.load_turn(session_id, queued_turn_id)
if session is None or turn is None:
raise KeyError("chat turn was not found")
if admitted_steward is not None and any(session.get(key) != admitted_steward.get(key) for key in (
"steward_context", "project_context", "channel_id", "goal_id", "agent_id",
"executor_endpoint_id", "manager_authorization_scope_id",
)):
raise ValueError("bound Session changed before queue steering")
active = controller.store.load_turn(session_id, str(session.get("active_turn_id") or "")) if session.get("active_turn_id") else None

def plan(phase):
return plan_queued_chat_steering(session, turn, active,
controller.store.steering_receipt(session_id, ingress_id),
ingress_id=ingress_id, operation_id=client_ingress_id, target=expected_turn_id, phase=phase,
web_origin_only=admitted_steward is not None)

decision = plan("prepare")
if decision["action"] in {"dispatch", "unresolved"}:
if decision["action"] == "dispatch":
turn = controller.store.write_queue_steering(session_id, turn, decision)
try:
if admitted_steward is not None:
steer_admitted_web_turn(controller, session, expected_turn_id=expected_turn_id,
client_ingress_id=ingress_id, message=turn["message"], queued_turn_id=queued_turn_id)
else:
controller.steer_active_turn(session_id=session_id, expected_turn_id=expected_turn_id,
client_ingress_id=ingress_id, message=turn["message"], _queued_turn_id=queued_turn_id)
except Exception:
# The durable ingress, including absence before any send,
# owns the outcome. Exception wording cannot release work.
pass
decision = plan("settle")
controller.store.write_queue_steering(session_id, turn, decision)
if decision["action"] != "complete":
raise RuntimeError(decision["error_code"])
return {"session_id": session_id, "queued_turn_id": queued_turn_id,
"turn_id": expected_turn_id, "client_ingress_id": client_ingress_id,
"status": "delivered"}

def deliver_native_mention(
controller, *, session_id: str, ingress_id: str, target_turn_id: str | None,
binding_matches: bool, text_only: bool, may_deliver_new: bool,
Expand Down Expand Up @@ -172,8 +290,7 @@ def reconcile_steering_delivery(controller, session, receipt) -> dict[str, Any]
from .codex_adapter import CodexAppServerAdapter
from ...control_plane.effect_runtime import effect_runtime_result

with controller.lock:
adapter = controller.adapters.get(session["session_id"])
adapter = controller.adapters.get(session["session_id"])
if not isinstance(adapter, CodexAppServerAdapter) or not adapter.healthcheck():
return None
capture = receipt.get("native_steering")
Expand Down
52 changes: 8 additions & 44 deletions loopx/chat_runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -527,49 +527,11 @@ def steer_queued_turn(
Only a proven non-delivery restores FIFO eligibility. A lost native
acknowledgement keeps the original input durably reserved.
"""
from .control_plane.chat_turn_acceptance import plan_queued_chat_steering
self._require_steering_session(session_id)
ingress_id = "queue-steer-" + hashlib.sha256(
json.dumps([session_id, queued_turn_id, client_ingress_id]).encode()
).hexdigest()[:40]
with self.store.queue_steering_lock(session_id, queued_turn_id):
session = self.store.load_session(session_id)
turn = self.store.load_turn(session_id, queued_turn_id)
if session is None or turn is None:
raise KeyError("chat turn was not found")
active = self.store.load_turn(session_id, str(session.get("active_turn_id") or "")) if session.get("active_turn_id") else None
from .capabilities.native_chat.queued_admission import steer_queued_turn

def plan(phase):
return plan_queued_chat_steering(session, turn, active,
self.store.steering_receipt(session_id, ingress_id),
ingress_id=ingress_id, operation_id=client_ingress_id, target=expected_turn_id, phase=phase)

decision = plan("prepare")
if decision["action"] == "unresolved":
try:
self.steer_active_turn(session_id=session_id, expected_turn_id=expected_turn_id,
client_ingress_id=ingress_id, message=turn["message"],
_queued_turn_id=queued_turn_id)
except Exception:
pass # Only the original receipt can complete the reservation.
decision = plan("settle")
if decision["action"] == "dispatch":
turn = self.store.write_queue_steering(session_id, turn, decision)
try:
self.steer_active_turn(session_id=session_id, expected_turn_id=expected_turn_id,
client_ingress_id=ingress_id, message=turn["message"],
_queued_turn_id=queued_turn_id)
except Exception:
# The durable ingress, including absence before any send,
# owns the outcome. Exception wording cannot release work.
pass
decision = plan("settle")
self.store.write_queue_steering(session_id, turn, decision)
if decision["action"] != "complete":
raise RuntimeError(decision["error_code"])
return {"session_id": session_id, "queued_turn_id": queued_turn_id,
"turn_id": expected_turn_id, "client_ingress_id": client_ingress_id,
"status": "delivered"}
self._require_steering_session(session_id)
return steer_queued_turn(self, session_id=session_id, queued_turn_id=queued_turn_id,
expected_turn_id=expected_turn_id, client_ingress_id=client_ingress_id)

def steer_active_turn(
self, *, session_id: str, client_ingress_id: str, message: str,
Expand Down Expand Up @@ -625,8 +587,10 @@ def fail_ingress(error_code: str, *, record: bool = True) -> NoReturn:
fail_ingress("live_steering_turn_mismatch")
if not active_turn_id:
fail_ingress("live_steering_requires_active_turn")
with self.lock:
adapter = self.adapters.get(session_id)
# Snapshot one adapter without taking the controller lock while a
# binding or queue fence is held. The native call still checks health
# and binds to the current upstream Turn.
adapter = self.adapters.get(session_id)
if not isinstance(adapter, CodexAppServerAdapter) or not adapter.healthcheck():
fail_ingress("live_steering_session_not_attached")
upstream_turn_id = ""
Expand Down
8 changes: 7 additions & 1 deletion loopx/chat_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import uuid
from collections.abc import Callable, Mapping
import webbrowser
from functools import partial
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from typing import TYPE_CHECKING, Any, Literal, cast
Expand Down Expand Up @@ -1086,7 +1087,12 @@ def _steer_turn(self, session_id: str, turn_id: str) -> None:
raise ValueError("a message of 1–12000 characters is required")
if not isinstance(ingress_id, str) or not ingress_id.strip():
raise ValueError("client_ingress_id is required")
turn, created = self.server.runtime_controller.steer_active_turn(
controller = self.server.runtime_controller
steer = controller.steer_active_turn
if is_loopback_host(str(self.server.server_address[0])):
from .capabilities.native_chat.queued_admission import steer_web_turn
steer = partial(steer_web_turn, controller)
turn, created = steer(
session_id=session_id, expected_turn_id=turn_id,
client_ingress_id=ingress_id, message=message,
)
Expand Down
4 changes: 3 additions & 1 deletion loopx/control_plane/chat_turn_acceptance.py
Original file line number Diff line number Diff line change
Expand Up @@ -192,11 +192,13 @@ def plan_native_mention_ingress(**facts: object) -> dict[str, Any]:
def plan_queued_chat_steering(
session: dict[str, Any], turn: dict[str, Any], active: dict[str, Any] | None,
receipt: dict[str, Any] | None, *, ingress_id: str, operation_id: str, target: str, phase: str,
web_origin_only: bool = False,
) -> dict[str, Any]:
return effect_runtime_result("chat.queue.steer", {
"phase": phase,
"request": {"client_ingress_id": ingress_id, "operation_id": operation_id, "target_turn_id": target},
"session": {"status": session.get("status"), "active_turn_id": session.get("active_turn_id")},
"session": {"status": session.get("status"), "active_turn_id": session.get("active_turn_id"),
"web_origin_only": web_origin_only},
"active_status": (active or {}).get("status"),
"turn": {"turn_id": turn["turn_id"], "status": turn["status"],
"origin": turn.get("origin"), "loopx_execution": turn.get("loopx_execution", False),
Expand Down
1 change: 1 addition & 0 deletions loopx/control_plane/turn_driver/chat_queue_steering.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ export function planQueuedChatSteering(input: JsonObject): QueueSteeringPlan {
const held = reservation(turn.reservation);
const reject = (code: string): QueueSteeringPlan => ({action: "reject", error_code: code});
if (session.status === "closed") return reject("session_closed");
if (session.web_origin_only === true && turn.origin !== "web") return reject("queue_steering_source_unavailable");
if (turn.mutation != null) return reject("queue_mutation_in_progress");
if (held?.status === "pending" &&
(held.client_ingress_id !== id || held.target_turn_id !== target)) {
Expand Down
12 changes: 12 additions & 0 deletions tests/control_plane_ts/chat_queue_steering.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,18 @@ test("uncertain delivery never dispatches again or becomes eligible FIFO work",
assert.deepEqual(selectQueuedChatTurns({turns: [{...expired, reservation: null}], include_reserved: true, capacity_at: "2026-01-01T00:00:00Z"}).turn_ids, []);
});

test("the private Steward App can steer only its own queued text", () => {
const f = facts();
const session = {...f.session, web_origin_only: true};
assert.equal(planQueuedChatSteering({...f, session}).action, "dispatch");
for (const origin of ["external", "lark", "peer"]) {
const turn = {...f.turn, origin};
assert.deepEqual(planQueuedChatSteering({...f, session, turn}),
{action: "reject", error_code: "queue_steering_source_unavailable"});
}
assert.equal(planQueuedChatSteering({...f, turn: {...f.turn, origin: "external"}}).action, "dispatch");
});

test("acknowledgement recovers after target completion while proven rejection restores queue", () => {
const f = facts(); f.turn.reservation = held;
assert.equal(planQueuedChatSteering({...f, session: {status: "ready", active_turn_id: null}, receipt}).action, "complete");
Expand Down
Loading
Loading