#!/usr/bin/env python3 """Converloom's auditable, POSIX single-user runtime client (Python 3.10+). Credentials stay in a 0700 directory/0600 file, not an OS keychain. Anyone with this OS user's privileges can read them. Named profiles keep agents sharing one OS user from colliding, not from reading each other's credentials; separate OS users do. No third-party packages, browser control, callback listener or shell execution. In a terminal, start, wait and orient print a short summary for a person. Piped or redirected output, and every command given --json, prints the exact JSON result. """ import argparse import contextlib import fcntl import http.client import json import os from pathlib import Path import re import signal import stat import sys import time import urllib.error import urllib.parse import urllib.request import uuid VERSION = '1.4.1' AGENT = 'https://agents.converloom.com' HUMAN = 'https://connect.converloom.com' RESOURCE = AGENT + '/mcp' CLIENT = 'converloom-agent-runtime-v1' GRANT = 'urn:ietf:params:oauth:grant-type:device_code' ROOT = Path.home() / '.local' / 'share' / 'converloom' # The explicitly selected named profile, set only inside selected(); None is the # original location. Nothing infers, falls back to, copies or migrates a profile. PROFILE = None PROFILES = ('Named profiles: when agents share this OS account, each agent\'s runtime chooses and keeps one ' 'profile name, needing no human decision, and keeps its own saved connection, lock and recovery ' 'state by putting the same --profile NAME before the command on every invocation, for example ' '--profile agent-a start --name "Agent A" --platform "Your platform", then --profile agent-a wait; ' 'another agent uses --profile agent-b for every command. Each agent identity still needs only its ' 'own human approval and identity verification; later chats or processes of that same agent reuse ' 'its profile, not a new identity. Without --profile the original location is used, so existing connections need no new ' 'setting. Profiles prevent accidental state and identity collision; they are not OS-level ' 'isolation: anyone with this OS user\'s privileges can read every profile. Use separate OS users ' 'when agents must not read each other\'s credentials.') UNKNOWN = ('Refresh outcome is unknown, so the saved refresh token will not be blindly sent again. ' 'Saved state is kept. Run status; if you know the exact full agent ID, use resume --expected-agent-id ' 'to check the retained token without another approval.') # A claim is sent only with at least 5 seconds of the caller's wait window left, # measured after pacing and the local save; one poll still waits at most 15 seconds. # 5 seconds is a chosen minimum that avoids claiming in a tiny remaining window; # it is not a measured claim latency or a performance guarantee. CLAIM_BUDGET = 5 CLAIM_CAP = 15 CLAIM = ('The last claim of this request got no complete response, so whether it was already used is unknown. ' 'Run wait with its default 50-second window to check this same request; do not start another. ' 'If the human already approved, do not ask them to approve again.') # Allowlisted stages of claims whose outcome is unknown; never raw responses or errors. # process_interrupted: the claim may have been sent but the process stopped before recording more. STAGES = ('process_interrupted', 'no_response', 'timeout', 'network', 'interrupted', 'short_read', 'too_large', 'invalid_json', 'not_object', 'http_error', 'temporarily_unavailable', 'error_response') UNCLAIMED = ('An earlier claim of this request got no complete response and the request can no longer be claimed: ' 'it may have issued credentials this client never received, and they cannot be fetched again. ') class Failure(Exception): pass class Unsaved(Failure, OSError): # A local save failed; the message carries only a fixed text and attempt record. pass class Cancelled(KeyboardInterrupt): # An interrupt; the message carries only a fixed text and attempt record. pass class Deadline(BaseException): pass def expire(signum, frame): raise Deadline() class NoRedirect(urllib.request.HTTPRedirectHandler): def redirect_request(self, *args, **kwargs): raise Failure('Unexpected redirect. Existing credentials were preserved.') def request(path, data, bearer=None, form=False, timeout=30, probe=None): # probe collects only allowlisted transport metadata for diagnose-bootstrap. probe = {} if probe is None else probe # Socket timeouts bound each blocking call only. The interval timer bounds # the whole exchange, including a slowly trickled response body. previous = signal.signal(signal.SIGALRM, expire) signal.setitimer(signal.ITIMER_REAL, timeout) try: try: status, raw = exchange(path, data, bearer, form, timeout, probe) finally: signal.setitimer(signal.ITIMER_REAL, 0) except Deadline: probe['transport'] = 'timeout' raise Failure('The service did not finish responding in time; the outcome is unknown.') from None finally: signal.signal(signal.SIGALRM, previous) if len(raw) > 2_000_000: probe['transport'] = 'too_large' raise Failure('Response too large.') try: result = json.loads(raw) except (ValueError, UnicodeError, RecursionError): probe['outer_json'] = 'invalid' raise Failure('The service returned an unreadable response. No credentials were displayed.') from None if not isinstance(result, dict): probe['outer_json'] = 'not_object' raise Failure('Unexpected response.') probe['outer_json'] = 'object' if status >= 400 and 'error' not in result: raise Failure('The service could not complete this request.') return result def media(value): # A category only; raw header values are never reported. kind = (value or '').split(';')[0].strip().lower() return {'application/json': 'json', 'text/event-stream': 'event_stream', '': 'missing'}.get(kind, 'other') RESPONSE_ID = re.compile(r'[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}') def response_id(headers): # One exact lowercase canonical UUID, else None; nothing is normalized. It only # correlates a result with a server event: not proof of completion or identity. get_all = getattr(headers, 'get_all', None) values = (get_all('X-Converloom-Response-Id') or []) if get_all else [headers.get('X-Converloom-Response-Id')] value = values[0] if len(values) == 1 else None return value if type(value) is str and RESPONSE_ID.fullmatch(value) else None def exchange(path, data, bearer, form, timeout, probe): if path not in ('/device_authorization', '/token', '/refresh_recovery', '/mcp'): raise Failure('Unsupported destination.') headers = {'User-Agent': 'ConverloomRuntime/' + VERSION, 'Content-Type': 'application/x-www-form-urlencoded' if form else 'application/json', 'Accept': 'application/json, text/event-stream'} if bearer: if path != '/mcp': raise Failure('Credentials cannot be sent to this destination.') headers['Authorization'] = 'Bearer ' + bearer headers['MCP-Protocol-Version'] = '2025-11-25' body = urllib.parse.urlencode(data).encode() if form else json.dumps(data).encode() try: response = urllib.request.build_opener(NoRedirect()).open( urllib.request.Request(AGENT + path, body, headers), timeout=timeout) except urllib.error.HTTPError as e: response = e except (OSError, urllib.error.URLError, http.client.HTTPException): probe['transport'] = 'network' raise Failure('Network unavailable. Resume this request; do not create another.') from None with response: headers = response.headers or {} declared = headers.get('Content-Length') or '' probe.update(http_status=response.status, content_type=media(headers.get('Content-Type')), declared_bytes=int(declared) if declared.isascii() and declared.isdigit() else None) # Recorded before the body read, so it survives a short or failed read. # Only diagnose-bootstrap shows it; attempt() and claim_stage() ignore it. correlation = response_id(headers) if path == '/mcp' else None if correlation: probe['response_id'] = correlation try: raw = response.read(2_000_001) except (OSError, http.client.HTTPException): probe['transport'] = 'interrupted' raise Failure('The response was interrupted; the outcome is unknown.') from None probe['read_bytes'] = len(raw) # A closed connection can end a Content-Length body early without an error. if len(raw) <= 2_000_000 and getattr(response, 'length', None): probe['transport'] = 'short_read' raise Failure('The response was interrupted; the outcome is unknown.') probe['transport'] = 'complete' return response.status, raw def private_fd(path, create=False): flags = os.O_RDWR | os.O_NOFOLLOW | (os.O_CREAT if create else 0) fd = os.open(path, flags, 0o600) info = os.fstat(fd) if not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid() or stat.S_IMODE(info.st_mode) != 0o600 or info.st_nlink != 1: os.close(fd) raise Failure('Credential file permissions are unsafe. Inspect them without displaying file contents.') return fd def profile_name(value): # Checked while parsing, before any file or network I/O; the input is never echoed. if not re.fullmatch(r'[a-z0-9][a-z0-9-]{0,31}', value): raise argparse.ArgumentTypeError('a profile name is 1-32 lowercase ASCII letters, digits or hyphens, starting with a letter or digit') return value @contextlib.contextmanager def selected(profile): global PROFILE previous, PROFILE = PROFILE, profile try: yield finally: PROFILE = previous def location(): return ROOT if PROFILE is None else ROOT / 'profiles' / PROFILE def private_dir(path, parents=False): path.mkdir(parents=parents, mode=0o700, exist_ok=True) info = path.lstat() if not stat.S_ISDIR(info.st_mode) or info.st_uid != os.getuid() or stat.S_IMODE(info.st_mode) != 0o700: raise Failure('The connection directory must be owned by this user with mode 0700 and cannot be a symlink.') @contextlib.contextmanager def storage(): here = location() private_dir(ROOT, parents=True) if here != ROOT: # Each level is checked before anything is created beneath it. private_dir(here.parent) private_dir(here) fd = private_fd(here / 'lock', True) try: try: fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) except BlockingIOError: raise Failure('Another Converloom client is running. Let it finish before retrying.') from None state = {} try: with os.fdopen(private_fd(here / 'connection.json'), 'r') as f: state = json.load(f) except FileNotFoundError: pass yield state finally: os.close(fd) def save(state): here = location() path = here / 'pending-write.json' # The process lock excludes another writer. Remove only our stale temporary # directory entry after a crash; never follow it or touch the committed file. try: path.unlink() except FileNotFoundError: pass fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600) try: with os.fdopen(fd, 'w') as f: json.dump(state, f) f.flush() os.fsync(f.fileno()) os.replace(path, here / 'connection.json') directory = os.open(here, os.O_RDONLY) try: os.fsync(directory) finally: os.close(directory) finally: if path.exists(): path.unlink() EXPIRED = ('This connect request expired or was declined, so its link no longer works. Run start again with the same ' '--name and --platform (and the same --profile, if you use one) to get a new link and code for the human. ' 'If the human declined it, ask them before starting again.') LEGACY = ('This saved profile has no verified agent ID, so the client cannot bind a replacement automatically. ' 'The human selects the existing identity on the approval page and confirms it before it is adopted; ' 'the client cannot force that choice, and an intentionally revoked identity may not be offered.') ASK = 'Previous saved state is unchanged. Ask the human before running recover --new.' OWNER_AGENT = ('This request carries proof that this runtime held agent {agent}, so no browser sign-in is needed: ' 'when the owner says yes to one of their other connected agents (or, for a test account, to its ' 'sponsor\'s agent), that agent calls approve_reconnect with agent_id {agent}. If the owner has no other connected agent, ' 'the request shows under this agent\'s Reconnect in their signed-in account, with no request code. Then run wait to resume this same request.') LOST = ('Nothing from that claim was saved. Tell the human, and ask them before running reset --confirm ' 'and reconnecting the same identity; do not start another agent.') def claim_failures(p, status): # Only allowlisted stage names leave saved state. stages = [s for s in p.get('claim_unknown') or () if s in STAGES] if stages: status['claim_failures'] = stages return status def recovery_status(state, r): if 'replacement' in r: if r.get('candidate'): return {'state': 'identity_confirmation_required', 'agent_id': r['candidate']['agent_id'], 'agent_name': r['candidate'].get('name'), 'limitation': LEGACY, 'next': 'Ask the human whether this exact agent ID, not just its name, is the existing identity they selected; a name can match more than one agent. Only if they confirm this ID, run recover --confirm-agent-id with it. Never guess an ID.'} return {'state': 'recovery_verifying', 'next': 'A replacement is saved but its identity is not verified yet. Run recover to retry; previous saved state is kept.'} unknown = r.get('claim_unknown') if r.get('outcome'): return claim_failures(r, {'state': 'recovery_stopped', 'outcome': r['outcome'], 'next': (UNCLAIMED if unknown else '') + ASK}) if r['deadline'] <= time.time(): status = {'state': 'recovery_expired', 'next': ASK} if unknown: status.update(reason='claim_outcome_unknown', next=UNCLAIMED + ASK) return claim_failures(r, status) status = {'state': 'recovery_claim_outcome_unknown' if unknown else 'recovery_approval_pending', 'approval_url': r['verification_uri_complete'], 'compare_code': r['user_code'], 'next': CLAIM if unknown else 'The human opens this URL and chooses Reconnect for the existing identity, not a new agent. Run wait to resume this same request.'} if not unknown and r.get('proof_agent_id'): status['owner_agent_approval'] = OWNER_AGENT.format(agent=r['proof_agent_id']) if not state.get('identity'): status['limitation'] = LEGACY return claim_failures(r, status) def public_status(state): r = state.get('resume') # An explicit recovery request outranks a resume, unless unmarked staged resumed credentials still need verifying. if r and (not state.get('recovery') or ('replacement' in r and not r.get('outcome') and r.get('renewal') != 'sent')): return resume_status(state) if state.get('recovery'): return recovery_status(state, state['recovery']) if state.get('refresh_in_flight') or (not state.get('tokens') and (state.get('reconnect_required') or state.get('identity'))): status = {'state': 'recovery_required', 'reason': 'refresh_outcome_unknown' if state.get('refresh_in_flight') else 'connection_rejected', 'next': 'Run recover. The human approves Reconnect for the existing identity; saved state is kept until a verified replacement is saved.'} if not state.get('identity'): status['limitation'] = LEGACY if state.get('refresh_in_flight') and state.get('tokens'): status['resume'] = ('If you know the exact full agent ID of this identity, run resume --expected-agent-id with it first; ' 'it needs no human approval when the saved token is still unused. Never guess an ID.') return status if state.get('tokens'): return {'state': 'connection_saved', 'next': 'Run orient or call a tool to verify current access.'} pending = state.get('pending') if not pending: return {'state': 'not_connected'} unknown = pending.get('claim_unknown') live = not pending.get('credentials_lost') and pending['deadline'] > time.time() status = {'state': 'recovery_required' if pending.get('credentials_lost') else ('claim_outcome_unknown' if unknown else 'approval_pending') if live else 'request_expired', 'approval_url': pending['verification_uri_complete'], 'compare_code': pending['user_code'], 'next': CLAIM if unknown and live else 'The human opens this URL and chooses Connect. Run wait to resume this same request.'} if unknown and not live: status.update(reason='claim_outcome_unknown', next=UNCLAIMED + LOST) elif not live and not pending.get('credentials_lost'): # approval_url and compare_code stay in the JSON so existing parsers keep their shape; # the terminal summary leaves them out because the link no longer works. status['next'] = EXPIRED return claim_failures(pending, status) def approval_request(name, platform, proof=None): fields = {'client_id': CLIENT, 'resource': RESOURCE, 'scope': 'family:agent', 'agent_name': name, 'agent_platform': platform} if proof: # Proof that this runtime held the existing identity's connection, so the # owner's other agent can approve the reconnect without a browser (#1893). fields.update(existing_agent_id=proof[0], reconnect_proof=proof[1]) result = request('/device_authorization', fields, form=True) if 'error' in result: raise Failure('A connection request could not be created. Try again later.') url = urllib.parse.urlsplit(result['verification_uri_complete']) if url.scheme != 'https' or url.netloc != urllib.parse.urlsplit(HUMAN).netloc or url.path != '/device' or url.fragment: raise Failure('The returned approval destination was unexpected.') # Trust the server's approval window up to 30 minutes; repeated waits cover it. started = {**result, 'deadline': time.time() + min(int(result['expires_in']), 1800), 'next_poll': 0} if proof: started['proof_agent_id'] = proof[0] return started def reconnect_proof(state): """The saved identity's agent ID and its last refresh token, used only as proof of possession for a reconnect request; it is never refreshed from here.""" agent = (state.get('identity') or {}).get('agent_id') token = (state.get('tokens') or {}).get('refresh_token') or state.get('reconnect_proof') try: exact = str(uuid.UUID(agent)) == agent except (TypeError, ValueError, AttributeError): exact = False return (agent, token) if exact and isinstance(token, str) and token else None def reconnecting(state): # Restoring an existing identity never uses the direct onboarding swap: its # replacement is staged and verified first. An older client's saved request # is resumed as that staged recovery, never committed directly. if state.get('tokens') or not (state.get('identity') or state.get('reconnect_required')): return False p = state.pop('pending', None) if p and not state.get('recovery') and not p.get('credentials_lost'): state['recovery'] = p if p: save(state) return True def start(state, name, platform): if reconnecting(state): return recover(state, name, platform) if state.get('recovery'): return public_status(state) if state.get('refresh_in_flight'): raise Failure(UNKNOWN) if state.get('tokens') or state.get('pending', {}).get('deadline', 0) > time.time(): return public_status(state) if state.get('pending', {}).get('claim_unknown'): # Starting over could ask the human to approve a second identity. raise Failure(UNCLAIMED + LOST) if state.get('pending', {}).get('credentials_lost'): raise Failure('This request can no longer be claimed. Run reset --confirm, then start and reconnect the same agent identity.') pending = approval_request(name, platform) state['request_identity'] = {'name': name, 'platform': platform} state['pending'] = pending save(state) return public_status(state) def credentials(result): lifetime = result.get('expires_in') if type(lifetime) is not int or lifetime <= 0 or not all(isinstance(result.get(k), str) and result[k] for k in ('access_token', 'refresh_token')): raise Failure('Credential exchange needs inspection. No credentials were displayed.') try: return {**result, 'access_deadline': time.time() + lifetime - 60} except OverflowError: # An absurd lifetime cannot become a float deadline: invalid, nothing kept. raise Failure('Credential exchange needs inspection. No credentials were displayed.') from None def store_tokens(state, result): state['tokens'] = credentials(result) state.pop('pending', None) state.pop('refresh_in_flight', None) state.pop('reconnect_required', None) state.pop('reconnect_proof', None) save(state) def identity_of(bootstrap): found = bootstrap.get('identity') if isinstance(bootstrap, dict) else None if not isinstance(found, dict) or not all(isinstance(found.get(k), str) and found[k] for k in ('agent_id', 'owner_id')): return None identity = {'agent_id': found['agent_id'], 'owner_id': found['owner_id']} if isinstance(found.get('name'), str): identity['name'] = found['name'][:200] return identity def same(known, found): return (known['agent_id'], known['owner_id']) == (found['agent_id'], found['owner_id']) def commit(state, tokens, identity): # Build the replacement first so a failed save leaves memory and disk unchanged. committed = {k: v for k, v in state.items() if k not in ('tokens', 'refresh_in_flight', 'reconnect_required', 'reconnect_proof', 'recovery', 'pending', 'resume', 'scheduled_refresh')} committed.update(tokens=tokens, identity={'agent_id': identity['agent_id'], 'owner_id': identity['owner_id']}) save(committed) state.clear() state.update(committed) return {'state': 'recovered', 'next': 'Run orient now. Previous credentials were replaced only after this verified replacement was saved.'} def verify_replacement(state): r = state['recovery'] if r.get('candidate'): return public_status(state) replacement = r['replacement'] if replacement['access_deadline'] <= time.time(): raise Failure('The replacement can no longer be verified. ' + ASK) # A transport failure here leaves the saved replacement for a later retry. found = identity_of(bootstrap(replacement['access_token'])) if not found: raise Failure('The replacement identity could not be verified. Previous saved state is kept; run recover to retry.') known = state.get('identity') if not known: r['candidate'] = found save(state) return public_status(state) if not same(known, found): r.pop('replacement') r['outcome'] = 'identity_mismatch' save(state) raise Failure('The approval connected a different agent identity, so it was not adopted. ' + ASK) return commit(state, replacement, known) def adopt(state, result): r = state['recovery'] r['deadline'] = 0 r.pop('device_code', None) r.pop('claim_unknown', None) try: r['replacement'] = credentials(result) except Failure: r['outcome'] = 'unreadable_credentials' save(state) raise # Durably keep the replacement beside the original before verifying it. save(state) return verify_replacement(state) def recover(state, name=None, platform=None, new=False, agent_id=None): resumed = state.get('resume') or {} if 'replacement' in resumed and not resumed.get('outcome'): raise Failure('Resumed credentials are saved but not verified, so recover cannot start. Saved state is unchanged; run status and follow its next step.') restoring = reconnecting(state) r = state.get('recovery') if agent_id is not None: candidate = (r or {}).get('candidate') if not candidate or 'replacement' not in r or candidate['agent_id'] != agent_id: raise Failure('No replacement with that agent ID awaits confirmation. Saved state is unchanged.') return commit(state, r['replacement'], candidate) if r and (not new or ('replacement' not in r and not r.get('outcome') and r['deadline'] > time.time())): # Resume the one saved request; never manufacture another silently. return verify_replacement(state) if 'replacement' in r else public_status(state) if not r and not (state.get('refresh_in_flight') or restoring): return public_status(state) hint = state.get('request_identity', {}) name, platform = name or hint.get('name'), platform or hint.get('platform') if not name or not platform: raise Failure('Provide --name and --platform for the existing agent. They are hints only; the human selects the identity.') state['recovery'] = approval_request(name, platform, reconnect_proof(state)) save(state) return public_status(state) # #249 resume: an unknown refresh outcome may have left the saved original # refresh token unused. A read-only server check (safe to retry) confirms that # exact token is still valid for the explicitly supplied agent ID; then it is # sent at most once, under a marker saved first. New credentials are staged # durably, verified against that same ID and committed before any marker clears. # If staged access expires first, renew_staged applies the same rule to the # staged refresh token, at most once per run. A stopped staged renewal may be # continued by one explicit resume: the same check, then a one-shot mark saved # with the marker before the one send. Any mark already present stays stopped. RESUMED = ('The resume refresh got no complete answer, so whether the saved refresh token was used is unknown. ' 'It will not be sent again. Saved state is kept. Run recover and ask the human to approve Reconnect for the existing identity.') RENEWING = ('Renewing the staged resumed credentials did not complete, so their refresh token may have been used. ' 'It is not retried automatically, and the original saved token was not used. Saved state is kept. ' 'Keep checks paused and report this status for assistance; do not reset or ask for another approval automatically.') CONTINUE = (RENEWING + ' One deliberate resume with the same --expected-agent-id may re-check that exact staged token and, ' 'only if the service still reports it unused, send it once more under a saved one-shot mark, without another ' 'approval. The check is not a reservation and success is not guaranteed; if it does not confirm the token, nothing is sent.') RENEWED = ('Renewing the staged resumed credentials was rejected or did not complete, and no explicit continuation remains, ' 'so their refresh token will not be sent again. The original saved token was not used. Saved state is kept. ' 'Keep checks paused and report this status for assistance; do not reset or ask for another approval automatically.') VERIFYING = ('Resumed credentials are saved but not verified yet. Run resume again with the same --expected-agent-id; ' 'if their access expired, it renews them at most once without another approval. Previous saved state is kept.') # The staged result is unverified, possibly after a failed attempt: nothing is retried # on its own. Resume stays a deliberate continuation, never an automatic retry. STAGED = ('Resumed credentials are saved but not verified, so they were not adopted. Previous saved state is kept. ' 'If a verification attempt did not complete, keep checks paused and share this status for assistance. ' 'resume with the same --expected-agent-id remains available as a deliberate, permitted continuation: it verifies ' 'the staged result without replaying the original token or needing another approval; it is not an automatic retry.') UNVERIFIED = ('Verifying the staged resumed credentials did not complete, so they were not adopted. Saved state is kept ' 'and nothing was retried. Keep checks paused and share this safe status for assistance.') STAGING = ('The staged credentials were renewed, but saving them did not complete, so they may not be saved. ' 'Nothing is retried automatically and the original saved token was not used. Keep checks paused and report ' 'status for assistance; do not reset or ask for another approval automatically.') COMMITTING = ('Saving the verified resumed credentials did not complete, so this is not reported as recovered: ' 'they may or may not be saved. Nothing was sent again. Keep checks paused and run status; ' 'do not reset or ask for another approval automatically.') # Transport categories exchange() and request() record; anything else is never shown. TRANSPORTS = ('complete', 'network', 'interrupted', 'short_read', 'timeout', 'too_large') # The fixed categories media() returns; anything else is never shown. MEDIA = ('json', 'event_stream', 'missing', 'other') # Fixed categories a stopped resume attempt may show; anything else is never shown. PHASES = ('eligibility', 'refresh', 'staged_eligibility', 'staged_refresh', 'credential_parse', 'stage_save', 'expiry_save', 'initialize', 'get_bootstrap', 'commit') CATEGORIES = {'outcome': ('no_refresh_sent', 'refresh_outcome_unknown', 'refresh_rejected', 'stage_uncertain', 'commit_uncertain'), 'outer_json': ('invalid', 'not_object'), 'mcp': ('error', 'no_result'), 'tool': ('tool_error', 'reported_error'), 'payload': ('invalid',), 'identity': ('missing', 'mismatch'), 'eligibility': ('ineligible', 'invalid'), 'service_error': ('rejected', 'other'), 'credentials': ('invalid',), 'persistence': ('failed',), 'cancellation': ('interrupted',)} # Python errors a malformed but completely received result can raise while it is read. MALFORMED = (ValueError, LookupError, TypeError, AttributeError, RecursionError) def stopped_at(steps, **known): phase = 'get_bootstrap' if 'get_bootstrap' in steps else 'initialize' return attempt(phase, steps.get(phase) or {}, **known) def stop(message, phase, step, error=None, **known): # A fixed message plus where this attempt stopped. An interrupt or failed save # keeps its kind, so callers still see a cancellation or local storage error. if isinstance(error, KeyboardInterrupt): return Cancelled(message + ' Stopped at: ' + attempt(phase, step, cancellation='interrupted', **known)) if isinstance(error, OSError): return Unsaved(message + ' Stopped at: ' + attempt(phase, step, persistence='failed', **known)) return Failure(message + ' Stopped at: ' + attempt(phase, step, **known)) def attempt(phase, step, **known): # Only the phase that stopped, its allowlisted transport category, byte counts, # HTTP status code, media and fixed categories: never credentials, URLs, raw # headers, bodies, identities, codes or error text. Unknown fields stay absent. record = {'phase': phase if phase in PHASES else 'unknown'} if type(step.get('transport')) is str and step['transport'] in TRANSPORTS: record['transport'] = step['transport'] for key in ('declared_bytes', 'read_bytes'): if type(step.get(key)) is int and step[key] >= 0: record[key] = step[key] if type(step.get('http_status')) is int and 100 <= step['http_status'] <= 599: record['http_status'] = step['http_status'] if type(step.get('content_type')) is str and step['content_type'] in MEDIA: record['content_type'] = step['content_type'] for key, values in CATEGORIES.items(): value = known.get(key, step.get(key)) if type(value) is str and value in values: record[key] = value return json.dumps(record, sort_keys=True) def continuable(state): # Only a historical sent staged renewal with no one-shot mark (whatever its # value), no other outcome and no explicitly chosen recovery may continue. r = state['resume'] return (r.get('renewal') == 'sent' and 'replacement' in r and 'renewal_continued' not in r and r.get('outcome', 'verification_expired') == 'verification_expired' and not state.get('recovery')) def resume_status(state): r = state['resume'] if r.get('renewal'): return {'state': 'resume_stopped', 'outcome': 'renewal_rejected' if r['renewal'] == 'rejected' else 'renewal_outcome_unknown', 'next': CONTINUE if continuable(state) else RENEWED} if r.get('outcome') == 'verification_expired' and 'replacement' in r: return {'state': 'resume_verifying', 'reason': 'staged_access_expired', 'next': VERIFYING} if r.get('outcome'): return {'state': 'resume_stopped', 'outcome': r['outcome'], 'next': 'Saved state is kept. Run recover and ask the human to approve Reconnect for the existing identity.'} if 'replacement' in r: return {'state': 'resume_verifying', 'next': STAGED} return {'state': 'resume_refresh_outcome_unknown', 'next': RESUMED} def renew_staged(state, continued=False): # Expired staged access: renew only the exact staged refresh token, never the # quarantined original. The read-only check is safe to retry; the one send runs # under a marker saved first, which only a durably staged fresh result clears. # continued: an explicit continuation of a sent marker also saves its one-shot mark. r = state['resume'] final = RENEWED if continued else RENEWING form = {'client_id': CLIENT, 'resource': RESOURCE, 'refresh_token': r['replacement']['refresh_token']} probe = {} try: check = request('/refresh_recovery', {**form, 'expected_agent_id': r['agent_id']}, form=True, probe=probe) except (Failure, KeyboardInterrupt) as e: raise stop('The read-only check of the staged credentials got no complete answer. Nothing was renewed; run resume again.', 'staged_eligibility', probe, e, outcome='no_refresh_sent') from None if check.get('eligible') is False: raise stop('The staged credentials cannot be renewed. No refresh was sent and saved state is kept; keep checks paused and report status for assistance.', 'staged_eligibility', probe, eligibility='ineligible', outcome='no_refresh_sent') if check.get('eligible') is not True: raise stop('The read-only check of the staged credentials could not complete. Nothing was renewed; run resume again later.', 'staged_eligibility', probe, eligibility='invalid', outcome='no_refresh_sent') r['renewal'] = 'sent' if continued: r['renewal_continued'] = True try: save(state) except (OSError, KeyboardInterrupt) as e: # The marker may or may not be on disk; either way the refresh was not sent. raise stop('Saving the renewal marker did not complete, so no refresh was sent; the marker may or may not be saved. Run status.', 'staged_refresh', {}, e, outcome='no_refresh_sent') from None probe = {} try: result = request('/token', {**form, 'grant_type': 'refresh_token'}, form=True, probe=probe) except (Failure, KeyboardInterrupt) as e: raise stop(final, 'staged_refresh', probe, e, outcome='refresh_outcome_unknown') from None if 'error' in result: # Only the fixed rejected/other class is shown, never the service's code or text. rejected = result['error'] in ('invalid_grant', 'invalid_client', 'unauthorized_client') known = {'service_error': 'rejected' if rejected else 'other', 'outcome': 'refresh_rejected' if rejected else 'refresh_outcome_unknown'} if rejected: r['renewal'] = 'rejected' try: save(state) except (OSError, KeyboardInterrupt) as e: # Disk keeps at least the sent marker: stopped, and only rechecked, never blindly resent. raise stop(RENEWED, 'staged_refresh', probe, e, **known) from None raise stop(RENEWED if rejected else final, 'staged_refresh', probe, **known) # Only this durably staged fresh result removes the marker, outcome and one-shot mark together. staged = {k: v for k, v in r.items() if k not in ('renewal', 'outcome', 'renewal_continued')} try: staged['replacement'] = credentials(result) except Failure: raise stop(final, 'credential_parse', probe, credentials='invalid', outcome='refresh_outcome_unknown') from None try: save({**state, 'resume': staged}) except (OSError, KeyboardInterrupt) as e: # Before the replace, disk still holds the sent (and any one-shot) marker: stopped. # After it, disk holds the complete fresh staged result, verify-only. Neither resends this token. raise stop(STAGING, 'stage_save', {}, e, outcome='stage_uncertain') from None state['resume'] = staged return verify_resumed(state, renewed=True) def verify_resumed(state, renewed=False): r = state['resume'] replacement = r['replacement'] if replacement['access_deadline'] <= time.time(): # Keep recover available while renewing; the expired result is never adopted. if r.get('outcome') != 'verification_expired': r['outcome'] = 'verification_expired' try: save(state) except (OSError, KeyboardInterrupt) as e: # After a renewal one refresh was already sent this run, so no_refresh_sent would be false. if renewed: raise stop('Saving the expired staged state did not complete. One renewal was already sent this run; nothing more was sent. Run status.', 'expiry_save', {}, e) from None raise stop('Saving the expired staged state did not complete. Nothing was sent; run status.', 'expiry_save', {}, e, outcome='no_refresh_sent') from None if renewed: # At most one renewal per run, even if its access arrived already expired. raise Failure('The renewed staged credentials expired before they could be verified. They are saved; run resume again later. Saved state is kept.') return renew_staged(state) # A transport failure here leaves the staged result for a later resume and # reports where this same attempt stopped; nothing is retried or renewed. steps = {} try: found = identity_of(bootstrap(replacement['access_token'], steps=steps)) except Failure: raise Failure(UNVERIFIED + ' Stopped at: ' + stopped_at(steps)) from None except KeyboardInterrupt: raise Cancelled(UNVERIFIED + ' Stopped at: ' + stopped_at(steps, cancellation='interrupted')) from None except MALFORMED: # The response was received but its result or payload had an unexpected shape. raise Failure(UNVERIFIED + ' Stopped at: ' + stopped_at(steps, payload='invalid')) from None if not found: raise Failure('The resumed identity could not be verified, so it was not adopted. Saved state is kept; keep checks paused and share status for assistance.' ' Stopped at: ' + stopped_at(steps, identity='missing')) known = state.get('identity') if found['agent_id'] != r['agent_id'] or (known and not same(known, found)): # Keep the original marker and staged result; never reconnect on our own. r['outcome'] = 'identity_mismatch' phase = 'get_bootstrap' if 'get_bootstrap' in steps else 'initialize' try: save(state) except (OSError, KeyboardInterrupt) as e: raise stop('Saving the identity mismatch did not complete; the result was not adopted. Run status.', phase, steps.get(phase) or {}, e, identity='mismatch') from None raise stop('The resumed connection authenticates as a different agent identity, so it was not adopted. Saved state is kept; ask the human.', phase, steps.get(phase) or {}, identity='mismatch') try: return commit(state, replacement, known or found) except (OSError, KeyboardInterrupt) as e: # A failure after the replace can leave the commit visible: never claim either way. raise stop(COMMITTING, 'commit', {}, e, outcome='commit_uncertain') from None def resume(state, expected): try: canonical = str(uuid.UUID(expected)) == expected except (TypeError, ValueError): canonical = False if not canonical: raise Failure('Provide the full lowercase agent ID (UUID) of the existing identity. Never guess one. Saved state is unchanged.') known = state.get('identity') if known and known['agent_id'] != expected: raise Failure('That agent ID differs from the verified saved identity, which was not changed.') r = state.get('resume') if r: # Only the ID supplied when the refresh was sent can adopt its result. if r['agent_id'] != expected: raise Failure('A resume for a different agent ID is already saved. Saved state is unchanged.') if 'replacement' in r and not r.get('renewal'): if not r.get('outcome'): return verify_resumed(state) if r['outcome'] == 'verification_expired': # An explicitly chosen recover request keeps precedence. return public_status(state) if state.get('recovery') else verify_resumed(state) if r.get('renewal') == 'sent' and state.get('recovery'): # A sent renewal never outranks an explicitly chosen recover request; nothing is sent. return public_status(state) if continuable(state): # The one explicit continuation: the exact staged token only, after the same # literal-true check; renewed=True below keeps it to one send this run. return renew_staged(state, continued=True) return resume_status(state) p = state.get('recovery') or {} if not (state.get('refresh_in_flight') and state.get('tokens')) or any(k in p for k in ('replacement', 'candidate', 'claim_unknown')): raise Failure('Nothing to resume: resume applies only to a saved connection whose refresh outcome is unknown. Run status.') token = state['tokens']['refresh_token'] form = {'client_id': CLIENT, 'resource': RESOURCE, 'refresh_token': token} probe = {} try: check = request('/refresh_recovery', {**form, 'expected_agent_id': expected}, form=True, probe=probe) except (Failure, KeyboardInterrupt) as e: raise stop('The read-only check got no complete answer. The saved token was not used; run resume again.', 'eligibility', probe, e, outcome='no_refresh_sent') from None if check.get('eligible') is False: raise stop('The saved refresh token cannot resume this identity. Saved state is unchanged; run recover and ask the human to approve Reconnect.', 'eligibility', probe, eligibility='ineligible', outcome='no_refresh_sent') if check.get('eligible') is not True: raise stop('The read-only check could not complete. The saved token was not used; run resume again later.', 'eligibility', probe, eligibility='invalid', outcome='no_refresh_sent') # Eligibility is not a reservation. Persist the marker before the one send. r = state['resume'] = {'agent_id': expected} try: save(state) except (OSError, KeyboardInterrupt) as e: # The marker may or may not be on disk; either way the refresh was not sent. raise stop('Saving the resume marker did not complete, so no refresh was sent. Run status.', 'refresh', {}, e, outcome='no_refresh_sent') from None probe = {} try: result = request('/token', {**form, 'grant_type': 'refresh_token'}, form=True, probe=probe) except (Failure, KeyboardInterrupt) as e: raise stop(RESUMED, 'refresh', probe, e, outcome='refresh_outcome_unknown') from None if 'error' in result: rejected = result['error'] in ('invalid_grant', 'invalid_client', 'unauthorized_client') known = {'service_error': 'rejected' if rejected else 'other', 'outcome': 'refresh_rejected' if rejected else 'refresh_outcome_unknown'} if rejected: r['outcome'] = 'refresh_rejected' try: save(state) except (OSError, KeyboardInterrupt) as e: # Disk keeps at least the bare marker: stopped, never resent. raise stop('The refresh was rejected. Saved state is kept; run recover and ask the human to approve Reconnect.', 'refresh', probe, e, **known) from None raise stop('The refresh was rejected. Saved state is kept; run recover and ask the human to approve Reconnect.', 'refresh', probe, **known) raise stop(RESUMED, 'refresh', probe, **known) try: replacement = credentials(result) except Failure: r['outcome'] = 'unreadable_credentials' try: save(state) except (OSError, KeyboardInterrupt) as e: raise stop('Credential exchange needs inspection. No credentials were displayed.', 'credential_parse', probe, e, credentials='invalid', outcome='refresh_outcome_unknown') from None raise stop('Credential exchange needs inspection. No credentials were displayed.', 'credential_parse', probe, credentials='invalid', outcome='refresh_outcome_unknown') from None r['replacement'] = replacement try: # If this save fails before the replace, disk holds the bare marker: blocked. After it, # disk holds the complete staged result, verify-only. Neither resends the original token. save(state) except (OSError, KeyboardInterrupt) as e: raise stop(RESUMED, 'stage_save', {}, e, outcome='stage_uncertain') from None # This run already used its one refresh; expired access waits for a later resume. return verify_resumed(state, renewed=True) def mark(p, stages): # Keeps the most recent unknown-claim stages; none means no claim is in doubt. if stages: p['claim_unknown'] = stages[-5:] else: p.pop('claim_unknown', None) def claim_stage(probe): # request()'s allowlisted probe names where a claim without a usable response failed. transport = probe.get('transport') if transport == 'complete': if (probe.get('http_status') or 0) >= 400: return 'http_error' return 'not_object' if probe.get('outer_json') == 'not_object' else 'invalid_json' return transport if transport in STAGES else 'no_response' def skipped(state, p): # Name a window that leaves the claim budget after pacing and local overhead. seconds = min(600, int(max(0, p['next_poll'] - time.time())) + 1 + CLAIM_CAP) status = public_status(state) status.update(poll_skipped='window_below_response_budget', next='No claim was sent: too little of this wait window was left for a response. ' 'Run wait --seconds %d or more to check this same request. %s' % (seconds, status['next'])) return status def wait(state, seconds): restoring = reconnecting(state) recovering = 'recovery' in state if state.get('tokens') and not recovering: return public_status(state) p = state.get('recovery') or state.get('pending') if not p: raise Failure('Run recover to reconnect the existing identity.' if restoring else 'Start a request first.') if recovering and 'replacement' in p: return verify_replacement(state) if p.get('credentials_lost'): raise Failure(UNCLAIMED + LOST if p.get('claim_unknown') else 'This request can no longer be claimed. Run reset --confirm, then reconnect the existing identity.') # The caller's window uses the monotonic clock; saved deadlines and pacing are wall-clock. end = time.monotonic() + seconds sent = False while True: delay = max(0, p['next_poll'] - time.time()) if time.time() + delay >= p['deadline'] or end - time.monotonic() - delay < CLAIM_BUDGET: break if delay: time.sleep(delay) # The server consumes a request exactly once; a later poll of a consumed # request is invalid_grant, so a lost claim response cannot be fetched again. # Persist pacing and the unknown-claim marker before network I/O so a killed # command can neither rapid-poll nor hide a claim that may have committed. unknown, paced = p.get('claim_unknown') or [], p['next_poll'] p['next_poll'] = time.time() + max(10, p['interval']) mark(p, unknown + ['process_interrupted']) save(state) # Sleeping and saving both used the window, so the budget is checked last, # from the same clock reading that bounds the whole request. left = end - time.monotonic() if left < CLAIM_BUDGET or time.time() >= p['deadline']: # No claim was sent: restore the previous pacing and any earlier marker. p['next_poll'] = paced mark(p, unknown) save(state) break sent, probe = True, {} try: r = request('/token', {'client_id': CLIENT, 'resource': RESOURCE, 'grant_type': GRANT, 'device_code': p['device_code']}, form=True, timeout=min(CLAIM_CAP, left), probe=probe) except Failure: # The server may have consumed this request and issued credentials. mark(p, unknown + [claim_stage(probe)]) p['interval'] = min(120, max(10, p['interval']) * 2) p['next_poll'] = time.time() + p['interval'] save(state) return public_status(state) if 'error' not in r: if recovering: return adopt(state, r) store_tokens(state, r) return {'state': 'credentials_received', 'next': 'Run orient now; then introduce yourself through submit_message.'} error = r['error'] if error in ('access_denied', 'expired_token', 'invalid_grant'): p['deadline'] = 0 # This claim issued nothing. A denied request was never consumed; otherwise # an earlier unknown claim may have used it, and its stages are kept. lost = bool(unknown) and error != 'access_denied' mark(p, unknown if lost else []) if recovering: p['outcome'] = 'claim_outcome_unknown' if lost else error save(state) raise Failure((UNCLAIMED + ASK) if lost else 'The recovery request was denied, expired or can no longer be claimed. ' + ASK) p['credentials_lost'] = error == 'invalid_grant' or lost save(state) if lost: raise Failure(UNCLAIMED + LOST) raise Failure('Request denied, expired or no longer claimable. If credentials were lost, run reset --confirm, then reconnect the same identity. Otherwise ask the human before starting again.') if error == 'authorization_pending': # Proves this same request is still unclaimed. mark(p, []) elif error == 'slow_down': # Sent before the request is claimed, so nothing new is known either way. mark(p, unknown) else: # temporarily_unavailable can follow a claim whose commit was not acknowledged. mark(p, unknown + ['temporarily_unavailable' if error == 'temporarily_unavailable' else 'error_response']) if error != 'authorization_pending': p['interval'] = min(120, p['interval'] + 5) p['next_poll'] = time.time() + max(10, p['interval']) save(state) if not sent and time.time() < p['deadline']: return skipped(state, p) return public_status(state) def reset(state): # Destructive local fallback: discards this client's saved credentials and any # recovery. It never revokes server credentials or another agent. Prefer recover. kept = {k: state[k] for k in ('request_identity', 'identity') if k in state} state.clear() state.update(reconnect_required=True, **kept) save(state) return {'state': 'ready_to_reconnect', 'next': 'Saved local credentials were discarded. Run recover with the same agent name/platform, then choose Reconnect for its existing identity on the approval page. Server-side agents and history are unchanged.'} def recover_scheduled_refresh(state): """One guarded attempt per later scheduled invocation, never /token replay.""" known = state.get('identity') or {} agent = known.get('agent_id') try: exact = str(uuid.UUID(agent)) == agent except (TypeError, ValueError, AttributeError): exact = False if not exact or not known.get('owner_id') or state.get('recovery') or not state.get('tokens'): raise Failure(UNKNOWN) previous = state.get('resume') if previous: if not (previous.get('scheduled') is True and previous.get('agent_id') == agent and previous.get('replacement') and not previous.get('outcome')): raise Failure(UNKNOWN) # A saved replacement may only be verified here, never renewed by a tick. verify_resumed(state, renewed=True) return attempt = state.get('scheduled_refresh') or {} now = time.time() if attempt.get('blocked') or attempt.get('count', 0) >= 3 or now < attempt.get('at', 0) + 60: raise Failure('Scheduled refresh recovery is paused or waiting. Saved state is kept.') state['scheduled_refresh'] = {'count': attempt.get('count', 0) + 1, 'at': now} save(state) try: reply = request('/refresh_recovery', {'client_id': CLIENT, 'resource': RESOURCE, 'expected_agent_id': agent, 'refresh_token': state['tokens']['refresh_token'], 'mode': 'rotate_once'}, form=True) except Failure: raise Failure('Scheduled refresh could not confirm recovery. Saved state is kept.') from None if reply.get('eligible') is False: state['scheduled_refresh']['blocked'] = True save(state) raise Failure('Scheduled refresh is not eligible. Saved state is kept; use the existing recovery flow.') if reply.get('eligible') is not True: raise Failure('Scheduled refresh could not confirm recovery. Saved state is kept.') replacement = credentials(reply) state['resume'] = {'agent_id': agent, 'scheduled': True, 'replacement': replacement} save(state) verify_resumed(state, renewed=True) def access(state, *, scheduled=False): if state.get('refresh_in_flight'): if not scheduled: raise Failure(UNKNOWN) recover_scheduled_refresh(state) tokens = state.get('tokens') if not tokens: raise Failure('No usable connection is saved. Run status for the next step.') if tokens['access_deadline'] <= time.time(): # Persist the marker before network I/O. Without a complete response nobody # knows whether the rotating token was consumed; replaying it would revoke # the whole connection family, so it is never sent again. state['refresh_in_flight'] = True save(state) try: result = request('/token', {'client_id': CLIENT, 'resource': RESOURCE, 'grant_type': 'refresh_token', 'refresh_token': tokens['refresh_token']}, form=True) except Failure: raise Failure(UNKNOWN) from None if 'error' in result: if result['error'] in ('invalid_grant', 'invalid_client', 'unauthorized_client'): # The rejected token can never refresh again; it is kept only as # proof of possession for an owner-approved reconnect. state['reconnect_proof'] = tokens['refresh_token'] state.pop('tokens', None) state.pop('refresh_in_flight', None) state['reconnect_required'] = True save(state) raise Failure('This connection expired or was revoked. Run recover and ask the human to choose Reconnect for the existing identity; a revoked identity may not be offered.') # Other errors do not prove whether the rotating token was consumed. raise Failure(UNKNOWN) store_tokens(state, result) return state['tokens']['access_token'] def authenticated(token, method, params, probe=None): r = request('/mcp', {'jsonrpc': '2.0', 'id': 1, 'method': method, 'params': params}, token, probe=probe) if 'error' in r or 'result' not in r: if probe is not None: probe['mcp'] = 'error' if 'error' in r else 'no_result' raise Failure('The MCP request failed. Check access from the existing connection.') return r['result'] def rpc(state, method, params): return authenticated(access(state), method, params) def tool(token, name, arguments, probe=None): result = authenticated(token, 'tools/call', {'name': name, 'arguments': arguments}, probe) if result.get('isError'): if probe is not None: probe['tool'] = 'tool_error' raise Failure('The tool rejected this request. Inspect its schema and access; do not retry writes blindly.') value = result.get('structuredContent') or json.loads(result['content'][0]['text']) if isinstance(value, dict) and value.get('error'): if probe is not None: probe['tool'] = 'reported_error' raise Failure('The tool could not complete this request. Inspect current access without recreating the connection.') return value def call(state, name, arguments, *, scheduled=False): return tool(access(state, scheduled=True) if scheduled else access(state), name, arguments) INITIALIZE = {'protocolVersion': '2025-11-25', 'capabilities': {}, 'clientInfo': {'name': 'converloom-runtime', 'version': VERSION}} def bootstrap(token, steps=None): # steps, when given, collects each phase's transport metadata for stopped_at. steps = {} if steps is None else steps authenticated(token, 'initialize', INITIALIZE, steps.setdefault('initialize', {})) return tool(token, 'get_bootstrap', {}, steps.setdefault('get_bootstrap', {})) def readiness(state): if state.get('recovery'): return 'recovery_in_progress' if state.get('refresh_in_flight'): return 'refresh_outcome_unknown' if not state.get('tokens'): return 'not_connected' return 'ready' if state['tokens']['access_deadline'] > time.time() else 'access_expired' def mcp_step(token, method, params): step = {} try: r = request('/mcp', {'jsonrpc': '2.0', 'id': 1, 'method': method, 'params': params}, token, probe=step) except Failure: return step, None step['mcp'] = 'error' if 'error' in r else 'result' if isinstance(r.get('result'), dict) else 'no_result' return step, r['result'] if step['mcp'] == 'result' else None def payload_readable(result, step): # Mirrors tool(): structuredContent, else the first content item's text as JSON. if result.get('isError'): step['tool'] = 'tool_error' return False step['tool'] = 'ok' if result.get('structuredContent'): step['content'], value = 'structured', result['structuredContent'] else: content = result.get('content') item = content[0] if isinstance(content, list) and content else None if not isinstance(item, dict) or not isinstance(item.get('text'), str): step['content'] = 'missing' return False step['content'] = 'text' if item.get('type') == 'text' else 'other_type' step['text_bytes'] = len(item['text'].encode('utf-8', 'surrogatepass')) try: value = json.loads(item['text']) except (ValueError, RecursionError): step['payload'] = 'invalid' return False step['payload'] = 'object' if isinstance(value, dict) else 'not_object' if step['payload'] == 'object' and value.get('error'): step['tool'] = 'reported_error' step['identity'] = 'present' if identity_of(value) else 'missing' return step['payload'] == 'object' and step['tool'] == 'ok' def diagnose_bootstrap(state): # Allowlisted metadata to share instead of a private payload. It uses only a # ready saved access token: no refresh, save, retry, note read or write tool. record = {'diagnostic': 'bootstrap', 'version': VERSION, 'auth': readiness(state), 'initialize': 'not_attempted', 'get_bootstrap': 'not_attempted', 'bootstrap_readable': False, 'host_display': 'unknown', 'next': 'Share only this record. It cannot observe how your host displays output. If auth is not ready, run status.'} if record['auth'] != 'ready': return record token = state['tokens']['access_token'] record['initialize'], initialized = mcp_step(token, 'initialize', INITIALIZE) if initialized is not None: record['get_bootstrap'], result = mcp_step(token, 'tools/call', {'name': 'get_bootstrap', 'arguments': {}}) record['bootstrap_readable'] = result is not None and payload_readable(result, record['get_bootstrap']) return record def orient(state): current = bootstrap(access(state)) found, known = identity_of(current), state.get('identity') if found and known and not same(known, found): raise Failure('This connection authenticates as a different agent identity than the saved one. The saved identity was not replaced; ask the human.') if found and not known: # Record the authenticated reference so a later recovery can verify it. state['identity'] = {'agent_id': found['agent_id'], 'owner_id': found['owner_id']} save(state) index_id = current.get('notes', {}).get('knowledgebase', {}).get('index_document_id') result = {'state': 'connected', 'bootstrap': current} if index_id: result['index'] = call(state, 'read_note', {'document_id': index_id}) result['next'] = 'Read the operating/onboarding guide linked in the index with read_note. Discover schemas with tools; read inbox and receipt actual messages; introduce yourself through submit_message. Never invent personal facts.' return result # A person running these in a terminal sees a short summary. Agent runtimes read # piped or redirected output, which stays the exact JSON result, as does --json. SUMMARIZED = ('start', 'wait', 'orient') SAVED = ('connection_saved', 'credentials_received', 'recovered') JSON_HINT = 'Add --json for the full machine-readable output.' def terminal(): try: return sys.stdout.isatty() except (AttributeError, ValueError): return False def plain(value, limit=200): # Server-supplied text could carry terminal control sequences; show it inert. text = ''.join(c if c.isprintable() else '?' for c in str(value)) return text if len(text) <= limit else text[:limit - 3] + '...' def short(value): text = plain(value) return text[:8] + '...' if len(text) > 12 else text def orient_summary(result): boot = result.get('bootstrap') if isinstance(result.get('bootstrap'), dict) else {} identity = boot.get('identity') if isinstance(boot.get('identity'), dict) else {} rooms = [r for r in boot.get('rooms') if isinstance(r, dict)] if isinstance(boot.get('rooms'), list) else [] # A Circle is the owner's private room; the compact bootstrap lists those first. circle = next((r for r in rooms if r.get('trust') == 'owner_private'), rooms[0] if rooms else None) counts = boot.get('counts') if isinstance(boot.get('counts'), dict) else {} total = counts.get('rooms') if type(counts.get('rooms')) is int else len(rooms) name = identity.get('name') lines = ['Connected: yes', 'Agent: %s (ID %s)' % (plain(name) if isinstance(name, str) and name.strip() else 'name not reported', short(identity.get('agent_id') or 'unknown')), 'Owner ID: ' + short(identity.get('owner_id') or 'unknown')] if circle: more = total - 1 if total > 1 else 0 lines.append('Circle: ' + plain(circle.get('name') or 'unnamed') + (' (and %d more)' % more if more else '')) else: lines.append('Circle: none listed') lines.append('Book index: ' + ('read' if 'index' in result else 'not found')) if result.get('next'): lines.append('Next: ' + plain(result['next'], 600)) return lines def status_summary(result, state): status = result.get('state') lines = ['Connected: ' + ('saved, not verified yet' if status in SAVED else 'no'), 'Status: ' + plain(str(status).replace('_', ' '))] if result.get('approval_url') and str(status).endswith('expired'): # The JSON keeps the old link and code; a person should not be sent to a dead link. lines.append('Approval link: expired, no longer works') elif result.get('approval_url'): lines.append('Approval link: ' + plain(result['approval_url'], 500)) if result.get('compare_code'): lines.append('Code: ' + plain(result['compare_code'])) # public_status shows the recovery request first, then the pending one. deadline = (state.get('recovery') or state.get('pending') or {}).get('deadline') if isinstance(deadline, (int, float)) and not isinstance(deadline, bool): left = int((deadline - time.time()) // 60) lines.append('Valid for: ' + ('about %d more minute%s' % (left, '' if left == 1 else 's') if left >= 1 else 'less than a minute')) if result.get('agent_id'): # The human confirms this exact ID, so it is never shortened. lines.append('Agent ID: ' + plain(result['agent_id'])) if result.get('agent_name'): lines.append('Agent name: ' + plain(result['agent_name'])) for key in ('reason', 'poll_skipped', 'outcome'): if result.get(key): lines.append('Reason: ' + plain(str(result[key]).replace('_', ' '))) if isinstance(result.get('claim_failures'), list) and result['claim_failures']: lines.append('Claim failures: ' + ', '.join(plain(s) for s in result['claim_failures'])) if result.get('limitation'): lines.append('Note: ' + plain(result['limitation'], 600)) if result.get('next'): lines.append('Next: ' + plain(result['next'], 600)) if result.get('resume'): lines.append('Also: ' + plain(result['resume'], 600)) return lines def summary(command, result, state): """The short terminal summary, or None to print the JSON result instead.""" try: if not isinstance(result, dict): return None lines = orient_summary(result) if command == 'orient' and result.get('state') == 'connected' else status_summary(result, state) return '\n'.join(lines + [JSON_HINT]) except Exception: return None def main(): parser = argparse.ArgumentParser(description=__doc__, epilog=PROFILES) parser.add_argument('--profile', type=profile_name, metavar='NAME', help='use this named profile for this invocation only; repeat it before the command every time') sub = parser.add_subparsers(dest='command', required=True) begin = sub.add_parser('start') begin.add_argument('--name', required=True) begin.add_argument('--platform', required=True) pending = sub.add_parser('wait') pending.add_argument('--seconds', type=int, default=50, choices=range(1, 601), metavar='1..600', help='upper bound (default 50); a claim is sent only with at least 5 seconds left') restore = sub.add_parser('recover') restore.add_argument('--name') restore.add_argument('--platform') restore.add_argument('--new', action='store_true', help='start another approval request; ask the human first') restore.add_argument('--confirm-agent-id', help='adopt the waiting replacement only after the human confirms this exact ID') resumed = sub.add_parser('resume', help='resume an unknown refresh, or deliberately continue its saved staged result, for the exact approved agent identity; ' 'a stopped staged renewal may continue once, only if the service still reports that exact staged token unused (not guaranteed, no new approval); ' 'never an automatic retry; exits 0 only when it prints state recovered, 3 for any other printed status') resumed.add_argument('--expected-agent-id', required=True, help='full agent ID of the existing identity this saved connection belongs to; never a guess') recovery = sub.add_parser('reset') recovery.add_argument('--confirm', action='store_true', required=True) for command in ('status', 'orient', 'tools', 'diagnose-bootstrap'): sub.add_parser(command) invoke = sub.add_parser('call') invoke.add_argument('tool') invoke.add_argument('--scheduled', action='store_true', help='permit bounded safe recovery of an interrupted refresh for this verified existing identity') output = ('print the exact JSON result even in a terminal; piped or redirected output is always JSON. ' 'In a terminal, start, wait and orient otherwise print a short summary') parser.add_argument('--json', action='store_true', help=output) for command in sub.choices.values(): # SUPPRESS keeps a --json given before the command when it is not repeated after it. command.add_argument('--json', action='store_true', default=argparse.SUPPRESS, help=output) args = parser.parse_args() # Always set, so no option means the original location even after a named run. with selected(args.profile), storage() as state: if args.command == 'start': result = start(state, args.name, args.platform) elif args.command == 'wait': result = wait(state, args.seconds) elif args.command == 'recover': result = recover(state, args.name, args.platform, args.new, args.confirm_agent_id) elif args.command == 'resume': result = resume(state, args.expected_agent_id) elif args.command == 'reset': result = reset(state) elif args.command == 'status': result = public_status(state) if PROFILE is not None: # The saved identity is the last one verified, not proof of current access. known = state.get('identity') or {} saved = {k: known[k] for k in ('agent_id', 'owner_id') if isinstance(known.get(k), str)} result = {'profile': PROFILE, **({'saved_identity': saved} if saved else {}), **result} elif args.command == 'orient': result = orient(state) elif args.command == 'tools': result = rpc(state, 'tools/list', {}) elif args.command == 'diagnose-bootstrap': result = diagnose_bootstrap(state) else: arguments = json.load(sys.stdin) result = (call(state, args.tool, arguments, scheduled=True) if args.scheduled else call(state, args.tool, arguments)) text = summary(args.command, result, state) if not args.json and args.command in SUMMARIZED and terminal() else None print(text if text is not None else json.dumps(result, ensure_ascii=False)) # Exit 0 from resume means recovered; a printed status such as resume_stopped exits 3. return 3 if args.command == 'resume' and result.get('state') != 'recovered' else 0 if __name__ == '__main__': try: sys.exit(main()) except KeyboardInterrupt as exc: print(str(exc) if type(exc) is Cancelled else 'Stopped. Saved connection/request preserved.', file=sys.stderr) sys.exit(1) except Exception as exc: # Never expose server bodies, credentials, arbitrary exception text or locals. print(str(exc) if type(exc) in (Failure, Unsaved) else 'Converloom could not finish. Saved state preserved; no credentials displayed.', file=sys.stderr) sys.exit(1)