Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions app/nullius/catalogue/agents/digitalmate/agent.json
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,65 @@
"{install}"
]
}
},
"release_v0.1.14": {
"upstream": {
"repository": "https://github.com/haowenz001/DigitalMate",
"branch": "nullius/release_v0.1.14",
"origin": "experiment",
"tested": "4f0334515ef6845bf2165dd87e3f00542a20cc03",
"license": "Apache-2.0",
"core": "release_v0.1.14 plus the Hive project workspace and session MCP ports, published on this fork branch; port proofs inherited from 0.1.13-fixes."
},
"install": {
"python": "3.13",
"project": ".",
"pip": [
"websockets==15.0.1",
"mcp==1.26.0"
]
},
"start": {
"acp": [
"{install}/.venv/bin/python",
"{here}/hive_acp.py",
"--install",
"{install}",
"--revision",
"4f0334515ef6845bf2165dd87e3f00542a20cc03"
]
}
},
"main-v31": {
"upstream": {
"repository": "https://github.com/openJiuwen-ai/DigitalMate",
"branch": "main",
"origin": "experiment",
"tested": "3667d5b82289ae7b781ca602fa5a88ef4f8fc726",
"license": "Apache-2.0",
"core": "DigitalMate main's v3.1 server, started as a local Home bring-up; text-only, no Host tool providers. Port proofs inherited from 0.1.13-fixes."
},
"install": {
"python": "3.13",
"project": ".",
"pip": [
"aiohttp==3.14.5",
"jsonschema==4.26.0",
"tzdata==2026.6",
"websockets==15.0.1"
]
},
"start": {
"command": [
"{install}/.venv/bin/python",
"{here}/main_v31.py",
"--install",
"{install}",
"--template",
"{here}/startup.template.toml",
"{prompt}"
]
}
}
}
}
267 changes: 267 additions & 0 deletions app/nullius/catalogue/agents/digitalmate/hive_acp.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,267 @@
"""ACP transport for the real Hive product, one isolated instance per session.

No history, tools or model calls live here. The child retains Hive's state and
returns only committed product answers. Unsupported MCP input fails closed.
"""
from __future__ import annotations

import argparse
import json
import os
from pathlib import Path
import signal
import socket
import subprocess
import sys
import threading
import tempfile
import time
import uuid

from run import stop


class Session:
def __init__(self, install: Path, revision: str, cwd: str, *, mcp_servers=None, patch=None):
root = Path(cwd)
if not root.is_absolute() or not root.is_dir():
raise ValueError("Session cwd must be an existing absolute directory")
with socket.socket() as reservation:
reservation.bind(('127.0.0.1', 0))
port = reservation.getsockname()[1]
self.lock = threading.Lock()
self.cancelled = threading.Event()
self.close_lock = threading.Lock()
self.config_home = None
extra = []
if patch:
from hive_patch import receipt
receipt(revision, patch) # refuse an unknown patch identity
extra = ['--mcp-patch', patch]
if mcp_servers:
servers = []
for row in mcp_servers:
if not isinstance(row, dict) or set(row) - {'name', 'command', 'args', 'env'}:
raise ValueError('Only stdio MCP server configuration is supported')
environment = {}
for item in row.get('env', []):
if (not isinstance(item, dict) or set(item) != {'name', 'value'}
or not isinstance(item['name'], str) or not isinstance(item['value'], str)
or item['name'] in environment):
raise ValueError('Invalid MCP server environment')
environment[item['name']] = item['value']
servers.append({**row, 'env': environment})
self.config_home = tempfile.TemporaryDirectory(prefix='digitalmate-mcp-', dir=Path.home())
config = Path(self.config_home.name) / 'servers.json'
with open(config, 'x', opener=lambda path, flags: os.open(path, flags, 0o600)) as handle:
json.dump({'cwd': str(root), 'servers': servers}, handle)
extra += ['--mcp-config', str(config)]
try:
self.process = subprocess.Popen(
[sys.executable, str(Path(__file__).with_name('hive_run.py')),
'--install', str(install), '--revision', revision, '--session', '--port', str(port), *extra],
cwd=root, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=sys.stderr,
text=True, bufsize=1, start_new_session=True)
except BaseException:
if self.config_home is not None:
self.config_home.cleanup()
raise

def ready(self):
try:
if self.read() != {'ready': True}:
raise RuntimeError('DigitalMate session did not become ready')
except BaseException:
self.close()
raise

def read(self):
line = self.process.stdout.readline()
if not line:
raise RuntimeError('DigitalMate session ended; inspect agent stderr')
return json.loads(line)

def prompt(self, text: str) -> str:
if not self.lock.acquire(blocking=False):
raise ValueError('A turn is already running in this session')
try:
if self.cancelled.is_set() or self.process.poll() is not None:
raise RuntimeError('Session ended; create a new session')
self.process.stdin.write(json.dumps({'prompt': text}) + '\n')
self.process.stdin.flush()
answer = self.read().get('answer')
if not isinstance(answer, str) or not answer.strip():
raise RuntimeError('DigitalMate returned no final answer')
return answer
finally:
self.lock.release()

