session_context_refs.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. """``@`` references of one turn: expanded once, in the session's workspace, on the text the model reads.
  2. The inbound prepare step, the classic CLI's API-only text (``cli_turn_v1.api_text``: voice prefix,
  3. model-switch and skills notes) and managed workers (``--safe-mode`` / ``--ignore-user-config``,
  4. which never pass the inbound step) all expand here. A local session's refusal is the turn's reply:
  5. its adapter delivers through settlement, so a side ``send`` would never reach the viewer.
  6. """
  7. import logging
  8. import os
  9. from contextlib import suppress
  10. from functools import partial
  11. from gateway.config import Platform
  12. logger = logging.getLogger(__name__)
  13. async def expand_references(text, *, cwd, context_length, plugins=True):
  14. """``(text, refusal)``: the expanded text, or the refusal when the injection was refused. A failed
  15. expansion leaves the text as typed."""
  16. from agent.i18n import t
  17. try:
  18. from agent.context_references import preprocess_context_references_async
  19. expand = partial(preprocess_context_references_async, cwd=cwd, context_length=context_length, allowed_root=cwd)
  20. result = await (expand(text) if plugins else expand(text, plugins=False))
  21. except Exception as exc:
  22. logger.warning("@ context reference expansion failed: %s", exc, exc_info=True)
  23. return text, None
  24. if result.blocked:
  25. return text, "\n".join(result.warnings) or t("gateway.notify.context_injection_refused")
  26. return (result.message if result.expanded else text), None
  27. def _inbound_cwd(runner, source):
  28. from gateway.session_policy import policy_for_source
  29. try:
  30. from tools.terminal_scope import terminal_env
  31. except ImportError:
  32. terminal_env = os.environ.get
  33. # A local session's references resolve in ITS workspace: this runs before the turn binds
  34. # the policy scope, so TERMINAL_CWD is still the daemon's own.
  35. if (policy := policy_for_source(runner, source)) is not None:
  36. return policy.cwd
  37. return terminal_env("TERMINAL_CWD", os.path.expanduser("~"))
  38. async def inbound_references(runner, source, session_key, text):
  39. """``expand_references`` for an inbound turn: a local session's policy cwd, else the terminal cwd."""
  40. try:
  41. cwd = _inbound_cwd(runner, source)
  42. context_length = await runner._inbound_model_context_length(source, session_key)
  43. except Exception as exc:
  44. logger.warning("@ context reference expansion failed: %s", exc, exc_info=True)
  45. return text, None
  46. return await expand_references(text, cwd=cwd, context_length=context_length)
  47. async def turn_references(runner, event, source, session_key, text):
  48. """An inbound turn's text with the references of the text the model reads expanded; None when
  49. refused. The classic CLI's committed ``api_text`` replaces ``text`` at the turn
  50. (``TurnRunner._prepare_turn_message``), so ITS references are expanded and rebound for this
  51. execution, and the returned text, the stored user row, is ``text`` with the same attached
  52. context, as a typed turn stores it: later turns still read the content. A refused local turn
  53. leaves its refusal on ``event`` for the prepare step to answer with."""
  54. from gateway.session_cli_turn import cli_turn, rebind_api_text
  55. api_text = cli_turn(event.message_id).get('api_text')
  56. target = text if api_text is None else api_text
  57. if "@" not in target:
  58. return text
  59. if source.platform == Platform.LOCAL:
  60. expanded, refusal = await inbound_references(runner, source, session_key, target)
  61. if refusal is not None:
  62. event._gateway_turn_refusal = refusal
  63. return None
  64. elif (expanded := await runner._expand_inbound_context_references(source, session_key, target)) is None:
  65. return None
  66. if api_text is None:
  67. return expanded
  68. rebind_api_text(event.message_id, expanded)
  69. # The expansion appends its context after the message, so that tail belongs to the stored row too.
  70. head = api_text.lstrip()
  71. tail = expanded[len(head):] if expanded.startswith(head) else ""
  72. return f"{text}{tail}".strip() if tail else text
  73. async def managed_turn_text(authority, row, policy):
  74. """``(text, refusal)`` for a managed worker's admitted text, expanded against the session's
  75. workspace. Built-in kinds only for a bypass session, which loads no plugins; the context length
  76. is the frozen policy's, never the profile file a bypass session must not read. ``None`` text means
  77. the admitted text as committed."""
  78. text = (row.get('payload') or {}).get('text')
  79. if not isinstance(text, str) or "@" not in text:
  80. return None, None
  81. try:
  82. from agent.model_metadata import get_model_context_length_async
  83. model_config = policy.config(authority).get('model') or {}
  84. pinned = model_config.get('context_length') if isinstance(model_config, dict) else None
  85. with suppress(TypeError, ValueError):
  86. pinned = int(pinned) if pinned is not None else None
  87. context_length = await get_model_context_length_async(
  88. policy.current_model(authority) or '', base_url=policy.base_url or '', api_key='',
  89. provider=policy.provider or '', config_context_length=pinned if isinstance(pinned, int) else None)
  90. except Exception as exc:
  91. logger.warning("@ context reference expansion failed: %s", exc, exc_info=True)
  92. return text, None
  93. return await expand_references(text, cwd=policy.cwd, context_length=context_length,
  94. plugins=not policy.ignore_user_config)
  95. def refused_turn_result(row, refusal):
  96. """A turn that never ran because its references were refused: the refusal is its answer, and a
  97. finite (``chat -q`` / ``-z``) prompt fails with it, as ``execute_admission`` settles a notice."""
  98. if row['payload'].get('finite') is True:
  99. return {'final_response': '', 'messages': [], 'failed': True, 'completed': False, 'error': refusal}
  100. return {'final_response': refusal, 'messages': []}