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
10 changes: 7 additions & 3 deletions docs/reference/original-project-collaboration.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,9 +102,13 @@ The original failed Turn remains failed; the panel separately reports a recovere
result. A failure before saved model output remains visible and cannot be
silently rerun as a new Turn under the same identity.

Read the result through the requester's existing manager inbox and use
`acknowledge-return` / MCP `consume_peer_result` to record consumption after
checking it. The saved requester route is verified at dispatch, source control,
Read the result with the requester's Turn-bound `read_context` tool. After
checking it, use `consume_peer_result` or the acknowledgement command in that
tool's result to record acceptance, deferral or rejection. A CLI Inbox read
can inspect the conclusion and leaves it pending until a bound tool supplies
it. Deferral keeps the same result visible on the next Turn. Managed Codex
invocations supply the current Turn identity to their built-in collaboration
server on both start and resume. The saved requester route is verified at dispatch, source control,
requester read and consumption. Results do not automatically go to the
recipient conversation's external audience.

Expand Down
15 changes: 12 additions & 3 deletions examples/peer-handoff-live-qualification.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
sys.path.insert(0, str(REPO_ROOT))

from loopx.chat_agent import CodexChatAgentSession # noqa: E402
from loopx.control_plane.collaboration.peers import read_inbox # noqa: E402
from loopx.control_plane.effect_runtime import restart_effect_runtime # noqa: E402


Expand Down Expand Up @@ -54,7 +55,7 @@ def qualify(workspace: Path, *, codex_bin: str, codex_home: Path) -> dict:
"acceptance": ["Allocated plus reserved equals demand", "Head and digest match"],
"return_requirement": "Return the verdict, exact head and artifact digest to requester",
}), encoding="utf-8")
env = {**os.environ, "LOOPX_CODEX_HOMES": str(codex_home)}
env = {**os.environ, "LOOPX_CODEX_HOMES": str(codex_home), "LOOPX_USAGE_PING": "0"}

