session_tool_events.py 1.2 KB

123456789101112131415161718192021222324252627282930
  1. """Viewer payload limits; the full tool input/output stays in canonical history."""
  2. import json
  3. MAX_TOOL_EVENT_CHARS = 64 * 1024
  4. def bounded_args(args):
  5. encoded = json.dumps(args, ensure_ascii=True, default=str)
  6. if len(encoded) <= MAX_TOOL_EVENT_CHARS:
  7. return args
  8. # Retain ordinary scalar paths/commands for editor locations even when a content field is large.
  9. result = {}
  10. remaining = MAX_TOOL_EVENT_CHARS // 2
  11. for key, value in args.items():
  12. if remaining <= 0 or len(result) >= 64:
  13. break
  14. name = str(key)[:256]
  15. text = value if isinstance(value, str) else json.dumps(value, ensure_ascii=True, default=str)
  16. text = text[:min(4096, remaining)]
  17. result[name] = text
  18. remaining -= len(json.dumps([name, text], ensure_ascii=True))
  19. return result
  20. def bounded_result(result, is_error):
  21. text = result if isinstance(result, str) else json.dumps(result, ensure_ascii=True, default=str)
  22. if len(text) <= MAX_TOOL_EVENT_CHARS:
  23. return text
  24. # ACP reads errors from the result as well as the event flag; keep valid JSON after truncation.
  25. return json.dumps({'error' if is_error else 'output': text[:MAX_TOOL_EVENT_CHARS // 2], 'truncated': True})