@senpi/runtime 3.0.293 → 3.0.295
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/daemon/mcp-endpoint.d.ts +2 -2
- package/dist/daemon/mcp-endpoint.d.ts.map +1 -1
- package/dist/daemon/mcp-endpoint.js +4 -3
- package/dist/daemon/mcp-endpoint.js.map +1 -1
- package/dist/daemon/route-table.js +1 -1
- package/dist/daemon/route-table.js.map +1 -1
- package/dist/deploy/packages/live-approval.d.ts +8 -1
- package/dist/deploy/packages/live-approval.d.ts.map +1 -1
- package/dist/deploy/packages/live-approval.js +40 -4
- package/dist/deploy/packages/live-approval.js.map +1 -1
- package/dist/deploy/packages/store.d.ts +2 -2
- package/dist/deploy/packages/store.js +2 -2
- package/dist/deploy/packages/uploaded-code.d.ts +3 -2
- package/dist/deploy/packages/uploaded-code.d.ts.map +1 -1
- package/dist/deploy/packages/uploaded-code.js +5 -4
- package/dist/deploy/packages/uploaded-code.js.map +1 -1
- package/dist/deploy/register.d.ts.map +1 -1
- package/dist/deploy/register.js +12 -5
- package/dist/deploy/register.js.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -5
- package/dist/index.js.map +1 -1
- package/dist/integrity-manifest.json +44 -35
- package/dist/runtime-api/intake/scanner-launcher.d.ts.map +1 -1
- package/dist/runtime-api/intake/scanner-launcher.js +39 -16
- package/dist/runtime-api/intake/scanner-launcher.js.map +1 -1
- package/dist/sandbox/network-mode.d.ts +21 -0
- package/dist/sandbox/network-mode.d.ts.map +1 -0
- package/dist/sandbox/network-mode.js +36 -0
- package/dist/sandbox/network-mode.js.map +1 -0
- package/dist/sandbox/runtime-socket.d.ts +33 -0
- package/dist/sandbox/runtime-socket.d.ts.map +1 -0
- package/dist/sandbox/runtime-socket.js +71 -0
- package/dist/sandbox/runtime-socket.js.map +1 -0
- package/dist/sandbox/uploaded-code.d.ts +7 -0
- package/dist/sandbox/uploaded-code.d.ts.map +1 -1
- package/dist/sandbox/uploaded-code.js +38 -2
- package/dist/sandbox/uploaded-code.js.map +1 -1
- package/dist/scanners/external/scaffold/__main__.py +10 -0
- package/dist/scanners/external/scaffold/http_post.py +46 -3
- package/dist/scanners/external/scaffold/requirements.txt +1 -1
- package/dist/scanners/external/scaffold/sandbox_net.py +256 -0
- package/dist/scanners/external/scaffold/scaffold.py +8 -1
- package/dist/scanners/external/scaffold/senpi_mcp.py +20 -1
- package/openclaw.plugin.json +1 -1
- package/package.json +1 -1
|
@@ -8,15 +8,16 @@
|
|
|
8
8
|
* environment built from an allow-list rather than inherited. Its market data goes through the
|
|
9
9
|
* read-only relay (`relay.ts`) with a token minted for that run, never the box's own key.
|
|
10
10
|
*/
|
|
11
|
-
import { chmodSync, chownSync, cpSync, existsSync, mkdtempSync, readdirSync, statSync } from "node:fs";
|
|
11
|
+
import { accessSync, chmodSync, chownSync, constants, copyFileSync, cpSync, existsSync, mkdtempSync, readdirSync, realpathSync, statSync } from "node:fs";
|
|
12
12
|
import { tmpdir } from "node:os";
|
|
13
|
-
import { join } from "node:path";
|
|
13
|
+
import { delimiter, isAbsolute, join } from "node:path";
|
|
14
14
|
import { PackageRefusal } from "../deploy/packages/files.js";
|
|
15
15
|
export const SANDBOX_UID = 65534;
|
|
16
16
|
export const SANDBOX_GID = 65534;
|
|
17
17
|
/** Variables a Python child legitimately needs that carry no credential. */
|
|
18
18
|
const PASSED_THROUGH = ["PATH", "LANG", "LC_ALL", "TZ", "SENPI_MCP_CALL_TIMEOUT_SECONDS"];
|
|
19
19
|
const scaffoldCopies = new Map();
|
|
20
|
+
const interpreterCopies = new Map();
|
|
20
21
|
/** Make `dir` and everything under it readable by anyone and writable only by its owner. */
|
|
21
22
|
function openForReading(dir) {
|
|
22
23
|
chmodSync(dir, 0o755);
|
|
@@ -44,6 +45,41 @@ export function sandboxScaffoldDir(scaffoldDir) {
|
|
|
44
45
|
scaffoldCopies.set(scaffoldDir, copy);
|
|
45
46
|
return copy;
|
|
46
47
|
}
|
|
48
|
+
function onPath(command, path) {
|
|
49
|
+
if (isAbsolute(command))
|
|
50
|
+
return command;
|
|
51
|
+
for (const dir of (path ?? "").split(delimiter)) {
|
|
52
|
+
if (dir === "")
|
|
53
|
+
continue;
|
|
54
|
+
const candidate = join(dir, command);
|
|
55
|
+
try {
|
|
56
|
+
accessSync(candidate, constants.X_OK);
|
|
57
|
+
return candidate;
|
|
58
|
+
}
|
|
59
|
+
catch {
|
|
60
|
+
// not in this dir
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
throw new Error(`${command} is not on PATH`);
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* A copy of the interpreter `command` that the sandbox user may run and not read. Linux starts a
|
|
67
|
+
* program the user cannot read as not dumpable, so from its first instruction no other process of
|
|
68
|
+
* the same user can read its /proc/<pid>/environ, where the run's tokens are. The copy is made once
|
|
69
|
+
* per process, in a dir with a random name that root owns.
|
|
70
|
+
*/
|
|
71
|
+
export function sandboxInterpreter(command, path = process.env.PATH) {
|
|
72
|
+
const made = interpreterCopies.get(command);
|
|
73
|
+
if (made !== undefined && existsSync(made))
|
|
74
|
+
return made;
|
|
75
|
+
const dir = mkdtempSync(join(tmpdir(), "senpi-sandbox-python-"));
|
|
76
|
+
chmodSync(dir, 0o711);
|
|
77
|
+
const copy = join(dir, "python3");
|
|
78
|
+
copyFileSync(realpathSync(onPath(command, path)), copy);
|
|
79
|
+
chmodSync(copy, 0o111);
|
|
80
|
+
interpreterCopies.set(command, copy);
|
|
81
|
+
return copy;
|
|
82
|
+
}
|
|
47
83
|
export class SandboxUnavailable extends PackageRefusal {
|
|
48
84
|
constructor(uid) {
|
|
49
85
|
super("E_PACKAGE_SANDBOX_UNAVAILABLE", `uploaded code runs only as an unprivileged user, and this process (uid ${uid ?? "unknown"}) cannot switch to one. Nothing was run.`);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"uploaded-code.js","sourceRoot":"","sources":["../../src/sandbox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C;QACvD,OAAO,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,SAAS,CAAC,CAAC;IACtC,CAAC;IAAC,MAAM,CAAC;QACP,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;IACxB,CAAC;AACH,CAAC"}
|
|
@@ -42,6 +42,14 @@ import traceback
|
|
|
42
42
|
|
|
43
43
|
|
|
44
44
|
def _main(argv=None) -> int:
|
|
45
|
+
from scaffold.sandbox_net import SandboxNetworkError, enter_network_mode
|
|
46
|
+
|
|
47
|
+
try:
|
|
48
|
+
network_mode = enter_network_mode(os.environ)
|
|
49
|
+
except SandboxNetworkError as exc:
|
|
50
|
+
print(f"[scaffold] network mode: {exc}", file=sys.stderr)
|
|
51
|
+
return 1
|
|
52
|
+
|
|
45
53
|
if argv is None:
|
|
46
54
|
argv = sys.argv
|
|
47
55
|
|
|
@@ -96,6 +104,8 @@ def _main(argv=None) -> int:
|
|
|
96
104
|
from scaffold.simulation_limits import CLASS_EXCEEDED_EXIT_CODE, hold_to_class
|
|
97
105
|
|
|
98
106
|
class_mb = hold_to_class(config)
|
|
107
|
+
if network_mode is not None:
|
|
108
|
+
log_event("network_mode", mode=network_mode)
|
|
99
109
|
|
|
100
110
|
# Resolve run_scaffold via the package symbol so a test stub patched onto the
|
|
101
111
|
# package (or this module) is picked up.
|
|
@@ -18,8 +18,12 @@ Note: the intake route is mounted at /signals. SIGNALS_PATH is already correct.
|
|
|
18
18
|
|
|
19
19
|
from __future__ import annotations
|
|
20
20
|
|
|
21
|
+
import http.client
|
|
21
22
|
import json
|
|
23
|
+
import os
|
|
24
|
+
import socket
|
|
22
25
|
import urllib.error
|
|
26
|
+
import urllib.parse
|
|
23
27
|
import urllib.request
|
|
24
28
|
from typing import Any
|
|
25
29
|
|
|
@@ -27,6 +31,26 @@ from typing import Any
|
|
|
27
31
|
SIGNALS_PATH = "/signals"
|
|
28
32
|
ERRORS_PATH = "/errors"
|
|
29
33
|
|
|
34
|
+
RUNTIME_SOCKET_ENV = "SENPI_RUNTIME_SOCKET"
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class UnixHTTPConnection(http.client.HTTPConnection):
|
|
38
|
+
"""An HTTP connection to a server on a Unix socket; the URL's host only fills the Host header."""
|
|
39
|
+
|
|
40
|
+
def __init__(self, socket_path: str, host: str, timeout: float):
|
|
41
|
+
super().__init__(host or "localhost", timeout=timeout)
|
|
42
|
+
self._socket_path = socket_path
|
|
43
|
+
|
|
44
|
+
def connect(self) -> None:
|
|
45
|
+
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
|
46
|
+
try:
|
|
47
|
+
sock.settimeout(self.timeout)
|
|
48
|
+
sock.connect(self._socket_path)
|
|
49
|
+
except BaseException:
|
|
50
|
+
sock.close()
|
|
51
|
+
raise
|
|
52
|
+
self.sock = sock
|
|
53
|
+
|
|
30
54
|
|
|
31
55
|
class TransportError(Exception):
|
|
32
56
|
"""Raised on connection failure, timeout, or non-JSON transport body."""
|
|
@@ -69,6 +93,9 @@ def post_json(url: str, body: dict, timeout: float) -> tuple[int, Any]:
|
|
|
69
93
|
)
|
|
70
94
|
|
|
71
95
|
data = json.dumps(body).encode("utf-8")
|
|
96
|
+
socket_path = os.environ.get(RUNTIME_SOCKET_ENV)
|
|
97
|
+
if socket_path:
|
|
98
|
+
return _post_unix(socket_path, url, data, timeout)
|
|
72
99
|
req = urllib.request.Request(
|
|
73
100
|
url,
|
|
74
101
|
data=data,
|
|
@@ -92,9 +119,25 @@ def post_json(url: str, body: dict, timeout: float) -> tuple[int, Any]:
|
|
|
92
119
|
except (urllib.error.URLError, OSError, TimeoutError) as exc:
|
|
93
120
|
raise TransportError(str(exc)) from exc
|
|
94
121
|
|
|
122
|
+
return (status, _parse(raw))
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _parse(raw: bytes) -> Any:
|
|
95
126
|
try:
|
|
96
|
-
|
|
127
|
+
return json.loads(raw.decode("utf-8")) if raw else None
|
|
97
128
|
except (json.JSONDecodeError, UnicodeDecodeError):
|
|
98
|
-
|
|
129
|
+
return None
|
|
130
|
+
|
|
99
131
|
|
|
100
|
-
|
|
132
|
+
def _post_unix(socket_path: str, url: str, data: bytes, timeout: float) -> tuple[int, Any]:
|
|
133
|
+
parts = urllib.parse.urlsplit(url)
|
|
134
|
+
path = (parts.path or "/") + (f"?{parts.query}" if parts.query else "")
|
|
135
|
+
conn = UnixHTTPConnection(socket_path, parts.netloc, timeout)
|
|
136
|
+
try:
|
|
137
|
+
conn.request("POST", path, body=data, headers={"Content-Type": "application/json", "Content-Length": str(len(data))})
|
|
138
|
+
resp = conn.getresponse()
|
|
139
|
+
return (resp.status, _parse(resp.read()))
|
|
140
|
+
except (OSError, http.client.HTTPException) as exc:
|
|
141
|
+
raise TransportError(str(exc)) from exc
|
|
142
|
+
finally:
|
|
143
|
+
conn.close()
|
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
"""How a run of uploaded code reaches the network.
|
|
2
|
+
|
|
3
|
+
The runtime starts uploaded code with SENPI_NETWORK_MODE set, and the scaffold enters that mode
|
|
4
|
+
before it loads the strategy's code:
|
|
5
|
+
|
|
6
|
+
- "open": the network as any simulation has it.
|
|
7
|
+
- "live": a seccomp filter makes socket() fail with EPERM for AF_INET and AF_INET6 and leaves
|
|
8
|
+
AF_UNIX, so the run's one way out is its host proxy (a Unix socket that tunnels to the hosts its
|
|
9
|
+
package declares). Every TCP connection the standard library opens goes through that proxy.
|
|
10
|
+
|
|
11
|
+
In both modes the process is made non-dumpable first, and the run's proxy and relay tokens leave
|
|
12
|
+
the environment, so a process the strategy starts does not inherit them. Every run is the same user,
|
|
13
|
+
and Linux lets a user read /proc/<pid>/environ of its own dumpable processes.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import ctypes
|
|
19
|
+
import errno
|
|
20
|
+
import os
|
|
21
|
+
import platform
|
|
22
|
+
import socket
|
|
23
|
+
import struct
|
|
24
|
+
import sys
|
|
25
|
+
from typing import MutableMapping, NamedTuple, Optional
|
|
26
|
+
|
|
27
|
+
NETWORK_MODE_ENV = "SENPI_NETWORK_MODE"
|
|
28
|
+
PROXY_SOCKET_ENV = "SENPI_HOST_PROXY_SOCKET"
|
|
29
|
+
PROXY_TOKEN_ENV = "SENPI_HOST_PROXY_TOKEN"
|
|
30
|
+
RELAY_TOKEN_ENV = "SENPI_AUTH_TOKEN"
|
|
31
|
+
|
|
32
|
+
_held: dict[str, str] = {}
|
|
33
|
+
|
|
34
|
+
PR_SET_DUMPABLE = 4
|
|
35
|
+
PR_SET_SECCOMP = 22
|
|
36
|
+
PR_SET_NO_NEW_PRIVS = 38
|
|
37
|
+
SECCOMP_MODE_FILTER = 2
|
|
38
|
+
|
|
39
|
+
SECCOMP_RET_KILL_PROCESS = 0x80000000
|
|
40
|
+
SECCOMP_RET_ERRNO = 0x00050000
|
|
41
|
+
SECCOMP_RET_ALLOW = 0x7FFF0000
|
|
42
|
+
|
|
43
|
+
BPF_LD_W_ABS = 0x20
|
|
44
|
+
BPF_JEQ_K = 0x15
|
|
45
|
+
BPF_JGE_K = 0x35
|
|
46
|
+
BPF_RET_K = 0x06
|
|
47
|
+
|
|
48
|
+
# seccomp_data: nr at 0, arch at 4, args[0] at 16 (its low 32 bits, on little-endian).
|
|
49
|
+
_NR = 0
|
|
50
|
+
_ARCH = 4
|
|
51
|
+
_ARG0 = 16
|
|
52
|
+
|
|
53
|
+
class _Arch(NamedTuple):
|
|
54
|
+
audit_arch: int
|
|
55
|
+
socket_nr: int
|
|
56
|
+
io_uring_setup_nr: int
|
|
57
|
+
x32_bit: Optional[int]
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
_ARCHES = {
|
|
61
|
+
"x86_64": _Arch(audit_arch=0xC000003E, socket_nr=41, io_uring_setup_nr=425, x32_bit=0x40000000),
|
|
62
|
+
"aarch64": _Arch(audit_arch=0xC00000B7, socket_nr=198, io_uring_setup_nr=425, x32_bit=None),
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class SandboxNetworkError(RuntimeError):
|
|
67
|
+
"""The run cannot enter the network mode the runtime asked for, so it must not start."""
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class _SockFprog(ctypes.Structure):
|
|
71
|
+
_fields_ = [("len", ctypes.c_ushort), ("filter", ctypes.c_void_p)]
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _assemble(code: list) -> bytes:
|
|
75
|
+
"""BPF from (op, jt, jf, k) tuples and label strings; a str jt/jf jumps to that label."""
|
|
76
|
+
labels: dict[str, int] = {}
|
|
77
|
+
count = 0
|
|
78
|
+
for ins in code:
|
|
79
|
+
if isinstance(ins, str):
|
|
80
|
+
labels[ins] = count
|
|
81
|
+
else:
|
|
82
|
+
count += 1
|
|
83
|
+
out = []
|
|
84
|
+
pos = 0
|
|
85
|
+
for ins in code:
|
|
86
|
+
if isinstance(ins, str):
|
|
87
|
+
continue
|
|
88
|
+
op, jt, jf, k = ins
|
|
89
|
+
jt = labels[jt] - pos - 1 if isinstance(jt, str) else jt
|
|
90
|
+
jf = labels[jf] - pos - 1 if isinstance(jf, str) else jf
|
|
91
|
+
out.append(struct.pack("=HBBI", op, jt, jf, k))
|
|
92
|
+
pos += 1
|
|
93
|
+
return b"".join(out)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _filter(a: _Arch) -> bytes:
|
|
97
|
+
# io_uring can open a socket without calling socket(), and the x32 ABI numbers socket()
|
|
98
|
+
# differently; both are refused so the socket() rule cannot be stepped around.
|
|
99
|
+
deny = SECCOMP_RET_ERRNO | errno.EPERM
|
|
100
|
+
return _assemble(
|
|
101
|
+
[
|
|
102
|
+
(BPF_LD_W_ABS, 0, 0, _ARCH),
|
|
103
|
+
(BPF_JEQ_K, 0, "kill", a.audit_arch),
|
|
104
|
+
(BPF_LD_W_ABS, 0, 0, _NR),
|
|
105
|
+
*([(BPF_JGE_K, "deny", 0, a.x32_bit)] if a.x32_bit is not None else []),
|
|
106
|
+
(BPF_JEQ_K, "deny", 0, a.io_uring_setup_nr),
|
|
107
|
+
(BPF_JEQ_K, 0, "allow", a.socket_nr),
|
|
108
|
+
(BPF_LD_W_ABS, 0, 0, _ARG0),
|
|
109
|
+
(BPF_JEQ_K, "deny", 0, socket.AF_INET),
|
|
110
|
+
(BPF_JEQ_K, "deny", 0, socket.AF_INET6),
|
|
111
|
+
"allow",
|
|
112
|
+
(BPF_RET_K, 0, 0, SECCOMP_RET_ALLOW),
|
|
113
|
+
"deny",
|
|
114
|
+
(BPF_RET_K, 0, 0, deny),
|
|
115
|
+
"kill",
|
|
116
|
+
(BPF_RET_K, 0, 0, SECCOMP_RET_KILL_PROCESS),
|
|
117
|
+
]
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def seccomp_program(machine: str) -> bytes:
|
|
122
|
+
"""The filter for `machine` (platform.machine()), as the kernel takes it."""
|
|
123
|
+
return _filter(_ARCHES[machine])
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _libc():
|
|
127
|
+
return ctypes.CDLL(None, use_errno=True)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _prctl(libc, option: int, arg: int) -> None:
|
|
131
|
+
ul = ctypes.c_ulong
|
|
132
|
+
if libc.prctl(ctypes.c_int(option), ul(arg), ul(0), ul(0), ul(0)) != 0:
|
|
133
|
+
err = ctypes.get_errno()
|
|
134
|
+
raise SandboxNetworkError(f"prctl({option}) failed: {os.strerror(err)}")
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _set_not_dumpable() -> None:
|
|
138
|
+
if sys.platform.startswith("linux"):
|
|
139
|
+
_prctl(_libc(), PR_SET_DUMPABLE, 0)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _thread_count() -> int:
|
|
143
|
+
with open("/proc/self/status", encoding="ascii") as fh:
|
|
144
|
+
for line in fh:
|
|
145
|
+
if line.startswith("Threads:"):
|
|
146
|
+
return int(line.split()[1])
|
|
147
|
+
return 0
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def install_seccomp() -> None:
|
|
151
|
+
"""Refuse socket() for AF_INET and AF_INET6 in this process and every thread and child it starts.
|
|
152
|
+
|
|
153
|
+
prctl(PR_SET_SECCOMP) filters the calling thread and what it starts after, so it is installed
|
|
154
|
+
while the process has no other thread.
|
|
155
|
+
"""
|
|
156
|
+
if not sys.platform.startswith("linux"):
|
|
157
|
+
raise SandboxNetworkError("live network mode needs Linux seccomp, and this is " + sys.platform)
|
|
158
|
+
machine = platform.machine()
|
|
159
|
+
if machine not in _ARCHES:
|
|
160
|
+
raise SandboxNetworkError(f"live network mode has no seccomp filter for {machine}")
|
|
161
|
+
threads = _thread_count()
|
|
162
|
+
if threads != 1:
|
|
163
|
+
raise SandboxNetworkError(f"the seccomp filter goes on before any other thread starts, and {threads} threads run")
|
|
164
|
+
prog = seccomp_program(machine)
|
|
165
|
+
libc = _libc()
|
|
166
|
+
_prctl(libc, PR_SET_NO_NEW_PRIVS, 1)
|
|
167
|
+
buf = ctypes.create_string_buffer(prog, len(prog))
|
|
168
|
+
fprog = _SockFprog(len(prog) // 8, ctypes.cast(buf, ctypes.c_void_p))
|
|
169
|
+
ul = ctypes.c_ulong
|
|
170
|
+
if libc.prctl(ctypes.c_int(PR_SET_SECCOMP), ul(SECCOMP_MODE_FILTER), ctypes.byref(fprog), ul(0), ul(0)) != 0:
|
|
171
|
+
raise SandboxNetworkError(f"installing the seccomp filter failed: {os.strerror(ctypes.get_errno())}")
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _read_head(sock: socket.socket) -> bytes:
|
|
175
|
+
head = b""
|
|
176
|
+
while not head.endswith(b"\r\n\r\n"):
|
|
177
|
+
chunk = sock.recv(1)
|
|
178
|
+
if not chunk:
|
|
179
|
+
break
|
|
180
|
+
head += chunk
|
|
181
|
+
if len(head) > 8192:
|
|
182
|
+
break
|
|
183
|
+
return head
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
class _Tunnel(socket.socket):
|
|
187
|
+
"""A Unix socket that carries a TCP connection: TCP options set on it (TCP_NODELAY) are moot."""
|
|
188
|
+
|
|
189
|
+
def setsockopt(self, level, *args):
|
|
190
|
+
if level == socket.IPPROTO_TCP:
|
|
191
|
+
return None
|
|
192
|
+
return super().setsockopt(level, *args)
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def route_through_proxy(proxy_socket: str, token: str) -> None:
|
|
196
|
+
"""Make socket.create_connection (which http.client and urllib use) tunnel through the run's proxy."""
|
|
197
|
+
|
|
198
|
+
def create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, source_address=None, **_kwargs):
|
|
199
|
+
host, port = address[0], address[1]
|
|
200
|
+
target = f"[{host}]:{port}" if ":" in str(host) else f"{host}:{port}"
|
|
201
|
+
sock = _Tunnel(socket.AF_UNIX, socket.SOCK_STREAM)
|
|
202
|
+
try:
|
|
203
|
+
if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT:
|
|
204
|
+
sock.settimeout(timeout)
|
|
205
|
+
sock.connect(proxy_socket)
|
|
206
|
+
sock.sendall(
|
|
207
|
+
f"CONNECT {target} HTTP/1.1\r\nHost: {target}\r\nProxy-Authorization: Bearer {token}\r\n\r\n".encode()
|
|
208
|
+
)
|
|
209
|
+
head = _read_head(sock)
|
|
210
|
+
status_line = head.split(b"\r\n", 1)[0].decode("latin-1")
|
|
211
|
+
parts = status_line.split(" ", 2)
|
|
212
|
+
if len(parts) >= 2 and parts[1] == "200":
|
|
213
|
+
return sock
|
|
214
|
+
rest = b""
|
|
215
|
+
while len(rest) < 4096:
|
|
216
|
+
chunk = sock.recv(4096)
|
|
217
|
+
if not chunk:
|
|
218
|
+
break
|
|
219
|
+
rest += chunk
|
|
220
|
+
why = rest.decode("utf-8", "replace").strip()
|
|
221
|
+
raise ConnectionRefusedError(
|
|
222
|
+
errno.ECONNREFUSED,
|
|
223
|
+
f"the run's host proxy refused {target}: {status_line or 'no answer'}" + (f" ({why})" if why else ""),
|
|
224
|
+
)
|
|
225
|
+
except BaseException:
|
|
226
|
+
sock.close()
|
|
227
|
+
raise
|
|
228
|
+
|
|
229
|
+
socket.create_connection = create_connection
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def held_token(name: str) -> Optional[str]:
|
|
233
|
+
"""A token enter_network_mode took out of the environment."""
|
|
234
|
+
return _held.get(name)
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def enter_network_mode(environ: MutableMapping[str, str] = os.environ) -> Optional[str]:
|
|
238
|
+
"""Enter the mode in SENPI_NETWORK_MODE; None when it is unset (code that is not uploaded)."""
|
|
239
|
+
mode = environ.get(NETWORK_MODE_ENV)
|
|
240
|
+
if mode is None:
|
|
241
|
+
return None
|
|
242
|
+
if mode not in ("open", "live"):
|
|
243
|
+
raise SandboxNetworkError(f"unknown {NETWORK_MODE_ENV} {mode!r}; the run does not start")
|
|
244
|
+
if mode == "live":
|
|
245
|
+
proxy, token = environ.get(PROXY_SOCKET_ENV), environ.get(PROXY_TOKEN_ENV)
|
|
246
|
+
if not proxy or not token:
|
|
247
|
+
raise SandboxNetworkError(f"live network mode needs the run's proxy ({PROXY_SOCKET_ENV}, {PROXY_TOKEN_ENV})")
|
|
248
|
+
_set_not_dumpable()
|
|
249
|
+
for name in (PROXY_TOKEN_ENV, RELAY_TOKEN_ENV):
|
|
250
|
+
value = environ.pop(name, None)
|
|
251
|
+
if value is not None:
|
|
252
|
+
_held[name] = value
|
|
253
|
+
if mode == "live":
|
|
254
|
+
install_seccomp()
|
|
255
|
+
route_through_proxy(proxy, token)
|
|
256
|
+
return mode
|
|
@@ -51,6 +51,7 @@ from .loop_primitives import (
|
|
|
51
51
|
_interruptible_sleep,
|
|
52
52
|
log_event,
|
|
53
53
|
)
|
|
54
|
+
from .sandbox_net import held_token
|
|
54
55
|
from .state_manager import StateManager
|
|
55
56
|
from .tick_metrics import cpu_seconds, measure_tick
|
|
56
57
|
|
|
@@ -94,7 +95,12 @@ def _build_senpi_mcp() -> Any:
|
|
|
94
95
|
so a test stub patched onto scaffold.senpi_mcp is honored. The per-call bound
|
|
95
96
|
comes from SENPI_MCP_CALL_TIMEOUT_SECONDS (see _read_call_timeout_seconds).
|
|
96
97
|
"""
|
|
97
|
-
api_key =
|
|
98
|
+
api_key = (
|
|
99
|
+
os.environ.get("SENPI_AUTH_TOKEN")
|
|
100
|
+
or held_token("SENPI_AUTH_TOKEN")
|
|
101
|
+
or os.environ.get("SENPI_API_KEY")
|
|
102
|
+
or None
|
|
103
|
+
)
|
|
98
104
|
mcp_url = os.environ.get("SENPI_MCP_URL") or None
|
|
99
105
|
if not api_key and not mcp_url:
|
|
100
106
|
return None
|
|
@@ -111,6 +117,7 @@ def _build_senpi_mcp() -> Any:
|
|
|
111
117
|
mcp_url=mcp_url,
|
|
112
118
|
write_allowlist=senpi_mcp_mod.PRODUCER_WRITE_ALLOWLIST,
|
|
113
119
|
call_timeout_seconds=_read_call_timeout_seconds(senpi_mcp_mod),
|
|
120
|
+
runtime_socket=os.environ.get("SENPI_RUNTIME_SOCKET") or None,
|
|
114
121
|
)
|
|
115
122
|
|
|
116
123
|
|
|
@@ -604,6 +604,22 @@ class _McpSession:
|
|
|
604
604
|
return not self.lifetime.done()
|
|
605
605
|
|
|
606
606
|
|
|
607
|
+
def _unix_client_factory(socket_path: str):
|
|
608
|
+
"""An httpx client factory for the SDK that sends every request to the runtime's Unix socket."""
|
|
609
|
+
import httpx
|
|
610
|
+
|
|
611
|
+
def factory(headers=None, timeout=None, auth=None):
|
|
612
|
+
return httpx.AsyncClient(
|
|
613
|
+
headers=headers,
|
|
614
|
+
timeout=timeout if timeout is not None else httpx.Timeout(30.0, read=300.0),
|
|
615
|
+
auth=auth,
|
|
616
|
+
follow_redirects=True,
|
|
617
|
+
transport=httpx.AsyncHTTPTransport(uds=socket_path),
|
|
618
|
+
)
|
|
619
|
+
|
|
620
|
+
return factory
|
|
621
|
+
|
|
622
|
+
|
|
607
623
|
class SenpiMcpClient:
|
|
608
624
|
"""Sync MCP client over the official async SDK with one persistent session.
|
|
609
625
|
|
|
@@ -626,9 +642,11 @@ class SenpiMcpClient:
|
|
|
626
642
|
mcp_url: Optional[str] = None,
|
|
627
643
|
write_allowlist: Iterable[str] = (),
|
|
628
644
|
call_timeout_seconds: Optional[float] = None,
|
|
645
|
+
runtime_socket: Optional[str] = None,
|
|
629
646
|
) -> None:
|
|
630
647
|
self._api_key = api_key
|
|
631
648
|
self._mcp_url = mcp_url
|
|
649
|
+
self._runtime_socket = runtime_socket
|
|
632
650
|
if call_timeout_seconds is None:
|
|
633
651
|
call_timeout_seconds = DEFAULT_CALL_TIMEOUT_SECONDS
|
|
634
652
|
if not is_valid_call_timeout(call_timeout_seconds):
|
|
@@ -830,7 +848,8 @@ class SenpiMcpClient:
|
|
|
830
848
|
from mcp.client.streamable_http import streamablehttp_client
|
|
831
849
|
|
|
832
850
|
headers = {"Authorization": f"Bearer {self._api_key}"}
|
|
833
|
-
|
|
851
|
+
extra = {"httpx_client_factory": _unix_client_factory(self._runtime_socket)} if self._runtime_socket else {}
|
|
852
|
+
async with streamablehttp_client(self._mcp_url, headers=headers, **extra) as (read, write, _):
|
|
834
853
|
async with ClientSession(read, write) as session:
|
|
835
854
|
await session.initialize()
|
|
836
855
|
ready.set_result(session)
|
package/openclaw.plugin.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"id": "runtime",
|
|
3
3
|
"name": "Senpi Runtime",
|
|
4
4
|
"description": "Senpi runtime plugin for OpenClaw. Orchestrates scanners, LLM-based trade decisions, and a DSL trailing stop-loss exit engine.",
|
|
5
|
-
"version": "3.0.
|
|
5
|
+
"version": "3.0.295",
|
|
6
6
|
"commandAliases": [
|
|
7
7
|
{
|
|
8
8
|
"name": "senpi"
|