def cli(agent, action, *args, ok=True):
process = subprocess.run([sys.executable, "-m", "loopx.cli",
Expand Down Expand Up @@ -170,15 +171,23 @@ def review_handler(name, arguments, identity):
def return_handler(name, arguments, identity):
assert identity["thread_id"] == requester_id
calls.append(name)
# The App server adapter supplies the verified active Turn.
turn_instance_id = identity["host_turn_id"]
if name == "peer_return_read":
result = cli("requester", "read")
result = read_inbox(
runtime, registry, "peer-qualification", "requester",
workspace=workspace, turn_instance_id=turn_instance_id,
)
item = next(item for item in result["peer_returns"]["items"]
if item["request_id"] == rid)
assert item["text"] == f"ACCEPT head={head} sha256={digest}"
return {"ok": True, "result": item}
if name == "peer_return_consume":
assert "peer_return_read" in calls
return cli("requester", "acknowledge-return", "--request-id", rid)
return cli(
"requester", "acknowledge-return", "--request-id", rid,
"--turn-instance-id", turn_instance_id, "--disposition", "accepted",
)
raise ValueError("unsupported qualification tool")

requester.bound_tool_handler = return_handler
Expand Down
46 changes: 33 additions & 13 deletions loopx/capabilities/manager_context/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,13 @@ work-context sources, while the full result text remains behind the existing
`manager-inbox read` command. This preserves asynchronous pull semantics and
does not interrupt an active Turn or treat visibility as consumption.

Ordinary peer results may wait for the next work Turn. Cancellation, blocking
and priority-control paths keep their immediate handling. The invocation-bound
`read_context` tool records a `model_turn` supply fact for the results it
returns. The required CLI read and its paged recovery record transport delivery.
Peer results stay eligible for the next Turn until a bound Turn accepts or
rejects them.

Outgoing requests to an original project conversation use the same typed address
reader as explicit peer returns. The agenda retains that conversation recipient
and its current revision without inventing a Goal/Agent receiver. A changed
Expand Down Expand Up @@ -734,6 +741,8 @@ Use the same registry, runtime root, Goal and Agent for every page. The scoped
MCP equivalent is `read_context(cursor=<next_cursor>)`; a call without arguments
still reads the first page. A cursor survives process restart and removal or
completion of its anchor request. It is a navigation position, not a grant.
When the MCP runs inside a managed work Turn, the host-bound Turn identity is
used for result delivery and is never accepted from model tool arguments.
Each call checks current registration and records reads only for returned requests.
`next_cursor: null` ends this scan, not the outstanding work. Pages are live,
ordered by request id; restart without a cursor to find new requests sorted
Expand Down Expand Up @@ -902,11 +911,15 @@ loopx manager-inbox report --goal-id research --agent-id worker \
Retry the same update with the same id and text. Each update has its own
`result_key`, retains the original audience and authority checks, and arrives
after verified delivery of the preceding result. Unknown delivery blocks later
sends rather than allowing them to overtake it. Peer readers acknowledge the
specific returned key with `acknowledge-return --result-key <key>` after reading
it; consuming the first result does not consume later updates. MCP callers use
the corresponding `return_result(update_id=...)` and
`consume_peer_result(result_key=...)`. Full texts stay in immutable receipts;
sends rather than allowing them to overtake it. After the bound tool supplies
an update, use its acknowledgement command with the exact `--result-key` or
call `consume_peer_result` with that key. `accepted` and `rejected` consume it.
`deferred` records the review but keeps it visible on the next Turn. Consuming
the first result does not consume later updates. MCP callers use the corresponding
`return_result(update_id=...)` and
`consume_peer_result(disposition=..., result_key=...)`; the MCP host binds the
current Turn identity and does not expose it as a model-selected argument.
Full texts stay in immutable receipts;
the typed publication planner receives identities and content digests.

The Chat server hosts a cheap local receipt pump (no model calls and no Codex
Expand Down Expand Up @@ -1137,17 +1150,23 @@ grant names the blocked recipient without recording a request. This replaces
the previous blanket refusal of external-source peer forwarding, without
granting execution, changing priorities or broadening the return audience.

The peer independently `acknowledge`s and `report`s a conclusion through the
same commands as a manager request. The original requester receives it in
`manager-inbox read` under `peer_returns`; its Turn-start hook keeps requiring
a read until the requester explicitly consumes the result:
The peer independently acknowledges a request and reports a conclusion
through the same commands as a manager request. The original requester can
inspect it under `peer_returns` in `manager-inbox read`. In a host with the
invocation-bound tools configured, use `read_context` to receive the result and
`consume_peer_result` after checking it. The result also carries a CLI
acknowledgement command for that exact delivery:

```sh
loopx manager-inbox read --goal-id allocation --agent-id builder
loopx manager-inbox acknowledge-return --goal-id allocation --agent-id builder \
--request-id <peer-request-id>
--request-id <peer-request-id> --turn-instance-id <supplied-turn-id> \
--disposition accepted
```

Use `--disposition deferred` to keep the same result in next-Turn attention.
After acceptance or rejection, only the same disposition from the same Turn
can replay the terminal acknowledgement.
On hosts that only provide the ordinary CLI read, the result stays pending.
Consumption does not mark a Todo done or certify peer acceptance. The requester
checks the actual artifact, incorporates or rejects the findings, and reports
the original owner conclusion through its original request. A second review
Expand Down Expand Up @@ -1207,8 +1226,9 @@ the normal governed Turn arguments:
Use the Python interpreter with this LoopX checkout/release installed and
absolute configuration paths. Each server exposes only `read_context`,
`assess_request`, `link_work`, `request_peer`, `return_result` and `consume_peer_result`.
Identity and filesystem roots are host-bound, absent from model tool arguments;
every call rechecks the registered actor. The server has no shell, Todo/lease
The managed invocation supplies the current Turn key to the scoped tool process.
Identity and filesystem roots are host-bound. Every call rechecks the
registered actor. The server has no shell, Todo/lease
writer, credential tools or network listener. Installing/configuring it does not
launch another worker or grant access to another Goal. Removing the patch and
restarting the worker disables these tools without deleting pending requests or
Expand Down
12 changes: 12 additions & 0 deletions loopx/cli_commands/manager_inbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,9 @@ def register_manager_inbox(subparsers, add_format):
help="For report: explicit relative file in the registered Goal workspace; bound-owner App only, at most four files.")
parser.add_argument("--update-id", help="For report: stable identity for a later conclusion; retry the same id and text.")
parser.add_argument("--result-key", help="For acknowledge-return: the exact peer result read; defaults to the initial conclusion.")
parser.add_argument("--turn-instance-id", help="For acknowledge-return: identify the work Turn that already received the peer result.")
parser.add_argument("--disposition", choices=("accepted", "deferred", "rejected"),
help="For acknowledge-return: whether this Turn used, deferred, or rejected the peer result.")
parser.add_argument("--related-todo-id", action="append", default=[])
parser.add_argument("--evidence-id", action="append", default=[])
parser.add_argument("--offset", type=int, default=0)
Expand Down Expand Up @@ -340,6 +343,10 @@ def handle_manager_inbox(args, registry_path, runtime_root):
raise ValueError("--attachment-ref is only supported for report")
if getattr(args, "result_key", None) is not None and args.manager_inbox_action != "acknowledge-return":
raise ValueError("--result-key is only supported for acknowledge-return")
if getattr(args, "turn_instance_id", None) is not None and args.manager_inbox_action not in {"read", "acknowledge-return"}:
raise ValueError("--turn-instance-id is only supported for read/acknowledge-return")
if getattr(args, "disposition", None) is not None and args.manager_inbox_action != "acknowledge-return":
raise ValueError("--disposition is only supported for acknowledge-return")
cursor = getattr(args, "cursor", None)
operation_cursor = getattr(args, "operation_cursor", None)
if cursor is not None and args.manager_inbox_action != "read":
Expand Down Expand Up @@ -440,17 +447,22 @@ def handle_manager_inbox(args, registry_path, runtime_root):
}
elif args.manager_inbox_action == "acknowledge-return":
from ..control_plane.collaboration.peers import consume_return
if not args.turn_instance_id or not args.disposition:
raise ValueError("acknowledge-return requires --turn-instance-id and --disposition")
result = consume_return(
runtime_root,
args.goal_id,
args.agent_id,
args.request_id,
registry=registry_path,
result_key=getattr(args, "result_key", None) or "conclusion",
turn_instance_id=args.turn_instance_id,
disposition=args.disposition,
)
elif args.manager_inbox_action == "read":
from ..control_plane.collaboration.peers import read_inbox
request_id = getattr(args, "request_id", None)
# Only the invocation-bound host reader can record Turn delivery.
result = read_inbox(runtime_root, registry_path, args.goal_id, args.agent_id,
workspace=Path.cwd(), cursor=cursor, operation_cursor=operation_cursor,
request_id=request_id)
Expand Down
51 changes: 45 additions & 6 deletions loopx/collaboration_mcp.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,14 +205,39 @@ def _mcp_module_command() -> list[str]:
)


