@evolvingmachines/sdk 0.0.52-project-sable.20260815.143c2cd → 0.0.52-project-sable.20260824.3dfecab

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.
@@ -0,0 +1,426 @@
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 Oe(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 Le(e=""){let t=process.env.EVOLVE_DASHBOARD_URL||O;if(!e)return t;let n=e.startsWith("/")?e:`/${e}`;return `${t.replace(/\/$/,"")}${n}`}var Ft=["e2b","daytona","modal"];function ue(e){return Le(`/api/managed/${e}`)}function Bt(){return `${ue("daytona")}/toolbox`}function qt(){return ue("e2b")}function Vt(e){return {"browser-use":{type:"http",url:Oe("/browser_use/mcp"),headers:{"x-litellm-api-key":`Bearer ${e}`}}}}var X="EVOLVE_API_KEY",Gt="E2B_API_KEY",Ht="DAYTONA_API_KEY",Kt="MODAL_TOKEN_ID",Yt="MODAL_TOKEN_SECRET",Wt="claude",zt=36e5,Xt=4,Qt=100,de="/home/user";function Zt(e,t){return t?t.replace(/\/+$/,"")||"/":e?e==="root"?"/root":`/home/${e}`:de}var O=process.env.EVOLVE_DASHBOARD_URL||"https://dashboard.evolvingmachines.ai",tn="x-litellm-customer-id",nn="x-litellm-tags",rn="run:",sn=".evolve-sdk/observability/sessions",an=["tag","provider","agent","model","sandboxId","sandbox_id","timestamp","event","events"],on=100,ln=5e3,un=3,dn=1e3;function Q(e){return e.delivery==="direct"}var ge=18181,S="/tmp/evolve-managed-secrets",_e=`${S}/proxy.py`,Z=`${S}/config.json`,C=`${S}/ca.crt`,B=`${S}/ca.key`,L=`${S}/ca-bundle.crt`,me=["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 gn(){return [...me]}var _n=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 Je(e){return (e||process.env.EVOLVE_DASHBOARD_URL||O).replace(/\/$/,"")}function Ue(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 Ne(e){return await e.text().catch(()=>"")}async function J(e,t,n={}){let r=await fetch(`${Je(e.dashboardUrl)}${t}`,{...n,headers:{Authorization:`Bearer ${Ue(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 Ne(r)}`);return await r.json()}function je(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 mn(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:je(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 Me(e){return Array.isArray(e)&&e.every(t=>typeof t=="string")}function ce(e){try{return new URL(e).protocol==="https:"}catch{return false}}function $e(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"&&ce(t.egressUrl)&&typeof t.channelUrl=="string"&&ce(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"||!Me(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 fn(e,t){let n=await J(e,"/api/managed-secrets/runtime-token",{method:"POST",body:JSON.stringify(t)});if(!$e(n))throw new Error("Invalid managed secret runtime token response");return n}async function bn(e,t){return (await J(e,"/api/managed-secrets/runtime-token",{method:"PATCH",body:JSON.stringify(t)})).ok}async function yn(e,t){return (await J(e,"/api/managed-secrets/runtime-token",{method:"DELETE",body:JSON.stringify(t)})).ok}var Fe=/^[A-Za-z0-9._-]{1,80}$/;function Be(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=pe(t.name,`managedSecrets[${n}].name`),a;if(t.label!==void 0){if(typeof t.label!="string"||!Fe.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:pe(t.as,`managedSecrets[${n}].as`);return {name:r,...a!==void 0?{label:a}:{},...o!==void 0?{as:o}:{}}})}function pe(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 qe(e){let t=new Set(["EVOLVE_API_KEY","EVOLVE_PROVIDER_RUNTIME_BINDING","GEMINI_DEFAULT_AUTH_TYPE",...me]),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 hn(e,t){if(!e)return;let n=Be(e),r=qe(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 Ve(e){return e.env.some(t=>!Q(t))}function kn(e){let t={};for(let a of e.env)Q(a)?t[a.envName]=a.value:t[a.envName]=a.placeholder;if(!Ve(e))return t;let n=`http://127.0.0.1:${ge}`;t.HTTPS_PROXY=n,t.https_proxy=n,t.NODE_EXTRA_CA_CERTS=C,t.SSL_CERT_FILE=L,t.REQUESTS_CA_BUNDLE=L,t.CURL_CA_BUNDLE=L,t.GIT_SSL_CAINFO=L;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 vn(e){let t=e.env.filter(r=>!Q(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:C,ca_key:B,port:ge,max_body_bytes:10*1024*1024},null,2)}function Rn(){return ["umask 077",`mkdir -p ${S}/certs`,`chmod 700 ${S} ${S}/certs`,`chmod 700 ${_e} 2>/dev/null || true`,`chmod 600 ${Z} 2>/dev/null || true`,`if [ ! -f ${B} ]; then openssl genrsa -out ${B} 2048 >/dev/null 2>&1; fi`,`if [ ! -f ${C} ]; then openssl req -x509 -new -nodes -key ${B} -sha256 -days 30 -subj "/CN=Evolve Managed Secrets" -addext "basicConstraints=critical,CA:TRUE" -addext "keyUsage=critical,keyCertSign,cRLSign" -out ${C} >/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" ${C} > ${L}; else cp ${C} ${L}; fi`,`if command -v update-ca-certificates >/dev/null 2>&1; then cp ${C} /usr/local/share/ca-certificates/evolve-managed-secrets.crt 2>/dev/null && update-ca-certificates >/dev/null 2>&1 || true; fi`].join(" && ")}function Sn(){return `umask 077 && exec python3 ${_e} ${Z}`}function Tn(){return `rm -f ${Z}`}var Ge=["QUEUED","RUNNING","SCORING","SCORED","SCORING_ERROR","INFRASTRUCTURE_ERROR","INDETERMINATE","CANCELLED"],He=["e2b","daytona","modal"];function ee(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 Ke(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 Ye=["trace-parsed","verifier","trace-stdout","trace-stderr","trace-atif","trajectory","agent-home"],fe=["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","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","import_not_found","import_too_large","invalid_archive","unpinned_git_ref","package_not_retained","package_corrupt","package_missing","internal_error"];function te(e){return typeof e=="string"&&fe.includes(e)}var We=["level","binary","none"];function ze(e,t,n){return e==="measured"&&t===0&&n.every(r=>(r??null)===null)}function be(e,t,n){return typeof e!="number"||!Number.isFinite(e)?{lane:"unmeasured"}:t==="measured"?ze(t,e,n)?{lane:"unmeasured"}:{lane:"measured",usd:e}:t==="measured_provisional"?{lane:"floor",usd:e}:{lane:"unmeasured"}}function q(e){let t=e.agent_result;return be(t?.cost_usd,e.spend_source,[t?.n_input_tokens,t?.n_cache_tokens,t?.n_output_tokens])}function Xe(e){let t=e.judge_result;return be(t?.cost_usd,e.judge_spend_source,[t?.n_input_tokens,t?.n_cache_tokens,t?.n_output_tokens])}function Qe(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 Ze(e){let t=q(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 ye(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 V(e){return JSON.stringify(e,null,2)+`
418
+ `}function he(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 et(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 tt(e){let t=e.agent_result;return t==null?t??null:q(e).lane==="measured"?t:{...t,cost_usd:null}}function nt(e){let{trial:t}=e,n={};if(n["config.json"]=V({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"]=V({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:tt(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=ye(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"]=V(t.verifier_result.rewards)),t.exception_info&&(n["exception.txt"]=`${t.exception_info.exception_type}: ${t.exception_info.exception_message}
421
+ `),n["evolve.json"]=V(he(t,e.job,e.userId)),n}var D=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 te(this.code)}};function Se(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 ie(e){let t=await e.text().catch(()=>""),n=e.headers?.get?.("x-request-id")??void 0,r=Se(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 D(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})}}catch(a){if(a instanceof D)throw a}throw new D(e.status,"unknown_error",t||e.statusText,{retryAfterSec:r,requestId:n})}var se=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;}},ct=1e3,pt=3e4,gt=new Set(["COMPLETED","CANCELLED","FAILED"]),_t=new Set(["job.completed","job.cancelled","job.failed"]),ke=2e3,mt=30*6e4;function N(e,t){let n=t?.apiKey||process.env[X];if(!n)throw new Error(`${e}() requires an API key. Set ${X} or pass { apiKey } in config.`);let r=(t?.baseUrl||process.env.EVOLVE_DASHBOARD_URL||O).replace(/\/$/,"");return {apiKey:n,baseUrl:r}}async function p(e,t,n){let r=await fetch(`${e.baseUrl}${t}`,{...n,headers:{Authorization:`Bearer ${e.apiKey}`,...n?.headers}});return r.ok||await ie(r),r}function ne(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 oe(e){return {name:e.name,version:e.version}}function Te(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 ft(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 bt(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 U(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:ft(e.manifest),source:bt(e.source)}}function Ee(e){return {code:e.code??"",step:e.step??"",message:e.message??"",excerpt:e.excerpt??null}}function yt(e){return Array.isArray(e)?e.filter(t=>t&&typeof t=="object").map(t=>({task_name:t.task_name??"",failure:Ee(t.failure??{})})):[]}function ht(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 kt(e){return {action:e.action,type:e.type,job_id:e.job_id}}function vt(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 Rt(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 St(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:oe(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 T(e){let t=e.trials??{};return {id:e.id,job_name:e.job_name,status:e.status,datasets:(e.datasets??[]).map(oe),agents:(e.agents??[]).map(Te),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:vt(e.retry),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,counts:e.counts,build_exclusions:St(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(kt),is_regrade:e.is_regrade===true,idempotent_replay:e.idempotent_replay===true,started_at:e.started_at,updated_at:e.updated_at,finished_at:e.finished_at??null}}function k(e,t){let n=e??{};return {items:Array.isArray(n.items)?n.items.map(t):[],nextCursor:n.nextCursor??null,hasMore:n.hasMore===true}}function v(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 A(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 Tt(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 Et(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 ae(e){return {id:e.id,job_id:e.job_id,task_name:e.task_name,source:e.source,agent_info:Tt(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,environment_setup:A(e.environment_setup),agent_setup:A(e.agent_setup),agent_execution:A(e.agent_execution),verifier:A(e.verifier),queue_wait:A(e.queue_wait),harness_bundle:A(e.harness_bundle),image_prepare:A(e.image_prepare),shared_verify_setup:A(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:ee(e.usage),max_trial_spend_usd:e.max_trial_spend_usd??null,sandbox_provider:e.sandbox_provider??null,sandbox_provider_degrade:Et(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(Rt):[],session_ref:e.session_ref??null,started_at:e.started_at??null,finished_at:e.finished_at??null}}function H(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 K(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 xe(e){let t=e??{};return {scored:t.scored??0,total:t.total??0}}function xt(e){return {id:e.id,datasets:(e.datasets??[]).map(oe),status:e.status,mean_reward:e.mean_reward??null,coverage:xe(e.coverage),cost_usd:e.cost_usd??0,agents:(e.agents||[]).map(Te),started_at:e.started_at}}function At(e){return {job_id:e.job_id,status:e.status,mean_reward:e.mean_reward??null,coverage:xe(e.coverage)}}function wt(e){return {task_name:e.task_name,disagreement:e.disagreement===true,cells:(e.cells||[]).map(At)}}function Ae(e){return {seq:e.seq,type:e.type,data:e.data??{}}}function Ct(e){return {trial_id:e.trial_id,task_name:e.task_name??null,match_count:e.match_count,events:(e.events||[]).map(Ae)}}function Pt(e){return e?e.suffix!==void 0?`bytes=-${e.suffix}`:e.start===void 0?null:`bytes=${e.start}-${e.end??""}`:null}function $(e){if(e?.aborted)throw e.reason instanceof Error?e.reason:new Error("Watch aborted")}function ve(e,t){return t?.aborted?true:e?.name==="AbortError"}function P(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 Dt(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,`
422
+ `);let a;for(;(a=t.indexOf(`
423
+
424
+ `))!==-1;){let o=t.slice(0,a);t=t.slice(a+2);let d,l,u=[];for(let s of o.split(`
425
+ `)){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(`
426
+ `)});}}}}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 F(e,t){let n=new FormData;for(let[r,a]of Object.entries(e))a!==void 0&&n.set(r,a);return t&&n.set("archive",new Blob([t.bytes],{type:"application/gzip"}),t.filename),n}function It(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 we="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"},z=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 Ce(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 z(r,t)}async function Pe(e,t){let n=e.headers.get(we);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 Ot(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 De(e,t,n){if(!e.body)throw new Error("Download response has no body");await mkdir(t,{recursive:true});let r=join(t,Ot(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 z(Number(i),u);let c=e.headers.get(we),_=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 Lt(e){let t=N("datasets",e);async function n(s){let i=await p(t,`/api/datasets/imports/${encodeURIComponent(s)}`);return K(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?U(s.active_version):null,latest_version:s.latest_version?U(s.latest_version):null,versions:(s.versions||[]).map(U),selected_version:s.selected_version?U(s.selected_version):null,tasks:k(s.tasks,ht),failed_tasks:yt(s.failed_tasks),upstream:r(s.upstream),created_at:s.created_at,updated_at:s.updated_at}}async function o(s,i){let c=ne(s),_=v(i,{version:c.version}),g=await p(t,`/api/datasets/${encodeURIComponent(c.name)}${_}`);return a(await g.json())}async function d(s,i){let c=i?.pollIntervalMs??ke,_=i?.settleTimeoutMs??mt,g=Date.now()+_,m=`${s.name}@${s.version}`,E=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}),j=async x=>{for(;;){$(i?.signal);try{return await x()}catch(b){if(!(b instanceof D)||b.status!==429&&b.status!==503)throw b;let M=g-Date.now();if(M<=0)throw h();await P(Math.min(Math.max((b.retryAfterSec??0)*1e3,c),M),i?.signal);}}};for(;;){$(i?.signal);let x=await j(()=>o(m,{limit:1})),b=x.selected_version;if(b){if(f=b,b.state!==E&&(E=b.state,i?.onVersion?.(b,x)),b.state==="FAILED")return j(()=>n(s.id));if(b.state==="READY"||b.state==="ARCHIVED")return s}if(Date.now()>=g)throw h();await P(c,i?.signal);}}function l(s){return {name:s.name,title:s.title??null,description:s.description??null,active_version:s.active_version?U(s.active_version):null,latest_version:s.latest_version?U(s.latest_version):null,upstream:r(s.upstream)}}async function u(s){let i=await p(t,`/api/datasets${v(s,{search:s?.search})}`);return k(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 se(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=ne(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 g=await(await p(t,`/api/datasets/${encodeURIComponent(c.name)}/versions/${encodeURIComponent(c.version)}/tasks/${encodeURIComponent(i)}/build`)).json();return {task_name:g.task_name??i,state:g.state,failure:g.failure&&typeof g.failure=="object"?Ee(g.failure):null,build_log_ref:g.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:m}=await import('fs'),{join:E}=await import('path');if(!(m(E(i.directory,"dataset.toml"))||m(E(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{tarGzipDirectory:c}=await import('./tar-KTM2224F.js'),_=await c(i.directory),g=await p(t,"/api/datasets/publish",{method:"POST",body:F({name:s.name,version:s.version},{bytes:_,filename:"corpus.tar.gz"})});return K(await g.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 p(t,"/api/datasets/publish",{method:"POST",body:F({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 K(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??ke,_=null;for(;;){$(i?.signal);let g;try{g=await n(s);}catch(m){if(m instanceof D&&(m.status===429||m.status===503)){await P(Math.max((m.retryAfterSec??0)*1e3,c),i?.signal);continue}throw m}if(g.status!==_&&(_=g.status,i?.onStatus?.(g)),g.status==="FAILED")return g;if(g.status==="COMPLETED")return d(g,i);await P(c,i?.signal);}},download:(async(s,i)=>{let c=ne(s),_=c.version?`?version=${encodeURIComponent(c.version)}`:"",g=await p(t,`/api/datasets/${encodeURIComponent(c.name)}/download${_}`);if(i?.stream){if(!g.body)throw new Error("Package response has no body");return g.body}if(i?.to)return De(g,i.to,`${c.name}-corpus.tar.gz`);let m=Buffer.from(await g.arrayBuffer());return Ce(g,m.length),await Pe(g,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}`:"",g=await p(t,`/api/datasets/imports${_}`);return k(await g.json(),K)},s)},async activate(s,i){let c=await p(t,`/api/datasets/${encodeURIComponent(s)}/versions/${encodeURIComponent(i)}/activate`,{method:"POST"});return a(await c.json())},async update(s,i){let c=await p(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 p(t,`/api/datasets/${encodeURIComponent(s)}`,{method:"DELETE"});}}}function Jt(e){let t=N("agents",e);return {async create(n){let r=await Re("agents().create()",n),a=await p(t,"/api/agents",{method:"POST",body:r});return H(await a.json())},list(n){return I(async r=>{let a=await p(t,`/api/agents${v(r)}`);return k(await a.json(),H)},n)},async get(n){let r=await p(t,`/api/agents/${encodeURIComponent(n)}`);return H(await r.json())},async delete(n){await p(t,`/api/agents/${encodeURIComponent(n)}`,{method:"DELETE"});},async upsert(n,r){let a=await Re("agents().upsert()",{...r,name:n}),o=await p(t,`/api/agents/${encodeURIComponent(n)}`,{method:"PUT",body:a});return H(await o.json())}}}async function Re(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}:{}};if(r){let{tarGzipDirectory:o}=await import('./tar-KTM2224F.js'),d=await o(t.directory);return F(a,{bytes:d,filename:"source.tar.gz"})}return F(a)}function re(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 Ut(e){let t=N("skills",e);return {async upload(n){if(typeof n!="string"||!n.trim())throw new Error("skills().upload() requires a local skill directory path");let{tarGzipDirectory:r}=await import('./tar-KTM2224F.js'),{basename:a,resolve:o}=await import('path'),d=a(o(n)),l=await r(n),s=await(await p(t,"/api/skills",{method:"POST",body:F({name:d||void 0},{bytes:l,filename:"skill.tar.gz"})})).json();return (Array.isArray(s.skills)?s.skills:[s]).map(re)},list(n){return I(async r=>{let a=await p(t,`/api/skills${v(r)}`);return k(await a.json(),re)},n)},async get(n){let a=await(await p(t,`/api/skills/${encodeURIComponent(n)}`)).json();return {...re(a),skill_md:a.skill_md??null}},async delete(n){await p(t,`/api/skills/${encodeURIComponent(n)}`,{method:"DELETE"});}}}function Nt(e){let t=N("jobs",e);async function n(l){let u=await p(t,`/api/jobs/${encodeURIComponent(l)}`);return T(await u.json())}async function r(l){let u=await p(t,`/api/jobs${v(l,{search:l?.search})}`);return k(await u.json(),T)}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=v(u,{status:u?.status?.length?u.status.join(","):void 0,dataset:u?.dataset}),i=await p(t,`/api/jobs/${encodeURIComponent(l)}/trials${s}`);return k(await i.json(),ae)}async function*d(l,u){let{onEvent:s,signal:i}=u??{},c=u?.reconnectDelayMs??ct,_=u?.maxReconnectDelayMs??pt,g=null,m=false,E=false,f=c;for(;!m;){$(i);let h;try{h=await fetch(`${t.baseUrl}/api/jobs/${encodeURIComponent(l)}/events`,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"text/event-stream",...g!==null?{"Last-Event-ID":String(g)}:{}},signal:i});}catch(y){if(ve(y,i))throw y;await P(f,i),f=Math.min(f*2,_);continue}if(!h.ok){if(h.status===429||h.status>=500){let y=await h.text().catch(()=>""),R=Se(y,h)??0,w=R>0?Math.max(R*1e3,f):f;await P(w,i),f=Math.min(f*2,_);continue}await ie(h);}if(!h.body)throw new Error("Event stream response has no body");let j=false,x=[],b=Dt(y=>{let R=Number(y.id),w={seq:Number.isInteger(R)?R:-1,type:y.event||"message",data:y.data?Mt(y.data):{}};Number.isInteger(R)&&(g=R),j=true,_t.has(w.type)&&(m=true),x.push(w);}),M=h.body.getReader(),Ie=new TextDecoder;try{for(;!m;){let{done:y,value:R}=await M.read();if(y)break;b.push(Ie.decode(R,{stream:!0}));for(let w of x)s?.(w),yield w;x.length=0;}}catch(y){if(ve(y,i))throw y}finally{await M.cancel().catch(()=>{});}if(m)break;$(i);let le=await n(l);if(gt.has(le.status)){if(E)return le;E=true;continue}j&&(f=c),await P(f,i),f=Math.min(f*2,_);}return n(l)}return {async start(l,u){let s=await p(t,"/api/jobs",{method:"POST",headers:{"Content-Type":"application/json",...u?.idempotencyKey?{"Idempotency-Key":u.idempotencyKey}:{}},body:JSON.stringify(l)});return T(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 p(t,`/api/jobs/${encodeURIComponent(l)}/tasks${v(s)}`);return k(await i.json(),a)},u)},watch(l,u){return It(d(l,u))},async cancel(l){let u=await p(t,`/api/jobs/${encodeURIComponent(l)}/cancel`,{method:"POST"});return T(await u.json())},async compare(l){let u=l.map(encodeURIComponent).join(","),i=await(await p(t,`/api/jobs/compare?ids=${u}`)).json();return {jobs:(i.jobs||[]).map(xt),taskMatrix:(i.taskMatrix||[]).map(wt)}},async resume(l,u,s){let i=await p(t,`/api/jobs/${encodeURIComponent(l)}/resume`,{method:"POST",headers:{"Content-Type":"application/json",...s?.idempotencyKey?{"Idempotency-Key":s.idempotencyKey}:{}},body:JSON.stringify(u??{})});return T(await i.json())},async retry(l,u,s){let i=await p(t,`/api/jobs/${encodeURIComponent(l)}/retry`,{method:"POST",headers:{"Content-Type":"application/json",...s?.idempotencyKey?{"Idempotency-Key":s.idempotencyKey}:{}},body:JSON.stringify(u??{})});return T(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 p(t,`/api/jobs/${encodeURIComponent(l)}/regrade`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});return T(await i.json())},download:(async(l,u)=>{let s=await p(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 De(s,u.to,`job-${l}-results.tar.gz`);let i=Buffer.from(await s.arrayBuffer());return Ce(s,i.length),await Pe(s,i),i}),async grep(l,u,s){let i=await p(t,`/api/jobs/${encodeURIComponent(l)}/grep${v(s,{q:u,type:s?.type})}`);return k(await i.json(),Ct)}}}function jt(e){let t=N("trials",e);async function n(a,o){let d=await p(t,`/api/trials/${encodeURIComponent(a)}/trace${v(o,{type:o?.type,grep:o?.grep,tail:o?.tail!==void 0?String(o.tail):void 0})}`);return k(await d.json(),Ae)}async function r(a,o){let l=await(await p(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 p(t,`/api/trials/${encodeURIComponent(a)}`);return ae(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 p(t,`/api/trials/${encodeURIComponent(a)}/regrade`,{method:"POST"});return T(await o.json())},async retry(a,o){let d=await p(t,`/api/trials/${encodeURIComponent(a)}/retry`,{method:"POST",...o?.idempotencyKey?{headers:{"Idempotency-Key":o.idempotencyKey}}:{}});return T(await d.json())},async stop(a){let d=await(await p(t,"/api/trials/stop",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({trial_ids:a})})).json();return {stopped:(d.stopped??[]).map(ae),already_terminal:d.already_terminal??[],not_found:d.not_found??[]}},async files(a,o){let d=await p(t,`/api/trials/${encodeURIComponent(a)}/files${v(o)}`);return k(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=Pt(d),s=await p(t,`/api/trials/${encodeURIComponent(a)}/files/${l}`,u?{headers:{Range:u}}:void 0);return Buffer.from(await s.arrayBuffer())}}}function Nn(e){let t=N("auth",e);return {async status(){let r=await(await p(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 Mt(e){try{let t=JSON.parse(e);return t&&typeof t=="object"?t:{value:t}}catch{return {raw:e}}}function jn(e){let t,n,r,a,o;return {get datasets(){return t??=Lt(e)},get agents(){return n??=Jt(e)},get jobs(){return r??=Nt(e)},get trials(){return a??=jt(e)},get skills(){return o??=Ut(e)},meta(){return $t(e)}}}async function $t(e){let t=(e?.baseUrl||process.env.EVOLVE_DASHBOARD_URL||O).replace(/\/$/,""),n=await fetch(`${t}/api/meta`);return n.ok||await ie(n),await n.json()}export{q as $,un as A,dn as B,ge as C,S as D,_e as E,Z as F,gn as G,_n as H,mn as I,fn as J,bn as K,yn as L,hn as M,Ve as N,kn as O,vn as P,Rn as Q,Sn as R,Tn as S,Ge as T,He as U,ee as V,Ke as W,Ye as X,fe as Y,te as Z,We as _,Oe as a,Xe as aa,Le as b,Qe as ba,Ft as c,Ze as ca,ue as d,he as da,Bt as e,et as ea,qt as f,nt as fa,Vt as g,D as ga,X as h,se as ha,Gt as i,Y as ia,Ht as j,W as ja,Kt as k,z as ka,Yt as l,Lt as la,Wt as m,Jt as ma,zt as n,Ut as na,Xt as o,Nt as oa,Qt as p,jt as pa,de as q,Nn as qa,Zt as r,jn as ra,O as s,$t as sa,tn as t,nn as u,rn as v,sn as w,an as x,on as y,ln as z};