run.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. """The one lifecycle every ``manage_connections`` operation follows, whatever the target kind.
  2. ``run_operation`` mints the op, registers it in ``live``, lets the kind prepare its targets (a
  3. managed mint, an MCP catalog check), emits the card through the session callback, then loops:
  4. sleep on ``op.wake`` for at most one tick, run the kind's ``observe`` hook, settle when every
  5. target is resolved or the deadline passes. ``connection.respond`` reaches the loop by transitioning
  6. the op through ``live`` and setting ``wake``; ``/stop`` sets the thread interrupt flag."""
  7. from __future__ import annotations
  8. import json
  9. import time
  10. from dataclasses import dataclass
  11. from typing import Any, Callable, Dict, List, Optional, Sequence
  12. from tools.connectors import live
  13. from tools.connectors.contract import SettleReason
  14. from tools.connectors.operation import ConnectionOperation, Target
  15. UNKNOWN_TARGET = "unknown_target"
  16. MIXED_KINDS = "mixed_kinds"
  17. LINK_STILL_VALID = "link_still_valid"
  18. SETTLED = "settled"
  19. NOT_ALLOWED = "not_allowed"
  20. REFUSED = "refused"
  21. WATCH_INTERVAL_SECONDS = 5.0
  22. # The interrupt flag has no wake hook, so the tick sleep is sliced and the flag read each slice.
  23. _WAKE_SLICE_SECONDS = 0.25
  24. Callback = Callable[[dict[str, Any]], Optional[str]]
  25. @dataclass
  26. class Kind:
  27. """Per-kind hooks. ``prepare`` runs once before the card; ``observe`` runs every tick and may
  28. transition targets; ``note`` is the model-facing guidance appended to the settled result."""
  29. prepare: Callable[[ConnectionOperation], None]
  30. observe: Callable[[ConnectionOperation], None]
  31. note: str
  32. # Replaces the per-target result for an operation the model reads differently (the display card).
  33. result: Optional[Callable[[ConnectionOperation], dict[str, Any]]] = None
  34. def reissue(operation: ConnectionOperation, names: Sequence[str], *, initiator: Optional[str] = None) -> Optional[str]:
  35. from tools.connectors.contract import Actor, TargetState, allowed
  36. targets = [operation.target(name) for name in names]
  37. if any(target is None for target in targets):
  38. return UNKNOWN_TARGET
  39. if len({target.kind for target in targets}) != 1:
  40. return MIXED_KINDS
  41. stale = [target.name for target in targets if target.state in (TargetState.failed, TargetState.expired)]
  42. if len(stale) != len(targets):
  43. return LINK_STILL_VALID
  44. if operation.settled:
  45. return SETTLED
  46. if any(allowed(target.kind, target.state, TargetState.initiated) is None for target in targets):
  47. return NOT_ALLOWED
  48. if targets[0].kind == "connector":
  49. from tools.connectors.managed import CARD_RETRY, managed_client, mint
  50. client = managed_client(creates_guest=True, initiator=initiator or CARD_RETRY, call=operation.call)
  51. mint(client, operation, stale, reinitiate=True, actor=Actor.user)
  52. return None
  53. from tools.connectors import catalog
  54. from tools.connectors.mcp import retry
  55. rerun = catalog.retry if catalog.owns(operation.op_id) else retry
  56. return REFUSED if rerun(operation, stale) else None
  57. def apply_answer(operation: ConnectionOperation, raw: str) -> None:
  58. """Hand the card's answer to the module running this operation (a catalog install or an MCP
  59. one); a managed operation's card only skips and continues, which the MCP fold also covers."""
  60. from tools.connectors import catalog, display, mcp
  61. if isinstance(operation, display.DisplayOperation):
  62. display.apply_answer(operation, raw)
  63. return
  64. (catalog.apply_answer if catalog.owns(operation.op_id) else mcp.apply_answer)(operation, raw)
  65. def respond(operation: ConnectionOperation, raw: str) -> bool:
  66. """The card's answer: apply it, settle once every target is resolved, close a settled operation. Returns whether it settled; raises ``IllegalTransition`` for an answer the operation refuses."""
  67. apply_answer(operation, raw)
  68. if not operation.settled and operation.all_resolved:
  69. operation.settle(SettleReason.all_resolved)
  70. if operation.settled:
  71. live.close(operation)
  72. return operation.settled
  73. def run_operation(
  74. targets: list[Target],
  75. kind: Kind,
  76. *,
  77. session_key: str,
  78. tool_call_id: Optional[str],
  79. connection_callback: Optional[Callback],
  80. tick_seconds: Optional[float] = None,
  81. with_urls_in_result: bool,
  82. call: Optional[Any] = None,
  83. ) -> str:
  84. """Block the tool thread until the operation settles; return the tool's JSON string."""
  85. return open_and_drive(
  86. ConnectionOperation(targets, session_key=session_key, tool_call_id=tool_call_id, call=call),
  87. kind,
  88. connection_callback=connection_callback,
  89. tick_seconds=tick_seconds,
  90. with_urls_in_result=with_urls_in_result,
  91. )
  92. def open_and_drive(
  93. operation: ConnectionOperation,
  94. kind: Kind,
  95. *,
  96. connection_callback: Optional[Callback],
  97. tick_seconds: Optional[float] = None,
  98. with_urls_in_result: bool,
  99. ) -> str:
  100. """Register ``operation`` as the session's open one and drive it; one open per session."""
  101. try:
  102. live.open(operation)
  103. except live.OperationAlreadyOpen as exc:
  104. from tools.registry import tool_error
  105. return tool_error(
  106. f"a connection operation is already open in this session ({exc.existing.op_id}); it settles "
  107. "when the user finishes with the card, on Continue, or at its deadline. Do not start another."
  108. )
  109. return drive_operation(
  110. operation,
  111. kind,
  112. connection_callback=connection_callback,
  113. tick_seconds=tick_seconds,
  114. with_urls_in_result=with_urls_in_result,
  115. )
  116. def drive_operation(
  117. operation: ConnectionOperation,
  118. kind: Kind,
  119. *,
  120. connection_callback: Optional[Callback],
  121. tick_seconds: Optional[float] = None,
  122. with_urls_in_result: bool,
  123. ) -> str:
  124. try:
  125. kind.prepare(operation)
  126. operation.settle_if_all_resolved()
  127. if connection_callback is not None and not operation.settled:
  128. connection_callback(operation.request_payload())
  129. _watch(operation, kind, tick_seconds)
  130. finally:
  131. live.close(operation)
  132. if kind.result is not None:
  133. return json.dumps(kind.result(operation), ensure_ascii=False)
  134. payload = operation.result(with_urls=with_urls_in_result)
  135. payload["status"] = "settled"
  136. payload["note"] = kind.note
  137. return json.dumps(payload, ensure_ascii=False)
  138. def _watch(operation: ConnectionOperation, kind: Kind, tick_seconds: Optional[float]) -> None:
  139. from tools.interrupt import is_interrupted
  140. tick = WATCH_INTERVAL_SECONDS if tick_seconds is None else tick_seconds
  141. while not operation.settled:
  142. if is_interrupted():
  143. operation.settle(SettleReason.interrupt)
  144. return
  145. if time.time() >= operation.deadline_at:
  146. operation.settle(SettleReason.deadline)
  147. return
  148. kind.observe(operation)
  149. # The card or the clock may have settled the op during the read; its result is frozen.
  150. if operation.settled or operation.settle_if_all_resolved():
  151. return
  152. _sleep_until_wake(operation, tick)
  153. def _sleep_until_wake(operation: ConnectionOperation, tick: float) -> None:
  154. """Sleep up to one tick, leaving early on ``wake``, the deadline, or the interrupt flag."""
  155. from tools.interrupt import is_interrupted
  156. until = min(time.time() + tick, operation.deadline_at)
  157. while not operation.settled and not is_interrupted():
  158. remaining = until - time.time()
  159. if remaining <= 0:
  160. break
  161. if operation.wake.wait(min(_WAKE_SLICE_SECONDS, remaining)):
  162. break
  163. operation.wake.clear()