def _bound_work_turn_identity(goal_id: str, agent_id: str, workspace: Path) -> str | None:
"""Read the host-owned Turn identity without exposing it as a model argument."""
from .turn_identity import normalize_turn_instance_id

host_turn_key = os.environ.get("LOOPX_TURN_KEY", "").strip()
turn_instance_id = normalize_turn_instance_id(host_turn_key or None)
if turn_instance_id is None:
return None
bound_workspace = os.environ.get("LOOPX_TURN_WORKSPACE")
if (os.environ.get("LOOPX_TURN_GOAL_ID") != goal_id
or os.environ.get("LOOPX_TURN_AGENT_ID") != agent_id
or not bound_workspace
or Path(bound_workspace).resolve() != workspace.resolve()):
raise ValueError("host-bound work Turn scope does not match the collaboration server")
return turn_instance_id


def create_server(
root: Path, registry: Path, goal_id: str, agent_id: str, workspace: Path,
execution_config: Path | None = None,
) -> FastMCP:
from mcp.server.fastmcp import FastMCP

server = FastMCP("loopx-collaboration")
register_collaboration_tools(server, root, registry, goal_id, agent_id, workspace)
register_collaboration_tools(
server,
root,
registry,
goal_id,
agent_id,
workspace,
turn_instance_id=_bound_work_turn_identity(goal_id, agent_id, workspace),
)
if execution_config is not None:
register_delegation_tools(server, Delegations(
root, registry, goal_id, agent_id, execution_config, reuse_preview=True,
Expand All @@ -221,7 +246,8 @@ def create_server(


def register_collaboration_tools(server: FastMCP, root: Path, registry: Path, goal_id: str,
agent_id: str, workspace: Path) -> None:
agent_id: str, workspace: Path, *,
turn_instance_id: str | None = None) -> None:
caller_goal_ref = capture_collaboration_goal_ref(
registry,
goal_id=goal_id,
Expand All @@ -248,6 +274,7 @@ def read_context(cursor: str | None = None) -> dict:
agent_id,
workspace=workspace,
cursor=cursor,
turn_instance_id=turn_instance_id,
caller_goal_ref=caller_goal_ref,
)
except InboxReadResponseAmbiguous as exc:
Expand Down Expand Up @@ -405,17 +432,27 @@ def original_conversation_collaboration(
operation=operation, parameters=parameters, chat_url=chat_url, caller_goal_ref=caller_goal_ref)

@server.tool()
def consume_peer_result(request_id: str, result_key: str = "conclusion") -> dict:
"""Acknowledge a read peer result, using its result_key for a later update.
This consumes only that result and never changes work state.
def consume_peer_result(
request_id: str,
disposition: Literal["accepted", "deferred", "rejected"],
result_key: str = "conclusion",
) -> dict:
"""Acknowledge a peer result supplied to this exact work Turn.

Deferred results remain visible on the next Turn. Accepted or rejected
results are consumed idempotently and never change work state.
"""
check_scope()
if turn_instance_id is None:
raise ValueError("peer result acknowledgement requires a host-bound work Turn")
return consume_return(
root,
goal_id,
agent_id,
request_id,
result_key=result_key,
turn_instance_id=turn_instance_id,
disposition=disposition,
registry=registry,
caller_goal_ref=caller_goal_ref,
)
Expand Down Expand Up @@ -1329,9 +1366,11 @@ def _execution_arguments(self, binding: dict, operation_id: str) -> list[str]:
"--workspace", binding["workspace"], "--operation-id", operation_id]
native_tools: list[str] = []
if turn_host_arg_option(binding["host_args"], "--host") == "codex-cli":
from .control_plane.turn_driver.codex_cli import LOOPX_DELEGATION_CODEX_MCP_SERVER_NAME

mcp_server = {
"schema_version": "codex_stdio_mcp_server_v0",
"name": "loopx_delegation",
"name": LOOPX_DELEGATION_CODEX_MCP_SERVER_NAME,
"command": [*_mcp_module_command(),
"--runtime-root",
str(self.root),
Expand Down
Loading
Loading