#!/usr/bin/env python3 """pipbit_connect.py: Pipbit Connect for an agent that can only run a command. One file, Python 3.9 or newer, standard library only (no pip). It speaks the Pipbit agent connect protocol v1 (SDK/connect_spec/v1/PROTOCOL.md) in the shapes a hosted agent can drive when its tools are "run a command, read its output when it exits": python3 pipbit_connect.py pair --spoken-name Megan # once: register by voice under the name people say (--start / --claim split it; # --voice-request "a warm, unhurried voice" or --voice-id picks the voice) python3 pipbit_connect.py wait # connect, block until ONE turn arrives, print it, exit python3 pipbit_connect.py reply --text "..." # answer the most recent turn (HTTPS, no socket needed) python3 pipbit_connect.py reply --silent # answer it with no words: it was not for you, or nothing should be spoken python3 pipbit_connect.py daemon --ensure # keep one socket up in the background (presence stays online) python3 pipbit_connect.py next # no network: block until the daemon has stored a turn, print it, exit python3 pipbit_connect.py status # what is pending, what happened last python3 pipbit_connect.py diag # walk the network path stage by stage (no credentials needed) Two ways to listen. `wait` is exit-per-message: it opens the socket, proves the agent's secret, waits for a turn, sends `turn.ack` and a deferred `turn.result` (the platform then holds the reply token for 900 s), prints the turn, closes cleanly and exits 0; nothing inside --max-wait exits 3 (run it again). Between two `wait` runs the agent is OFFLINE to the platform: a turn or a hand-off that lands in that gap fails at once (there is no server-side mailbox), and every run spends one of the 10 hellos a minute the broker allows. `daemon` removes the gap: one long-lived process keeps the socket up, acknowledges and defers every turn into the state file, reconnects on its own, and `next` hands those turns out one at a time with no network at all, so a loop of `next` / think / `reply` costs nothing on the wire and the agent shows online the whole time. `daemon --ensure` starts it detached when it is not running and is safe to call from every loop iteration or a cron job; a VM swap that kills it is repaired by the next `--ensure`. A refusal that new credentials or an operator must fix exits 2 (stop). Anything else that broke exits 1. `reply` exits 4 when the platform refused the reply (token gone, cancelled, expired). Network: an `HTTPS_PROXY` (or `https_proxy`) URL is honoured for both the WebSocket (an HTTP CONNECT tunnel, with basic auth from the URL) and the HTTPS calls, as it must be inside a sandbox whose only egress is such a proxy. PIPBIT_CA_BUNDLE names a CA file for a proxy that re-signs TLS. Configuration, first match wins: command-line flags, PIPBIT_* environment variables, the constants just below (fill them in for a bench run where a pasted script must carry its own secret), then the state file `pair` wrote. Every step is stamped and appended to a JSON-lines ledger, so a test reads times from the file, never from memory. """ from __future__ import annotations import argparse import base64 import copy import hashlib import hmac import json import os import platform as _platform import random import re import secrets import shlex import signal import socket import ssl import struct import subprocess import sys import time import unicodedata import urllib.error import urllib.parse import urllib.request from typing import Any, Dict, List, Optional, Tuple try: # POSIX only; the state file lock is a no-op elsewhere import fcntl except ImportError: # pragma: no cover fcntl = None # type: ignore[assignment] # --------------------------------------------------------------------------- # Bench constants. Leave empty in the shipped file: `pair` fills the state # file and the other commands read it. For a pasted test copy, put the # agent's name and secret here so the script never asks its host for a # credential (a hosted agent's vault cannot sign the hello proof). # --------------------------------------------------------------------------- AGENT_NAME = "" AGENT_SECRET = "" BASE_URL = "https://api.pipbit.ai" CONNECT_URL = "wss://api.pipbit.ai/v1/connect" CLIENT_NAME = "pipbit-connect-cli" CLIENT_VERSION = "0.4.6" SUBPROTOCOL = "pipbit.connect.v1" PROTOCOL_VERSIONS = [1] CAPABILITIES = ["cancel", "redelivery"] # PROTOCOL.md section 14: the client reads the timing numbers from hello.ack; # these are the fallbacks when an ack omits one. DEFAULT_PING_INTERVAL_S = 30 DEFAULT_PONG_DEADLINE_S = 10 HELLO_ANSWER_TIMEOUT_S = 10.0 CONNECT_TIMEOUT_S = 120.0 # long: a sandbox may hold the tunnel open while its supervisor asks the person REPLY_TOKEN_TTL_S = 900 SEEN_TTL_S = 900 # de-duplication window for redelivered turns (section 8) SUPERSEDED_HOLDOFF_S = (30.0, 40.0) # section 10: at least 30 s with jitter DAEMON_UPGRADE_WAIT_S = 5.0 # how long `daemon --ensure` waits for an older daemon to leave before giving up DAEMON_VERSION_UNRECORDED = "pre-0.4.1" # daemons before 0.4.1 never wrote their version into the state file STATE_DIR_DEFAULT = os.path.join(os.path.expanduser("~"), ".pipbit_connect") INTRO_UTTERANCE = "__pipbit_agent_connected__" EVENT_UTTERANCE = "__pipbit_environment_event__" EXIT_TURN = 0 # a turn was delivered (wait/next) / the reply was accepted (reply) EXIT_ERROR = 1 # something broke that a retry may fix EXIT_STOP = 2 # do not run again until an operator or new credentials fix it EXIT_NOTHING = 3 # nothing to deliver this time; run again EXIT_REFUSED = 4 # reply: the platform refused the reply (token gone, cancelled, ...) # --------------------------------------------------------------------------- # Time stamps: wall clock in UTC with milliseconds, plus the raw epoch float. # --------------------------------------------------------------------------- def mint_secret() -> str: """A secret in the platform's own grammar: pb_live_sk_ plus 32 letters or digits from the OS's randomness.""" alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" return "pb_live_sk_" + "".join(secrets.choice(alphabet) for _ in range(32)) def now_iso(t: Optional[float] = None) -> str: t = time.time() if t is None else t return time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(t)) + f".{int((t % 1) * 1000):03d}Z" def stamp() -> Dict[str, Any]: t = time.time() return {"t": t, "iso": now_iso(t)} def describe_error(err: BaseException) -> str: """`str(err)` is empty for a bare TimeoutError; always name the class.""" text = str(err).strip() return f"{type(err).__name__}: {text}" if text else type(err).__name__ def note(text: str) -> None: print(f"[{now_iso()}] {text}", file=sys.stderr) sys.stderr.flush() # --------------------------------------------------------------------------- # TLS and proxy plumbing shared by the WebSocket and the HTTPS calls # --------------------------------------------------------------------------- def tls_context() -> ssl.SSLContext: cafile = os.environ.get("PIPBIT_CA_BUNDLE") or None ctx = ssl.create_default_context(cafile=cafile) if os.environ.get("PIPBIT_TLS_INSECURE") == "1": # Diagnostic only, for a proxy that re-signs TLS with a CA the # system store does not hold: prefer PIPBIT_CA_BUNDLE. ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE return ctx def proxy_for(scheme: str, host: str) -> Optional[urllib.parse.SplitResult]: """The HTTPS_PROXY (or HTTP_PROXY) URL as a parsed value, unless NO_PROXY names the host. A hosted agent's sandbox usually sets these for every shell; a fresh process sees the current credentials.""" for name in ("no_proxy", "NO_PROXY"): entries = [e.strip() for e in os.environ.get(name, "").split(",") if e.strip()] for entry in entries: if entry == "*" or host == entry or host.endswith("." + entry.lstrip(".")): return None if host in ("127.0.0.1", "localhost", "::1"): return None names = ("HTTPS_PROXY", "https_proxy") if scheme in ("wss", "https") else ("HTTP_PROXY", "http_proxy") for name in names: value = os.environ.get(name) if value: try: parsed = urllib.parse.urlsplit(value if "://" in value else "http://" + value) except ValueError: continue if parsed.hostname: if parsed.port is None: # One default for the tunnel and for urllib alike. netloc = parsed.netloc + ":3128" parsed = parsed._replace(netloc=netloc) return parsed return None class ProxyRefused(ConnectionError): """The CONNECT proxy answered something other than 200 (407 = its credentials rotated under a long-lived process; a fresh process reads the current ones).""" def __init__(self, status_line: str) -> None: super().__init__(f"proxy refused CONNECT: {status_line}") self.status_line = status_line def open_tunnel(proxy: urllib.parse.SplitResult, host: str, port: int, timeout: float) -> socket.socket: raw = socket.create_connection((proxy.hostname, proxy.port or 3128), timeout=timeout) request = f"CONNECT {host}:{port} HTTP/1.1\r\nHost: {host}:{port}\r\n" if proxy.username is not None: creds = f"{urllib.parse.unquote(proxy.username)}:{urllib.parse.unquote(proxy.password or '')}" request += "Proxy-Authorization: Basic " + base64.b64encode(creds.encode("utf-8")).decode("ascii") + "\r\n" request += "\r\n" raw.sendall(request.encode("ascii")) head = b"" while b"\r\n\r\n" not in head: chunk = raw.recv(4096) if not chunk: raw.close() raise ConnectionError("proxy closed the connection during CONNECT") head += chunk if len(head) > 65536: raw.close() raise ConnectionError("proxy CONNECT response too large") status_line = head.split(b"\r\n", 1)[0].decode("iso-8859-1") parts = status_line.split(" ", 2) if len(parts) < 2 or parts[1] != "200": raw.close() raise ProxyRefused(status_line) return raw HTTP_TIMEOUT_S = 120.0 # same reason as CONNECT_TIMEOUT_S def http_json(method: str, url: str, body: Optional[Dict[str, Any]] = None, headers: Optional[Dict[str, str]] = None, timeout: float = HTTP_TIMEOUT_S) -> Tuple[int, Any]: data = None if body is None else json.dumps(body).encode("utf-8") req = urllib.request.Request(url, data=data, method=method) req.add_header("Accept", "application/json") req.add_header("User-Agent", f"{CLIENT_NAME}/{CLIENT_VERSION}") if data is not None: req.add_header("Content-Type", "application/json") for k, v in (headers or {}).items(): req.add_header(k, v) # The same proxy decision as the WebSocket path (proxy_for), handed to # urllib explicitly; it tunnels HTTPS with CONNECT and sends the URL's # credentials as basic auth. target = urllib.parse.urlsplit(url) proxy = proxy_for(target.scheme, target.hostname or "") proxies = {"https": proxy.geturl(), "http": proxy.geturl()} if proxy is not None else {} opener = urllib.request.build_opener(urllib.request.ProxyHandler(proxies), urllib.request.HTTPSHandler(context=tls_context())) try: with opener.open(req, timeout=timeout) as resp: raw = resp.read() status = resp.status except urllib.error.HTTPError as err: raw = err.read() status = err.code try: parsed = json.loads(raw.decode("utf-8")) if raw else None except ValueError: parsed = {"raw": raw[:1000].decode("utf-8", "replace")} return status, parsed # --------------------------------------------------------------------------- # A minimal RFC 6455 client over the standard library: TCP or CONNECT tunnel, # TLS, the HTTP upgrade with the subprotocol, masked text frames out, # text/ping/pong/close frames in. Fragmented messages are reassembled. Nothing # else is needed for this protocol: the broker sends no WebSocket-level pings # of its own and only ever sends text frames. # --------------------------------------------------------------------------- _WS_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" OP_CONT, OP_TEXT, OP_BINARY, OP_CLOSE, OP_PING, OP_PONG = 0x0, 0x1, 0x2, 0x8, 0x9, 0xA class SocketClosed(Exception): """The peer closed the WebSocket (code and reason as it sent them).""" def __init__(self, code: Optional[int], reason: str = "") -> None: super().__init__(f"websocket closed code={code} reason={reason!r}") self.code = code self.reason = reason class WebSocket: def __init__(self, url: str, *, subprotocol: str = SUBPROTOCOL, timeout: float = CONNECT_TIMEOUT_S) -> None: self.url = url self.subprotocol = subprotocol self.selected_protocol: Optional[str] = None self.via_proxy: Optional[str] = None self._sock: Optional[socket.socket] = None self._buf = b"" self._closed = False self._connect(timeout) # -- connection --------------------------------------------------------- def _connect(self, timeout: float) -> None: scheme, rest = self.url.split("://", 1) if scheme not in ("ws", "wss"): raise ValueError(f"not a WebSocket URL: {self.url}") hostport, _, path = rest.partition("/") path = "/" + path if ":" in hostport: host, port_text = hostport.rsplit(":", 1) port = int(port_text) else: host, port = hostport, (443 if scheme == "wss" else 80) proxy = proxy_for(scheme, host) if proxy is not None: raw = open_tunnel(proxy, host, port, timeout) self.via_proxy = f"{proxy.hostname}:{proxy.port or 3128}" else: raw = socket.create_connection((host, port), timeout=timeout) if scheme == "wss": raw = tls_context().wrap_socket(raw, server_hostname=host) self._sock = raw key = base64.b64encode(os.urandom(16)).decode("ascii") host_header = host if port in (80, 443) else f"{host}:{port}" request = ( f"GET {path} HTTP/1.1\r\n" f"Host: {host_header}\r\n" "Upgrade: websocket\r\n" "Connection: Upgrade\r\n" f"Sec-WebSocket-Key: {key}\r\n" "Sec-WebSocket-Version: 13\r\n" f"Sec-WebSocket-Protocol: {self.subprotocol}\r\n" f"User-Agent: {CLIENT_NAME}/{CLIENT_VERSION}\r\n" "\r\n" ) raw.sendall(request.encode("ascii")) head = b"" while b"\r\n\r\n" not in head: chunk = raw.recv(4096) if not chunk: raise ConnectionError("connection closed during the WebSocket handshake") head += chunk if len(head) > 65536: raise ConnectionError("handshake response too large") header_bytes, self._buf = head.split(b"\r\n\r\n", 1) lines = header_bytes.decode("iso-8859-1").split("\r\n") status_line = lines[0] parts = status_line.split(" ", 2) if len(parts) < 2 or parts[1] != "101": body = self._buf[:512].decode("utf-8", "replace") raise ConnectionError(f"WebSocket upgrade refused: {status_line} {body}".strip()) headers = {} for line in lines[1:]: name, _, value = line.partition(":") headers[name.strip().lower()] = value.strip() expected = base64.b64encode(hashlib.sha1((key + _WS_GUID).encode("ascii")).digest()).decode("ascii") if headers.get("sec-websocket-accept") != expected: raise ConnectionError("WebSocket upgrade: bad Sec-WebSocket-Accept") self.selected_protocol = headers.get("sec-websocket-protocol") if self.selected_protocol != self.subprotocol: raise ConnectionError(f"server did not select subprotocol {self.subprotocol} (got {self.selected_protocol!r})") # -- frames ------------------------------------------------------------- def _send_frame(self, opcode: int, payload: bytes) -> None: assert self._sock is not None header = bytearray([0x80 | opcode]) n = len(payload) if n < 126: header.append(0x80 | n) elif n < 65536: header.append(0x80 | 126) header += struct.pack("!H", n) else: header.append(0x80 | 127) header += struct.pack("!Q", n) mask = os.urandom(4) header += mask masked = bytes(b ^ mask[i % 4] for i, b in enumerate(payload)) self._sock.sendall(bytes(header) + masked) def send_text(self, text: str) -> None: self._send_frame(OP_TEXT, text.encode("utf-8")) def _read_exact(self, n: int, deadline: Optional[float]) -> bytes: assert self._sock is not None while len(self._buf) < n: if deadline is not None: remaining = deadline - time.monotonic() if remaining <= 0: raise socket.timeout("read deadline") self._sock.settimeout(remaining) else: self._sock.settimeout(None) chunk = self._sock.recv(65536) if not chunk: raise SocketClosed(None, "connection dropped") self._buf += chunk out, self._buf = self._buf[:n], self._buf[n:] return out def _read_frame(self, deadline: Optional[float]) -> Tuple[bool, int, bytes]: # Nothing is taken out of the buffer until the whole frame is in # it: a read deadline that fires mid-frame (the ping tick landing # while a large turn straddles two TLS records) must leave the # parser aligned for the next call. assert self._sock is not None def need(n: int) -> None: while len(self._buf) < n: if deadline is not None: remaining = deadline - time.monotonic() if remaining <= 0: raise socket.timeout("read deadline") self._sock.settimeout(remaining) else: self._sock.settimeout(None) chunk = self._sock.recv(65536) if not chunk: raise SocketClosed(None, "connection dropped") self._buf += chunk need(2) b0, b1 = self._buf[0], self._buf[1] fin = bool(b0 & 0x80) opcode = b0 & 0x0F masked = bool(b1 & 0x80) n = b1 & 0x7F offset = 2 if n == 126: need(4) (n,) = struct.unpack("!H", self._buf[2:4]) offset = 4 elif n == 127: need(10) (n,) = struct.unpack("!Q", self._buf[2:10]) offset = 10 mask = b"" if masked: need(offset + 4) mask = bytes(self._buf[offset:offset + 4]) offset += 4 need(offset + n) payload = bytes(self._buf[offset:offset + n]) self._buf = self._buf[offset + n:] if masked: payload = bytes(b ^ mask[i % 4] for i, b in enumerate(payload)) return fin, opcode, payload def recv_text(self, timeout: Optional[float]) -> str: """The next complete text message. Raises socket.timeout when nothing arrived in time (the connection is still fine), SocketClosed when the peer closed. Answers WebSocket pings itself.""" deadline = None if timeout is None else time.monotonic() + timeout message = b"" message_opcode: Optional[int] = None while True: fin, opcode, payload = self._read_frame(deadline) if opcode == OP_PING: self._send_frame(OP_PONG, payload) continue if opcode == OP_PONG: continue if opcode == OP_CLOSE: code = struct.unpack("!H", payload[:2])[0] if len(payload) >= 2 else None reason = payload[2:].decode("utf-8", "replace") try: self._send_frame(OP_CLOSE, payload[:2]) except OSError: pass self._closed = True raise SocketClosed(code, reason) if opcode in (OP_TEXT, OP_BINARY): message_opcode = opcode message = payload elif opcode == OP_CONT: message += payload else: continue if fin: if message_opcode == OP_BINARY: message, message_opcode = b"", None continue return message.decode("utf-8") def close(self, code: int = 1000, reason: str = "") -> None: if self._sock is None: return if not self._closed: try: self._send_frame(OP_CLOSE, struct.pack("!H", code) + reason.encode("utf-8")) self._closed = True # Give the peer a moment to answer the close so the broker # logs a clean 1000 rather than a dropped connection. try: while True: _, opcode, _ = self._read_frame(time.monotonic() + 1.0) if opcode == OP_CLOSE: break except (OSError, SocketClosed): pass except OSError: pass try: self._sock.close() except OSError: pass self._sock = None # --------------------------------------------------------------------------- # Configuration and state # --------------------------------------------------------------------------- def _first(*values: Optional[str]) -> str: for value in values: if value: return value return "" class State: """`/.json` (credentials, pending turns, de-dup memory, counters, the daemon's pid) and `/.ledger.jsonl` (every stamped event). Writers take the lock file; readers see whole files because every write is an atomic replace.""" def __init__(self, state_dir: str, agent: str) -> None: self.state_dir = state_dir self.agent = agent or "_unnamed" self.path = os.path.join(state_dir, f"{self.agent}.json") self.lock_path = os.path.join(state_dir, f"{self.agent}.lock") self.ledger_path = os.path.join(state_dir, f"{self.agent}.ledger.jsonl") self.pid_path = os.path.join(state_dir, f"{self.agent}.daemon.pid") self.daemon_log_path = os.path.join(state_dir, f"{self.agent}.daemon.log") self.data: Dict[str, Any] = {} self._lock_fh = None self.reload() def reload(self) -> None: self.data = {"pending": [], "seen": {}, "counters": {}} if os.path.exists(self.path): try: with open(self.path, "r", encoding="utf-8") as fh: self.data.update(json.load(fh)) except (OSError, ValueError): pass self.data.setdefault("pending", []) self.data.setdefault("seen", {}) self.data.setdefault("counters", {}) def only_agent(self) -> str: """When one agent has ever paired here, its name is the default.""" names = paired_agents(self.state_dir) return names[0] if len(names) == 1 else "" def __enter__(self) -> "State": os.makedirs(self.state_dir, mode=0o700, exist_ok=True) if fcntl is not None: self._lock_fh = open(self.lock_path, "a+") fcntl.flock(self._lock_fh.fileno(), fcntl.LOCK_EX) self.reload() return self def __exit__(self, *exc: Any) -> None: try: if exc[0] is None: self.save() finally: if self._lock_fh is not None: if fcntl is not None: fcntl.flock(self._lock_fh.fileno(), fcntl.LOCK_UN) self._lock_fh.close() self._lock_fh = None def save(self) -> None: os.makedirs(self.state_dir, mode=0o700, exist_ok=True) cutoff = time.time() - SEEN_TTL_S self.data["seen"] = {k: v for k, v in self.data["seen"].items() if v >= cutoff} self.data["pending"] = [p for p in self.data["pending"] if p.get("expires_t", 0) >= cutoff] # A turn whose reply token has expired is never handed out again # (next_unhanded skips it; reply reads only its ids to refuse it), # so its words leave the file now; the entry itself stays one seen # window longer so a redelivery is still recognised. now = time.time() for p in self.data["pending"]: if p.get("expires_t", 0) <= now: for key in ("utterance", "handoff_context", "conversation_tail"): p.pop(key, None) tmp = self.path + ".tmp" with open(tmp, "w", encoding="utf-8") as fh: json.dump(self.data, fh, indent=1, sort_keys=True) os.chmod(tmp, 0o600) os.replace(tmp, self.path) def ledger(self, event: str, **fields: Any) -> Dict[str, Any]: os.makedirs(self.state_dir, mode=0o700, exist_ok=True) record = {"event": event, "pid": os.getpid(), **stamp(), **fields} with open(self.ledger_path, "a", encoding="utf-8") as fh: fh.write(json.dumps(record, sort_keys=True) + "\n") return record def bump(self, counter: str) -> None: self.data["counters"][counter] = int(self.data["counters"].get(counter, 0)) + 1 def remember_turn(self, turn: Dict[str, Any]) -> None: self.data["seen"][turn["request_id"]] = time.time() self.data["pending"] = [p for p in self.data["pending"] if p["request_id"] != turn["request_id"]] self.data["pending"].append(turn) def next_unhanded(self) -> Optional[Dict[str, Any]]: now = time.time() for p in self.data["pending"]: if not p.get("handed_out") and not p.get("cancelled") and p.get("expires_t", 0) > now: return p return None def latest_handed_out(self) -> Optional[Dict[str, Any]]: """The turn `wait` or `next` most recently handed to the host, cancelled or expired ones included: those belong to the host's reply too (it hears the refusal), never to a later `next`.""" handed = [p for p in self.data["pending"] if p.get("handed_out")] return handed[-1] if handed else None def settle(self, request_id: str, outcome: str) -> None: self.data["pending"] = [p for p in self.data["pending"] if p["request_id"] != request_id] self.data["seen"][request_id] = time.time() self.data["last_settled"] = {"request_id": request_id, "outcome": outcome, **stamp()} # -- the daemon's pid ---------------------------------------------------- def daemon_pid(self) -> Optional[int]: try: with open(self.pid_path, "r", encoding="utf-8") as fh: pid = int(fh.read().strip() or "0") except (OSError, ValueError): return None if pid <= 0: return None try: os.kill(pid, 0) except ProcessLookupError: return None except PermissionError: return None # A recycled pid after a VM swap must not pass for our daemon: # where /proc exists, the process must be this script's daemon. try: with open(f"/proc/{pid}/cmdline", "rb") as fh: cmdline = fh.read() if b"pipbit_connect" not in cmdline or b"daemon" not in cmdline: return None except OSError: pass # no /proc (macOS): liveness is all we can check return pid def write_pid(self) -> None: os.makedirs(self.state_dir, mode=0o700, exist_ok=True) with open(self.pid_path, "w", encoding="utf-8") as fh: fh.write(str(os.getpid())) # -- the blocking `next` ------------------------------------------------- def listener_live(self) -> Optional[Dict[str, Any]]: """The `listener` entry `next` wrote while it blocks, when that process is still alive and still inside its own wait; else None. A `next` killed by its sandbox never clears its entry, so the pid must answer a signal 0 (PermissionError means it exists) and the deadline must not have passed: a recycled pid after a VM swap can pass the first check, so the deadline is the real ceiling.""" entry = self.data.get("listener") if not isinstance(entry, dict): return None try: pid = int(entry.get("pid") or 0) deadline_t = float(entry.get("deadline_t") or 0) except (TypeError, ValueError): return None if pid <= 0 or time.time() >= deadline_t: return None try: os.kill(pid, 0) except ProcessLookupError: return None except PermissionError: pass return entry def clear_pid(self) -> None: try: with open(self.pid_path, "r", encoding="utf-8") as fh: if int(fh.read().strip() or "0") == os.getpid(): os.remove(self.pid_path) except (OSError, ValueError): pass LEDGER_TAIL_BYTES = 64 * 1024 WAIT_ESTIMATE_DEFAULT_S = 60 WAIT_ESTIMATE_MAX_S = 600 LISTENER_CONTINUOUS_S = 1.0 # a `next` re-run within a second is the same listener, not a gap HANDED_OUT_ANSWERING_S = 120.0 # after a turn was handed out, the loop is answering it, not away def estimate_wait_s(state: "State") -> float: """How long a turn that arrives now will probably wait for a `next`, read from the agent's own ledger: each `next.start` paired with the `next.idle` or `next.handed_out` of the same pid is one listening interval; the quiet stretches between intervals are the cadence (a scheduled run every minute leaves a gap of about a minute). The estimate is the median gap less the time already spent quiet, floored at 0 and capped at WAIT_ESTIMATE_MAX_S. With no ledger, a torn ledger or fewer than two gaps it is the conservative WAIT_ESTIMATE_DEFAULT_S. Only the tail of the file is read, so this stays cheap enough to run under the state lock (it never touches the network).""" try: with open(state.ledger_path, "rb") as fh: fh.seek(0, os.SEEK_END) size = fh.tell() start = max(0, size - LEDGER_TAIL_BYTES) fh.seek(start) blob = fh.read() except OSError: return float(WAIT_ESTIMATE_DEFAULT_S) if start > 0: # The tail begins mid-line: drop the fragment before the first newline. blob = blob.split(b"\n", 1)[1] if b"\n" in blob else b"" open_starts: Dict[int, float] = {} intervals: List[Tuple[float, float]] = [] for raw in blob.split(b"\n"): if not raw.strip(): continue try: record = json.loads(raw.decode("utf-8")) except (ValueError, UnicodeDecodeError): continue # a half-written line (the ledger is appended without the lock) if not isinstance(record, dict): continue event = record.get("event") try: pid = int(record.get("pid") or 0) t = float(record.get("t") or 0) except (TypeError, ValueError): continue if event == "next.start": open_starts[pid] = t elif event in ("next.idle", "next.handed_out") and pid in open_starts: intervals.append((open_starts.pop(pid), t, event)) intervals.sort() if intervals: # A listener that just took a turn is composing its answer and will # run `next` again the moment it has replied (the skill's loop): the # agent is on it, not away between scheduled runs. Seen 2026-10-01 # 02:15:46: a hint of 154 s sent while the previous answer was # three seconds from done. last_start, last_end, last_event = max(intervals, key=lambda item: item[1]) if last_event == "next.handed_out" and (time.time() - last_end) < HANDED_OUT_ANSWERING_S: return 0.0 gaps: List[float] = [] covered_until: Optional[float] = None for start_t, end_t, _event in intervals: if covered_until is not None: gap = start_t - covered_until if gap > LISTENER_CONTINUOUS_S: gaps.append(gap) covered_until = end_t if covered_until is None else max(covered_until, end_t) if covered_until is None or len(gaps) < 2: return float(WAIT_ESTIMATE_DEFAULT_S) gaps.sort() mid = len(gaps) // 2 median = gaps[mid] if len(gaps) % 2 else (gaps[mid - 1] + gaps[mid]) / 2.0 remaining = median - (time.time() - covered_until) return round(min(float(WAIT_ESTIMATE_MAX_S), max(0.0, remaining)), 1) class Config: def __init__(self, args: argparse.Namespace) -> None: self.state_dir = args.state_dir or os.environ.get("PIPBIT_STATE_DIR") or STATE_DIR_DEFAULT self.agent = _first(getattr(args, "agent", None), os.environ.get("PIPBIT_AGENT_NAME"), AGENT_NAME) self.secret = _first(getattr(args, "secret", None), os.environ.get("PIPBIT_AGENT_SECRET"), AGENT_SECRET) self.base_url = _first(getattr(args, "base_url", None), os.environ.get("PIPBIT_BASE_URL"), BASE_URL) self.connect_url = _first(getattr(args, "connect_url", None), os.environ.get("PIPBIT_CONNECT_URL"), CONNECT_URL) self.json_only = bool(getattr(args, "json", False)) self.args = args # The state file fills whatever is still missing. self.state = State(self.state_dir, self.agent) saved = self.state.data.get("credentials") or {} if not self.agent: self.agent = saved.get("agent_name") or read_default_agent(self.state_dir) or self.state.only_agent() if self.agent: self.state = State(self.state_dir, self.agent) saved = self.state.data.get("credentials") or {} if not self.secret: self.secret = saved.get("secret") or "" if saved.get("base_url") and getattr(args, "base_url", None) is None and not os.environ.get("PIPBIT_BASE_URL"): self.base_url = saved["base_url"] if saved.get("connect_url") and getattr(args, "connect_url", None) is None and not os.environ.get("PIPBIT_CONNECT_URL"): self.connect_url = saved["connect_url"] def require_credentials(self) -> None: if not self.agent or not self.secret: names = paired_agents(self.state_dir) if len(names) > 1 and not self.agent: raise SystemExit( f"several agents are paired here ({', '.join(names)}) and none is marked as the default: " "pass --agent , or pair again (the latest pairing becomes the default)" ) raise SystemExit( "no agent credentials: run `pair --spoken-name \"\"` first, set PIPBIT_AGENT_NAME and " "PIPBIT_AGENT_SECRET, or fill in AGENT_NAME and AGENT_SECRET at the top of this file" ) def self_command(self, *args: str) -> List[str]: """This script, with the same explicit settings, for a detached child.""" cmd = [sys.executable, os.path.abspath(__file__)] for flag, value in (("--agent", getattr(self.args, "agent", None)), ("--secret", getattr(self.args, "secret", None)), ("--base-url", getattr(self.args, "base_url", None)), ("--connect-url", getattr(self.args, "connect_url", None)), ("--state-dir", self.state_dir)): if value: cmd += [flag, value] cmd += list(args) # The listening flags travel with a spawned daemon too. if getattr(self.args, "echo", False): cmd += ["--echo", "--echo-prefix", getattr(self.args, "echo_prefix", "You said: ")] if getattr(self.args, "intro_reply", None): cmd += ["--intro-reply", self.args.intro_reply] return cmd # --------------------------------------------------------------------------- # Output for the caller (a person, or a model reading a command's output) # --------------------------------------------------------------------------- def emit(cfg: Config, human: str, record: Dict[str, Any]) -> None: if not cfg.json_only and human: print(human) print("JSON " + json.dumps(record, sort_keys=True)) sys.stdout.flush() # --------------------------------------------------------------------------- # The protocol # --------------------------------------------------------------------------- def build_hello(agent: str, secret: str) -> Dict[str, Any]: timestamp = str(int(time.time())) nonce = base64.urlsafe_b64encode(os.urandom(16)).decode("ascii").rstrip("=") signed = f"{timestamp}.{nonce}.{agent}".encode("utf-8") signature = hmac.new(secret.encode("utf-8"), signed, hashlib.sha256).hexdigest() return { "type": "hello", "protocol_versions": PROTOCOL_VERSIONS, "agent": agent, "client": { "name": CLIENT_NAME, "version": CLIENT_VERSION, "runtime": f"{_platform.python_implementation().lower()}/{_platform.python_version()}", }, "capabilities": CAPABILITIES, "auth": {"method": "hmac-v1", "timestamp": timestamp, "nonce": nonce, "signature": signature}, } class Link: """One socket, from dial to hello.ack, with the numbers the ack carried.""" def __init__(self, cfg: Config) -> None: self.cfg = cfg self.t_dial = time.time() self.ws = WebSocket(cfg.connect_url) self.t_open = time.time() self.ws.send_text(json.dumps(build_hello(cfg.agent, cfg.secret))) self.ack: Dict[str, Any] = {} self.t_ack: Optional[float] = None self.error: Optional[Dict[str, Any]] = None self._next_id = 0 self.ping_interval = DEFAULT_PING_INTERVAL_S self.pong_deadline = DEFAULT_PONG_DEADLINE_S self._await_ack() def _await_ack(self) -> None: deadline = time.monotonic() + HELLO_ANSWER_TIMEOUT_S while True: remaining = deadline - time.monotonic() if remaining <= 0: raise TimeoutError("no hello.ack within the hello timeout") frame = json.loads(self.ws.recv_text(remaining)) kind = frame.get("type") if kind == "hello.ack": self.ack = frame self.t_ack = time.time() self.ping_interval = float(frame.get("ping_interval_s") or DEFAULT_PING_INTERVAL_S) self.pong_deadline = float(frame.get("pong_deadline_s") or DEFAULT_PONG_DEADLINE_S) return if kind == "hello.error": self.error = frame return # Anything else before the ack is unexpected but harmless. def next_id(self) -> str: self._next_id += 1 return f"c-{self._next_id}" def send(self, frame: Dict[str, Any]) -> None: self.ws.send_text(json.dumps(frame)) def summary(self) -> Dict[str, Any]: return { "connection_id": self.ack.get("connection_id"), "dial_ms": round((self.t_open - self.t_dial) * 1000), "hello_ms": round(((self.t_ack or time.time()) - self.t_open) * 1000), "resumed": self.ack.get("resumed"), "redelivered": self.ack.get("redelivered"), "capabilities": self.ack.get("capabilities"), "limits": self.ack.get("limits"), "via_proxy": self.ws.via_proxy, } def _close_code_verdict(code: Optional[int]) -> Tuple[int, str]: """PROTOCOL.md section 10: what the close code tells this client to do.""" if code in (4000, 4002, 4004, 4005, 4009): return EXIT_STOP, "do not run again until an operator or new credentials fix this" if code == 4001: return EXIT_NOTHING, "another copy of this agent connected; wait at least 30 s before running again" if code == 4003: return EXIT_NOTHING, "policy or quota; wait the usual hold-off before running again" return EXIT_NOTHING, "run again" def _hello_error_verdict(frame: Dict[str, Any]) -> Tuple[int, str]: error = frame.get("error") if error in ("authentication_failed", "transport_mismatch", "connect_not_enabled", "agent_suspended", "protocol_unsupported"): return EXIT_STOP, "do not run again until an operator or new credentials fix this" if error == "rate_limited": return EXIT_NOTHING, f"too many connections; wait {frame.get('retry_after_s', 30)} s before running again" return EXIT_ERROR, "unexpected hello.error" def _turn_record(cfg: Config, frame: Dict[str, Any], link: Link, t_recv: float, t_ack: float, inline: Optional[str], waited_s: float) -> Dict[str, Any]: payload = frame.get("payload") or {} utterance = payload.get("utterance", "") kind = "turn" if utterance == INTRO_UTTERANCE: kind = "intro" elif utterance == EVENT_UTTERANCE: kind = "event" conversation = payload.get("conversation") or [] return { "event": "turn", "kind": kind, "request_id": frame.get("request_id") or payload.get("request_id"), "reply_token": payload.get("reply_token"), "utterance": utterance, "handoff_context": payload.get("handoff_context"), "conversation_tail": conversation[-6:], "session_id": payload.get("session_id"), "subject_id": payload.get("subject_id"), "agent_session_id": payload.get("agent_session_id"), "manager_name": payload.get("manager_name"), "speaker_verified": payload.get("speaker_verified"), "speaker_basis": payload.get("speaker_basis"), # How the person engaged this agent (spec 1.8.0): "named" or # "router"; None from an older Pipbit, like the speaker fields. "engagement": payload.get("engagement"), "environment_event": payload.get("environment_event"), "redelivery": bool(frame.get("redelivery")), "received_at": now_iso(t_recv), "received_t": t_recv, "ack_ms": round((t_ack - t_recv) * 1000), "answered_inline": inline, "expires_at": now_iso(t_recv + REPLY_TOKEN_TTL_S), "expires_t": t_recv + REPLY_TOKEN_TTL_S, "waited_s": round(waited_s, 3), "link": link.summary(), "agent": cfg.agent, } def _pending_entry(rec: Dict[str, Any], handed_out: bool) -> Dict[str, Any]: return { "request_id": rec["request_id"], "reply_token": rec["reply_token"], "utterance": rec["utterance"], "handoff_context": rec["handoff_context"], "kind": rec["kind"], "engagement": rec.get("engagement"), "conversation_tail": rec["conversation_tail"], "received_t": rec["received_t"], "received_at": rec["received_at"], "expires_t": rec["expires_t"], "handed_out": handed_out, } # The fields of a turn record that hold words: the person's utterance, the # hand-off context, an environment event's text and an inline answer. _SPEECH_FIELDS = ("utterance", "handoff_context", "environment_event", "answered_inline") def _text_free(rec: Dict[str, Any]) -> Dict[str, Any]: """A copy of a turn record (or a pending entry) with no words in it, for the ledger, the daemon's log and `status`: each speech field becomes its character count under `_chars`, and the conversation tail becomes its roles with a `text_chars` each. Pipbit stores no transcripts (DOC/debug-capture-kickoff.md section 2.7); only the state file's pending list keeps a turn's words, until `wait` or `next` has handed it to the hosting agent and `reply` has settled it.""" out: Dict[str, Any] = {} for key, value in rec.items(): if key in _SPEECH_FIELDS: if value is None or value == "": out[f"{key}_chars"] = 0 else: out[f"{key}_chars"] = len(value if isinstance(value, str) else json.dumps(value, sort_keys=True)) elif key == "conversation_tail": tail = value if isinstance(value, list) else [] out["conversation_tail"] = [ {"role": (item.get("role") if isinstance(item, dict) else None), "text_chars": len(str(item.get("text") or "")) if isinstance(item, dict) else 0} for item in tail ] else: out[key] = value return out # What each engagement kind asks of the agent, in the words the SDK's # Request.engagement_note() uses, so an agent reading this output and one # reading the SDK hear the same rule. A kind this copy does not know is # shown as its word alone. ENGAGEMENT_NOTES = { "named": "the person asked for you by name; stay with them until they end the conversation " "or ask for Pip, and do not hand back after answering", "router": "this request was sent to you without your name; answer it and stay available for " "a correction, and do not hand back yourself, the floor returns to Pip on its own", } def describe_turn(rec: Dict[str, Any], inline: Optional[str]) -> str: lines = [f"PIPBIT TURN request_id={rec['request_id']} reply_token={rec['reply_token']} received_at={rec['received_at']}"] if rec["kind"] == "intro": lines.append("kind: the person just switched to this agent; your reply is the greeting.") if rec.get("handoff_context"): lines.append(f"they also said: {rec['handoff_context']}") else: lines.append(f"utterance: {rec['utterance']}") engagement = rec.get("engagement") if isinstance(engagement, str) and re.fullmatch(r"[a-z_]{1,32}", engagement): gloss = ENGAGEMENT_NOTES.get(engagement) lines.append(f"engagement: {engagement}" + (f" ({gloss})." if gloss else ".")) if inline is not None: lines.append(f"answered inline: {inline}") else: lines.append(f"to answer (within 15 minutes): python3 {os.path.basename(sys.argv[0])} reply --token {rec['reply_token']} --text \"...\"") lines.append("not for you, or nothing to say: the same reply with --silent in place of --text") return "\n".join(lines) class Session: """One connected socket being served: the frame loop shared by `wait` (one turn, then return) and `daemon` (every turn, forever). Returns why it stopped: ("turn", record) after a delivered turn in wait mode, ("deadline", None), ("closed", SocketClosed), ("error", str).""" def __init__(self, cfg: Config, link: Link, *, deliver_once: bool, echo: bool, echo_prefix: str, intro_reply: Optional[str], print_events: bool, on_turn) -> None: self.cfg = cfg self.link = link self.deliver_once = deliver_once self.echo = echo self.echo_prefix = echo_prefix self.intro_reply = intro_reply self.print_events = print_events self.on_turn = on_turn self.delivered = 0 self.t_start = time.time() def run(self, max_wait: Optional[float]) -> Tuple[str, Any]: cfg, link, state = self.cfg, self.link, self.cfg.state next_ping = time.monotonic() + link.ping_interval pending_pong: Optional[Tuple[int, float]] = None deadline = None if max_wait is None else time.monotonic() + max_wait try: while True: now_m = time.monotonic() if deadline is not None and now_m >= deadline: return "deadline", None if pending_pong is not None and now_m - pending_pong[1] > link.pong_deadline: state.ledger("link.pong_timeout", agent=cfg.agent) return "error", "no pong within the deadline; the link is dead" if now_m >= next_ping: ts = int(time.time() * 1000) link.send({"type": "ping", "ts": ts}) pending_pong = (ts, now_m) next_ping = now_m + link.ping_interval limit = next_ping if deadline is None else min(deadline, next_ping) if pending_pong is not None: limit = min(limit, pending_pong[1] + link.pong_deadline) timeout = max(0.05, limit - time.monotonic()) try: text = link.ws.recv_text(timeout) except socket.timeout: continue try: frame = json.loads(text) except ValueError: note(f"non-JSON frame ignored: {text[:80]!r}") continue kind = frame.get("type") if kind == "ping": link.send({"type": "pong", "ts": frame.get("ts")}) elif kind == "pong": if pending_pong is not None and frame.get("ts") == pending_pong[0]: state.ledger("link.pong", rtt_ms=round((time.monotonic() - pending_pong[1]) * 1000), agent=cfg.agent) pending_pong = None elif kind == "turn": outcome = self._on_turn_frame(frame) if outcome is not None and self.deliver_once: return "turn", outcome elif kind == "cancel": self._on_cancel(frame) elif kind == "revoked": state.ledger("link.revoked", reason=frame.get("reason"), message=frame.get("message"), agent=cfg.agent) note(f"revoked: {frame.get('reason')}: {frame.get('message')}") elif kind == "close": state.ledger("link.close_notice", reason=frame.get("reason"), by=frame.get("by_connection_id"), agent=cfg.agent) note(f"server is closing this socket: {frame.get('reason')}") elif kind == "error": state.ledger("link.protocol_error", frame=frame, agent=cfg.agent) note(f"protocol error frame: {frame}") else: note(f"unknown frame type ignored: {kind}") except SocketClosed as closed: return "closed", closed except (OSError, ConnectionError) as err: return "error", describe_error(err) def _on_turn_frame(self, frame: Dict[str, Any]) -> Optional[Dict[str, Any]]: cfg, link, state = self.cfg, self.link, self.cfg.state t_recv = time.time() payload = frame.get("payload") or {} request_id = frame.get("request_id") or payload.get("request_id") link.send({"type": "turn.ack", "request_id": request_id}) t_ack = time.time() utterance = payload.get("utterance", "") with state: if request_id in state.data["seen"]: state.ledger("turn.duplicate", request_id=request_id, agent=cfg.agent) note(f"duplicate turn {request_id} acknowledged again, not delivered twice") return None if utterance == EVENT_UTTERANCE: # Ack only (section 8); nothing is waiting on an answer. rec = _turn_record(cfg, frame, link, t_recv, t_ack, None, t_recv - self.t_start) state.data["seen"][request_id] = t_recv state.ledger("turn.event", **_text_free({k: v for k, v in rec.items() if k != "event"})) if self.print_events: rec["event"] = "event" emit(cfg, f"PIPBIT EVENT {rec['environment_event']}", rec) return None inline: Optional[str] = None if utterance == INTRO_UTTERANCE and self.intro_reply: inline = self.intro_reply elif self.echo: inline = f"{self.echo_prefix}{payload.get('handoff_context') or utterance}" expected: Optional[float] = None if inline is not None: link.send({"type": "turn.result", "request_id": request_id, "result": {"text": inline}}) else: # The wait hint (spec 1.6.0): 0 when a handler already has # the turn (`wait` hands it out itself; a `next` is blocking), # else the cadence read from the ledger. The bridge tells the # person to hold on when it is long. Computed here because the # lock already holds a fresh state file; it reads no network. expected = 0.0 if self.deliver_once or state.listener_live() is not None else estimate_wait_s(state) link.send({"type": "turn.result", "request_id": request_id, "result": {"status": "deferred", "expected_wait_s": expected}}) rec = _turn_record(cfg, frame, link, t_recv, t_ack, inline, t_recv - self.t_start) rec["expected_wait_s"] = expected if inline is None: state.remember_turn(_pending_entry(rec, handed_out=self.deliver_once)) else: state.data["seen"][request_id] = t_recv state.bump("turns") state.ledger("turn.received", **_text_free({k: v for k, v in rec.items() if k != "event"})) self.delivered += 1 self.on_turn(rec, inline) return rec def _on_cancel(self, frame: Dict[str, Any]) -> None: cfg, link, state = self.cfg, self.link, self.cfg.state request_id = frame.get("request_id") with state: pending = next((p for p in state.data["pending"] if p["request_id"] == request_id), None) if pending is not None: # From this socket's view the turn was handed out already; # the reply step will find it marked cancelled and skip it. pending["cancelled"] = True pending["cancel_reason"] = frame.get("reason") # Nothing will hand this turn out any more; its words # leave the state file now, the ids stay for the reply's # refusal. for key in ("utterance", "handoff_context", "conversation_tail"): pending.pop(key, None) outcome = "already_replied" elif request_id in state.data["seen"]: outcome = "already_replied" else: outcome = "unknown" state.ledger("turn.cancel", request_id=request_id, reason=frame.get("reason"), outcome=outcome, agent=cfg.agent) link.send({"type": "cancel.ack", "request_id": request_id, "outcome": outcome}) note(f"turn {request_id} cancelled by the platform ({frame.get('reason')})") def dial(cfg: Config, *, purpose: str) -> Tuple[Optional[Link], Optional[Tuple[int, str, Dict[str, Any]]]]: """Open a link and complete the hello. Returns (link, None) on success, else (None, (exit_code, human_text, ledger_record)).""" state = cfg.state try: link = Link(cfg) except ProxyRefused as err: rec = state.ledger(f"{purpose}.proxy_refused", status=err.status_line, agent=cfg.agent) return None, (EXIT_NOTHING, f"PIPBIT the egress proxy refused the tunnel ({err.status_line}); a fresh process reads fresh proxy credentials, run again.", rec) except (OSError, ConnectionError, TimeoutError, SocketClosed, ValueError) as err: rec = state.ledger(f"{purpose}.dial_failed", error=describe_error(err), agent=cfg.agent) return None, (EXIT_ERROR, f"PIPBIT could not connect: {describe_error(err)}", rec) if link.error is not None: code, advice = _hello_error_verdict(link.error) rec = state.ledger(f"{purpose}.refused", hello_error=link.error, advice=advice, agent=cfg.agent, link=link.summary()) try: link.ws.close() except Exception: pass return None, (code, f"PIPBIT refused the connection: {link.error.get('error')} ({link.error.get('message', '')}). {advice}.", rec) with state: state.data["last_link"] = {**link.summary(), **stamp()} state.bump("hellos") state.ledger(f"{purpose}.connected", agent=cfg.agent, link=link.summary()) return link, None # --------------------------------------------------------------------------- # wait: exit-per-message # --------------------------------------------------------------------------- def cmd_wait(cfg: Config, args: argparse.Namespace) -> int: cfg.require_credentials() state = cfg.state pid = state.daemon_pid() if pid is not None: rec = state.ledger("wait.daemon_running", daemon_pid=pid, agent=cfg.agent) emit(cfg, f"PIPBIT the daemon (pid {pid}) already holds the socket for {cfg.agent}; use `next` to take its turns (or stop the daemon).", rec) return EXIT_ERROR max_wait = float(args.max_wait) t_start = time.time() state.ledger("wait.start", agent=cfg.agent, max_wait_s=max_wait, echo=bool(args.echo)) link, failure = dial(cfg, purpose="wait") if link is None: assert failure is not None code, human, rec = failure emit(cfg, human, rec) return code note(f"connected as {cfg.agent} connection_id={link.ack.get('connection_id')} (dial {link.summary()['dial_ms']} ms, hello {link.summary()['hello_ms']} ms); waiting up to {max_wait:.0f} s") def on_turn(rec: Dict[str, Any], inline: Optional[str]) -> None: emit(cfg, describe_turn(rec, inline), rec) session = Session(cfg, link, deliver_once=True, echo=bool(args.echo), echo_prefix=args.echo_prefix, intro_reply=args.intro_reply, print_events=bool(args.events), on_turn=on_turn) why, detail = session.run(max_wait) try: link.ws.close(1000, "done") except Exception: pass state.ledger("wait.end", why=why, delivered=session.delivered, waited_s=round(time.time() - t_start, 3), agent=cfg.agent) if why == "turn": return EXIT_TURN if why == "deadline": rec = {"event": "idle", "waited_s": round(time.time() - t_start, 3), "agent": cfg.agent, "link": link.summary()} emit(cfg, f"PIPBIT no turn in {max_wait:.0f} s (connection was healthy). Run `wait` again to keep listening.", rec) return EXIT_NOTHING if why == "closed": code, advice = _close_code_verdict(detail.code) rec = state.ledger("wait.closed_by_server", code=detail.code, reason=detail.reason, advice=advice, agent=cfg.agent) if session.delivered: return EXIT_TURN emit(cfg, f"PIPBIT closed the connection (code {detail.code} {detail.reason}). {advice}.", rec) return code rec = state.ledger("wait.link_error", error=str(detail), agent=cfg.agent) if session.delivered: return EXIT_TURN emit(cfg, f"PIPBIT link error: {detail}", rec) return EXIT_ERROR # --------------------------------------------------------------------------- # daemon: one long-lived socket, every turn stored for `next` # --------------------------------------------------------------------------- def _script_hash() -> str: """A short digest of this file's bytes. The daemon records it next to its version so that ANY change to the script replaces the daemon, not only one that remembered to bump CLIENT_VERSION (2026-10-01: two fixes shipped under 0.4.1 and the running daemon kept the old bytes).""" try: with open(os.path.abspath(__file__), "rb") as fh: return hashlib.sha256(fh.read()).hexdigest()[:16] except OSError: return "" def _daemon_version_stale(state: "State") -> Optional[str]: """When the running daemon was started from another copy of this script, a label for what it runs: the version it recorded (DAEMON_VERSION_UNRECORDED when it wrote none: every daemon before 0.4.1 left no record), with "other bytes" when the version matches but the file changed under it. None when it runs exactly this copy. Only meaningful when daemon_pid() says a daemon is alive.""" state.reload() recorded = state.data.get("daemon_version") recorded_hash = state.data.get("daemon_script_hash") if recorded == CLIENT_VERSION: current = _script_hash() if recorded_hash == current or not current: return None return f"{recorded} (other bytes)" return str(recorded) if recorded else DAEMON_VERSION_UNRECORDED def _upgrade_in_progress(state: "State") -> Optional[Dict[str, Any]]: """The marker another process wrote while it replaces the daemon, when that process is still alive and inside its deadline; else None. A `next` whose auto-ensure lands between the old daemon leaving and the new one claiming the pid file must not spawn a daemon of its own: two daemons supersede each other on the broker (close 4001) and the agent is offline for the redial hold-off.""" state.reload() entry = state.data.get("daemon_upgrading") if not isinstance(entry, dict): return None try: pid = int(entry.get("pid") or 0) deadline_t = float(entry.get("deadline_t") or 0) except (TypeError, ValueError): return None if pid <= 0 or pid == os.getpid() or time.time() >= deadline_t: return None try: os.kill(pid, 0) except ProcessLookupError: return None except PermissionError: pass return entry def _clear_upgrade_marker(state: "State") -> None: with state: entry = state.data.get("daemon_upgrading") if isinstance(entry, dict) and entry.get("pid") == os.getpid(): state.data.pop("daemon_upgrading", None) def _retire_daemon_for_upgrade(cfg: Config, state: "State", running: int, from_version: str) -> bool: """Stop a daemon that runs an older copy of this script so the ensure that follows spawns one from the current copy. True when the old daemon is gone and a fresh one should be spawned. False when it must stay this time: it holds a turn it acknowledged that no `next` has taken yet (a restart would drop the socket while the platform waits; the next ensure tries again), or it did not leave within DAEMON_UPGRADE_WAIT_S (a second daemon beside it would only supersede it on the broker, close 4001).""" if state.next_unhanded() is not None: state.ledger("daemon.upgrade_deferred", from_version=from_version, to_version=CLIENT_VERSION, daemon_pid=running, agent=cfg.agent) print(f"PIPBIT daemon (pid {running}, version {from_version}) holds a turn nobody has taken yet; " f"the upgrade to {CLIENT_VERSION} waits for the next `daemon --ensure` or `next`.") return False # The marker goes down before the signal: from here until the new # daemon has claimed the pid file, every other ensure stands down. with state: state.data["daemon_upgrading"] = {"pid": os.getpid(), "from_version": from_version, "deadline_t": time.time() + DAEMON_UPGRADE_WAIT_S + 10.0, **stamp()} try: os.kill(running, signal.SIGTERM) except ProcessLookupError: pass deadline = time.time() + DAEMON_UPGRADE_WAIT_S while time.time() < deadline and state.daemon_pid() is not None: time.sleep(0.05) if state.daemon_pid() is not None: _clear_upgrade_marker(state) state.ledger("daemon.upgrade_failed", from_version=from_version, to_version=CLIENT_VERSION, daemon_pid=running, waited_s=DAEMON_UPGRADE_WAIT_S, agent=cfg.agent) print(f"PIPBIT daemon (pid {running}, version {from_version}) did not stop within {DAEMON_UPGRADE_WAIT_S:.0f} s; " f"left running. Run `daemon --stop`, then `daemon --ensure`, to get {CLIENT_VERSION}.") return False return True def cmd_daemon(cfg: Config, args: argparse.Namespace) -> int: cfg.require_credentials() state = cfg.state running = state.daemon_pid() if args.stop: # Sticky: a `next` still looping somewhere must not bring the # daemon back (its self-healing is for a VM swap, not for this). # The next explicit `daemon --ensure` lifts it. with state: state.data["daemon_stopped"] = stamp() if running is None: print("PIPBIT daemon is not running.") return EXIT_NOTHING os.kill(running, signal.SIGTERM) print(f"PIPBIT daemon (pid {running}) asked to stop.") return EXIT_TURN if args.ensure: if not getattr(args, "auto", False) and state.data.get("daemon_stopped"): with state: state.data.pop("daemon_stopped", None) upgrading_from = None other = _upgrade_in_progress(state) if other is not None: # Another process is mid-replacement (the old daemon leaving, # the new one not yet on the pid file): a daemon spawned now # would be the second one. It will be there within a beat. print(f"PIPBIT daemon upgrade in progress (pid {other.get('pid')}); not starting another daemon.") return EXIT_TURN if running is not None: # A daemon from an older copy of this script (the person re-fetched # the file, 2026-10-01) is replaced here; otherwise ensure is a no-op. # Not while an operator's stop is in flight: that daemon is leaving. stale_from = None if state.data.get("daemon_stopped") else _daemon_version_stale(state) if stale_from is None: print(f"PIPBIT daemon already running (pid {running}); log {state.daemon_log_path}") return EXIT_TURN if not _retire_daemon_for_upgrade(cfg, state, running, stale_from): return EXIT_TURN upgrading_from = stale_from fatal = (state.data.get("daemon_fatal") or {}) if fatal and not args.reset and upgrading_from is None: print(f"PIPBIT daemon stopped for good at {fatal.get('iso')}: {fatal.get('reason')}. Fix that, then `daemon --ensure --reset`.") return EXIT_STOP with state: state.data.pop("daemon_fatal", None) os.makedirs(state.state_dir, mode=0o700, exist_ok=True) log_fh = open(state.daemon_log_path, "a") child = subprocess.Popen(cfg.self_command("daemon"), stdin=subprocess.DEVNULL, stdout=log_fh, stderr=log_fh, start_new_session=True, close_fds=True) log_fh.close() # Wait briefly for the child to claim the pid file so the caller's # very next `next` sees it. for _ in range(40): if state.daemon_pid() == child.pid: break time.sleep(0.05) state.ledger("daemon.spawned", daemon_pid=child.pid, agent=cfg.agent) if upgrading_from is not None: _clear_upgrade_marker(state) state.ledger("daemon.upgraded", from_version=upgrading_from, to_version=CLIENT_VERSION, old_daemon_pid=running, daemon_pid=child.pid, agent=cfg.agent) print(f"PIPBIT daemon upgraded from {upgrading_from} to {CLIENT_VERSION} (old pid {running}, new pid {child.pid}).") print(f"PIPBIT daemon started (pid {child.pid}); log {state.daemon_log_path}") return EXIT_TURN if running is not None and running != os.getpid(): print(f"PIPBIT daemon already running (pid {running}).") return EXIT_ERROR # The version goes into the state file first, the pid second: an ensure # that races this start and sees the pid must also see the version, or # it would take a daemon that was born a moment ago for an old one. with state: state.data["daemon_version"] = CLIENT_VERSION state.data["daemon_script_hash"] = _script_hash() state.write_pid() stopping = {"flag": False} def _stop(signum, _frame) -> None: stopping["flag"] = True raise KeyboardInterrupt signal.signal(signal.SIGTERM, _stop) signal.signal(signal.SIGINT, _stop) if args.reset: with state: state.data.pop("daemon_fatal", None) def on_turn(rec: Dict[str, Any], inline: Optional[str]) -> None: # The daemon's stdout is its log: one line per turn, with no words # in it (lengths only); `next` hands the stored turn, words and # all, to whoever is looping. print("JSON " + json.dumps(_text_free({k: v for k, v in rec.items() if k not in ("conversation_tail", "link")}), sort_keys=True)) sys.stdout.flush() state.ledger("daemon.start", agent=cfg.agent, pid=os.getpid()) note(f"daemon for {cfg.agent} starting (pid {os.getpid()})") backoff = 1.0 exit_code = EXIT_NOTHING live: Dict[str, Any] = {"link": None} # the socket to close cleanly on SIGTERM try: while not stopping["flag"]: link, failure = dial(cfg, purpose="daemon") live["link"] = link if link is None: assert failure is not None code, human, rec = failure note(human) if code == EXIT_STOP: with state: state.data["daemon_fatal"] = {"reason": human, **stamp()} exit_code = EXIT_STOP break if rec.get("event", "").endswith(".proxy_refused"): # The proxy's credentials rotated under this process; its # environment is frozen at spawn. Leave now (pid file # cleared, nothing fatal recorded) so the next `next` or # `daemon --ensure` respawns a process that reads the # current HTTPS_PROXY. state.ledger("daemon.exit_for_fresh_env", agent=cfg.agent) exit_code = EXIT_NOTHING break retry = float((rec.get("hello_error") or {}).get("retry_after_s") or 0) or backoff time.sleep(min(retry, 300) + random.uniform(0, 1)) backoff = min(backoff * 2, 60) continue backoff = 1.0 note(f"connected as {cfg.agent} connection_id={link.ack.get('connection_id')} via_proxy={link.summary()['via_proxy']}") session = Session(cfg, link, deliver_once=False, echo=bool(args.echo), echo_prefix=args.echo_prefix, intro_reply=args.intro_reply, print_events=False, on_turn=on_turn) why, detail = session.run(None) live["link"] = None try: link.ws.close(1000, "done") except Exception: pass if why == "closed": code, advice = _close_code_verdict(detail.code) state.ledger("daemon.closed_by_server", code=detail.code, reason=detail.reason, advice=advice, agent=cfg.agent) note(f"closed by server (code {detail.code} {detail.reason}); {advice}") if code == EXIT_STOP: with state: state.data["daemon_fatal"] = {"reason": f"closed {detail.code} {detail.reason}", **stamp()} exit_code = EXIT_STOP break if detail.code == 4001: time.sleep(random.uniform(*SUPERSEDED_HOLDOFF_S)) elif detail.code == 4003: time.sleep(random.uniform(*SUPERSEDED_HOLDOFF_S)) else: time.sleep(random.uniform(0.5, 2.0)) else: state.ledger("daemon.link_error", why=why, error=str(detail), agent=cfg.agent) note(f"link ended ({why}): {detail}; redialling in {backoff:.0f} s") time.sleep(backoff + random.uniform(0, 1)) backoff = min(backoff * 2, 60) except KeyboardInterrupt: # SIGTERM from `daemon --stop` (or Ctrl-C): say goodbye properly so # the broker logs a clean 1000 and marks presence offline at once. link = live.get("link") if link is not None: try: link.ws.close(1000, "stopped") except Exception: pass finally: # The version record is only meaningful while this process lives; # it goes before the pid so nobody reads it next to a dead pid. with state: state.data.pop("daemon_version", None) state.data.pop("daemon_script_hash", None) state.clear_pid() state.ledger("daemon.stop", agent=cfg.agent, exit_code=exit_code, pid=os.getpid()) note("daemon stopped") return exit_code # --------------------------------------------------------------------------- # next: hand out the daemon's next stored turn, no network # --------------------------------------------------------------------------- def cmd_next(cfg: Config, args: argparse.Namespace) -> int: cfg.require_credentials() state = cfg.state max_wait = float(args.max_wait) t_start = time.time() ensure_args = argparse.Namespace(ensure=True, stop=False, reset=False, echo=False, echo_prefix="", intro_reply=None, auto=True) if state.daemon_pid() is None: if state.data.get("daemon_stopped"): # An operator's `daemon --stop` is sticky, and it must end the # scheduled task too: that task runs `next` every minute and # stops itself only on exit code 2, so an exit 1 here would have # it spend a model run a minute for nothing, for ever. rec = state.ledger("next.no_daemon", agent=cfg.agent, stopped=True) emit(cfg, "PIPBIT the daemon was stopped on purpose (`daemon --stop`), so this run ends and a scheduled " "task that sees this exit code stops too. To listen again, run `daemon --ensure` and create the " "scheduled task again if it stopped.", rec) return EXIT_STOP if args.no_ensure: rec = state.ledger("next.no_daemon", agent=cfg.agent, stopped=False) emit(cfg, "PIPBIT the daemon is not running; start it with `daemon --ensure`.", rec) return EXIT_ERROR code = cmd_daemon(cfg, ensure_args) if code == EXIT_STOP: return EXIT_STOP elif not args.no_ensure and not state.data.get("daemon_stopped") and _daemon_version_stale(state) is not None: # The script was fetched again while a daemon from the old copy kept # running: the ensure replaces it (or defers, with a pending turn). code = cmd_daemon(cfg, ensure_args) if code == EXIT_STOP: return EXIT_STOP state.ledger("next.start", agent=cfg.agent, max_wait_s=max_wait) # While this process blocks, the state file says so: the daemon reads # the entry to tell the platform a handler is already waiting # (expected_wait_s 0). One entry, not a list: the Listen loop and the # scheduled task may overlap, and whichever `next` wrote last owns it, # so the clean-up below only removes its own pid. A `next` killed # outright leaves its entry behind; the daemon checks the pid and the # deadline before believing it. On a host without fcntl there is no # lock, and this write can lose a race with the daemon's own save # (the daemon reloads under the lock elsewhere); Muse runs Linux. with state: state.data["listener"] = {"pid": os.getpid(), "started_t": t_start, "deadline_t": t_start + max_wait, **stamp()} try: return _next_loop(cfg, args, state, max_wait, t_start) finally: with state: entry = state.data.get("listener") if isinstance(entry, dict) and entry.get("pid") == os.getpid(): state.data.pop("listener", None) def _next_loop(cfg: Config, args: argparse.Namespace, state: "State", max_wait: float, t_start: float) -> int: while True: with state: turn = state.next_unhanded() if turn is not None: turn["handed_out"] = True turn["handed_out_at"] = now_iso() state.bump("handed_out") # Snapshot under the lock: the save on leaving this block # strips an entry's words the instant its token expires, and # the host is still owed this turn's words. turn = dict(turn) if turn is not None: rec = {**turn, "event": "turn", "agent": cfg.agent, "waited_s": round(time.time() - t_start, 3), "queue_age_s": round(time.time() - turn.get("received_t", time.time()), 3)} state.ledger("next.handed_out", request_id=turn["request_id"], queue_age_s=rec["queue_age_s"], agent=cfg.agent) emit(cfg, describe_turn(rec, None), rec) return EXIT_TURN if time.time() - t_start >= max_wait: break if state.daemon_pid() is None and not args.no_ensure: # The daemon died under us (a VM swap, a fatal close): bring it # back so the socket is up while this process keeps waiting. # Not after an operator's `daemon --stop`: then this process # ends, telling the host the loop is over. state.reload() if state.data.get("daemon_stopped"): rec = state.ledger("next.daemon_stopped", agent=cfg.agent) emit(cfg, "PIPBIT the daemon was stopped on purpose; this loop is over. Start again with `daemon --ensure`.", rec) return EXIT_STOP code = cmd_daemon(cfg, argparse.Namespace(ensure=True, stop=False, reset=False, echo=False, echo_prefix="", intro_reply=None, auto=True)) if code == EXIT_STOP: return EXIT_STOP time.sleep(float(args.poll)) # Ledgered, so a scheduled run's length and cadence can be read later # (the 2026-09-30 one-turn-per-run crawl was found from the bridge's # side; this puts the same fact in the agent's own ledger). The daemon's # wait estimate pairs this line with the run's `next.start` by pid. rec = state.ledger("next.idle", agent=cfg.agent, waited_s=round(time.time() - t_start, 3), daemon_pid=state.daemon_pid(), last_link=state.data.get("last_link")) rec["event"] = "idle" emit(cfg, f"PIPBIT no turn in {max_wait:.0f} s (daemon pid {rec['daemon_pid']} is holding the socket). Run `next` again to keep listening.", rec) return EXIT_NOTHING # --------------------------------------------------------------------------- # reply # --------------------------------------------------------------------------- def _mark_pending(state: "State", token: str, **fields: Any) -> None: """Set fields on the pending turn with this reply token, if it is one (a --token the daemon never saw has no record to mark).""" for entry in state.data.get("pending", []): if entry.get("reply_token") == token: entry.update(fields) return def cmd_reply(cfg: Config, args: argparse.Namespace) -> int: cfg.require_credentials() state = cfg.state silent = bool(getattr(args, "silent", False)) text = args.text # A silence is the reply with no words (0.4.5): the same token, the same # gate and the same refusals, and the Pipbit says nothing. It exists # because since 2026-10-01 the Pipbit watches every deferred turn for # its answer: a turn the agent left unanswered on purpose (the # microphone heard a television, the person spoke to someone else) made # it tell the person the agent was working on it and, five minutes # later, that the agent never answered. `what` names the thing in every # line this command prints. what = "silence" if silent else "reply" if silent and text is not None: # Refused before anything is sent: the platform answers 400 to a # silence that carries words, and a host that typed both has not # decided which it means. rec = state.ledger("reply.refused", agent=cfg.agent, reply_token=args.token, status=None, result={"reason": "silent_with_text", "local": True}) emit(cfg, "PIPBIT reply --silent takes no --text; a silence has no words. Drop one of them; nothing was sent.", rec) return EXIT_ERROR if not silent and (text is None or not text.strip()): note("reply needs --text (or --silent, when nothing should be spoken)") return EXIT_ERROR if args.token: target = next((p for p in state.data["pending"] if p["reply_token"] == args.token), None) or \ {"reply_token": args.token, "request_id": args.request_id or "?"} else: target = state.latest_handed_out() if target is None: rec = state.ledger("reply.no_pending", agent=cfg.agent) emit(cfg, "PIPBIT nothing to reply to: no turn has been handed out. Run `wait` or `next` first.", rec) return EXIT_REFUSED if target.get("cancelled") or target.get("expires_t", 0) <= time.time(): why = "reply_token_cancelled" if target.get("cancelled") else "reply_token_expired" rec = state.ledger("reply.refused", agent=cfg.agent, request_id=target.get("request_id"), reply_token=target.get("reply_token"), status=None, result={"reason": why, "local": True}) with state: state.settle(target.get("request_id") or target["reply_token"], f"refused:{why}") emit(cfg, f"PIPBIT the turn you are answering was {'withdrawn by the person' if why == 'reply_token_cancelled' else 'too old to answer'} ({why}); nothing was sent.", rec) return EXIT_REFUSED token = target["reply_token"] body: Dict[str, Any] = {"reply_token": token} if silent: body["silent"] = True else: body["text"] = text if args.handback: body["handback"] = True if args.handback_reason: body["handback_reason"] = args.handback_reason t_send = time.time() received_t = target.get("received_t") if args.via == "socket" and state.daemon_pid() is not None: # Seen live 2026-09-29: an agent that answered over HTTPS and then # again with --via socket superseded its own daemon on every turn # (close 4001), and the daemon's 30 to 40 s hold-off left the agent # unreachable for the person's next words. The socket form exists # for comparison only; it is never the way to reach a live daemon. rec = state.ledger("reply.refused", agent=cfg.agent, request_id=target.get("request_id"), reply_token=token, status=None, result={"reason": "daemon_holds_socket", "local": True}) emit(cfg, "PIPBIT reply --via socket refused: the daemon holds this agent's socket, and a second socket would knock " "it offline for 30 to 40 s. Every reply already reaches the platform over HTTPS; drop --via socket.", rec) return EXIT_ERROR if args.via == "socket": status, result = _reply_over_socket(cfg, body) else: try: status, result = http_json( "POST", cfg.base_url.rstrip("/") + "/v1/replies", body, # return=minimal: an acknowledgement with nothing token-like in # it. A sandbox safety layer (Muse's) was cutting off the full # reply record on the way back, so the reply landed but the # process never heard so, and the agent sent it again. {"Authorization": f"Bearer {cfg.secret}", "X-Pipbit-Agent": cfg.agent, "Prefer": "return=minimal"}, ) except (OSError, urllib.error.URLError) as err: # The request may well have landed; only the answer is missing # (a cut response, a dropped connection). Remember that on the # turn, so a repeat that the platform refuses as "not pending" # reads as what it is: delivered the first time. with state: _mark_pending(state, token, reply_answer_lost_at=now_iso()) rec = state.ledger("reply.send_failed", error=describe_error(err), reply_token=token, agent=cfg.agent, silent=silent) emit(cfg, f"PIPBIT the platform's answer to this {what} never arrived ({describe_error(err)}). The {what} itself " f"most likely landed. Run the same {what} once more: if the platform then says the turn is no longer " "pending, the first one was delivered and there is nothing more to do.", rec) return EXIT_ERROR t_done = time.time() ok = 200 <= int(status) < 300 if (not ok and isinstance(result, dict) and result.get("reason") == "reply_token_not_pending" and target.get("reply_answer_lost_at")): rec = state.ledger("reply.delivered_earlier", agent=cfg.agent, request_id=target.get("request_id"), reply_token=token, status=status, lost_at=target.get("reply_answer_lost_at"), silent=silent) with state: state.settle(target.get("request_id") or token, "sent") emit(cfg, f"PIPBIT this turn was already answered: your earlier {what} landed although its answer was lost. " "Nothing more to do.", rec) return EXIT_TURN rec = state.ledger( "reply.sent" if ok else "reply.refused", agent=cfg.agent, request_id=target.get("request_id"), reply_token=token, via=args.via, status=status, result=result, silent=silent, text_chars=0 if silent else len(text), sent_at=now_iso(t_send), accepted_at=now_iso(t_done), http_ms=round((t_done - t_send) * 1000), turn_to_reply_s=(round(t_send - received_t, 3) if received_t else None), handback=bool(args.handback), ) reason = (result or {}).get("reason") if isinstance(result, dict) else None definitive = ok or (status in (400, 403, 404, 409) and reason) or status in (403, 404) with state: if definitive: # A refusal the platform meant (token gone, cancelled, expired, # not ours) settles the turn; a 5xx, a 429 or a broken link # leaves it pending so a retry can answer it. state.settle(target.get("request_id") or token, "replied" if ok else f"refused:{status}") state.bump("replies" if ok else "replies_refused") if ok: emit(cfg, f"PIPBIT {what} accepted (status {status}) for {token}; {rec['turn_to_reply_s']} s after the turn arrived.", rec) return EXIT_TURN emit(cfg, f"PIPBIT {what} refused: status {status} {json.dumps(result)[:300]}" + ("" if definitive else " (the turn is still pending; run reply again)"), rec) if definitive: return EXIT_REFUSED return EXIT_ERROR def _reply_over_socket(cfg: Config, body: Dict[str, Any]) -> Tuple[int, Any]: """The frame form: a fresh hello, one reply frame, wait for its result. A daemon socket would be superseded by this dial, so the HTTPS route is the default.""" link, failure = dial(cfg, purpose="reply") if link is None: assert failure is not None return 503, {"error": "not_connected", "message": failure[1]} frame = {"type": "reply", "id": link.next_id(), **body} link.send(frame) deadline = time.monotonic() + 30 try: while time.monotonic() < deadline: incoming = json.loads(link.ws.recv_text(deadline - time.monotonic())) kind = incoming.get("type") if kind == "result" and incoming.get("ref") == frame["id"]: if incoming.get("ok"): return int(incoming.get("status_code", 202)), incoming.get("data") return int(incoming.get("status_code", 500)), { "error": incoming.get("error"), "reason": incoming.get("reason"), "message": incoming.get("message")} if kind == "error" and incoming.get("ref") == frame["id"]: return 400, incoming if kind == "ping": link.send({"type": "pong", "ts": incoming.get("ts")}) elif kind == "turn": # A turn arriving on the reply socket is acknowledged and # deferred so it is not lost, and stored for `next`/`reply`. rid = incoming.get("request_id") link.send({"type": "turn.ack", "request_id": rid}) payload = incoming.get("payload") or {} t = time.time() with cfg.state as st: # The same wait hint the daemon sends (spec 1.6.0). expected = 0.0 if st.listener_live() is not None else estimate_wait_s(st) link.send({"type": "turn.result", "request_id": rid, "result": {"status": "deferred", "expected_wait_s": expected}}) st.remember_turn({ "request_id": rid, "reply_token": payload.get("reply_token"), "utterance": payload.get("utterance"), "handoff_context": payload.get("handoff_context"), # The kind rides every stored turn, as _pending_entry keeps # it, so `next` hands this one out with it too (spec 1.8.0). "engagement": payload.get("engagement"), "kind": "turn", "conversation_tail": [], "received_t": t, "received_at": now_iso(t), "expires_t": t + REPLY_TOKEN_TTL_S, "handed_out": False}) cfg.state.ledger("reply.turn_arrived_on_reply_socket", request_id=rid, agent=cfg.agent) return 504, {"error": "timeout", "message": "no result frame within 30 s"} except socket.timeout: return 504, {"error": "timeout", "message": "no result frame within 30 s"} except SocketClosed as closed: return 503, {"error": "closed", "code": closed.code, "reason": closed.reason} except OSError as err: return 503, {"error": "link_error", "message": describe_error(err)} finally: link.ws.close(1000, "done") # --------------------------------------------------------------------------- # pair: RFC 8628 device flow, spoken approval # --------------------------------------------------------------------------- # The platform files every agent under an internal name: 2 to 64 characters # of lowercase letters, digits, underscores and hyphens, starting with a # letter or digit, unique across every Pipbit agent there is. The name # people say (the platform's display_name) is separate and need not be # unique: Pip's pairing sentence, the roster and "Megan, ..." all use the # spoken one. So `pair` takes the spoken name, derives the internal one by # the OpenClaw plugin's rule (the Python SDK's slug plus the plugin's three # repairs: accents folded, a leading separator dropped, room left for the # suffix), and when that derived name is already taken retries once with a # short random suffix ("megan-7f3a"); the spoken name stays what the person # said. An internal name given explicitly with --name is exact: taken means # stop and say so, as before. AGENT_NAME_RE = re.compile(r"^[a-z0-9][a-z0-9_-]{1,63}$") AGENT_NAME_MAX_LENGTH = 64 NAME_SUFFIX_LENGTH = 5 # "-" plus four hex digits DERIVED_NAME_MAX_LENGTH = AGENT_NAME_MAX_LENGTH - NAME_SUFFIX_LENGTH def agent_name_from_spoken(spoken: str) -> str: """`Home Brain` becomes `home-brain`, `Zoë` becomes `zoe`, `Café Bot` becomes `cafe-bot`. Accents are folded to plain letters, every run of other characters becomes one hyphen, repeated hyphens collapse, and separators at the ends go (the grammar wants a letter or digit first). Cut to leave room for the taken-name suffix. Returns "" when nothing usable is left; AGENT_NAME_RE is the final judge.""" folded = unicodedata.normalize("NFKD", str(spoken or "")) folded = "".join(ch for ch in folded if not unicodedata.combining(ch)) name = re.sub(r"[^a-z0-9_-]+", "-", folded.strip().lower()) name = re.sub(r"-{2,}", "-", name).strip("-") name = re.sub(r"^[-_]+", "", name) if len(name) > DERIVED_NAME_MAX_LENGTH: name = name[:DERIVED_NAME_MAX_LENGTH].rstrip("-_") return name def with_name_suffix(base: str) -> str: """`megan` becomes `megan-7f3a`: what a taken name gets on the retry.""" return f"{base[:DERIVED_NAME_MAX_LENGTH].rstrip('-_')}-{secrets.token_hex(2)}" def paired_agents(state_dir: str) -> List[str]: """The agents with a state file here (a pairing in progress is not one).""" try: return sorted(f[:-5] for f in os.listdir(state_dir) if f.endswith(".json") and not f.startswith("_") and not f.startswith("pairing-") and not f.endswith(".daemon.json")) except OSError: return [] def _default_agent_path(state_dir: str) -> str: return os.path.join(state_dir, "default_agent") def read_default_agent(state_dir: str) -> str: """The agent paired most recently here, which every command uses when no name is given: a second pairing (a rename, a new Pipbit, a bench agent left behind) must not make the client ask for --agent.""" try: with open(_default_agent_path(state_dir), "r", encoding="utf-8") as fh: name = fh.read().strip() except OSError: return "" return name if name and os.path.exists(os.path.join(state_dir, f"{name}.json")) else "" def write_default_agent(state_dir: str, name: str) -> None: os.makedirs(state_dir, mode=0o700, exist_ok=True) path = _default_agent_path(state_dir) with open(path, "w", encoding="utf-8") as fh: fh.write(name + "\n") os.chmod(path, 0o600) def _pairing_path(state_dir: str, name: str) -> str: return os.path.join(state_dir, f"pairing-{name}.json") def _load_pairing(state_dir: str, name: str) -> Optional[Dict[str, Any]]: path = _pairing_path(state_dir, name) try: with open(path, "r", encoding="utf-8") as fh: pairing = json.load(fh) except (OSError, ValueError): return None if float(pairing.get("expires_t", 0)) <= time.time() and not pairing.get("claim_attempted_at"): # Never claimed: nothing the platform could hold under our secret. try: os.remove(path) except OSError: pass return None return pairing def _save_pairing(state_dir: str, name: str, pairing: Dict[str, Any]) -> None: os.makedirs(state_dir, mode=0o700, exist_ok=True) path = _pairing_path(state_dir, name) with open(path, "w", encoding="utf-8") as fh: json.dump(pairing, fh, indent=1) os.chmod(path, 0o600) def _drop_pairing(state_dir: str, name: str) -> None: try: os.remove(_pairing_path(state_dir, name)) except OSError: pass # Words that say nothing about a voice and would only take up label slots # (the platform keeps at most 20 labels in a list field). No adjective is # in here: "kind" and "gentle" describe a voice. _VOICE_WORDS_SKIPPED = frozenset(( "a", "an", "the", "and", "or", "with", "of", "to", "as", "is", "are", "be", "like", "that", "who", "which", "i", "me", "my", "you", "your", "want", "would", "please", "voice", "voices", "sound", "sounds", "sounding", "speak", "speaks", "speaking", "talk", "talks", "talking", "give", "yourself", "have", "has", "one", "someone", "something", "bit", )) # The platform's own negator list (inworld_voices._NEGATORS), applied there # to the gender words only: every other word after "not" still counts FOR # the voice it names ("not too fast" would pull toward a fast voice). So a # negated wish is dropped here, the negator and the two words after it (the # platform's window), rather than passed along inverted. _VOICE_NEGATORS = frozenset(( "no", "not", "non", "less", "least", "without", "never", "stop", "drop", "dont", "doesnt", "isnt", "arent", "wasnt", "cant", "avoid", "lose", )) _VOICE_NEGATION_WINDOW = 2 # A word: letters or digits in any script, with apostrophes and hyphens # inside ("fast-talking", "Zoë"). _VOICE_WORD_RE = re.compile(r"[^\W_](?:[^\W_]|['\u2019-])*") VOICE_LABELS_MAX = 20 def voice_request_from_words(words: str) -> Dict[str, Any]: """The platform's structured voice_request from a few words of the person's own ("a warm, unhurried British woman"). Each word becomes one persona_tags label, lowercased, in the order said; duplicates, the empty words above and negated wishes (a negator plus the two words after it) are dropped; at most VOICE_LABELS_MAX are kept. The platform renders the labels back into text for its catalog matcher (every word counts there) and scores them one by one against its built-in voice profiles when the catalog is not available, so single words are the shape that works for both. Empty when no word is left.""" labels: List[str] = [] negated_until = -1 for index, raw in enumerate(_VOICE_WORD_RE.findall(str(words or ""))): label = raw.strip("'\u2019-").lower() if label.replace("'", "").replace("\u2019", "") in _VOICE_NEGATORS: negated_until = index + _VOICE_NEGATION_WINDOW continue if index <= negated_until: continue if not label or label in _VOICE_WORDS_SKIPPED or label in labels or len(label) > 64: continue labels.append(label) if len(labels) >= VOICE_LABELS_MAX: break return {"persona_tags": labels} if labels else {} def _voice_fields(args: argparse.Namespace) -> Dict[str, Any]: """The pairing-start body's voice part from the pair flags: an exact --voice-id, else --voice-request's words as persona_tags, else nothing (the platform's default pairing voice). Both flags at once, or words that leave no label, are the caller's to refuse before this is sent.""" voice_id = " ".join(str(getattr(args, "voice_id", None) or "").split()) if voice_id: return {"voice_id": voice_id} words = str(getattr(args, "voice_request", None) or "") if words.strip(): request = voice_request_from_words(words) if request: return {"voice_request": request} return {} def _start_pairing(cfg: Config, args: argparse.Namespace, key: str, spoken: str, requested: str, voice: Optional[Dict[str, Any]] = None) -> Tuple[Optional[Dict[str, Any]], int]: """POST the pairing start for *requested* (the internal name), retrying once with a random suffix when the platform says the name is taken and the name was derived from the spoken one (an explicit --name is exact). Saves the pairing under *key* (the un-suffixed name, which is what a later --claim is run with), prints the sentence to say, and returns the pairing, or (None, exit code) with the reason printed. *voice* is the body's voice part (``voice_id`` or ``voice_request``); when None it is read from the flags. It is kept in the pairing file so that a start repeated for a name taken at the claim, under a ``--claim`` run that carries no voice flags, asks for the same voice.""" base = cfg.base_url.rstrip("/") body: Dict[str, Any] = { "requested_name": requested, "client": {"name": args.client_name, "version": CLIENT_VERSION, "runtime": f"{_platform.python_implementation().lower()}/{_platform.python_version()}"}, } if spoken: body["display_name"] = spoken if args.agency_name: body["agency_name"] = args.agency_name if args.description: body["description"] = args.description if getattr(args, "multi_user", False): # Absent means owner-only for a paired agent (the platform's rule # since 2026-10-01); only a shared household agent says otherwise. body["multi_user"] = True voice = dict(voice) if voice is not None else _voice_fields(args) body.update(voice) for attempt in (1, 2): try: status, start = http_json("POST", base + "/v1/connect/pairings", body) except (OSError, urllib.error.URLError) as err: print(f"PIPBIT pairing could not reach the platform: {describe_error(err)}") return None, EXIT_ERROR if status == 201 and isinstance(start, dict): break word = start.get("error") if isinstance(start, dict) else None if status == 409 and word == "name_taken" and attempt == 1 and not args.name: body["requested_name"] = with_name_suffix(key) print(f"PIPBIT the agent name {requested} is taken on Pipbit; trying {body['requested_name']} " f"(the spoken name stays {spoken or requested}).") continue message = start.get("message") if isinstance(start, dict) else None print(f"PIPBIT pairing could not start: status {status} {word or ''} {message or json.dumps(start)[:300]}") return None, (EXIT_STOP if status in (400, 409) else EXIT_ERROR) t0 = time.time() pairing = { "pairing_id": start["pairing_id"], "device_code": start["device_code"], # Minted here, kept here, sent with the claim: the platform then # returns no secret, so nothing secret ever travels back into a # sandbox whose safety layer cuts off a reply that carries one. "secret": mint_secret(), "requested_name": start.get("requested_name") or body["requested_name"], "display_name": start.get("display_name") or spoken or "", "instructions": start.get("instructions") or f"On your Pipbit, say the pairing code {start.get('user_code_display')} for {spoken or requested}.", "interval": float(start.get("interval") or 5), "expires_t": t0 + float(start.get("expires_in") or 600), "started_at": now_iso(t0), "base_url": base, "voice": voice, } _save_pairing(cfg.state_dir, key, pairing) State(cfg.state_dir, pairing["requested_name"]).ledger("pair.start", pairing_id=pairing["pairing_id"], requested_name=pairing["requested_name"], display_name=pairing["display_name"], expires_t=pairing["expires_t"], voice=voice) print("PIPBIT pairing started. " + pairing["instructions"]) return pairing, EXIT_TURN def _pair_flags(args: argparse.Namespace, key: str, spoken: str) -> str: """The name flags exactly as this run was given them, shell-quoted, so the printed command resumes the same pairing file.""" flags = [] if args.name: flags.append(f"--name {shlex.quote(key)}") if spoken: flags.append(f"--spoken-name {shlex.quote(spoken)}") return " ".join(flags) def _pair_command_hint(args: argparse.Namespace, key: str, spoken: str, half: str = "--claim") -> str: """The claim (or start) command as the person, or their agent, should type it.""" return f"python3 {os.path.basename(sys.argv[0])} pair {_pair_flags(args, key, spoken)} {half}" def _say_then_claim(args: argparse.Namespace, key: str, spoken: str, expires_t: float, more: bool = False) -> None: remaining = int(expires_t - time.time()) print(f"The code is good for {remaining} s{' more' if more else ''}. Once it has been said, run: " f"{_pair_command_hint(args, key, spoken)}") sys.stdout.flush() def cmd_pair(cfg: Config, args: argparse.Namespace) -> int: """The RFC 8628 device flow in two halves that a run-to-exit host can drive separately: the start prints the sentence to say and exits at once (--start), the claim polls until the person has said it (--claim). A pairing in progress is kept on disk, so a claim killed by a command timeout is resumed by running the command again; plain `pair` does both halves in one process. --spoken-name is the name people say ("Megan"); the internal agent name is derived from it (agent_name_from_spoken) unless --name gives one. A taken internal name gets a random suffix, at the start (409) or, when someone registered it between the start and the claim (410 name_taken), by starting again with a new code to say.""" spoken = " ".join(str(args.spoken_name or "").split()) if args.name: key = str(args.name).strip() elif spoken: key = agent_name_from_spoken(spoken) else: print("PIPBIT pair needs --spoken-name (the name people say to their Pipbit) or --name (the platform's internal name).") return EXIT_STOP if args.voice_id and args.voice_request: print("PIPBIT give --voice-id (an exact voice) or --voice-request (a few words describing one), not both.") return EXIT_STOP if args.voice_request and not voice_request_from_words(args.voice_request): print(f"PIPBIT --voice-request needs a few words that say what the voice should be like (a wish for what it " f"should not be gives Pipbit nothing to match); {args.voice_request!r} leaves none.") return EXIT_STOP if not AGENT_NAME_RE.match(key): print(f"PIPBIT no usable agent name comes out of {spoken or key!r} (the platform wants 2 to 64 lowercase letters, " "digits, hyphens or underscores); give one with --name.") return EXIT_STOP pairing = _load_pairing(cfg.state_dir, key) if args.claim and pairing is None: print(f"PIPBIT no pairing in progress for {spoken or key}; run `{_pair_command_hint(args, key, spoken, '--start')}` first.") return EXIT_STOP if pairing is None: pairing, code = _start_pairing(cfg, args, key, spoken, requested=key) if pairing is None: return code if args.start: _say_then_claim(args, key, spoken, pairing["expires_t"]) return EXIT_NOTHING else: print("PIPBIT pairing in progress. " + pairing["instructions"]) wanted = _voice_fields(args) if wanted and wanted != dict(pairing.get("voice") or {}): # The platform was already asked, at the start, for the voice # this pairing carries; a flag on the resume cannot change it. print("PIPBIT the pairing in progress keeps the voice it was started with; a different voice flag " "applies to a new pairing only.") if args.start: _say_then_claim(args, key, spoken, pairing["expires_t"], more=True) return EXIT_NOTHING remaining = int(pairing["expires_t"] - time.time()) print(f"(waiting up to {remaining} s for the approval; polling every {int(pairing['interval'])} s)") sys.stdout.flush() return _claim_pairing(cfg, args, key, spoken, pairing) def _claim_pairing(cfg: Config, args: argparse.Namespace, key: str, spoken: str, pairing: Dict[str, Any]) -> int: base = cfg.base_url.rstrip("/") pairing_id, device_code, interval = pairing["pairing_id"], pairing["device_code"], float(pairing["interval"]) if not pairing.get("secret"): pairing["secret"] = mint_secret() _save_pairing(cfg.state_dir, key, pairing) local_secret = pairing["secret"] agent_name = pairing["requested_name"] state = State(cfg.state_dir, agent_name) def paired(secret: str, how: str, agent: Optional[Dict[str, Any]] = None) -> int: with state: state.data["credentials"] = { "agent_name": agent_name, "secret": secret, "base_url": pairing.get("base_url") or base, "connect_url": cfg.connect_url, "paired_at": now_iso(), "pairing_id": pairing_id, } _drop_pairing(cfg.state_dir, key) write_default_agent(cfg.state_dir, agent_name) # The voice the platform settled on (an exact id, the closest # match to the words, or its default) comes back on the claim's # agent record; a claim proven by hello has none to show. voice_id = str((agent or {}).get("voice_id") or "").strip() if isinstance(agent, dict) else "" state.ledger("pair.claimed", agent=agent_name, how=how, display_name=pairing.get("display_name") or "", voice_id=voice_id) print(f"PIPBIT paired: agent {agent_name} is set up. Credentials saved to {state.path}.") if pairing.get("display_name"): print(f"On their Pipbit the person says \"{pairing['display_name']}, ...\" to reach this agent.") if voice_id: print(f"Voice: {voice_id}.") print(f"Next: python3 {os.path.basename(sys.argv[0])} daemon --ensure (or `wait`)") return EXIT_TURN def verify_by_hello() -> str: """The claim's reply never arrived, or the pairing reads claimed: the only proof that the platform registered the agent with the secret minted here is a hello that is acknowledged. Returns "accepted", "rejected" (the platform said authentication_failed: the secret is not the one it holds) or "unknown" (could not tell: no link, a rate limit, a policy refusal), and only "rejected" may ever cost the minted secret its file.""" probe = copy.copy(cfg) probe.agent, probe.secret = agent_name, local_secret try: link = Link(probe) except (OSError, ConnectionError, TimeoutError, SocketClosed, ValueError) as err: print(f"PIPBIT could not verify the pairing by connecting: {describe_error(err)}") return "unknown" if link.error is None: verdict = "accepted" elif link.error.get("error") == "authentication_failed": print("PIPBIT the platform did not accept the minted secret (authentication_failed).") verdict = "rejected" else: print(f"PIPBIT could not verify the pairing: the platform answered {link.error.get('error')}.") verdict = "unknown" try: link.ws.close(1000, "verified") except Exception: pass return verdict deadline = pairing["expires_t"] if not pairing.get("claim_attempted_at"): pairing["claim_attempted_at"] = now_iso() _save_pairing(cfg.state_dir, key, pairing) while time.time() < deadline: try: status, answer = http_json("POST", f"{base}/v1/connect/pairings/{pairing_id}/token", {"device_code": device_code, "secret": local_secret}) except (OSError, urllib.error.URLError) as err: print(f"PIPBIT pairing poll got no reply: {describe_error(err)}; checking whether the claim landed anyway...") pairing["claim_attempted_at"] = now_iso() _save_pairing(cfg.state_dir, key, pairing) if verify_by_hello() == "accepted": return paired(local_secret, "hello after a lost reply") print(f"Run `{_pair_command_hint(args, key, spoken)}` again (the pairing and its secret are kept).") return EXIT_ERROR if status == 428: time.sleep(interval) continue if status == 410 and isinstance(answer, dict) and answer.get("error") == "pairing_failed" \ and answer.get("reason") == "name_taken" and not args.name: # Someone registered the name between the start and the claim. # The platform ended this pairing; start another under a # suffixed name, which means a new code for the person to say. print(f"PIPBIT the agent name {agent_name} was registered by someone else before the claim; " "starting again with a suffix (a new code to say).") state.ledger("pair.name_taken_at_claim", requested_name=agent_name, pairing_id=pairing_id) _drop_pairing(cfg.state_dir, key) fresh, code = _start_pairing(cfg, args, key, spoken, requested=with_name_suffix(key), voice=_voice_fields(args) or dict(pairing.get("voice") or {})) if fresh is None: return code if args.claim: _say_then_claim(args, key, spoken, fresh["expires_t"]) return EXIT_NOTHING remaining = int(fresh["expires_t"] - time.time()) print(f"(waiting up to {remaining} s for the approval; polling every {int(fresh['interval'])} s)") sys.stdout.flush() return _claim_pairing(cfg, args, key, spoken, fresh) if status == 200 and isinstance(answer, dict): # An older platform ignores the supplied secret and mints one; # whichever the platform actually stored is the one to keep. return paired(answer.get("secret") or local_secret, "claim reply", agent=answer.get("agent")) word = (answer or {}).get("error") if isinstance(answer, dict) else None if status == 410 and word == "pairing_claimed": print("PIPBIT the pairing reads claimed already; checking the minted secret...") verdict = verify_by_hello() if verdict == "accepted": return paired(local_secret, "hello after pairing_claimed") if verdict == "unknown": print(f"Could not tell yet; run `{_pair_command_hint(args, key, spoken)}` again (the pairing and its secret are kept).") return EXIT_ERROR print(f"PIPBIT pairing ended: status {status} {word or ''} {json.dumps(answer)[:300]}") state.ledger("pair.ended", status=status, error=word) _drop_pairing(cfg.state_dir, key) return EXIT_STOP if status == 410 else EXIT_ERROR # Past the local deadline. A claim that was attempted may have landed # without a reply: only the platform's own word (a 410) or a rejected # hello may cost the minted secret its file. if pairing.get("claim_attempted_at"): verdict = verify_by_hello() if verdict == "accepted": return paired(local_secret, "hello after the local deadline") if verdict == "unknown": print(f"PIPBIT the pairing's local deadline passed and the claim could not be verified; run `{_pair_command_hint(args, key, spoken)}` again.") return EXIT_ERROR _drop_pairing(cfg.state_dir, key) print("PIPBIT pairing expired before it was approved. Run pair again.") return EXIT_NOTHING # --------------------------------------------------------------------------- # diag: walk the exact network path the client takes, one stage at a time # --------------------------------------------------------------------------- def _redact_proxy(value: Optional[str]) -> Optional[str]: """A proxy URL with its password hidden; anything that does not parse as a URL is returned as it is (the value is never a secret then).""" if not value: return value try: parsed = urllib.parse.urlsplit(value if "://" in value else "http://" + value) except ValueError: return value if parsed.username is None: return value return f"{parsed.scheme}://{parsed.username}:***@{parsed.hostname}:{parsed.port or 3128}" def cmd_diag(cfg: Config, args: argparse.Namespace) -> int: """Each stage prints one line: what was tried, how long it took, and exactly how it failed (exception class and text). Needs no credentials. The stages mirror the client's own path: proxy discovery, TCP to the proxy, the CONNECT tunnel, TLS (with the certificate's issuer, which shows a re-signing proxy), one HTTPS request, then the WebSocket upgrade to the broker (no hello is sent; the broker closes it).""" connect = urllib.parse.urlsplit(cfg.connect_url) base = urllib.parse.urlsplit(cfg.base_url) host = connect.hostname or "" port = connect.port or (443 if connect.scheme == "wss" else 80) tls = connect.scheme == "wss" verdicts: List[str] = [] def line(stage: str, ok: bool, text: str, t0: float, *, info: bool = False) -> None: # An informational stage never fails the run (name resolution when # a proxy resolves names for us; the comparison connections). if not ok and not info: verdicts.append(stage) tag = "ok" if ok else ("info" if info else "FAIL") print(f"[{tag}] {stage}: {text} ({(time.time() - t0) * 1000:.0f} ms)") sys.stdout.flush() print(f"pipbit_connect diag {CLIENT_VERSION} at {now_iso()} python {_platform.python_version()} on {_platform.system()} {_platform.release()}") print(f"target: {cfg.connect_url} and {cfg.base_url}") for name in ("HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy", "NO_PROXY", "no_proxy", "PIPBIT_CA_BUNDLE", "SSL_CERT_FILE", "REQUESTS_CA_BUNDLE"): if os.environ.get(name): shown = _redact_proxy(os.environ[name]) if name.lower() in ("https_proxy", "http_proxy") else os.environ[name] print(f"env {name}={shown}") proxy = proxy_for(connect.scheme, host) print(f"proxy for {host}: {(proxy.hostname + ':' + str(proxy.port or 3128)) if proxy else 'none (direct)'}") paths = ssl.get_default_verify_paths() print(f"tls trust: cafile={paths.cafile} capath={paths.capath} openssl={ssl.OPENSSL_VERSION}") # 1. name resolution, for the record (a sandbox may answer fake addresses) t0 = time.time() try: addrs = sorted({ai[4][0] for ai in socket.getaddrinfo(host, port, proto=socket.IPPROTO_TCP)}) line("resolve", True, f"{host} -> {', '.join(addrs)}", t0) except OSError as err: line("resolve", False, describe_error(err) + (" (a proxy resolves names itself, so this alone is not a failure)" if proxy else ""), t0, info=proxy is not None) addrs = [] # 2. the socket the client would use: tunnel or direct raw: Optional[socket.socket] = None t0 = time.time() if proxy is not None: try: praw = socket.create_connection((proxy.hostname, proxy.port or 3128), timeout=30) line("tcp to proxy", True, f"{proxy.hostname}:{proxy.port or 3128} connected", t0) except OSError as err: line("tcp to proxy", False, describe_error(err), t0) praw = None if praw is not None: t0 = time.time() request = f"CONNECT {host}:{port} HTTP/1.1\r\nHost: {host}:{port}\r\n" if proxy.username is not None: creds = f"{urllib.parse.unquote(proxy.username)}:{urllib.parse.unquote(proxy.password or '')}" request += "Proxy-Authorization: Basic " + base64.b64encode(creds.encode()).decode() + "\r\n" request += "\r\n" try: praw.sendall(request.encode("ascii")) praw.settimeout(float(args.timeout)) head = b"" while b"\r\n\r\n" not in head: chunk = praw.recv(4096) if not chunk: raise ConnectionError("proxy closed the connection without any CONNECT response") head += chunk status_line = head.split(b"\r\n", 1)[0].decode("iso-8859-1") if status_line.split(" ")[1:2] == ["200"]: line("CONNECT", True, status_line, t0) raw = praw else: line("CONNECT", False, f"proxy answered: {status_line}", t0) praw.close() except (OSError, ConnectionError, IndexError) as err: line("CONNECT", False, describe_error(err), t0) try: praw.close() except OSError: pass if addrs and args.direct: t0 = time.time() try: d = socket.create_connection((addrs[0], port), timeout=5) d.close() line("direct tcp (comparison)", True, f"{addrs[0]}:{port} accepted a direct connection", t0) except OSError as err: line("direct tcp (comparison)", False, f"{addrs[0]}:{port}: {describe_error(err)}", t0, info=True) else: try: raw = socket.create_connection((host, port), timeout=30) line("tcp direct", True, f"{host}:{port} connected", t0) except OSError as err: line("tcp direct", False, describe_error(err), t0) # 3. TLS through whatever socket we have sock: Optional[socket.socket] = raw if raw is not None and tls: t0 = time.time() try: sock = tls_context().wrap_socket(raw, server_hostname=host) cert = sock.getpeercert() or {} issuer = ", ".join("=".join(part) for rdn in cert.get("issuer", ()) for part in rdn) subject = ", ".join("=".join(part) for rdn in cert.get("subject", ()) for part in rdn) line("tls", True, f"{sock.version()} verified; subject [{subject}] issuer [{issuer}]", t0) except ssl.SSLError as err: line("tls", False, describe_error(err), t0) sock = None # Show who signed the certificate, so a re-signing proxy is named. t0 = time.time() try: praw2 = open_tunnel(proxy, host, port, 30) if proxy is not None else socket.create_connection((host, port), timeout=30) ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE peek = ctx.wrap_socket(praw2, server_hostname=host) der = peek.getpeercert(binary_form=True) or b"" peek.close() line("tls (unverified peek)", True, f"handshake works without verification; certificate is {len(der)} bytes DER; " "set PIPBIT_CA_BUNDLE to the sandbox's CA file (see `tls trust` above) if the issuer is the proxy's", t0) except (OSError, ConnectionError, ssl.SSLError) as err: line("tls (unverified peek)", False, describe_error(err), t0) except OSError as err: line("tls", False, describe_error(err), t0) sock = None # 4. one HTTPS request on that connection if sock is not None: t0 = time.time() path = "/v1/connect/status" req = (f"GET {path} HTTP/1.1\r\nHost: {host}\r\nUser-Agent: {CLIENT_NAME}/{CLIENT_VERSION}\r\n" "Accept: application/json\r\nConnection: close\r\n\r\n") try: sock.sendall(req.encode("ascii")) sock.settimeout(float(args.timeout)) data = b"" while len(data) < 65536: chunk = sock.recv(4096) if not chunk: break data += chunk head = data.split(b"\r\n", 1)[0].decode("iso-8859-1") if data else "" body = data.split(b"\r\n\r\n", 1)[1][:120].decode("utf-8", "replace") if b"\r\n\r\n" in data else "" if head: line("https request", True, f"{head} body={body!r}", t0) else: line("https request", False, "connection closed with no HTTP response", t0) except OSError as err: line("https request", False, describe_error(err), t0) try: sock.close() except OSError: pass # 5. the WebSocket upgrade to the broker (no hello; the broker will close it) t0 = time.time() try: ws = WebSocket(cfg.connect_url, timeout=float(args.timeout)) line("websocket upgrade", True, f"101 with subprotocol {ws.selected_protocol}" + (f" via proxy {ws.via_proxy}" if ws.via_proxy else ""), t0) try: ws.close(1000, "diag") except Exception: pass except (OSError, ConnectionError, ValueError, SocketClosed) as err: line("websocket upgrade", False, describe_error(err), t0) # 6. the same HTTPS request the way `reply` and `pair` make it (urllib + ProxyHandler) t0 = time.time() try: status, body = http_json("GET", cfg.base_url.rstrip("/") + "/v1/connect/status", timeout=float(args.timeout)) line("urllib request", True, f"status {status} body={json.dumps(body)[:100]}", t0) except (OSError, urllib.error.URLError) as err: line("urllib request", False, describe_error(err), t0) failed = verdicts print("DIAG " + ("all stages passed" if not failed else "failed at: " + ", ".join(failed))) return EXIT_TURN if not failed else EXIT_ERROR # --------------------------------------------------------------------------- # status / ledger # --------------------------------------------------------------------------- def cmd_status(cfg: Config, args: argparse.Namespace) -> int: state = cfg.state now = time.time() pending = [ {**_text_free({k: v for k, v in p.items() if k not in ("received_t", "expires_t", "conversation_tail")}), "age_s": round(now - p.get("received_t", now), 1), "expires_in_s": round(p.get("expires_t", now) - now, 1)} for p in state.data["pending"] ] proxy = proxy_for("wss", urllib.parse.urlsplit(cfg.connect_url).hostname or "") rec = { "event": "status", "agent": cfg.agent or None, "base_url": cfg.base_url, "connect_url": cfg.connect_url, "credentials": "present" if cfg.secret else "missing", "proxy": f"{proxy.hostname}:{proxy.port or 3128}" if proxy else None, "daemon_pid": state.daemon_pid(), "daemon_version": state.data.get("daemon_version") if state.daemon_pid() else None, "daemon_fatal": state.data.get("daemon_fatal"), "daemon_stopped": state.data.get("daemon_stopped"), "listener": state.data.get("listener"), "listener_live": state.listener_live() is not None, "state_file": state.path, "ledger": state.ledger_path, "pending": pending, "last_link": state.data.get("last_link"), "last_settled": state.data.get("last_settled"), "counters": state.data.get("counters"), } human = ( f"PIPBIT agent={cfg.agent or '(none)'} credentials={'present' if cfg.secret else 'missing'} " f"daemon={'running pid %s' % rec['daemon_pid'] if rec['daemon_pid'] else 'not running'} " f"listener={'pid %s' % rec['listener']['pid'] if rec['listener_live'] else 'none'} " f"pending_turns={len(pending)} counters={json.dumps(state.data.get('counters'))}" ) emit(cfg, human, rec) return EXIT_TURN def cmd_use(cfg: Config, args: argparse.Namespace) -> int: """Make one paired agent the one every command uses when --agent is not given. For a state directory with more than one pairing (a bench agent left behind, a rename) that predates the default-agent record `pair` now writes: the Muse on 2026-10-01 had `megan` and a deleted `muse` and every bare command refused to choose.""" names = paired_agents(cfg.state_dir) current = read_default_agent(cfg.state_dir) name = str(getattr(args, "name", None) or "").strip() if not name: print(f"PIPBIT default agent: {current or '(none)'}; paired here: {', '.join(names) or '(none)'}") return EXIT_TURN if current else EXIT_NOTHING if name not in names: print(f"PIPBIT no agent named {name} is paired here; paired: {', '.join(names) or '(none)'}") return EXIT_ERROR write_default_agent(cfg.state_dir, name) print(f"PIPBIT default agent is now {name}; commands without --agent use it.") return EXIT_TURN def cmd_ledger(cfg: Config, args: argparse.Namespace) -> int: path = cfg.state.ledger_path if not os.path.exists(path): print(f"no ledger yet at {path}") return EXIT_NOTHING with open(path, "r", encoding="utf-8") as fh: lines = fh.readlines() for line in lines[-int(args.last):]: sys.stdout.write(line) return EXIT_TURN # --------------------------------------------------------------------------- def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(prog="pipbit_connect.py", description=__doc__.split("\n\n")[0]) parser.add_argument("--agent", help="agent name (else PIPBIT_AGENT_NAME, the constants, or the state file)") parser.add_argument("--secret", help="agent secret (else PIPBIT_AGENT_SECRET, the constants, or the state file)") parser.add_argument("--base-url", dest="base_url", help=f"platform HTTP base (default {BASE_URL})") parser.add_argument("--connect-url", dest="connect_url", help=f"broker WebSocket URL (default {CONNECT_URL})") parser.add_argument("--state-dir", dest="state_dir", help=f"where state and the ledger live (default {STATE_DIR_DEFAULT})") parser.add_argument("--json", action="store_true", help="print only the JSON line") sub = parser.add_subparsers(dest="command", required=True) def listening_flags(p: argparse.ArgumentParser) -> None: p.add_argument("--echo", action="store_true", help="answer every turn inline with an echo (a transport-only baseline)") p.add_argument("--echo-prefix", dest="echo_prefix", default="You said: ", help="prefix for --echo answers") p.add_argument("--intro-reply", dest="intro_reply", default=None, help="answer the connect-intro turn inline with this greeting") p_wait = sub.add_parser("wait", help="connect and block until one turn arrives (or --max-wait passes), then exit") p_wait.add_argument("--max-wait", dest="max_wait", type=float, default=120, help="seconds to wait for a turn (default 120)") p_wait.add_argument("--events", action="store_true", help="also print environment-event turns (always acknowledged)") listening_flags(p_wait) p_daemon = sub.add_parser("daemon", help="keep one socket up; store every turn for `next`") p_daemon.add_argument("--ensure", action="store_true", help="start a detached daemon if none is running, then exit") p_daemon.add_argument("--stop", action="store_true", help="stop the running daemon") p_daemon.add_argument("--reset", action="store_true", help="forget a fatal stop and try again") listening_flags(p_daemon) p_next = sub.add_parser("next", help="block until the daemon has stored a turn, print it, exit (no network)") p_next.add_argument("--max-wait", dest="max_wait", type=float, default=120, help="seconds to wait for a turn (default 120)") p_next.add_argument("--poll", type=float, default=0.2, help="seconds between looks at the state file") p_next.add_argument("--no-ensure", dest="no_ensure", action="store_true", help="do not start the daemon when it is not running") p_reply = sub.add_parser("reply", help="answer the most recent turn, in words or with a silence") p_reply.add_argument("--text", default=None, help="what the Pipbit should say (required unless --silent)") p_reply.add_argument("--silent", action="store_true", help="answer with no words: the turn was not for you, or nothing should be spoken; the Pipbit stops " "waiting for you and says nothing. Takes no --text; --handback may ride along") p_reply.add_argument("--token", help="reply token to answer (default: the most recent turn handed out)") p_reply.add_argument("--request-id", dest="request_id", help="request id, for the ledger, when --token is given") p_reply.add_argument("--handback", action="store_true", help="hand control back to Pip after this reply") p_reply.add_argument("--handback-reason", dest="handback_reason", default=None) p_reply.add_argument("--via", choices=["http", "socket"], default="http", help="HTTPS reply route (default). `socket` sends the reply frame on a fresh socket, for comparison only; refused while the daemon is running") p_pair = sub.add_parser("pair", help="register this agent by voice (RFC 8628 device flow)") p_pair.add_argument("--spoken-name", "--display-name", dest="spoken_name", default=None, help="the name people say to their Pipbit, e.g. Megan; the internal agent name is derived from it") p_pair.add_argument("--name", default=None, help="the platform's internal agent name (lowercase, unique across Pipbit), e.g. megan; derived from --spoken-name when omitted") p_pair.add_argument("--agency-name", dest="agency_name", default=None, help="who makes the agent, e.g. Meta (default: Self-hosted)") p_pair.add_argument("--description", default=None) p_pair.add_argument("--voice-id", dest="voice_id", default=None, help="an exact voice from Pipbit's catalog (default: the platform's pairing voice)") p_pair.add_argument("--voice-request", dest="voice_request", default=None, help='a few words describing the voice wanted, e.g. "a warm, unhurried British woman"; ' "Pipbit picks the closest voice") p_pair.add_argument("--multi-user", dest="multi_user", action="store_true", help="let every voice on a shared Pipbit reach this agent (default: the person who paired it alone)") p_pair.add_argument("--client-name", dest="client_name", default="Pipbit Connect CLI", help="what Pip says the code belongs to") p_pair.add_argument("--start", action="store_true", help="print the sentence to say and exit; claim later with --claim") p_pair.add_argument("--claim", action="store_true", help="poll a pairing started earlier until it is approved") sub.add_parser("status", help="show credentials presence, the daemon, pending turns and counters") p_diag = sub.add_parser("diag", help="walk the network path stage by stage (proxy, CONNECT, TLS, HTTPS, WebSocket upgrade); no credentials needed") p_diag.add_argument("--timeout", type=float, default=30, help="seconds to wait at each stage") p_diag.add_argument("--direct", action="store_true", help="also try a direct TCP connection past the proxy, for comparison") p_ledger = sub.add_parser("ledger", help="print the last ledger lines") p_ledger.add_argument("--last", default=50) p_use = sub.add_parser("use", help="make the agent every command uses when --agent is not given; no name shows the current one") p_use.add_argument("name", nargs="?", help="a paired agent's name") return parser def main(argv: Optional[List[str]] = None) -> int: args = build_parser().parse_args(argv) cfg = Config(args) commands = { "wait": cmd_wait, "daemon": cmd_daemon, "next": cmd_next, "reply": cmd_reply, "pair": cmd_pair, "status": cmd_status, "ledger": cmd_ledger, "diag": cmd_diag, "use": cmd_use, } return commands[args.command](cfg, args) if __name__ == "__main__": try: sys.exit(main()) except KeyboardInterrupt: sys.exit(EXIT_NOTHING)