@evolvingmachines/sdk 0.0.53 → 0.0.55-train-2026-08-31.20260831.d974a5b
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/README.md +4 -0
- package/dist/chunk-7UNADEUP.js +428 -0
- package/dist/chunk-NVI5CCTO.js +11 -0
- package/dist/cli/index.cjs +38 -0
- package/dist/cli/index.d.cts +204 -0
- package/dist/cli/index.d.ts +204 -0
- package/dist/cli/index.js +17 -0
- package/dist/index.cjs +144 -92
- package/dist/index.d.cts +1856 -315
- package/dist/index.d.ts +1856 -315
- package/dist/index.js +56 -444
- package/dist/managed-modal-IJW62SSK.js +4 -0
- package/dist/tar-SO35VKIU.js +1 -0
- package/dist/types-CcBwkYhq.d.cts +3317 -0
- package/dist/types-CcBwkYhq.d.ts +3317 -0
- package/dist/upload-HB55JKIS.js +1 -0
- package/harness-capabilities.json +385 -0
- package/hosted-error-codes.json +91 -0
- package/package.json +41 -10
- package/spec/atif/README.md +45 -0
- package/spec/atif/trajectory.schema.json +865 -0
- package/spec/openapi.yaml +9471 -0
package/README.md
CHANGED
|
@@ -1,7 +1,11 @@
|
|
|
1
|
+
<br><br>
|
|
2
|
+
|
|
1
3
|
<p align="center">
|
|
2
4
|
<img src="https://raw.githubusercontent.com/evolving-machines-lab/evolve/main/logo/evolving-machines-ink.png" alt="Evolving Machines" width="380">
|
|
3
5
|
</p>
|
|
4
6
|
|
|
7
|
+
<br><br>
|
|
8
|
+
|
|
5
9
|
# Evolving Machines — Evolve SDK (TypeScript)
|
|
6
10
|
|
|
7
11
|
Evolve SDK lets you run and orchestrate terminal-based AI agents in secure sandboxes with built-in observability.
|
|
@@ -0,0 +1,428 @@
|
|
|
1
|
+
import {createWriteStream}from'fs';import {mkdir,rename,rm}from'fs/promises';import {join,basename}from'path';import {Readable}from'stream';import {pipeline}from'stream/promises';function Ue(e=""){let t=process.env.EVOLVE_GATEWAY_URL||"https://swarmkit-gateway-692833842999.us-central1.run.app";if(!e)return t;let n=e.startsWith("/")?e:`/${e}`;return `${t}${n}`}function Ne(e=""){let t=process.env.EVOLVE_DASHBOARD_URL||L;if(!e)return t;let n=e.startsWith("/")?e:`/${e}`;return `${t.replace(/\/$/,"")}${n}`}var Xt=["e2b","daytona","modal"];function ge(e){return Ne(`/api/managed/${e}`)}function Qt(){return `${ge("daytona")}/toolbox`}function Zt(){return ge("e2b")}function en(e){return {"browser-use":{type:"http",url:Ue("/browser_use/mcp"),headers:{"x-litellm-api-key":`Bearer ${e}`}}}}var Z="EVOLVE_API_KEY",tn="E2B_API_KEY",nn="DAYTONA_API_KEY",rn="MODAL_TOKEN_ID",sn="MODAL_TOKEN_SECRET",an="claude",on=36e5,ln=4,un=100,_e="/home/user";function dn(e,t){return t?t.replace(/\/+$/,"")||"/":e?e==="root"?"/root":`/home/${e}`:_e}var L=process.env.EVOLVE_DASHBOARD_URL||"https://dashboard.evolvingmachines.ai",pn="x-litellm-customer-id",gn="x-litellm-tags",_n="run:",mn=".evolve-sdk/observability/sessions",fn=["tag","provider","agent","model","sandboxId","sandbox_id","timestamp","event","events"],bn=100,yn=5e3,hn=3,kn=1e3;function ee(e){return e.delivery==="direct"}var be=18181,S="/tmp/evolve-managed-secrets",ye=`${S}/proxy.py`,te=`${S}/config.json`,D=`${S}/ca.crt`,q=`${S}/ca.key`,j=`${S}/ca-bundle.crt`,he=["HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","http_proxy","https_proxy","all_proxy","NO_PROXY","no_proxy","NODE_EXTRA_CA_CERTS","SSL_CERT_FILE","REQUESTS_CA_BUNDLE","CURL_CA_BUNDLE","GIT_SSL_CAINFO"];function An(){return [...he]}var Tn=String.raw`#!/usr/bin/env python3
|
|
2
|
+
import base64
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import select
|
|
6
|
+
import secrets
|
|
7
|
+
import socket
|
|
8
|
+
import ssl
|
|
9
|
+
import subprocess
|
|
10
|
+
import sys
|
|
11
|
+
import tempfile
|
|
12
|
+
import threading
|
|
13
|
+
import time
|
|
14
|
+
import urllib.error
|
|
15
|
+
import urllib.request
|
|
16
|
+
|
|
17
|
+
for key in ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy"]:
|
|
18
|
+
os.environ.pop(key, None)
|
|
19
|
+
|
|
20
|
+
CONFIG_PATH = sys.argv[1]
|
|
21
|
+
with open(CONFIG_PATH, "r", encoding="utf-8") as f:
|
|
22
|
+
CONFIG = json.load(f)
|
|
23
|
+
try:
|
|
24
|
+
os.unlink(CONFIG_PATH)
|
|
25
|
+
except FileNotFoundError:
|
|
26
|
+
pass
|
|
27
|
+
|
|
28
|
+
MAX_BODY_BYTES = int(CONFIG.get("max_body_bytes", 10 * 1024 * 1024))
|
|
29
|
+
CONNECT_TIMEOUT_SECONDS = 15
|
|
30
|
+
SOCKET_TIMEOUT_SECONDS = 130
|
|
31
|
+
MAX_WORKERS = 100
|
|
32
|
+
WORKERS = threading.BoundedSemaphore(MAX_WORKERS)
|
|
33
|
+
HOST_PATTERNS = [h.lower() for h in CONFIG["hosts"]]
|
|
34
|
+
PLACEHOLDERS = set(CONFIG["placeholders"])
|
|
35
|
+
PLACEHOLDER_BYTES = [p.encode("utf-8") for p in CONFIG["placeholders"]]
|
|
36
|
+
BASE_DIR = CONFIG["base_dir"]
|
|
37
|
+
CERT_DIR = os.path.join(BASE_DIR, "certs")
|
|
38
|
+
os.makedirs(CERT_DIR, exist_ok=True)
|
|
39
|
+
CHANNEL_SECRET = secrets.token_urlsafe(32)
|
|
40
|
+
|
|
41
|
+
def register_channel():
|
|
42
|
+
payload = json.dumps({}).encode("utf-8")
|
|
43
|
+
req = urllib.request.Request(
|
|
44
|
+
CONFIG["channel_url"],
|
|
45
|
+
data=payload,
|
|
46
|
+
method="POST",
|
|
47
|
+
headers={
|
|
48
|
+
"content-type": "application/json",
|
|
49
|
+
"accept": "application/json",
|
|
50
|
+
"x-evolve-managed-secret-token": CONFIG["token"],
|
|
51
|
+
"x-evolve-managed-secret-binding": CONFIG["binding"],
|
|
52
|
+
"x-evolve-managed-secret-channel": CHANNEL_SECRET,
|
|
53
|
+
},
|
|
54
|
+
)
|
|
55
|
+
with urllib.request.urlopen(req, timeout=30) as resp:
|
|
56
|
+
if resp.status < 200 or resp.status >= 300:
|
|
57
|
+
raise RuntimeError("managed secret channel registration failed")
|
|
58
|
+
|
|
59
|
+
def host_matches(pattern, host):
|
|
60
|
+
host = host.lower()
|
|
61
|
+
if pattern.startswith("*."):
|
|
62
|
+
base = pattern[2:]
|
|
63
|
+
return host != base and host.endswith("." + base)
|
|
64
|
+
return host == pattern
|
|
65
|
+
|
|
66
|
+
def is_managed_host(host):
|
|
67
|
+
clean = host.split(":", 1)[0].strip("[]").lower()
|
|
68
|
+
return any(host_matches(pattern, clean) for pattern in HOST_PATTERNS)
|
|
69
|
+
|
|
70
|
+
def safe_name(host):
|
|
71
|
+
return "".join(ch if ch.isalnum() or ch in "._-" else "_" for ch in host)[:180]
|
|
72
|
+
|
|
73
|
+
def ensure_cert(host):
|
|
74
|
+
name = safe_name(host)
|
|
75
|
+
cert = os.path.join(CERT_DIR, name + ".crt")
|
|
76
|
+
key = os.path.join(CERT_DIR, name + ".key")
|
|
77
|
+
if os.path.exists(cert) and os.path.exists(key):
|
|
78
|
+
return cert, key
|
|
79
|
+
csr = os.path.join(CERT_DIR, name + ".csr")
|
|
80
|
+
ext = os.path.join(CERT_DIR, name + ".ext")
|
|
81
|
+
san = "IP:" + host if host.replace(".", "").isdigit() else "DNS:" + host
|
|
82
|
+
with open(ext, "w", encoding="utf-8") as f:
|
|
83
|
+
f.write("basicConstraints=critical,CA:FALSE\n")
|
|
84
|
+
f.write("keyUsage=critical,digitalSignature,keyEncipherment\n")
|
|
85
|
+
f.write("subjectAltName=" + san + "\n")
|
|
86
|
+
f.write("extendedKeyUsage=serverAuth\n")
|
|
87
|
+
subprocess.run(
|
|
88
|
+
["openssl", "req", "-newkey", "rsa:2048", "-nodes", "-keyout", key, "-subj", "/CN=" + host, "-out", csr],
|
|
89
|
+
check=True,
|
|
90
|
+
stdout=subprocess.DEVNULL,
|
|
91
|
+
stderr=subprocess.DEVNULL,
|
|
92
|
+
)
|
|
93
|
+
subprocess.run(
|
|
94
|
+
[
|
|
95
|
+
"openssl", "x509", "-req", "-in", csr,
|
|
96
|
+
"-CA", CONFIG["ca_cert"], "-CAkey", CONFIG["ca_key"], "-CAcreateserial",
|
|
97
|
+
"-out", cert, "-days", "30", "-sha256", "-extfile", ext,
|
|
98
|
+
],
|
|
99
|
+
check=True,
|
|
100
|
+
stdout=subprocess.DEVNULL,
|
|
101
|
+
stderr=subprocess.DEVNULL,
|
|
102
|
+
)
|
|
103
|
+
return cert, key
|
|
104
|
+
|
|
105
|
+
def pipe_raw(client, host, port):
|
|
106
|
+
upstream = socket.create_connection((host, port), timeout=CONNECT_TIMEOUT_SECONDS)
|
|
107
|
+
client.settimeout(SOCKET_TIMEOUT_SECONDS)
|
|
108
|
+
upstream.settimeout(SOCKET_TIMEOUT_SECONDS)
|
|
109
|
+
try:
|
|
110
|
+
client.sendall(b"HTTP/1.1 200 Connection Established\r\n\r\n")
|
|
111
|
+
sockets = [client, upstream]
|
|
112
|
+
while True:
|
|
113
|
+
readable, _, _ = select.select(sockets, [], [], 120)
|
|
114
|
+
if not readable:
|
|
115
|
+
break
|
|
116
|
+
for sock in readable:
|
|
117
|
+
data = sock.recv(65536)
|
|
118
|
+
if not data:
|
|
119
|
+
return
|
|
120
|
+
(upstream if sock is client else client).sendall(data)
|
|
121
|
+
finally:
|
|
122
|
+
upstream.close()
|
|
123
|
+
|
|
124
|
+
def recv_until(sock, marker, limit=65536):
|
|
125
|
+
data = b""
|
|
126
|
+
while marker not in data:
|
|
127
|
+
chunk = sock.recv(4096)
|
|
128
|
+
if not chunk:
|
|
129
|
+
break
|
|
130
|
+
data += chunk
|
|
131
|
+
if len(data) > limit:
|
|
132
|
+
raise RuntimeError("request headers too large")
|
|
133
|
+
return data
|
|
134
|
+
|
|
135
|
+
def parse_headers(blob):
|
|
136
|
+
head, rest = blob.split(b"\r\n\r\n", 1)
|
|
137
|
+
lines = head.decode("iso-8859-1").split("\r\n")
|
|
138
|
+
request_line = lines[0]
|
|
139
|
+
headers = {}
|
|
140
|
+
for line in lines[1:]:
|
|
141
|
+
if not line or ":" not in line:
|
|
142
|
+
continue
|
|
143
|
+
name, value = line.split(":", 1)
|
|
144
|
+
headers[name.strip()] = value.strip()
|
|
145
|
+
return request_line, headers, rest
|
|
146
|
+
|
|
147
|
+
def header_value(headers, name):
|
|
148
|
+
wanted = name.lower()
|
|
149
|
+
for key, value in headers.items():
|
|
150
|
+
if key.lower() == wanted:
|
|
151
|
+
return value
|
|
152
|
+
return None
|
|
153
|
+
|
|
154
|
+
def read_chunked_body(sock, initial):
|
|
155
|
+
data = initial
|
|
156
|
+
body = b""
|
|
157
|
+
while True:
|
|
158
|
+
while b"\r\n" not in data:
|
|
159
|
+
chunk = sock.recv(4096)
|
|
160
|
+
if not chunk:
|
|
161
|
+
raise RuntimeError("incomplete chunked request")
|
|
162
|
+
data += chunk
|
|
163
|
+
line, data = data.split(b"\r\n", 1)
|
|
164
|
+
size = int((line.split(b";", 1)[0].strip() or b"0"), 16)
|
|
165
|
+
if size == 0:
|
|
166
|
+
return body
|
|
167
|
+
if len(body) + size > MAX_BODY_BYTES:
|
|
168
|
+
raise RuntimeError("request body too large")
|
|
169
|
+
while len(data) < size + 2:
|
|
170
|
+
chunk = sock.recv(65536)
|
|
171
|
+
if not chunk:
|
|
172
|
+
raise RuntimeError("incomplete chunked request")
|
|
173
|
+
data += chunk
|
|
174
|
+
body += data[:size]
|
|
175
|
+
data = data[size + 2:]
|
|
176
|
+
|
|
177
|
+
def read_request(tls_sock):
|
|
178
|
+
blob = recv_until(tls_sock, b"\r\n\r\n")
|
|
179
|
+
if not blob:
|
|
180
|
+
return None
|
|
181
|
+
request_line, headers, rest = parse_headers(blob)
|
|
182
|
+
transfer_encoding = (header_value(headers, "Transfer-Encoding") or "").lower()
|
|
183
|
+
if "chunked" in transfer_encoding:
|
|
184
|
+
return request_line, headers, read_chunked_body(tls_sock, rest)
|
|
185
|
+
length = int(header_value(headers, "Content-Length") or "0")
|
|
186
|
+
if length > MAX_BODY_BYTES:
|
|
187
|
+
raise RuntimeError("request body too large")
|
|
188
|
+
body = rest
|
|
189
|
+
while len(body) < length:
|
|
190
|
+
chunk = tls_sock.recv(min(65536, length - len(body)))
|
|
191
|
+
if not chunk:
|
|
192
|
+
break
|
|
193
|
+
body += chunk
|
|
194
|
+
return request_line, headers, body[:length]
|
|
195
|
+
|
|
196
|
+
def uses_placeholder(path, headers, body):
|
|
197
|
+
if any(ph in path for ph in PLACEHOLDERS):
|
|
198
|
+
return True
|
|
199
|
+
if any(ph in value for ph in PLACEHOLDERS for value in headers.values()):
|
|
200
|
+
return True
|
|
201
|
+
return any(ph_b in body for ph_b in PLACEHOLDER_BYTES)
|
|
202
|
+
|
|
203
|
+
def brokered_status(transport_status, transport_reason, payload):
|
|
204
|
+
# A brokered reply carries the TRUE upstream status inside the payload;
|
|
205
|
+
# the dashboard's own status reports only the health of the hop to it.
|
|
206
|
+
# Servers older than the status lane omit it: those fall back.
|
|
207
|
+
status = payload.get("status")
|
|
208
|
+
if isinstance(status, bool) or not isinstance(status, int) or not 100 <= status <= 599:
|
|
209
|
+
return transport_status, transport_reason
|
|
210
|
+
reason = payload.get("statusText")
|
|
211
|
+
return status, reason if isinstance(reason, str) else ""
|
|
212
|
+
|
|
213
|
+
def egress_failure(exc):
|
|
214
|
+
body = json.dumps({
|
|
215
|
+
"error": "managed secret egress request failed",
|
|
216
|
+
"detail": str(exc),
|
|
217
|
+
}).encode("utf-8")
|
|
218
|
+
return 502, "Managed Secret Egress Unavailable", {
|
|
219
|
+
"headers": {"content-type": "application/json"},
|
|
220
|
+
"bodyBase64": base64.b64encode(body).decode("ascii"),
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
def call_dashboard(method, url, headers, body):
|
|
224
|
+
payload = json.dumps({
|
|
225
|
+
"method": method,
|
|
226
|
+
"url": url,
|
|
227
|
+
"headers": headers,
|
|
228
|
+
"bodyBase64": base64.b64encode(body).decode("ascii") if body else "",
|
|
229
|
+
}).encode("utf-8")
|
|
230
|
+
req = urllib.request.Request(
|
|
231
|
+
CONFIG["egress_url"],
|
|
232
|
+
data=payload,
|
|
233
|
+
method="POST",
|
|
234
|
+
headers={
|
|
235
|
+
"content-type": "application/json",
|
|
236
|
+
"accept": "application/json",
|
|
237
|
+
"x-evolve-managed-secret-token": CONFIG["token"],
|
|
238
|
+
"x-evolve-managed-secret-binding": CONFIG["binding"],
|
|
239
|
+
"x-evolve-managed-secret-channel": CHANNEL_SECRET,
|
|
240
|
+
},
|
|
241
|
+
)
|
|
242
|
+
try:
|
|
243
|
+
with urllib.request.urlopen(req, timeout=130) as resp:
|
|
244
|
+
result = json.loads(resp.read().decode("utf-8"))
|
|
245
|
+
if not isinstance(result, dict):
|
|
246
|
+
raise ValueError("managed secret egress returned a non-object response")
|
|
247
|
+
status, reason = brokered_status(resp.status, resp.reason, result)
|
|
248
|
+
return status, reason, result
|
|
249
|
+
except urllib.error.HTTPError as err:
|
|
250
|
+
text = err.read().decode("utf-8", "replace")
|
|
251
|
+
return err.code, "Managed Secret Egress Error", {"headers": {"content-type": "application/json"}, "bodyBase64": base64.b64encode(text.encode()).decode("ascii")}
|
|
252
|
+
except (urllib.error.URLError, OSError, ValueError) as err:
|
|
253
|
+
# Connection reset, SSL EOF, timeout, or an unreadable body: the agent
|
|
254
|
+
# gets a typed 502 and the proxy keeps serving.
|
|
255
|
+
return egress_failure(err)
|
|
256
|
+
|
|
257
|
+
def read_limited_response(stream):
|
|
258
|
+
chunks = []
|
|
259
|
+
total = 0
|
|
260
|
+
while True:
|
|
261
|
+
chunk = stream.read(65536)
|
|
262
|
+
if not chunk:
|
|
263
|
+
break
|
|
264
|
+
total += len(chunk)
|
|
265
|
+
if total > MAX_BODY_BYTES:
|
|
266
|
+
raise RuntimeError("response body too large")
|
|
267
|
+
chunks.append(chunk)
|
|
268
|
+
return b"".join(chunks)
|
|
269
|
+
|
|
270
|
+
def call_direct(method, url, headers, body):
|
|
271
|
+
hop_by_hop = {"connection", "proxy-connection", "keep-alive", "transfer-encoding", "upgrade", "host", "content-length"}
|
|
272
|
+
request_headers = {k: v for k, v in headers.items() if k.lower() not in hop_by_hop}
|
|
273
|
+
req = urllib.request.Request(
|
|
274
|
+
url,
|
|
275
|
+
data=body if body else None,
|
|
276
|
+
method=method,
|
|
277
|
+
headers=request_headers,
|
|
278
|
+
)
|
|
279
|
+
try:
|
|
280
|
+
with urllib.request.urlopen(req, timeout=130) as resp:
|
|
281
|
+
return resp.status, resp.reason, {
|
|
282
|
+
"headers": dict(resp.headers.items()),
|
|
283
|
+
"bodyBase64": base64.b64encode(read_limited_response(resp)).decode("ascii"),
|
|
284
|
+
}
|
|
285
|
+
except urllib.error.HTTPError as err:
|
|
286
|
+
return err.code, err.reason, {
|
|
287
|
+
"headers": dict(err.headers.items()),
|
|
288
|
+
"bodyBase64": base64.b64encode(read_limited_response(err)).decode("ascii"),
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
def send_response(tls_sock, status, reason, result):
|
|
292
|
+
body = base64.b64decode(result.get("bodyBase64") or "")
|
|
293
|
+
headers = {str(k): str(v) for k, v in (result.get("headers") or {}).items()}
|
|
294
|
+
headers["content-length"] = str(len(body))
|
|
295
|
+
headers["connection"] = "close"
|
|
296
|
+
status_line = ("HTTP/1.1 %d %s\r\n" % (status, reason or "")).encode("ascii", "replace")
|
|
297
|
+
header_blob = b"".join((name + ": " + value + "\r\n").encode("iso-8859-1", "replace") for name, value in headers.items())
|
|
298
|
+
tls_sock.sendall(status_line + header_blob + b"\r\n" + body)
|
|
299
|
+
|
|
300
|
+
def dispatch_managed_request(method, url, headers, body):
|
|
301
|
+
if uses_placeholder(url, headers, body):
|
|
302
|
+
return call_dashboard(method, url, headers, body)
|
|
303
|
+
return call_direct(method, url, headers, body)
|
|
304
|
+
|
|
305
|
+
def handle_managed_connect(client, host, port):
|
|
306
|
+
client.sendall(b"HTTP/1.1 200 Connection Established\r\n\r\n")
|
|
307
|
+
cert, key = ensure_cert(host)
|
|
308
|
+
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
|
309
|
+
ctx.load_cert_chain(cert, key)
|
|
310
|
+
client.settimeout(SOCKET_TIMEOUT_SECONDS)
|
|
311
|
+
tls_sock = ctx.wrap_socket(client, server_side=True)
|
|
312
|
+
tls_sock.settimeout(SOCKET_TIMEOUT_SECONDS)
|
|
313
|
+
try:
|
|
314
|
+
request = read_request(tls_sock)
|
|
315
|
+
if not request:
|
|
316
|
+
return
|
|
317
|
+
request_line, headers, body = request
|
|
318
|
+
parts = request_line.split()
|
|
319
|
+
if len(parts) < 2:
|
|
320
|
+
raise RuntimeError("bad request line")
|
|
321
|
+
method, path = parts[0].upper(), parts[1]
|
|
322
|
+
if path.startswith("http://") or path.startswith("https://"):
|
|
323
|
+
url = path
|
|
324
|
+
else:
|
|
325
|
+
url = "https://%s%s" % (host if port == 443 else host + ":" + str(port), path)
|
|
326
|
+
status, reason, result = dispatch_managed_request(method, url, headers, body)
|
|
327
|
+
send_response(tls_sock, status, reason, result)
|
|
328
|
+
finally:
|
|
329
|
+
try:
|
|
330
|
+
tls_sock.close()
|
|
331
|
+
except Exception:
|
|
332
|
+
pass
|
|
333
|
+
|
|
334
|
+
def handle_client(client):
|
|
335
|
+
try:
|
|
336
|
+
client.settimeout(SOCKET_TIMEOUT_SECONDS)
|
|
337
|
+
blob = recv_until(client, b"\r\n\r\n")
|
|
338
|
+
if not blob:
|
|
339
|
+
return
|
|
340
|
+
request_line, headers, rest = parse_headers(blob)
|
|
341
|
+
parts = request_line.split()
|
|
342
|
+
if len(parts) < 3:
|
|
343
|
+
return
|
|
344
|
+
if parts[0].upper() == "CONNECT":
|
|
345
|
+
target = parts[1]
|
|
346
|
+
if ":" in target:
|
|
347
|
+
host, port_s = target.rsplit(":", 1)
|
|
348
|
+
port = int(port_s)
|
|
349
|
+
else:
|
|
350
|
+
host, port = target, 443
|
|
351
|
+
host = host.strip("[]")
|
|
352
|
+
if is_managed_host(host):
|
|
353
|
+
handle_managed_connect(client, host, port)
|
|
354
|
+
else:
|
|
355
|
+
pipe_raw(client, host, port)
|
|
356
|
+
return
|
|
357
|
+
client.sendall(b"HTTP/1.1 501 Not Implemented\r\ncontent-length: 0\r\nconnection: close\r\n\r\n")
|
|
358
|
+
except Exception as exc:
|
|
359
|
+
try:
|
|
360
|
+
body = json.dumps({"error": str(exc)}).encode("utf-8")
|
|
361
|
+
client.sendall(b"HTTP/1.1 502 Bad Gateway\r\ncontent-type: application/json\r\ncontent-length: " + str(len(body)).encode() + b"\r\nconnection: close\r\n\r\n" + body)
|
|
362
|
+
except Exception:
|
|
363
|
+
pass
|
|
364
|
+
finally:
|
|
365
|
+
try:
|
|
366
|
+
client.close()
|
|
367
|
+
except Exception:
|
|
368
|
+
pass
|
|
369
|
+
|
|
370
|
+
def close_quietly(sock):
|
|
371
|
+
try:
|
|
372
|
+
sock.close()
|
|
373
|
+
except Exception:
|
|
374
|
+
pass
|
|
375
|
+
|
|
376
|
+
def reject_client(client):
|
|
377
|
+
try:
|
|
378
|
+
client.sendall(b"HTTP/1.1 503 Service Unavailable\r\ncontent-length: 0\r\nconnection: close\r\n\r\n")
|
|
379
|
+
except Exception:
|
|
380
|
+
pass
|
|
381
|
+
close_quietly(client)
|
|
382
|
+
|
|
383
|
+
def serve():
|
|
384
|
+
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|
385
|
+
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
|
386
|
+
server.bind(("127.0.0.1", int(CONFIG["port"])))
|
|
387
|
+
server.listen(100)
|
|
388
|
+
while True:
|
|
389
|
+
# The listener outlives every connection: nothing a single accept or
|
|
390
|
+
# handoff raises may end the loop, or the sandbox loses egress for the
|
|
391
|
+
# rest of the session.
|
|
392
|
+
try:
|
|
393
|
+
client, _ = server.accept()
|
|
394
|
+
except Exception:
|
|
395
|
+
time.sleep(0.05)
|
|
396
|
+
continue
|
|
397
|
+
if not WORKERS.acquire(blocking=False):
|
|
398
|
+
reject_client(client)
|
|
399
|
+
continue
|
|
400
|
+
# Bound per thread: the loop rebinds the client on the next accept.
|
|
401
|
+
def run_client(sock=client):
|
|
402
|
+
try:
|
|
403
|
+
handle_client(sock)
|
|
404
|
+
except Exception:
|
|
405
|
+
pass
|
|
406
|
+
finally:
|
|
407
|
+
WORKERS.release()
|
|
408
|
+
try:
|
|
409
|
+
threading.Thread(target=run_client, daemon=True).start()
|
|
410
|
+
except Exception:
|
|
411
|
+
WORKERS.release()
|
|
412
|
+
close_quietly(client)
|
|
413
|
+
|
|
414
|
+
if __name__ == "__main__":
|
|
415
|
+
register_channel()
|
|
416
|
+
serve()
|
|
417
|
+
`;function Me(e){return (e||process.env.EVOLVE_DASHBOARD_URL||L).replace(/\/$/,"")}function $e(e){let t=e.apiKey||process.env.EVOLVE_API_KEY;if(!t)throw new Error("EVOLVE_API_KEY is required for managed secrets");return t}async function Fe(e){return await e.text().catch(()=>"")}async function J(e,t,n={}){let r=await fetch(`${Me(e.dashboardUrl)}${t}`,{...n,headers:{Authorization:`Bearer ${$e(e)}`,accept:"application/json",...n.body?{"content-type":"application/json"}:{},...n.headers||{}}});if(!r.ok)throw new Error(`Managed secrets request failed (${r.status}): ${await Fe(r)}`);return await r.json()}function Be(e){let t=n=>Array.isArray(n)?n.filter(r=>typeof r=="string"):[];return {id:String(e.id??""),name:String(e.name??""),...typeof e.label=="string"?{label:e.label}:{},...e.delivery==="brokered"||e.delivery==="direct"?{delivery:e.delivery}:{},allowedHosts:t(e.allowed_hosts??e.allowedHosts),allowedPathPrefixes:t(e.allowed_path_prefixes??e.allowedPathPrefixes),allowedMethods:t(e.allowed_methods??e.allowedMethods),createdAt:String(e.created_at??e.createdAt??""),updatedAt:String(e.updated_at??e.updatedAt??""),lastUsedAt:typeof(e.last_used_at??e.lastUsedAt)=="string"?e.last_used_at??e.lastUsedAt:null}}function Sn(e={}){return {async list(){return (await J(e,"/api/managed-secrets")).secrets??[]},async set(t){let n={name:t.name,value:t.value,delivery:t.delivery,...t.label!==void 0?{label:t.label}:{},...t.allowedHosts!==void 0?{allowed_hosts:t.allowedHosts}:{},...t.allowedPathPrefixes!==void 0?{allowed_path_prefixes:t.allowedPathPrefixes}:{},...t.allowedMethods!==void 0?{allowed_methods:t.allowedMethods}:{}},r=await J(e,"/api/managed-secrets",{method:"POST",body:JSON.stringify(n)});return {status:r.status,secret:Be(r.secret??{})}},async delete(t){let n=await J(e,"/api/managed-secrets",{method:"DELETE",body:JSON.stringify({name:t.name,...t.label!==void 0?{label:t.label}:{}})});return {ok:n.ok,name:n.name,label:n.label}}}}function qe(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function me(e){try{return new URL(e).protocol==="https:"}catch{return false}}function Ve(e){if(!e||typeof e!="object"||Array.isArray(e))return false;let t=e;return typeof t.token=="string"&&t.token.startsWith("evrt_")&&typeof t.bindingSecret=="string"&&t.bindingSecret.startsWith("evrb_")&&typeof t.egressUrl=="string"&&me(t.egressUrl)&&typeof t.channelUrl=="string"&&me(t.channelUrl)&&typeof t.expiresAt=="string"&&Array.isArray(t.env)&&t.env.every(n=>{if(!n||typeof n!="object"||Array.isArray(n))return false;let r=n;return typeof r.name!="string"||typeof r.envName!="string"||!qe(r.allowedHosts)?false:r.delivery==="direct"?typeof r.value=="string"&&r.value.length>0:(r.delivery===void 0||r.delivery==="brokered")&&typeof r.placeholder=="string"&&r.placeholder.startsWith("evsec_")&&r.value===void 0})}async function xn(e,t){let n=await J(e,"/api/managed-secrets/runtime-token",{method:"POST",body:JSON.stringify(t)});if(!Ve(n))throw new Error("Invalid managed secret runtime token response");return n}async function En(e,t){return (await J(e,"/api/managed-secrets/runtime-token",{method:"PATCH",body:JSON.stringify(t)})).ok}async function wn(e,t){return (await J(e,"/api/managed-secrets/runtime-token",{method:"DELETE",body:JSON.stringify(t)})).ok}var He=/^[A-Za-z0-9._-]{1,80}$/;function Ge(e){if(!Array.isArray(e)||e.length===0)throw new Error("withManagedSecrets() requires at least one secret");return e.map((t,n)=>{if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`managedSecrets[${n}] must be an object with a name`);let r=fe(t.name,`managedSecrets[${n}].name`),a;if(t.label!==void 0){if(typeof t.label!="string"||!He.test(t.label.trim()))throw new Error(`managedSecrets[${n}].label may contain only letters, numbers, dots, underscores, and hyphens (at most 80 characters)`);a=t.label.trim();}let o=t.as===void 0?void 0:fe(t.as,`managedSecrets[${n}].as`);return {name:r,...a!==void 0?{label:a}:{},...o!==void 0?{as:o}:{}}})}function fe(e,t){if(typeof e!="string"||!e.trim())throw new Error(`${t} is required`);let n=e.trim().toUpperCase();if(!/^[A-Z_][A-Z0-9_]{0,127}$/.test(n))throw new Error(`${t} must be a valid environment variable name`);if(n.startsWith("EVOLVE_"))throw new Error(`${t} cannot use the reserved EVOLVE_ prefix`);return n}function Ke(e){let t=new Set(["EVOLVE_API_KEY","EVOLVE_PROVIDER_RUNTIME_BINDING","GEMINI_DEFAULT_AUTH_TYPE",...he]),n=r=>{r&&t.add(r);};n(e.apiKeyEnv),n(e.baseUrlEnv),n(e.customHeadersEnv),n(e.gatewayConfigEnv),e.spendTrackingEnvs&&(n(e.spendTrackingEnvs.sessionTagEnv),n(e.spendTrackingEnvs.runTagEnv));for(let r of Object.values(e.providerEnvMap??{}))n(r.keyEnv);return t}function Cn(e,t){if(!e)return;let n=Ge(e),r=Ke(t),a=new Set;for(let o of n){let d=o.as||o.name;if(r.has(d))throw new Error(`${d} is reserved for Evolve-managed sandbox services and cannot be used as a managed secret env var`);if(a.has(d))throw new Error(`duplicate managed secret env var: ${d}`);a.add(d);}return n}function ze(e){return e.env.some(t=>!ee(t))}function Pn(e){let t={};for(let a of e.env)ee(a)?t[a.envName]=a.value:t[a.envName]=a.placeholder;if(!ze(e))return t;let n=`http://127.0.0.1:${be}`;t.HTTPS_PROXY=n,t.https_proxy=n,t.NODE_EXTRA_CA_CERTS=D,t.SSL_CERT_FILE=j,t.REQUESTS_CA_BUNDLE=j,t.CURL_CA_BUNDLE=j,t.GIT_SSL_CAINFO=j;let r=new URL(e.egressUrl).hostname;return t.NO_PROXY=`localhost,127.0.0.1,::1,${r}`,t.no_proxy=t.NO_PROXY,t}function Dn(e){let t=e.env.filter(r=>!ee(r)),n=Array.from(new Set(t.flatMap(r=>r.allowedHosts)));return JSON.stringify({egress_url:e.egressUrl,channel_url:e.channelUrl,token:e.token,binding:e.bindingSecret,hosts:n,placeholders:t.map(r=>r.placeholder),base_dir:S,ca_cert:D,ca_key:q,port:be,max_body_bytes:10*1024*1024},null,2)}function In(){return ["umask 077",`mkdir -p ${S}/certs`,`chmod 700 ${S} ${S}/certs`,`chmod 700 ${ye} 2>/dev/null || true`,`chmod 600 ${te} 2>/dev/null || true`,`if [ ! -f ${q} ]; then openssl genrsa -out ${q} 2048 >/dev/null 2>&1; fi`,`if [ ! -f ${D} ]; then openssl req -x509 -new -nodes -key ${q} -sha256 -days 30 -subj "/CN=Evolve Managed Secrets" -addext "basicConstraints=critical,CA:TRUE" -addext "keyUsage=critical,keyCertSign,cRLSign" -out ${D} >/dev/null 2>&1; fi`,`SYSTEM_CA_BUNDLE=""; for p in /etc/ssl/certs/ca-certificates.crt /etc/pki/tls/certs/ca-bundle.crt /etc/ssl/ca-bundle.pem; do if [ -f "$p" ]; then SYSTEM_CA_BUNDLE="$p"; break; fi; done; if [ -n "$SYSTEM_CA_BUNDLE" ]; then cat "$SYSTEM_CA_BUNDLE" ${D} > ${j}; else cp ${D} ${j}; fi`,`if command -v update-ca-certificates >/dev/null 2>&1; then cp ${D} /usr/local/share/ca-certificates/evolve-managed-secrets.crt 2>/dev/null && update-ca-certificates >/dev/null 2>&1 || true; fi`].join(" && ")}function On(){return `umask 077 && exec python3 ${ye} ${te}`}function Ln(){return `rm -f ${te}`}var Ye=["QUEUED","RUNNING","SCORING","SCORED","SCORING_ERROR","INFRASTRUCTURE_ERROR","INDETERMINATE","CANCELLED"],We=["e2b","daytona","modal"];function V(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;if(typeof t.provisional!="boolean")return null;let n=r=>typeof r=="number"&&Number.isFinite(r)?r:null;return {provisional:t.provisional,spent_usd:n(t.spent_usd),input_tokens:n(t.input_tokens),cached_input_tokens:n(t.cached_input_tokens),output_tokens:n(t.output_tokens),as_of:typeof t.as_of=="string"?t.as_of:null}}function Xe(e){let t=e.stats?.evals??{},n=[];for(let r of Object.keys(t).sort()){let a=t[r]?.pass_at_k??{},o=[];for(let d of Object.keys(a)){let l=Number(d),u=a[d];!Number.isFinite(l)||typeof u!="number"||!Number.isFinite(u)||o.push({k:l,value:u});}o.length!==0&&(o.sort((d,l)=>d.k-l.k),n.push({evals_key:r,points:o}));}return n}var Qe=["trace-parsed","verifier","trace-stdout","trace-stderr","trace-atif","trajectory","agent-home"],Ze=["trace-stdout","trace-stderr","agent-home"],ke=["missing_authorization","invalid_api_key","credential_service_unavailable","rate_limited","insufficient_credits","invalid_json","invalid_input","invalid_limit","invalid_status","invalid_visibility","invalid_cursor","invalid_after","invalid_format","invalid_ids","invalid_multipart","idempotency_key_reused","dataset_not_found","dataset_version_not_found","dataset_name_taken","dataset_in_use","dataset_not_owned","upstream_not_watchable","no_active_version","version_not_ready","version_not_activatable","unknown_task_names","no_tasks","task_not_found","task_failed_to_build","agent_not_found","agent_name_taken","agent_name_reserved","agent_invalid_name","agent_source_required","agent_source_conflict","agent_invalid_env","agent_too_large","agent_limit_reached","skill_not_found","skill_name_not_found","skill_ref_invalid","skill_unresolvable","skill_invalid","skill_in_use","skill_too_large","skill_limit_reached","too_many_concurrent_skill_uploads","secret_not_found","secret_ambiguous","secret_brokered_unsupported","secret_exists","agent_version_not_found","agent_version_unresolvable","agent_kwarg_unsupported","agent_config_unsupported","agent_config_key_refused","agent_preset_unsupported","job_too_large","provider_unsupported","job_not_found","job_not_terminal","no_failed_trials","trial_not_found","trial_not_settled","concurrent_update","regrade_source_ineligible","no_regradable_trials","invalid_rubric","analysis_already_running","no_analyzable_trials","not_a_job_dir","invalid_trial","upload_too_large","job_uploaded","job_already_uploaded","too_many_concurrent_job_uploads","import_not_found","import_too_large","too_many_concurrent_imports","invalid_archive","unpinned_git_ref","package_not_retained","package_corrupt","package_missing","too_many_concurrent_package_downloads","internal_error"];function ne(e){return typeof e=="string"&&ke.includes(e)}var et=["level","binary","none"];function tt(e,t,n){return e==="measured"&&t===0&&n.every(r=>(r??null)===null)}function ve(e,t,n){return typeof e!="number"||!Number.isFinite(e)?{lane:"unmeasured"}:t==="measured"?tt(t,e,n)?{lane:"unmeasured"}:{lane:"measured",usd:e}:t==="measured_provisional"?{lane:"floor",usd:e}:{lane:"unmeasured"}}function H(e){let t=e.agent_result;return ve(t?.cost_usd,e.spend_source,[t?.n_input_tokens,t?.n_cache_tokens,t?.n_output_tokens])}function nt(e){let t=e.judge_result;return ve(t?.cost_usd,e.judge_spend_source,[t?.n_input_tokens,t?.n_cache_tokens,t?.n_output_tokens])}function rt(e,t){return typeof e!="number"||!Number.isFinite(e)?{lane:"unmeasured"}:typeof t=="number"&&t>0?{lane:"floor",usd:e}:{lane:"measured",usd:e}}function st(e){let t=H(e);if(t.lane!=="unmeasured")return t;let n=e.usage;return n&&n.provisional&&typeof n.spent_usd=="number"?{lane:"floor",usd:n.spent_usd}:t}function re(e){let t={};for(let[n,r]of Object.entries(e)){let a=n.replace(/^\/+/,""),o=a.split("/");o.length>1&&o[0]==="root"?o.shift():o.length>2&&o[0]==="home"&&o.splice(0,2),o[0].length>1&&o[0].startsWith(".")&&(o[0]=o[0].slice(1));let d=o.join("/");d in t?t[a]=r:t[d]=r;}return t}function U(e){return JSON.stringify(e,null,2)+`
|
|
418
|
+
`}function Re(e,t,n){return {trial_id:e.id,job_id:e.job_id,user_id:n,provider:e.sandbox_provider,gateway:{cost_usd:e.agent_result?.cost_usd??null,n_input_tokens:e.agent_result?.n_input_tokens??null,n_cache_tokens:e.agent_result?.n_cache_tokens??null,n_output_tokens:e.agent_result?.n_output_tokens??null,spend_source:e.spend_source,max_trial_spend_usd:e.max_trial_spend_usd,judge:e.judge_result?{cost_usd:e.judge_result.cost_usd,n_input_tokens:e.judge_result.n_input_tokens,n_cache_tokens:e.judge_result.n_cache_tokens,n_output_tokens:e.judge_result.n_output_tokens,spend_source:e.judge_spend_source??null}:null},regrade_lineage:{is_regrade:t?.is_regrade??false,source_jobs:t?.source_jobs??[],n_retries:e.n_retries,retries:e.retries}}}function at(e,t){return {job_id:e.id,user_id:t,provider:e.sandbox_provider,gateway:{cost_usd:e.stats.cost_usd??null,judge_cost_usd:e.stats.judge_cost_usd??null,n_unmeasured_trials:e.stats.n_unmeasured_trials??null,n_unmeasured_judge_trials:e.stats.n_unmeasured_judge_trials??null,n_input_tokens:e.stats.n_input_tokens??null,n_cache_tokens:e.stats.n_cache_tokens??null,n_output_tokens:e.stats.n_output_tokens??null,max_trial_spend_usd:e.max_trial_spend_usd,worst_case_spend_usd:e.worst_case_spend_usd},regrade_lineage:{is_regrade:e.is_regrade,source_jobs:e.source_jobs}}}function it(e){let t=e.agent_result;return t==null?t??null:H(e).lane==="measured"?t:{...t,cost_usd:null}}function ot(e){let{trial:t}=e,n={};if(n["config.json"]=U({trial_name:t.id,task:{name:t.task_name,source:t.source},agent:{name:t.agent_info.name,version:t.agent_info.version,model_name:t.agent_info.model_info.name,reasoning_effort:t.agent_info.reasoning_effort}}),n["result.json"]=U({trial_name:t.id,task_name:t.task_name,status:t.status,reward:t.reward,verifier_result:t.verifier_result,exception_info:t.exception_info,agent_result:it(t),started_at:t.started_at,finished_at:t.finished_at,environment_setup:t.environment_setup,agent_setup:t.agent_setup,agent_execution:t.agent_execution,verifier:t.verifier}),e.atif!==null&&(n["agent/trajectory.json"]=e.atif),e.stdout!==null&&(n["agent/stdout.log"]=e.stdout),e.stderr!==null&&(n["agent/stderr.log"]=e.stderr),e.events.length>0&&(n["agent/trace-parsed.jsonl"]=e.events.map(r=>JSON.stringify(r)).join(`
|
|
419
|
+
`)+`
|
|
420
|
+
`),e.home!==null){let r=re(e.home);for(let a of Object.keys(r))n[`agent/sessions/${a}`]=r[a];}return e.verifierLog!==null&&(n["verifier/test-stdout.txt"]=e.verifierLog),t.verifier_result?.rewards&&(n["verifier/reward.json"]=U(t.verifier_result.rewards)),t.exception_info&&(n["exception.txt"]=`${t.exception_info.exception_type}: ${t.exception_info.exception_message}
|
|
421
|
+
`),n["evolve.json"]=U(Re(t,e.job,e.userId)),n}function Ae(e,t,n){return {analysis_id:e.id,analyzed_trial_id:t.analyzed_trial_id,job_id:t.job_id,task_name:t.task_name,user_id:n,provider:t.sandbox_provider,sandbox_id:t.sandbox_id,status:e.status,model_name:e.model_name,gateway:{cost_usd:e.estimated_cost_usd,n_input_tokens:e.usage?.input_tokens??null,n_cache_tokens:e.usage?.cached_input_tokens??null,n_output_tokens:e.usage?.output_tokens??null}}}function lt(e){let t={};if(t["analysis.json"]=U(e.analysis),e.stdout!==null&&(t["agent/stdout.log"]=e.stdout),e.stderr!==null&&(t["agent/stderr.log"]=e.stderr),e.transcript.events.length>0&&(t["agent/trace-parsed.jsonl"]=e.transcript.events.map(n=>JSON.stringify(n)).join(`
|
|
422
|
+
`)+`
|
|
423
|
+
`),e.home!==null){let n=re(e.home);for(let r of Object.keys(n))t[`agent/sessions/${r}`]=n[r];}return t["evolve.json"]=U(Ae(e.analysis,e.transcript,e.userId)),t}var R=class extends Error{status;code;param;details;retryAfterSec;requestId;constructor(t,n,r,a){super(r),this.name="EvolveApiError",this.status=t,this.code=n,a?.param!==void 0&&(this.param=a.param),a?.details!==void 0&&(this.details=a.details),a?.retryAfterSec!==void 0&&(this.retryAfterSec=a.retryAfterSec),a?.requestId!==void 0&&(this.requestId=a.requestId);}isKnownCode(){return ne(this.code)}};function xe(e,t){try{let o=JSON.parse(e)?.error?.retryAfterSec;if(typeof o=="number"&&Number.isFinite(o))return o}catch{}let n=t.headers?.get?.("retry-after");if(typeof n!="string"||n.trim()==="")return;let r=Number(n);return Number.isFinite(r)?r:void 0}async function Q(e){let t=await e.text().catch(()=>""),n=e.headers?.get?.("x-request-id")??void 0,r=xe(t,e);try{let a=JSON.parse(t);if(a?.error&&typeof a.error=="object"){let o=typeof a.error.code=="string"?a.error.code:"unknown_error",d=typeof a.error.message=="string"?a.error.message:e.statusText;throw new R(e.status,o,d,{param:typeof a.error.param=="string"?a.error.param:void 0,details:a.error.details&&typeof a.error.details=="object"?a.error.details:void 0,retryAfterSec:r,requestId:typeof a.error.requestId=="string"?a.error.requestId:n})}if(typeof a?.error=="string")throw new R(e.status,"unknown_error",a.error,{retryAfterSec:r,requestId:n})}catch(a){if(a instanceof R)throw a}throw new R(e.status,"unknown_error",t||e.statusText,{retryAfterSec:r,requestId:n})}var ie=class extends Error{dataset;constructor(t){super(`Dataset "${t}" has no active version`),this.name="NoActiveVersionError",this.dataset=t;}},Y=class extends Error{name="ImportSettleError";code;importId;dataset;version;state;constructor(t,n,r){super(n),this.code=t,this.importId=r.importId,this.dataset=r.dataset,this.version=r.version,this.state=r.state;}},bt=1e3,yt=3e4,ht=new Set(["COMPLETED","CANCELLED","FAILED"]),kt=new Set(["job.completed","job.cancelled","job.failed"]),oe=2e3,vt=30*6e4;function O(e,t){let n=t?.apiKey||process.env[Z];if(!n)throw new Error(`${e}() requires an API key. Set ${Z} or pass { apiKey } in config.`);let r=(t?.baseUrl||process.env.EVOLVE_DASHBOARD_URL||L).replace(/\/$/,"");return {apiKey:n,baseUrl:r}}async function g(e,t,n){let r=await fetch(`${e.baseUrl}${t}`,{...n,headers:{Authorization:`Bearer ${e.apiKey}`,...n?.headers}});return r.ok||await Q(r),r}function se(e){let t=e.indexOf("@");if(t===-1)return {name:e.trim()};let n=e.slice(0,t).trim(),r=e.slice(t+1).trim();if(!n||!r)throw new Error(`Invalid dataset ref "${e}": expected "name" or "name@version"`);return {name:n,version:r}}function de(e){return {name:e.name,version:e.version}}function Ee(e){let t=e.kwargs,n=Array.isArray(e.skills)?e.skills.filter(o=>typeof o=="string"):[],r=Array.isArray(e.skill_locks)?e.skill_locks:null,a=r?r.flatMap(o=>{if(!o||typeof o!="object")return [];let d=o;return typeof d.name!="string"||typeof d.digest!="string"?[]:[{name:d.name,source:typeof d.source=="string"?d.source:"",digest:d.digest,git_url:typeof d.git_url=="string"?d.git_url:null,git_commit_id:typeof d.git_commit_id=="string"?d.git_commit_id:null}]}):null;return {name:e.name,model_name:e.model_name,version:e.version??null,reasoning_effort:e.reasoning_effort??null,kwargs:t&&typeof t=="object"&&!Array.isArray(t)?t:null,preset:typeof e.preset=="string"?e.preset:null,skills:n,skill_locks:a}}function Rt(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;if(typeof t.name!="string")return null;let n=Array.isArray(t.authors)?t.authors.flatMap(r=>{if(!r||typeof r!="object"||Array.isArray(r))return [];let a=r;return typeof a.name!="string"?[]:[{name:a.name,email:typeof a.email=="string"?a.email:null}]}):[];return {name:t.name,version:typeof t.version=="string"?t.version:null,description:typeof t.description=="string"?t.description:"",authors:n,keywords:Array.isArray(t.keywords)?t.keywords.filter(r=>typeof r=="string"):[],task_count:typeof t.task_count=="number"?t.task_count:null}}function At(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;return typeof t.ref!="string"||typeof t.commit!="string"?null:{git_url:typeof t.git_url=="string"?t.git_url:null,ref:t.ref,commit:t.commit,path:typeof t.path=="string"?t.path:null}}function N(e){return {version:e.version,state:e.state,created_at:e.created_at,task_count:e.task_count??0,n_failed_tasks:typeof e.n_failed_tasks=="number"?e.n_failed_tasks:0,manifest:Rt(e.manifest),source:At(e.source)}}function we(e){return {code:e.code??"",step:e.step??"",message:e.message??"",excerpt:e.excerpt??null}}function Tt(e){return Array.isArray(e)?e.filter(t=>t&&typeof t=="object").map(t=>({task_name:t.task_name??"",failure:we(t.failure??{})})):[]}function St(e){return {task_name:e.task_name,agent_timeout_sec:e.agent_timeout_sec,verifier_timeout_sec:e.verifier_timeout_sec,gpus:typeof e.gpus=="number"&&e.gpus>0?e.gpus:0,gpu_types:Array.isArray(e.gpu_types)&&e.gpu_types.length>0?e.gpu_types.map(String):null,providers:e.providers}}function xt(e){return {action:e.action,type:e.type,job_id:e.job_id}}function Et(e){let t=e&&typeof e=="object"?e:{};return {max_retries:typeof t.max_retries=="number"?t.max_retries:0,include_exceptions:Array.isArray(t.include_exceptions)?t.include_exceptions:null,exclude_exceptions:Array.isArray(t.exclude_exceptions)?t.exclude_exceptions:[],wait_multiplier:typeof t.wait_multiplier=="number"?t.wait_multiplier:1,min_wait_sec:typeof t.min_wait_sec=="number"?t.min_wait_sec:1,max_wait_sec:typeof t.max_wait_sec=="number"?t.max_wait_sec:60}}function wt(e){return {attempt_number:e.attempt_number,exception_info:e.exception_info??{exception_type:"InfrastructureError",exception_message:""},cost_usd:e.cost_usd??null,started_at:e.started_at??null,settled_at:e.settled_at??null}}function G(e){return typeof e=="number"?e:null}function Ct(e){return Array.isArray(e)?e.filter(t=>t&&typeof t=="object").map(t=>{let n=typeof t.n_tasks_ran=="number"?t.n_tasks_ran:0;return {dataset:de(t.dataset??{}),n_tasks_ran:n,n_tasks_selected:typeof t.n_tasks_selected=="number"?t.n_tasks_selected:n,n_tasks_failed_to_build:typeof t.n_tasks_failed_to_build=="number"?t.n_tasks_failed_to_build:0,failed_task_names:Array.isArray(t.failed_task_names)?t.failed_task_names.map(String):[],note:t.note??""}}):[]}function Pt(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;if(typeof t.uploaded_at!="string")return null;let n=t.reported_totals,r=o=>typeof o=="number"&&Number.isFinite(o)?o:null,a=n&&typeof n=="object"&&!Array.isArray(n)&&Number.isInteger(n.n_trials_reporting)?{cost_usd:r(n.cost_usd),n_input_tokens:r(n.n_input_tokens),n_cache_tokens:r(n.n_cache_tokens),n_output_tokens:r(n.n_output_tokens),n_trials_reporting:n.n_trials_reporting}:null;return {original_job_id:typeof t.original_job_id=="string"?t.original_job_id:null,original_job_name:typeof t.original_job_name=="string"?t.original_job_name:null,uploaded_at:t.uploaded_at,reported_totals:a}}function k(e){let t=e.trials??{};return {id:e.id,job_name:e.job_name,status:e.status,datasets:(e.datasets??[]).map(de),agents:(e.agents??[]).map(Ee),n_attempts:e.n_attempts,n_concurrent_trials:e.n_concurrent_trials,max_trial_spend_usd:e.max_trial_spend_usd,worst_case_spend_usd:e.worst_case_spend_usd,retry:Et(e.retry),analyze:e.analyze&&typeof e.analyze=="object"&&!Array.isArray(e.analyze)?e.analyze:null,timeout_multiplier:typeof e.timeout_multiplier=="number"?e.timeout_multiplier:1,agent_timeout_multiplier:G(e.agent_timeout_multiplier),verifier_timeout_multiplier:G(e.verifier_timeout_multiplier),agent_setup_timeout_multiplier:G(e.agent_setup_timeout_multiplier),environment_build_timeout_multiplier:G(e.environment_build_timeout_multiplier),sandbox_provider:e.sandbox_provider??null,counts:e.counts,build_exclusions:Ct(e.build_exclusions),n_total_trials:e.n_total_trials??0,trials:{total:t.total??0,byStatus:t.byStatus??{}},stats:e.stats??{},failure:e.failure??null,source_jobs:(e.source_jobs??[]).map(xt),is_regrade:e.is_regrade===true,upload:Pt(e.upload),idempotent_replay:e.idempotent_replay===true,started_at:e.started_at,updated_at:e.updated_at,finished_at:e.finished_at??null}}function v(e,t){let n=e??{};return {items:Array.isArray(n.items)?n.items.map(t):[],nextCursor:n.nextCursor??null,hasMore:n.hasMore===true}}function A(e,t){let n=new URLSearchParams;e?.limit!==void 0&&n.set("limit",String(e.limit)),e?.cursor&&n.set("cursor",e.cursor);for(let[a,o]of Object.entries(t??{}))o!==void 0&&n.set(a,o);let r=n.toString();return r?`?${r}`:""}function w(e){if(!e||typeof e!="object")return null;let t=e;return {started_at:t.started_at??null,finished_at:t.finished_at??null}}function Dt(e){let t=e.model_info??{};return {name:e.name,version:e.version??null,model_info:{name:t.name,provider:t.provider??null},reasoning_effort:e.reasoning_effort??null}}function ce(e){return !e||typeof e!="object"||Array.isArray(e)?null:{...e,usage:V(e.usage)}}function It(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let{from:t,to:n,reason:r}=e;return typeof t!="string"||typeof n!="string"||typeof r!="string"?null:{from:t,to:n,reason:r}}function le(e){return {id:e.id,job_id:e.job_id,task_name:e.task_name,source:e.source,agent_info:Dt(e.agent_info||{}),attempt:e.attempt,status:e.status,reward:e.reward??null,verifier_result:e.verifier_result??null,exception_info:e.exception_info??null,agent_result:e.agent_result??null,judge_result:e.judge_result??null,analysis:ce(e.analysis),environment_setup:w(e.environment_setup),agent_setup:w(e.agent_setup),agent_execution:w(e.agent_execution),verifier:w(e.verifier),queue_wait:w(e.queue_wait),harness_bundle:w(e.harness_bundle),image_prepare:w(e.image_prepare),shared_verify_setup:w(e.shared_verify_setup),harness_bundle_cache_hit:typeof e.harness_bundle_cache_hit=="boolean"?e.harness_bundle_cache_hit:null,step_results:e.step_results??null,spend_source:e.spend_source??null,judge_spend_source:e.judge_spend_source??null,live_spent_usd:e.live_spent_usd??null,live_spend_at:e.live_spend_at??null,usage:V(e.usage),max_trial_spend_usd:e.max_trial_spend_usd??null,sandbox_provider:e.sandbox_provider??null,sandbox_provider_degrade:It(e.sandbox_provider_degrade),gpu_cost:e.gpu_cost&&typeof e.gpu_cost=="object"&&!Array.isArray(e.gpu_cost)?e.gpu_cost:null,sandbox_id:e.sandbox_id??null,verifier_sandbox_id:e.verifier_sandbox_id??null,verifier_environment_mode:e.verifier_environment_mode??null,attempt_phase:e.attempt_phase??null,n_retries:e.n_retries??0,retries:Array.isArray(e.retries)?e.retries.map(wt):[],session_ref:e.session_ref??null,upload:Ot(e.upload),started_at:e.started_at??null,finished_at:e.finished_at??null}}function Ot(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;if(typeof t.original_trial_name!="string"||typeof t.original_task_name!="string")return null;let n=t.reported_agent_result,r=a=>typeof a=="number"&&Number.isFinite(a)?a:null;return {original_trial_id:typeof t.original_trial_id=="string"?t.original_trial_id:null,original_trial_name:t.original_trial_name,original_task_name:t.original_task_name,reported_agent_result:n&&typeof n=="object"&&!Array.isArray(n)?{n_input_tokens:r(n.n_input_tokens),n_cache_tokens:r(n.n_cache_tokens),n_output_tokens:r(n.n_output_tokens),cost_usd:r(n.cost_usd)}:null}}function K(e){return {name:e.name,source:e.source,run_command:e.run_command,env:e.env??{},created_at:e.created_at,updated_at:e.updated_at}}function z(e){let t={id:e.id,status:e.status,name:e.name,version:e.version,failure:e.failure??null,warnings:e.warnings??[]};return typeof e.task_count=="number"&&(t.task_count=e.task_count),typeof e.created_at=="string"&&(t.created_at=e.created_at),typeof e.updated_at=="string"&&(t.updated_at=e.updated_at),t}function Ce(e){let t=e??{};return {scored:t.scored??0,total:t.total??0}}function Lt(e){return {id:e.id,datasets:(e.datasets??[]).map(de),status:e.status,mean_reward:e.mean_reward??null,coverage:Ce(e.coverage),cost_usd:e.cost_usd??0,agents:(e.agents||[]).map(Ee),started_at:e.started_at}}function jt(e){return {job_id:e.job_id,status:e.status,mean_reward:e.mean_reward??null,coverage:Ce(e.coverage)}}function Jt(e){return {task_name:e.task_name,disagreement:e.disagreement===true,cells:(e.cells||[]).map(jt)}}function Pe(e){return {seq:e.seq,type:e.type,data:e.data??{}}}function Ut(e){return {trial_id:e.trial_id,task_name:e.task_name??null,match_count:e.match_count,events:(e.events||[]).map(Pe)}}function Nt(e){return e?e.suffix!==void 0?`bytes=-${e.suffix}`:e.start===void 0?null:`bytes=${e.start}-${e.end??""}`:null}function M(e){if(e?.aborted)throw e.reason instanceof Error?e.reason:new Error("Watch aborted")}function Te(e,t){return t?.aborted?true:e?.name==="AbortError"}function x(e,t){return new Promise((n,r)=>{let a=setTimeout(()=>{t?.removeEventListener("abort",o),n();},e),o=()=>{clearTimeout(a),r(t?.reason instanceof Error?t.reason:new Error("Watch aborted"));};t?.addEventListener("abort",o,{once:true});})}function Mt(e){let t="",n=false;return {push(r){n&&(r="\r"+r,n=false),r.endsWith("\r")&&(r=r.slice(0,-1),n=true),t+=r.replace(/\r\n|\r/g,`
|
|
424
|
+
`);let a;for(;(a=t.indexOf(`
|
|
425
|
+
|
|
426
|
+
`))!==-1;){let o=t.slice(0,a);t=t.slice(a+2);let d,l,u=[];for(let s of o.split(`
|
|
427
|
+
`)){if(!s||s.startsWith(":"))continue;let i=s.indexOf(":"),c=i===-1?s:s.slice(0,i),_=i===-1?"":s.slice(i+1);_.startsWith(" ")&&(_=_.slice(1)),c==="id"?d=_:c==="event"?l=_:c==="data"&&u.push(_);}(d!==void 0||l!==void 0||u.length>0)&&e({id:d,event:l,data:u.join(`
|
|
428
|
+
`)});}}}}function I(e,t){let n,r=()=>n??=e({limit:t?.limit,cursor:t?.cursor});return {then(a,o){return r().then(a,o)},catch(a){return r().catch(a)},finally(a){return r().finally(a)},async*[Symbol.asyncIterator](){let a=t?.cursor;for(;;){let o=await e({limit:t?.limit,cursor:a});for(let d of o.items)yield d;if(!o.nextCursor)return;a=o.nextCursor;}}}}function ue(e){let t=new FormData;for(let[n,r]of Object.entries(e))r!==void 0&&t.set(n,r);return t}async function De(e,t,n){let{postMultipartFile:r}=await import('./upload-HB55JKIS.js'),a=await r({url:`${e.baseUrl}${t}`,method:n.method??"POST",headers:{Authorization:`Bearer ${e.apiKey}`},fields:n.fields,file:n.file});return a.ok||await Q(a),a}async function B(e,t,n){let{tarGzipDirectoryToFile:r}=await import('./tar-SO35VKIU.js'),{mkdtemp:a,rm:o}=await import('fs/promises'),{tmpdir:d}=await import('os'),{join:l}=await import('path'),u=await a(l(d(),"evolve-upload-"));try{let s=l(u,n.filename);return await r(n.directory,s),await De(e,t,{method:n.method,fields:n.fields,file:{path:s,filename:n.filename}})}finally{await o(u,{recursive:true,force:true});}}function $t(e){let t,n=()=>(t||(t=(async()=>{let r=await e.next();for(;!r.done;)r=await e.next();return r.value})()),t);return {then(r,a){return n().then(r,a)},catch(r){return n().catch(r)},finally(r){return n().finally(r)},[Symbol.asyncIterator](){return e}}}var Ie="x-package-sha256",W=class extends Error{constructor(n,r){super(`downloaded bytes do not match the digest the server stated (expected ${n}, got ${r})`);this.expected=n;this.actual=r;}name="EvolveDigestMismatchError"},X=class extends Error{constructor(n,r){super(`download ended early: the server declared ${n} bytes and ${r} arrived`);this.expectedBytes=n;this.receivedBytes=r;}name="EvolveIncompleteDownloadError"};function Oe(e,t){let n=e.headers.get("Content-Length");if(n===null)return;let r=Number(n);if(Number.isFinite(r)&&t!==r)throw new X(r,t)}async function Le(e,t){let n=e.headers.get(Ie);if(!n)return;let{createHash:r}=await import('crypto'),a=r("sha256").update(t).digest("hex");if(a!==n)throw new W(n,a)}function Ft(e,t){let r=(e.headers.get("Content-Disposition")||"").match(/filename="([^"]+)"/);if(!r)return t;let a=basename(r[1]);return a===""||a==="."||a===".."||/[/\\]/.test(a)||/[\u0000-\u001f]/.test(a)?t:a}async function je(e,t,n){if(!e.body)throw new Error("Download response has no body");await mkdir(t,{recursive:true});let r=join(t,Ft(e,n)),{createHash:a,randomBytes:o}=await import('crypto'),d=`${r}.${o(8).toString("hex")}.part`,l=a("sha256"),u=0,s=Readable.fromWeb(e.body);s.on("data",i=>{l.update(i),u+=i.length;});try{await pipeline(s,createWriteStream(d));let i=e.headers.get("Content-Length");if(i!==null&&u!==Number(i))throw new X(Number(i),u);let c=e.headers.get(Ie),_=l.digest("hex");if(c&&_!==c)throw new W(c,_);await rename(d,r);}catch(i){throw await rm(d,{force:true}).catch(()=>{}),i}return r}function Bt(e){let t=O("datasets",e);async function n(s){let i=await g(t,`/api/datasets/imports/${encodeURIComponent(s)}`);return z(await i.json())}function r(s){if(!s||typeof s!="object")return null;let i=s;return {git_url:i.git_url??null,ref:i.ref,current_commit:i.current_commit,path:i.path??null,latest_commit:i.latest_commit??null,acked_commit:i.acked_commit??null,moved:i.moved===true,behind_by:typeof i.behind_by=="number"?i.behind_by:null,checked_at:i.checked_at??null,error:i.error??null,auto_import:i.auto_import===true}}function a(s){return {name:s.name,title:s.title??null,description:s.description??null,active_version:s.active_version?N(s.active_version):null,latest_version:s.latest_version?N(s.latest_version):null,versions:(s.versions||[]).map(N),selected_version:s.selected_version?N(s.selected_version):null,tasks:v(s.tasks,St),failed_tasks:Tt(s.failed_tasks),upstream:r(s.upstream),created_at:s.created_at,updated_at:s.updated_at}}async function o(s,i){let c=se(s),_=A(i,{version:c.version}),p=await g(t,`/api/datasets/${encodeURIComponent(c.name)}${_}`);return a(await p.json())}async function d(s,i){let c=i?.pollIntervalMs??oe,_=i?.settleTimeoutMs??vt,p=Date.now()+_,m=`${s.name}@${s.version}`,C=null,f=null,h=()=>f?.state==="FAILED"?new Y("settle_timeout",`Import ${s.id}'s dataset "${s.name}" version "${s.version}" settled FAILED, but the final import read kept answering rate-limited/unavailable past the ${_}ms settle budget. Read the failure with datasets().getImport("${s.id}").`,{importId:s.id,dataset:s.name,version:s.version,state:f.state}):new Y("settle_timeout",`Import ${s.id} completed, but dataset "${s.name}" version "${s.version}" did not settle within ${_}ms: last observed state ${f?.state??"never observed"}. Keep following with datasets().get("${m}").`,{importId:s.id,dataset:s.name,version:s.version,state:f?.state??null}),$=async E=>{for(;;){M(i?.signal);try{return await E()}catch(b){if(!(b instanceof R)||b.status!==429&&b.status!==503)throw b;let F=p-Date.now();if(F<=0)throw h();await x(Math.min(Math.max((b.retryAfterSec??0)*1e3,c),F),i?.signal);}}};for(;;){M(i?.signal);let E=await $(()=>o(m,{limit:1})),b=E.selected_version;if(b){if(f=b,b.state!==C&&(C=b.state,i?.onVersion?.(b,E)),b.state==="FAILED")return $(()=>n(s.id));if(b.state==="READY"||b.state==="ARCHIVED")return s}if(Date.now()>=p)throw h();await x(c,i?.signal);}}function l(s){return {name:s.name,title:s.title??null,description:s.description??null,active_version:s.active_version?N(s.active_version):null,latest_version:s.latest_version?N(s.latest_version):null,upstream:r(s.upstream)}}async function u(s){let i=await g(t,`/api/datasets${A(s,{search:s?.search})}`);return v(await i.json(),l)}return {list(s){return I(i=>u({...i,search:s?.search}),s)},get:o,async getActive(s,i){let c=await o(s,i);if(c.active_version===null)throw new ie(s);return {name:c.name,title:c.title,description:c.description,active_version:c.active_version,version:c.active_version.version,tasks:c.tasks??{items:[],nextCursor:null,hasMore:false},versions:c.versions??[],created_at:c.created_at,updated_at:c.updated_at}},async getTaskBuild(s,i){let c=se(s);if(c.version===void 0)throw new Error(`datasets().getTaskBuild() needs "name@version" \u2014 a task's build outcome belongs to one immutable version (got "${s}")`);let p=await(await g(t,`/api/datasets/${encodeURIComponent(c.name)}/versions/${encodeURIComponent(c.version)}/tasks/${encodeURIComponent(i)}/build`)).json();return {task_name:p.task_name??i,state:p.state,failure:p.failure&&typeof p.failure=="object"?we(p.failure):null,build_log_ref:p.build_log_ref??null}},async publish(s){let i=s.source;if(i?.directory){if(s.name===void 0||s.version===void 0){let{existsSync:_}=await import('fs'),{join:p}=await import('path');if(!(_(p(i.directory,"dataset.toml"))||_(p(i.directory,"tasks","dataset.toml"))))throw new Error(`datasets().publish() needs ${s.name===void 0?"a name":"a version"} \u2014 pass it explicitly, or add a dataset.toml manifest to the corpus directory (the server then derives name and version from it)`)}let c=await B(t,"/api/datasets/publish",{fields:{name:s.name,version:s.version},directory:i.directory,filename:"corpus.tar.gz"});return z(await c.json())}if(i&&"git_url"in i&&i.git_url){if(s.name===void 0||s.version===void 0)throw new Error("datasets().publish() requires name and version for a git source \u2014 a dataset.toml manifest can only supply them for a directory source, because a git repository is cloned server-side after the publish is accepted");let c=await g(t,"/api/datasets/publish",{method:"POST",body:ue({name:s.name,version:s.version,git_url:i.git_url,git_ref:i.git_ref,...i.git_path!==void 0?{git_path:i.git_path}:{}})});return z(await c.json())}throw new Error("datasets().publish() requires either a git source ({ source: { git_url, git_ref } }) or a local corpus directory ({ source: { directory } }), plus name and version (both optional for a directory whose corpus carries a dataset.toml manifest)")},getImport:n,async watchImport(s,i){let c=i?.pollIntervalMs??oe,_=null;for(;;){M(i?.signal);let p;try{p=await n(s);}catch(m){if(m instanceof R&&(m.status===429||m.status===503)){await x(Math.max((m.retryAfterSec??0)*1e3,c),i?.signal);continue}throw m}if(p.status!==_&&(_=p.status,i?.onStatus?.(p)),p.status==="FAILED")return p;if(p.status==="COMPLETED")return d(p,i);await x(c,i?.signal);}},download:(async(s,i)=>{let c=se(s),_=c.version?`?version=${encodeURIComponent(c.version)}`:"",p=await g(t,`/api/datasets/${encodeURIComponent(c.name)}/download${_}`);if(i?.stream){if(!p.body)throw new Error("Package response has no body");return p.body}if(i?.to)return je(p,i.to,`${c.name}-corpus.tar.gz`);let m=Buffer.from(await p.arrayBuffer());return Oe(p,m.length),await Le(p,m),m}),listImports(s){return I(async i=>{let c=new URLSearchParams;i.limit!==void 0&&c.set("limit",String(i.limit)),i.cursor!==void 0&&c.set("cursor",i.cursor),s?.status!==void 0&&c.set("status",s.status),s?.dataset!==void 0&&c.set("dataset",s.dataset);let _=c.toString()?`?${c}`:"",p=await g(t,`/api/datasets/imports${_}`);return v(await p.json(),z)},s)},async activate(s,i){let c=await g(t,`/api/datasets/${encodeURIComponent(s)}/versions/${encodeURIComponent(i)}/activate`,{method:"POST"});return a(await c.json())},async update(s,i){let c=await g(t,`/api/datasets/${encodeURIComponent(s)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});return l(await c.json())},async delete(s){await g(t,`/api/datasets/${encodeURIComponent(s)}`,{method:"DELETE"});}}}function qt(e){let t=O("agents",e);return {async create(n){let r=Se("agents().create()",n),a=r.directory?await B(t,"/api/agents",{fields:r.fields,directory:r.directory,filename:"source.tar.gz"}):await g(t,"/api/agents",{method:"POST",body:ue(r.fields)});return K(await a.json())},list(n){return I(async r=>{let a=await g(t,`/api/agents${A(r)}`);return v(await a.json(),K)},n)},async get(n){let r=await g(t,`/api/agents/${encodeURIComponent(n)}`);return K(await r.json())},async delete(n){await g(t,`/api/agents/${encodeURIComponent(n)}`,{method:"DELETE"});},async upsert(n,r){let a=Se("agents().upsert()",{...r,name:n}),o=a.directory?await B(t,`/api/agents/${encodeURIComponent(n)}`,{method:"PUT",fields:a.fields,directory:a.directory,filename:"source.tar.gz"}):await g(t,`/api/agents/${encodeURIComponent(n)}`,{method:"PUT",body:ue(a.fields)});return K(await o.json())}}}function Se(e,t){let n=typeof t.install_script=="string",r=typeof t.directory=="string";if(n&&r)throw new Error(`${e} takes EITHER an install script ({ install_script }) or a local directory ({ directory }), not both`);if(!n&&!r)throw new Error(`${e} requires either an install script ({ install_script }) or a local directory ({ directory }), plus run_command`);let a={name:t.name,run_command:t.run_command,...t.env!==void 0?{env:JSON.stringify(t.env)}:{},...n?{install_script:t.install_script}:{}};return r?{fields:a,directory:t.directory}:{fields:a}}function ae(e){return {id:e.id,name:e.name,digest:e.digest,size_bytes:e.size_bytes??0,description:e.description??null,ref:e.ref??`upload:${e.id}`,created_at:e.created_at}}function Vt(e){let t=O("skills",e);return {async upload(n){if(typeof n!="string"||!n.trim())throw new Error("skills().upload() requires a local skill directory path");let{basename:r,resolve:a}=await import('path'),o=r(a(n)),l=await(await B(t,"/api/skills",{fields:{name:o||void 0},directory:n,filename:"skill.tar.gz"})).json();return (Array.isArray(l.skills)?l.skills:[l]).map(ae)},list(n){return I(async r=>{let a=await g(t,`/api/skills${A(r)}`);return v(await a.json(),ae)},n)},async get(n){let a=await(await g(t,`/api/skills/${encodeURIComponent(n)}`)).json();return {...ae(a),skill_md:a.skill_md??null}},async delete(n){await g(t,`/api/skills/${encodeURIComponent(n)}`,{method:"DELETE"});}}}function Ht(e){let t=O("jobs",e);async function n(l){let u=await g(t,`/api/jobs/${encodeURIComponent(l)}`);return k(await u.json())}async function r(l){let u=await g(t,`/api/jobs${A(l,{search:l?.search})}`);return v(await u.json(),k)}function a(l){let u=l.trials??{};return {task_name:l.task_name,source:l.source,trials:{total:u.total??0,byStatus:u.byStatus??{}},mean_reward:l.mean_reward??null,cost_usd:l.cost_usd??null}}async function o(l,u){let s=A(u,{status:u?.status?.length?u.status.join(","):void 0,dataset:u?.dataset}),i=await g(t,`/api/jobs/${encodeURIComponent(l)}/trials${s}`);return v(await i.json(),le)}async function*d(l,u){let{onEvent:s,signal:i}=u??{},c=u?.reconnectDelayMs??bt,_=u?.maxReconnectDelayMs??yt,p=null,m=false,C=false,f=c;for(;!m;){M(i);let h;try{h=await fetch(`${t.baseUrl}/api/jobs/${encodeURIComponent(l)}/events`,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"text/event-stream",...p!==null?{"Last-Event-ID":String(p)}:{}},signal:i});}catch(y){if(Te(y,i))throw y;await x(f,i),f=Math.min(f*2,_);continue}if(!h.ok){if(h.status===429||h.status>=500){let y=await h.text().catch(()=>""),T=xe(y,h)??0,P=T>0?Math.max(T*1e3,f):f;await x(P,i),f=Math.min(f*2,_);continue}await Q(h);}if(!h.body)throw new Error("Event stream response has no body");let $=false,E=[],b=Mt(y=>{let T=Number(y.id),P={seq:Number.isInteger(T)?T:-1,type:y.event||"message",data:y.data?Yt(y.data):{}};Number.isInteger(T)&&(p=T),$=true,kt.has(P.type)&&(m=true),E.push(P);}),F=h.body.getReader(),Je=new TextDecoder;try{for(;!m;){let{done:y,value:T}=await F.read();if(y)break;b.push(Je.decode(T,{stream:!0}));for(let P of E)s?.(P),yield P;E.length=0;}}catch(y){if(Te(y,i))throw y}finally{await F.cancel().catch(()=>{});}if(m)break;M(i);let pe=await n(l);if(ht.has(pe.status)){if(C)return pe;C=true;continue}$&&(f=c),await x(f,i),f=Math.min(f*2,_);}return n(l)}return {async start(l,u){let s=await g(t,"/api/jobs",{method:"POST",headers:{"Content-Type":"application/json",...u?.idempotencyKey?{"Idempotency-Key":u.idempotencyKey}:{}},body:JSON.stringify(l)});return k(await s.json())},get:n,list(l){return I(u=>r({...u,search:l?.search}),l)},trials(l,u){return I(s=>o(l,{...s,status:u?.status,dataset:u?.dataset}),u)},tasks(l,u){return I(async s=>{let i=await g(t,`/api/jobs/${encodeURIComponent(l)}/tasks${A(s)}`);return v(await i.json(),a)},u)},watch(l,u){return $t(d(l,u))},async cancel(l){let u=await g(t,`/api/jobs/${encodeURIComponent(l)}/cancel`,{method:"POST"});return k(await u.json())},async compare(l){let u=l.map(encodeURIComponent).join(","),i=await(await g(t,`/api/jobs/compare?ids=${u}`)).json();return {jobs:(i.jobs||[]).map(Lt),taskMatrix:(i.taskMatrix||[]).map(Jt)}},async resume(l,u,s){let i=await g(t,`/api/jobs/${encodeURIComponent(l)}/resume`,{method:"POST",headers:{"Content-Type":"application/json",...s?.idempotencyKey?{"Idempotency-Key":s.idempotencyKey}:{}},body:JSON.stringify(u??{})});return k(await i.json())},async retry(l,u,s){let i=await g(t,`/api/jobs/${encodeURIComponent(l)}/retry`,{method:"POST",headers:{"Content-Type":"application/json",...s?.idempotencyKey?{"Idempotency-Key":s.idempotencyKey}:{}},body:JSON.stringify(u??{})});return k(await i.json())},async regrade(l,u){let s={};u?.statuses?.length&&(s.statuses=u.statuses),u?.task_name!==void 0&&(s.task_name=u.task_name);let i=await g(t,`/api/jobs/${encodeURIComponent(l)}/regrade`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});return k(await i.json())},async analyze(l,u){let s=await g(t,`/api/jobs/${encodeURIComponent(l)}/analyze`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u??{})});return k(await s.json())},async watchAnalysis(l,u){let s=u?.pollIntervalMs??oe,i=null;for(;;){M(u?.signal);let c;try{c=await n(l);}catch(p){if(p instanceof R&&(p.status===429||p.status===503)){await x(Math.max((p.retryAfterSec??0)*1e3,s),u?.signal);continue}throw p}let _=c.stats.analysis??null;if(_){let p=JSON.stringify([_.n_completed,_.n_failed,_.n_pending]);if(p!==i&&(i=p,u?.onStats?.(c)),_.n_pending===0)return c}await x(s,u?.signal);}},download:(async(l,u)=>{let s=await g(t,`/api/jobs/${encodeURIComponent(l)}/download`);if(u?.stream){if(!s.body)throw new Error("Download response has no body");return s.body}if(u?.to)return je(s,u.to,`job-${l}-results.tar.gz`);let i=Buffer.from(await s.arrayBuffer());return Oe(s,i.length),await Le(s,i),i}),async upload(l,u){if(typeof l!="string"||!l.trim())throw new Error("jobs().upload() requires a job directory (or .tar.gz archive) path");let{stat:s}=await import('fs/promises');if((await s(l).catch(()=>null))?.isFile()){let f=await De(t,"/api/jobs/upload",{fields:{dataset:u?.dataset},file:{path:l,filename:"job.tar.gz"}});return k(await f.json())}let{existsSync:c}=await import('fs'),{join:_,resolve:p}=await import('path'),m=p(l);for(let f of ["result.json","config.json"])if(!c(_(m,f)))throw new Error(`${m} does not contain ${f}`);let C=await B(t,"/api/jobs/upload",{fields:{dataset:u?.dataset},directory:m,filename:"job.tar.gz"});return k(await C.json())},async delete(l){let s=await(await g(t,`/api/jobs/${encodeURIComponent(l)}`,{method:"DELETE"})).json();return {job_id:s.job_id??l,trials_deleted:s.trials_deleted??0,analyses_deleted:s.analyses_deleted??0}},async grep(l,u,s){let i=await g(t,`/api/jobs/${encodeURIComponent(l)}/grep${A(s,{q:u,type:s?.type})}`);return v(await i.json(),Ut)}}}function Gt(e){let t=O("trials",e);async function n(a,o){let d=await g(t,`/api/trials/${encodeURIComponent(a)}/trace${A(o,{type:o?.type,grep:o?.grep,tail:o?.tail!==void 0?String(o.tail):void 0})}`);return v(await d.json(),Pe)}async function r(a,o){let l=await(await g(t,`/api/trials/${encodeURIComponent(a)}/trace?stream=${o}`)).json();return o==="agent-home"?l.files??null:l.log??null}return {async get(a){let o=await g(t,`/api/trials/${encodeURIComponent(a)}`);return le(await o.json())},trace:n,artifact:r,async*traceEvents(a,o){let d=o?.cursor;for(;;){let l=await n(a,{...o,cursor:d});for(let u of l.items)yield u;if(!l.nextCursor)return;d=l.nextCursor;}},async regrade(a){let o=await g(t,`/api/trials/${encodeURIComponent(a)}/regrade`,{method:"POST"});return k(await o.json())},async retry(a,o){let d=await g(t,`/api/trials/${encodeURIComponent(a)}/retry`,{method:"POST",...o?.idempotencyKey?{headers:{"Idempotency-Key":o.idempotencyKey}}:{}});return k(await d.json())},async stop(a){let d=await(await g(t,"/api/trials/stop",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({trial_ids:a})})).json();return {stopped:(d.stopped??[]).map(le),stopped_analyses:(d.stopped_analyses??[]).map(ce).filter(l=>l!==null),already_terminal:d.already_terminal??[],not_found:d.not_found??[]}},async files(a,o){let d=await g(t,`/api/trials/${encodeURIComponent(a)}/files${A(o)}`);return v(await d.json(),l=>({path:l.path,size_bytes:l.size_bytes}))},async file(a,o,d){let l=o.split("/").filter(Boolean).map(encodeURIComponent).join("/"),u=Nt(d),s=await g(t,`/api/trials/${encodeURIComponent(a)}/files/${l}`,u?{headers:{Range:u}}:void 0);return Buffer.from(await s.arrayBuffer())}}}function Kt(e){let t=e?.update;return typeof t?.sessionUpdate=="string"?t.sessionUpdate:"unknown"}function zt(e){let t=O("analyses",e),n=new Set;async function r(o){if(n.has(o))return;let d;try{d=await g(t,`/api/traces/trials/${encodeURIComponent(o)}/artifacts?what=analysis`);}catch(l){throw l instanceof R&&l.status===400?new Error(`"${o}" is not an analysis run (the artifacts door refuses it typed) \u2014 for a trial's artifacts use trials()`):l}await d.text().catch(()=>{}),n.add(o);}async function a(o,d){await r(o);let u=await(await g(t,`/api/traces/trials/${encodeURIComponent(o)}/artifacts?what=${d}`)).json();return d==="agent-home"?u.files??null:u.log??null}return {async get(o){let l=await(await g(t,`/api/traces/trials/${encodeURIComponent(o)}/artifacts?what=analysis`)).json(),u=ce(l.analysis);if(u===null)throw new Error(`The analysis feed served no readable verdict object for "${o}"`);return u},async transcript(o,d){let l=d?.since;if(l!==void 0&&(!Number.isInteger(l)||l<0))throw new Error(`transcript() since must be a non-negative integer, got ${l}`);let s=await(await g(t,`/api/traces/trials/${encodeURIComponent(o)}/events`+(l!==void 0?`?since=${l}`:""))).json(),i=s.session??{};if(i.kind!=="analysis"){let p=typeof i.kind=="string"?i.kind:"trial";throw new Error(`"${o}" is not an analysis run (the feed resolves it as a ${p}) \u2014 for a trial's trace use trials()`)}let c=l??0,_=Array.isArray(s.events)?s.events:[];return {id:typeof i.id=="string"?i.id:o,analyzed_trial_id:typeof i.analyzedTrialId=="string"?i.analyzedTrialId:null,job_id:typeof i.jobId=="string"?i.jobId:null,task_name:typeof i.tag=="string"?i.tag:null,model_name:typeof i.model=="string"?i.model:null,sandbox_provider:typeof i.provider=="string"?i.provider:null,sandbox_id:typeof i.sandboxId=="string"?i.sandboxId:null,is_ended:i.isEnded===true,total:typeof s.total=="number"?s.total:c+_.length,events:_.map((p,m)=>({seq:c+m,type:Kt(p),data:p&&typeof p=="object"&&!Array.isArray(p)?p:{}}))}},artifact:a}}function Yn(e){let t=O("auth",e);return {async status(){let r=await(await g(t,"/api/auth/status")).json(),a=r.key??{};return {user_id:r.user_id,email:r.email??null,key:{id:a.id,label:a.label??null,created_at:a.created_at,last_used_at:a.last_used_at??null}}}}}function Yt(e){try{let t=JSON.parse(e);return t&&typeof t=="object"?t:{value:t}}catch{return {raw:e}}}function Wn(e){let t,n,r,a,o,d;return {get datasets(){return t??=Bt(e)},get agents(){return n??=qt(e)},get jobs(){return r??=Ht(e)},get trials(){return a??=Gt(e)},get analyses(){return o??=zt(e)},get skills(){return d??=Vt(e)},meta(){return Wt(e)}}}async function Wt(e){let t=(e?.baseUrl||process.env.EVOLVE_DASHBOARD_URL||L).replace(/\/$/,""),n=await fetch(`${t}/api/meta`);return n.ok||await Q(n),await n.json()}export{et as $,hn as A,kn as B,be as C,S as D,ye as E,te as F,An as G,Tn as H,Sn as I,xn as J,En as K,wn as L,Cn as M,ze as N,Pn as O,Dn as P,In as Q,On as R,Ln as S,Ye as T,We as U,V,Xe as W,Qe as X,Ze as Y,ke as Z,ne as _,Ue as a,H as aa,Ne as b,nt as ba,Xt as c,rt as ca,ge as d,st as da,Qt as e,Re as ea,Zt as f,at as fa,en as g,ot as ga,Z as h,Ae as ha,tn as i,lt as ia,nn as j,R as ja,rn as k,ie as ka,sn as l,Y as la,an as m,W as ma,on as n,X as na,ln as o,Bt as oa,un as p,qt as pa,_e as q,Vt as qa,dn as r,Ht as ra,L as s,Gt as sa,pn as t,zt as ta,gn as u,Yn as ua,_n as v,Wn as va,mn as w,Wt as wa,fn as x,bn as y,yn as z};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import {randomUUID}from'crypto';import {createReadStream}from'fs';import {stat}from'fs/promises';import {request as request$1}from'http';import {request}from'https';var A=6e5,T=class extends Error{name="EvolveUploadTimeoutError";constructor(o,i){super(`upload to ${o} timed out: no socket activity for ${Math.round(i/1e3)}s`);}};function $(t,o){return new Promise((i,l)=>{t.write(o,f=>f?l(f):i());})}async function z(t){let o=`----evolve${randomUUID().replace(/-/g,"")}`,i=[];for(let[r,n]of Object.entries(t.fields))n!==void 0&&i.push(`--${o}\r
|
|
2
|
+
Content-Disposition: form-data; name="${r}"\r
|
|
3
|
+
\r
|
|
4
|
+
${n}\r
|
|
5
|
+
`);i.push(`--${o}\r
|
|
6
|
+
Content-Disposition: form-data; name="archive"; filename="${t.file.filename}"\r
|
|
7
|
+
Content-Type: application/gzip\r
|
|
8
|
+
\r
|
|
9
|
+
`);let l=Buffer.from(i.join(""),"utf8"),f=Buffer.from(`\r
|
|
10
|
+
--${o}--\r
|
|
11
|
+
`,"utf8"),{size:q}=await stat(t.file.path),v=new URL(t.url),s=(v.protocol==="https:"?request:request$1)(v,{method:t.method,headers:{...t.headers,"Content-Type":`multipart/form-data; boundary=${o}`,"Content-Length":String(l.length+q+f.length)}}),P=t.timeoutMs??A,a,h,M=new Promise((r,n)=>{h=n;});M.catch(()=>{});let g=r=>Promise.race([r,M]),c,m=()=>{c!==void 0&&clearTimeout(c),c=setTimeout(()=>{a=new T(t.url,P),s.destroy(a),h(a);},P),c.unref();};s.on("error",r=>h(a??r)),m();let y,R=new Promise((r,n)=>{s.on("response",u=>{y=u,m(),r(u);}),s.on("error",u=>{y===void 0&&n(u);});});R.catch(()=>{});let b=createReadStream(t.file.path);try{let r=(async()=>{await $(s,l),m();for await(let e of b)await $(s,e),m();await new Promise(e=>{s.end(f,e);});})();try{await g(r);}catch(e){if(b.destroy(),y===void 0)throw s.destroy(),a??e}let n=await g(R).catch(e=>{throw a??e}),u=(async()=>{let e=[];for await(let d of n)m(),e.push(d);return Buffer.concat(e)})(),B=await g(u).catch(e=>{throw a??e}),p=n.statusCode??0,w=new Headers;for(let[e,d]of Object.entries(n.headers))if(typeof d=="string")w.set(e,d);else if(Array.isArray(d))for(let U of d)w.append(e,U);let C=p!==204&&p!==205&&p!==304;return new Response(C?B:null,{status:p,statusText:n.statusMessage??"",headers:w})}finally{c!==void 0&&clearTimeout(c);}}export{A as a,T as b,z as c};
|