pipe_demo.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. #!/usr/bin/env python3
  2. """Exercise the framed host protocol without granting owner fields to a model."""
  3. import json
  4. import struct
  5. import subprocess
  6. import sys
  7. def read_exact(stream, size):
  8. data = bytearray()
  9. while len(data) < size:
  10. part = stream.read(size - len(data))
  11. if not part:
  12. raise EOFError("worker closed the pipe")
  13. data.extend(part)
  14. return bytes(data)
  15. def main():
  16. command = sys.argv[1:] or ["./bin/cfbrowser", "serve"]
  17. process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
  18. try:
  19. request = {"version": 1, "id": 1, "method": "tools.call", "params": {
  20. "owner": {"environmentId": "local", "threadId": "t1", "runId": "r1"},
  21. "name": "cf_browser_session", "arguments": {"operation": "list"}}}
  22. payload = json.dumps(request).encode("utf-8")
  23. process.stdin.write(struct.pack(">I", len(payload)) + payload)
  24. process.stdin.flush()
  25. length = struct.unpack(">I", read_exact(process.stdout, 4))[0]
  26. if not 0 < length <= 512 * 1024:
  27. raise ValueError("invalid response length")
  28. print(json.loads(read_exact(process.stdout, length)))
  29. finally:
  30. process.stdin.close()
  31. try:
  32. process.wait(timeout=5)
  33. except subprocess.TimeoutExpired:
  34. process.kill()
  35. process.wait()
  36. if __name__ == "__main__":
  37. main()