def close(self):
# SIGTERM reaches hive_run's cleanup, which stops the owned product.
with self.close_lock:
if self.cancelled.is_set():
return
self.cancelled.set()
stop(self.process)
self.process.stdin.close()
self.process.stdout.close()
if self.config_home is not None:
self.config_home.cleanup()


BEE_PORTS = (19100, 19101, 19102)


def wait_ports_free(timeout=30.0):
"""The owned Bee runtime binds fixed loopback ports; a restart needs them back."""
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
free = True
for port in BEE_PORTS:
with socket.socket() as probe:
probe.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
probe.bind(('127.0.0.1', port))
except OSError:
free = False
break
if free:
return True
time.sleep(0.5)
return False


class Server:
def __init__(self, install: Path, revision: str, output=None, factory=Session, patch=None):
self.install, self.revision, self.factory = install, revision, factory
self.patch = patch
self.output = output or sys.stdout
self.output_lock = threading.Lock()
self.state_lock = threading.Lock()
self.sessions = {}
self.closed = False

def close_sessions(self):
"""A fresh ACP session replaces the previous product instance in this trial."""
with self.state_lock:
sessions = list(self.sessions.values())
self.sessions.clear()
for session in sessions:
session.close()
if sessions:
wait_ports_free()

def send(self, frame):
with self.output_lock:
self.output.write(json.dumps({'jsonrpc': '2.0', **frame}) + '\n')
self.output.flush()

def handle(self, request):
identity = request.get('id')
method, params = request.get('method'), request.get('params') or {}
try:
if method == 'initialize':
result = {'protocolVersion': 1, 'agentInfo': {'name': 'digitalmate-hive', 'version': self.revision + ('+mcp.' + self.patch[:12] if self.patch else '')},
'agentCapabilities': {'loadSession': False, 'promptCapabilities': {},
'mcpCapabilities': {'http': False, 'sse': False}},
'authMethods': []}
elif method == 'session/new':
self.close_sessions()
options = {'mcp_servers': params.get('mcpServers')}
if self.patch:
options['patch'] = self.patch
session = self.factory(self.install, self.revision, params.get('cwd', ''), **options)
sid = uuid.uuid4().hex
with self.state_lock:
if self.closed:
session.close()
raise RuntimeError('Adapter is closing')
self.sessions[sid] = session
try:
session.ready()
except BaseException:
with self.state_lock:
self.sessions.pop(sid, None)
session.close()
raise
result = {'sessionId': sid}
elif method in ('session/prompt', 'session/cancel'):
sid = params.get('sessionId')
with self.state_lock:
session = self.sessions.get(sid)
if session is None:
raise ValueError('Unknown session')
if method == 'session/cancel':
session.close()
return
blocks = params.get('prompt')
if not isinstance(blocks, list) or not blocks or any(
not isinstance(b, dict) or b.get('type') != 'text' or not isinstance(b.get('text'), str)
for b in blocks):
raise ValueError('Only text prompts are supported')
try:
answer = session.prompt(''.join(b['text'] for b in blocks))
except Exception:
if not session.cancelled.is_set():
raise
result = {'stopReason': 'cancelled'}
else:
if session.cancelled.is_set():
result = {'stopReason': 'cancelled'}
else:
self.send({'method': 'session/update', 'params': {'sessionId': sid,
'update': {'sessionUpdate': 'agent_message_chunk',
'content': {'type': 'text', 'text': answer}}}})
result = {'stopReason': 'end_turn'}
else:
if identity is not None:
self.send({'id': identity, 'error': {'code': -32601, 'message': 'Method not supported'}})
return
if identity is not None:
self.send({'id': identity, 'result': result})
except Exception as error:
if identity is not None:
self.send({'id': identity, 'error': {'code': -32602 if isinstance(error, ValueError) else -32603,
'message': str(error)}})

def close(self):
with self.state_lock:
self.closed = True
sessions = list(self.sessions.values())
for session in sessions:
session.close()


def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--install', type=Path, required=True)
parser.add_argument('--revision', required=True)
parser.add_argument('--mcp-patch')
args = parser.parse_args()
server = Server(args.install.resolve(), args.revision, patch=args.mcp_patch)
def interrupted(signum, frame):
raise SystemExit(128 + signum)
for signum in (signal.SIGINT, signal.SIGTERM):
signal.signal(signum, interrupted)
workers = []
try:
for line in sys.stdin:
try:
request = json.loads(line)
if not isinstance(request, dict):
raise ValueError('Request must be an object')
except ValueError:
server.send({'id': None, 'error': {'code': -32700, 'message': 'Invalid JSON-RPC request'}})
continue
worker = threading.Thread(target=server.handle, args=(request,), daemon=True)
workers = [item for item in workers if item.is_alive()]
workers.append(worker)
worker.start()
finally:
server.close()
for worker in workers:
worker.join(timeout=1)


if __name__ == '__main__':
main()
Loading