@evolvingmachines/sdk 0.0.52-project-sable.20260730.c2cb2d2 → 0.0.52-project-sable.20260810.ca7ed91

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 CHANGED
@@ -1,4 +1,12 @@
1
- # Evolve SDK TypeScript SDK
1
+ <br><br>
2
+
3
+ <p align="center">
4
+ <img src="https://raw.githubusercontent.com/evolving-machines-lab/evolve/main/logo/evolving-machines-ink.png" alt="Evolving Machines" width="380">
5
+ </p>
6
+
7
+ <br><br>
8
+
9
+ # Evolving Machines — Evolve SDK (TypeScript)
2
10
 
3
11
  Evolve SDK lets you run and orchestrate terminal-based AI agents in secure sandboxes with built-in observability.
4
12
 
@@ -0,0 +1,6 @@
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 pe(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 ge(e=""){let t=process.env.EVOLVE_DASHBOARD_URL||E;if(!e)return t;let n=e.startsWith("/")?e:`/${e}`;return `${t.replace(/\/$/,"")}${n}`}var at=["e2b","daytona","modal"];function Y(e){return ge(`/api/managed/${e}`)}function it(){return `${Y("daytona")}/toolbox`}function ot(){return Y("e2b")}function lt(e){return {"browser-use":{type:"http",url:pe("/browser_use/mcp"),headers:{"x-litellm-api-key":`Bearer ${e}`}}}}var N="EVOLVE_API_KEY",ut="E2B_API_KEY",ct="DAYTONA_API_KEY",dt="MODAL_TOKEN_ID",pt="MODAL_TOKEN_SECRET",gt="claude",mt=36e5,_t=4,ft=100,X="/home/user";function bt(e,t){return t?t.replace(/\/+$/,"")||"/":e?e==="root"?"/root":`/home/${e}`:X}var E=process.env.EVOLVE_DASHBOARD_URL||"https://dashboard.evolvingmachines.ai",Rt="x-litellm-customer-id",vt="x-litellm-tags",kt="run:",At=".evolve-sdk/observability/sessions",xt=["tag","provider","agent","model","sandboxId","sandbox_id","timestamp","event","events"],St=100,Tt=5e3,ht=3,Dt=1e3;var me=["QUEUED","RUNNING","SCORING","SCORED","SCORING_ERROR","INFRASTRUCTURE_ERROR","INDETERMINATE","CANCELLED"],_e=["e2b","daytona","modal"];function fe(e){let t=e.stats?.evals??{},n=[];for(let s of Object.keys(t).sort()){let a=t[s]?.pass_at_k??{},l=[];for(let c of Object.keys(a)){let u=Number(c),r=a[c];!Number.isFinite(u)||typeof r!="number"||!Number.isFinite(r)||l.push({k:u,value:r});}l.length!==0&&(l.sort((c,u)=>c.k-u.k),n.push({evals_key:s,points:l}));}return n}var be=["trace-parsed","verifier","trace-stdout","trace-stderr","trace-atif","trajectory","agent-home"],Q=["missing_authorization","invalid_api_key","credential_service_unavailable","rate_limited","insufficient_credits","invalid_json","invalid_input","invalid_limit","invalid_status","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","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","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 M(e){return typeof e=="string"&&Q.includes(e)}var ye=["level","binary","none"];var T=class extends Error{status;code;param;details;retryAfterSec;requestId;constructor(t,n,s,a){super(s),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 M(this.code)}};function ne(e,t){try{let l=JSON.parse(e)?.error?.retryAfterSec;if(typeof l=="number"&&Number.isFinite(l))return l}catch{}let n=t.headers?.get?.("retry-after");if(typeof n!="string"||n.trim()==="")return;let s=Number(n);return Number.isFinite(s)?s:void 0}async function H(e){let t=await e.text().catch(()=>""),n=e.headers?.get?.("x-request-id")??void 0,s=ne(t,e);try{let a=JSON.parse(t);if(a?.error&&typeof a.error=="object"){let l=typeof a.error.code=="string"?a.error.code:"unknown_error",c=typeof a.error.message=="string"?a.error.message:e.statusText;throw new T(e.status,l,c,{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:s,requestId:typeof a.error.requestId=="string"?a.error.requestId:n})}}catch(a){if(a instanceof T)throw a}throw new T(e.status,"unknown_error",t||e.statusText,{retryAfterSec:s,requestId:n})}var G=class extends Error{dataset;constructor(t){super(`Dataset "${t}" has no active version`),this.name="NoActiveVersionError",this.dataset=t;}},F=class extends Error{name="GateRunningError";code="gate_running";dataset;version;gate;constructor(t,n,s,a){super(s),this.dataset=t,this.version=n,this.gate=a;}};function De(e){let t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return {status:typeof t.status=="string"?t.status:"PENDING",tasks:typeof t.tasks=="number"?t.tasks:0,unverified:typeof t.unverified=="number"?t.unverified:0,ineligible:typeof t.ineligible=="number"?t.ineligible:0}}var Pe=1e3,Ee=3e4,we=new Set(["COMPLETED","CANCELLED","FAILED"]),Ie=new Set(["job.completed","job.cancelled","job.failed"]),Ce=2e3,Oe=new Set(["COMPLETED","FAILED"]);function h(e,t){let n=t?.apiKey||process.env[N];if(!n)throw new Error(`${e}() requires an API key. Set ${N} or pass { apiKey } in config.`);let s=(t?.baseUrl||process.env.EVOLVE_DASHBOARD_URL||E).replace(/\/$/,"");return {apiKey:n,baseUrl:s}}async function d(e,t,n){let s=await fetch(`${e.baseUrl}${t}`,{...n,headers:{Authorization:`Bearer ${e.apiKey}`,...n?.headers}});return s.ok||await H(s),s}function Z(e){let t=e.indexOf("@");if(t===-1)return {name:e.trim()};let n=e.slice(0,t).trim(),s=e.slice(t+1).trim();if(!n||!s)throw new Error(`Invalid dataset ref "${e}": expected "name" or "name@version"`);return {name:n,version:s}}function re(e){return {name:e.name,version:e.version}}function se(e){let t=e.kwargs,n=Array.isArray(e.skills)?e.skills.filter(l=>typeof l=="string"):[],s=Array.isArray(e.skill_locks)?e.skill_locks:null,a=s?s.flatMap(l=>{if(!l||typeof l!="object")return [];let c=l;return typeof c.name!="string"||typeof c.digest!="string"?[]:[{name:c.name,source:typeof c.source=="string"?c.source:"",digest:c.digest,git_url:typeof c.git_url=="string"?c.git_url:null,git_commit_id:typeof c.git_commit_id=="string"?c.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 Je(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;if(typeof t.status!="string")return null;let n=t.failure&&typeof t.failure=="object"&&!Array.isArray(t.failure)?t.failure:{},s=typeof t.code=="string"?t.code:n.code,a=typeof t.message=="string"?t.message:n.message,l=Le(Array.isArray(t.failed_tasks)?t.failed_tasks:n.failed_tasks),c=typeof t.failed_task_count=="number"?t.failed_task_count:n.failed_task_count;return {status:t.status,attempts:typeof t.attempts=="number"?t.attempts:0,code:typeof s=="string"?s:null,message:typeof a=="string"?a:null,failed_tasks:l,failed_task_count:typeof c=="number"?c:l.length}}function Le(e){if(!Array.isArray(e))return [];let t=[];for(let n of e){if(!n||typeof n!="object"||Array.isArray(n))continue;let s=n;typeof s.task_name=="string"&&t.push({task_name:s.task_name,outcome:typeof s.outcome=="string"?s.outcome:null,reasons:Array.isArray(s.reasons)?s.reasons.filter(a=>typeof a=="string"):[]});}return t}function je(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(s=>{if(!s||typeof s!="object"||Array.isArray(s))return [];let a=s;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(s=>typeof s=="string"):[],task_count:typeof t.task_count=="number"?t.task_count:null}}function Ue(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 w(e){return {version:e.version,state:e.state,created_at:e.created_at,task_count:e.task_count??0,manifest:je(e.manifest),source:Ue(e.source),gate:Je(e.gate)}}function Ve(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;return typeof t.outcome!="string"?null:{outcome:t.outcome,flaky:t.flaky===true,reasons:Array.isArray(t.reasons)?t.reasons.filter(n=>typeof n=="string"):[],ran_at:typeof t.ran_at=="string"?t.ran_at:null}}function Ne(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,gate:Ve(e.gate)}}function Me(e){return {action:e.action,type:e.type,job_id:e.job_id}}function $e(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 Ge(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 I(e){return typeof e=="number"?e:null}function R(e){let t=e.trials??{};return {id:e.id,job_name:e.job_name,status:e.status,datasets:(e.datasets??[]).map(re),agents:(e.agents??[]).map(se),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:$e(e.retry),timeout_multiplier:typeof e.timeout_multiplier=="number"?e.timeout_multiplier:1,agent_timeout_multiplier:I(e.agent_timeout_multiplier),verifier_timeout_multiplier:I(e.verifier_timeout_multiplier),agent_setup_timeout_multiplier:I(e.agent_setup_timeout_multiplier),environment_build_timeout_multiplier:I(e.environment_build_timeout_multiplier),sandbox_provider:e.sandbox_provider,counts:e.counts,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(Me),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 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 k(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,l]of Object.entries(t??{}))l!==void 0&&n.set(a,l);let s=n.toString();return s?`?${s}`:""}function C(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 Fe(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 Be(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let{from:t,to:n,reason:s}=e;return typeof t!="string"||typeof n!="string"||typeof s!="string"?null:{from:t,to:n,reason:s}}function B(e){return {id:e.id,job_id:e.job_id,task_name:e.task_name,source:e.source,agent_info:Fe(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:C(e.environment_setup),agent_setup:C(e.agent_setup),agent_execution:C(e.agent_execution),verifier:C(e.verifier),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,max_trial_spend_usd:e.max_trial_spend_usd??null,sandbox_provider:e.sandbox_provider??null,sandbox_provider_degrade:Be(e.sandbox_provider_degrade),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(Ge):[],session_ref:e.session_ref??null,started_at:e.started_at??null,finished_at:e.finished_at??null}}function O(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 J(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 ae(e){let t=e??{};return {scored:t.scored??0,total:t.total??0}}function qe(e){return {id:e.id,datasets:(e.datasets??[]).map(re),status:e.status,mean_reward:e.mean_reward??null,coverage:ae(e.coverage),cost_usd:e.cost_usd??0,agents:(e.agents||[]).map(se),started_at:e.started_at}}function He(e){return {job_id:e.job_id,status:e.status,mean_reward:e.mean_reward??null,coverage:ae(e.coverage)}}function Ke(e){return {task_name:e.task_name,disagreement:e.disagreement===true,cells:(e.cells||[]).map(He)}}function We(e){return {seq:e.seq,type:e.type,data:e.data??{}}}function q(e){if(e?.aborted)throw e.reason instanceof Error?e.reason:new Error("Watch aborted")}function ee(e,t){return t?.aborted?true:e?.name==="AbortError"}function D(e,t){return new Promise((n,s)=>{let a=setTimeout(()=>{t?.removeEventListener("abort",l),n();},e),l=()=>{clearTimeout(a),s(t?.reason instanceof Error?t.reason:new Error("Watch aborted"));};t?.addEventListener("abort",l,{once:true});})}function ze(e){let t="",n=false;return {push(s){n&&(s="\r"+s,n=false),s.endsWith("\r")&&(s=s.slice(0,-1),n=true),t+=s.replace(/\r\n|\r/g,`
2
+ `);let a;for(;(a=t.indexOf(`
3
+
4
+ `))!==-1;){let l=t.slice(0,a);t=t.slice(a+2);let c,u,r=[];for(let i of l.split(`
5
+ `)){if(!i||i.startsWith(":"))continue;let o=i.indexOf(":"),g=o===-1?i:i.slice(0,o),p=o===-1?"":i.slice(o+1);p.startsWith(" ")&&(p=p.slice(1)),g==="id"?c=p:g==="event"?u=p:g==="data"&&r.push(p);}(c!==void 0||u!==void 0||r.length>0)&&e({id:c,event:u,data:r.join(`
6
+ `)});}}}}function S(e,t){let n,s=()=>n??=e({limit:t?.limit,cursor:t?.cursor});return {then(a,l){return s().then(a,l)},catch(a){return s().catch(a)},finally(a){return s().finally(a)},async*[Symbol.asyncIterator](){let a=t?.cursor;for(;;){let l=await e({limit:t?.limit,cursor:a});for(let c of l.items)yield c;if(!l.nextCursor)return;a=l.nextCursor;}}}}function P(e,t){let n=new FormData;for(let[s,a]of Object.entries(e))a!==void 0&&n.set(s,a);return t&&n.set("archive",new Blob([t.bytes],{type:"application/gzip"}),t.filename),n}function Ye(e){let t,n=()=>(t||(t=(async()=>{let s=await e.next();for(;!s.done;)s=await e.next();return s.value})()),t);return {then(s,a){return n().then(s,a)},catch(s){return n().catch(s)},finally(s){return n().finally(s)},[Symbol.asyncIterator](){return e}}}var ie="x-package-sha256",L=class extends Error{constructor(n,s){super(`downloaded bytes do not match the digest the server stated (expected ${n}, got ${s})`);this.expected=n;this.actual=s;}name="EvolveDigestMismatchError"},j=class extends Error{constructor(n,s){super(`download ended early: the server declared ${n} bytes and ${s} arrived`);this.expectedBytes=n;this.receivedBytes=s;}name="EvolveIncompleteDownloadError"};function oe(e,t){let n=e.headers.get("Content-Length");if(n===null)return;let s=Number(n);if(Number.isFinite(s)&&t!==s)throw new j(s,t)}async function le(e,t){let n=e.headers.get(ie);if(!n)return;let{createHash:s}=await import('crypto'),a=s("sha256").update(t).digest("hex");if(a!==n)throw new L(n,a)}function Xe(e,t){let s=(e.headers.get("Content-Disposition")||"").match(/filename="([^"]+)"/);if(!s)return t;let a=basename(s[1]);return a===""||a==="."||a===".."||/[/\\]/.test(a)||/[\u0000-\u001f]/.test(a)?t:a}async function ue(e,t,n){if(!e.body)throw new Error("Download response has no body");await mkdir(t,{recursive:true});let s=join(t,Xe(e,n)),{createHash:a,randomBytes:l}=await import('crypto'),c=`${s}.${l(8).toString("hex")}.part`,u=a("sha256"),r=0,i=Readable.fromWeb(e.body);i.on("data",o=>{u.update(o),r+=o.length;});try{await pipeline(i,createWriteStream(c));let o=e.headers.get("Content-Length");if(o!==null&&r!==Number(o))throw new j(Number(o),r);let g=e.headers.get(ie),p=u.digest("hex");if(g&&p!==g)throw new L(g,p);await rename(c,s);}catch(o){throw await rm(c,{force:true}).catch(()=>{}),o}return s}function Qe(e){let t=h("datasets",e);async function n(r){let i=await d(t,`/api/datasets/imports/${encodeURIComponent(r)}`);return J(await i.json())}function s(r){if(!r||typeof r!="object")return null;let i=r;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(r){return {name:r.name,title:r.title??null,description:r.description??null,active_version:r.active_version?w(r.active_version):null,versions:(r.versions||[]).map(w),selected_version:r.selected_version?w(r.selected_version):null,tasks:v(r.tasks,Ne),upstream:s(r.upstream),created_at:r.created_at,updated_at:r.updated_at}}async function l(r,i){let o=Z(r),g=k(i,{version:o.version}),p=await d(t,`/api/datasets/${encodeURIComponent(o.name)}${g}`);return a(await p.json())}function c(r){return {name:r.name,title:r.title??null,description:r.description??null,active_version:r.active_version?w(r.active_version):null,upstream:s(r.upstream)}}async function u(r){let i=await d(t,`/api/datasets${k(r,{search:r?.search})}`);return v(await i.json(),c)}return {list(r){return S(i=>u({...i,search:r?.search}),r)},get:l,async getActive(r,i){let o=await l(r,i);if(o.active_version===null)throw new G(r);return {name:o.name,title:o.title,description:o.description,active_version:o.active_version,version:o.active_version.version,tasks:o.tasks??{items:[],nextCursor:null,hasMore:false},versions:o.versions??[],created_at:o.created_at,updated_at:o.updated_at}},async publish(r){let i=r.source;if(i?.directory){if(r.name===void 0||r.version===void 0){let{existsSync:m}=await import('fs'),{join:A}=await import('path');if(!(m(A(i.directory,"dataset.toml"))||m(A(i.directory,"tasks","dataset.toml"))))throw new Error(`datasets().publish() needs ${r.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:o}=await import('./tar-KTM2224F.js'),g=await o(i.directory),p=await d(t,"/api/datasets/publish",{method:"POST",body:P({name:r.name,version:r.version},{bytes:g,filename:"corpus.tar.gz"})});return J(await p.json())}if(i&&"git_url"in i&&i.git_url){if(r.name===void 0||r.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 o=await d(t,"/api/datasets/publish",{method:"POST",body:P({name:r.name,version:r.version,git_url:i.git_url,git_ref:i.git_ref,...i.git_path!==void 0?{git_path:i.git_path}:{}})});return J(await o.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(r,i){let o=i?.pollIntervalMs??Ce,g=null;for(;;){q(i?.signal);let p;try{p=await n(r);}catch(m){if(m instanceof T&&(m.status===429||m.status===503)){await D(Math.max((m.retryAfterSec??0)*1e3,o),i?.signal);continue}throw m}if(p.status!==g&&(g=p.status,i?.onStatus?.(p)),Oe.has(p.status))return p;await D(o,i?.signal);}},download:(async(r,i)=>{let o=Z(r),g=o.version?`?version=${encodeURIComponent(o.version)}`:"",p=await d(t,`/api/datasets/${encodeURIComponent(o.name)}/download${g}`);if(i?.stream){if(!p.body)throw new Error("Package response has no body");return p.body}if(i?.to)return ue(p,i.to,`${o.name}-corpus.tar.gz`);let m=Buffer.from(await p.arrayBuffer());return oe(p,m.length),await le(p,m),m}),listImports(r){return S(async i=>{let o=new URLSearchParams;i.limit!==void 0&&o.set("limit",String(i.limit)),i.cursor!==void 0&&o.set("cursor",i.cursor),r?.status!==void 0&&o.set("status",r.status),r?.dataset!==void 0&&o.set("dataset",r.dataset);let g=o.toString()?`?${o}`:"",p=await d(t,`/api/datasets/imports${g}`);return v(await p.json(),J)},r)},async activate(r,i){let o=await d(t,`/api/datasets/${encodeURIComponent(r)}/versions/${encodeURIComponent(i)}/activate`,{method:"POST"});if(o.status===202){let g=await o.json();throw new F(r,i,typeof g.message=="string"?g.message:`Dataset "${r}" version "${i}" is still being proven by its activation gate`,De(g.gate))}return a(await o.json())},async update(r,i){let o=await d(t,`/api/datasets/${encodeURIComponent(r)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});return c(await o.json())},async delete(r){await d(t,`/api/datasets/${encodeURIComponent(r)}`,{method:"DELETE"});}}}function Ze(e){let t=h("agents",e);return {async create(n){let s=await te("agents().create()",n),a=await d(t,"/api/agents",{method:"POST",body:s});return O(await a.json())},list(n){return S(async s=>{let a=await d(t,`/api/agents${k(s)}`);return v(await a.json(),O)},n)},async get(n){let s=await d(t,`/api/agents/${encodeURIComponent(n)}`);return O(await s.json())},async delete(n){await d(t,`/api/agents/${encodeURIComponent(n)}`,{method:"DELETE"});},async upsert(n,s){let a=await te("agents().upsert()",{...s,name:n}),l=await d(t,`/api/agents/${encodeURIComponent(n)}`,{method:"PUT",body:a});return O(await l.json())}}}async function te(e,t){let n=typeof t.install_script=="string",s=typeof t.directory=="string";if(n&&s)throw new Error(`${e} takes EITHER an install script ({ install_script }) or a local directory ({ directory }), not both`);if(!n&&!s)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(s){let{tarGzipDirectory:l}=await import('./tar-KTM2224F.js'),c=await l(t.directory);return P(a,{bytes:c,filename:"source.tar.gz"})}return P(a)}function $(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 et(e){let t=h("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:s}=await import('./tar-KTM2224F.js'),{basename:a,resolve:l}=await import('path'),c=a(l(n)),u=await s(n),i=await(await d(t,"/api/skills",{method:"POST",body:P({name:c||void 0},{bytes:u,filename:"skill.tar.gz"})})).json();return (Array.isArray(i.skills)?i.skills:[i]).map($)},list(n){return S(async s=>{let a=await d(t,`/api/skills${k(s)}`);return v(await a.json(),$)},n)},async get(n){let a=await(await d(t,`/api/skills/${encodeURIComponent(n)}`)).json();return {...$(a),skill_md:a.skill_md??null}},async delete(n){await d(t,`/api/skills/${encodeURIComponent(n)}`,{method:"DELETE"});}}}function tt(e){let t=h("jobs",e);async function n(u){let r=await d(t,`/api/jobs/${encodeURIComponent(u)}`);return R(await r.json())}async function s(u){let r=await d(t,`/api/jobs${k(u,{search:u?.search})}`);return v(await r.json(),R)}function a(u){let r=u.trials??{};return {task_name:u.task_name,source:u.source,trials:{total:r.total??0,byStatus:r.byStatus??{}},mean_reward:u.mean_reward??null,cost_usd:u.cost_usd??null}}async function l(u,r){let i=k(r,{status:r?.status?.length?r.status.join(","):void 0,dataset:r?.dataset}),o=await d(t,`/api/jobs/${encodeURIComponent(u)}/trials${i}`);return v(await o.json(),B)}async function*c(u,r){let{onEvent:i,signal:o}=r??{},g=r?.reconnectDelayMs??Pe,p=r?.maxReconnectDelayMs??Ee,m=null,A=false,U=false,f=g;for(;!A;){q(o);let b;try{b=await fetch(`${t.baseUrl}/api/jobs/${encodeURIComponent(u)}/events`,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"text/event-stream",...m!==null?{"Last-Event-ID":String(m)}:{}},signal:o});}catch(_){if(ee(_,o))throw _;await D(f,o),f=Math.min(f*2,p);continue}if(!b.ok){if(b.status===429||b.status>=500){let _=await b.text().catch(()=>""),y=ne(_,b)??0,x=y>0?Math.max(y*1e3,f):f;await D(x,o),f=Math.min(f*2,p);continue}await H(b);}if(!b.body)throw new Error("Event stream response has no body");let K=false,V=[],ce=ze(_=>{let y=Number(_.id),x={seq:Number.isInteger(y)?y:-1,type:_.event||"message",data:_.data?rt(_.data):{}};Number.isInteger(y)&&(m=y),K=true,Ie.has(x.type)&&(A=true),V.push(x);}),W=b.body.getReader(),de=new TextDecoder;try{for(;!A;){let{done:_,value:y}=await W.read();if(_)break;ce.push(de.decode(y,{stream:!0}));for(let x of V)i?.(x),yield x;V.length=0;}}catch(_){if(ee(_,o))throw _}finally{await W.cancel().catch(()=>{});}if(A)break;q(o);let z=await n(u);if(we.has(z.status)){if(U)return z;U=true;continue}K&&(f=g),await D(f,o),f=Math.min(f*2,p);}return n(u)}return {async start(u,r){let i=await d(t,"/api/jobs",{method:"POST",headers:{"Content-Type":"application/json",...r?.idempotencyKey?{"Idempotency-Key":r.idempotencyKey}:{}},body:JSON.stringify(u)});return R(await i.json())},get:n,list(u){return S(r=>s({...r,search:u?.search}),u)},trials(u,r){return S(i=>l(u,{...i,status:r?.status,dataset:r?.dataset}),r)},tasks(u,r){return S(async i=>{let o=await d(t,`/api/jobs/${encodeURIComponent(u)}/tasks${k(i)}`);return v(await o.json(),a)},r)},watch(u,r){return Ye(c(u,r))},async cancel(u){let r=await d(t,`/api/jobs/${encodeURIComponent(u)}/cancel`,{method:"POST"});return R(await r.json())},async compare(u){let r=u.map(encodeURIComponent).join(","),o=await(await d(t,`/api/jobs/compare?ids=${r}`)).json();return {jobs:(o.jobs||[]).map(qe),taskMatrix:(o.taskMatrix||[]).map(Ke)}},async resume(u,r,i){let o=await d(t,`/api/jobs/${encodeURIComponent(u)}/resume`,{method:"POST",headers:{"Content-Type":"application/json",...i?.idempotencyKey?{"Idempotency-Key":i.idempotencyKey}:{}},body:JSON.stringify(r??{})});return R(await o.json())},async retry(u,r,i){let o=await d(t,`/api/jobs/${encodeURIComponent(u)}/retry`,{method:"POST",headers:{"Content-Type":"application/json",...i?.idempotencyKey?{"Idempotency-Key":i.idempotencyKey}:{}},body:JSON.stringify(r??{})});return R(await o.json())},async regrade(u,r){let i={};r?.statuses?.length&&(i.statuses=r.statuses),r?.task_name!==void 0&&(i.task_name=r.task_name);let o=await d(t,`/api/jobs/${encodeURIComponent(u)}/regrade`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});return R(await o.json())},download:(async(u,r)=>{let i=await d(t,`/api/jobs/${encodeURIComponent(u)}/download`);if(r?.stream){if(!i.body)throw new Error("Download response has no body");return i.body}if(r?.to)return ue(i,r.to,`job-${u}-results.tar.gz`);let o=Buffer.from(await i.arrayBuffer());return oe(i,o.length),await le(i,o),o})}}function nt(e){let t=h("trials",e);async function n(a,l){let c=await d(t,`/api/trials/${encodeURIComponent(a)}/trace${k(l)}`);return v(await c.json(),We)}async function s(a,l){let u=await(await d(t,`/api/trials/${encodeURIComponent(a)}/trace?stream=${l}`)).json();return l==="agent-home"?u.files??null:u.log??null}return {async get(a){let l=await d(t,`/api/trials/${encodeURIComponent(a)}`);return B(await l.json())},trace:n,artifact:s,async*traceEvents(a,l){let c=l?.cursor;for(;;){let u=await n(a,{cursor:c,limit:l?.limit});for(let r of u.items)yield r;if(!u.nextCursor)return;c=u.nextCursor;}},async regrade(a){let l=await d(t,`/api/trials/${encodeURIComponent(a)}/regrade`,{method:"POST"});return R(await l.json())},async retry(a,l){let c=await d(t,`/api/trials/${encodeURIComponent(a)}/retry`,{method:"POST",...l?.idempotencyKey?{headers:{"Idempotency-Key":l.idempotencyKey}}:{}});return R(await c.json())},async stop(a){let c=await(await d(t,"/api/trials/stop",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({trial_ids:a})})).json();return {stopped:(c.stopped??[]).map(B),already_terminal:c.already_terminal??[],not_found:c.not_found??[]}}}}function Ut(e){let t=h("auth",e);return {async status(){let s=await(await d(t,"/api/auth/status")).json(),a=s.key??{};return {user_id:s.user_id,email:s.email??null,key:{id:a.id,label:a.label??null,created_at:a.created_at,last_used_at:a.last_used_at??null}}}}}function rt(e){try{let t=JSON.parse(e);return t&&typeof t=="object"?t:{value:t}}catch{return {raw:e}}}function Vt(e){let t,n,s,a,l;return {get datasets(){return t??=Qe(e)},get agents(){return n??=Ze(e)},get jobs(){return s??=tt(e)},get trials(){return a??=nt(e)},get skills(){return l??=et(e)},meta(){return st(e)}}}async function st(e){let t=(e?.baseUrl||process.env.EVOLVE_DASHBOARD_URL||E).replace(/\/$/,""),n=await fetch(`${t}/api/meta`);return n.ok||await H(n),await n.json()}export{ht as A,Dt as B,me as C,_e as D,fe as E,be as F,Q as G,M as H,ye as I,T as J,G as K,F as L,L as M,j as N,Qe as O,Ze as P,et as Q,tt as R,nt as S,Ut as T,Vt as U,st as V,pe as a,ge as b,at as c,Y as d,it as e,ot as f,lt as g,N as h,ut as i,ct as j,dt as k,pt as l,gt as m,mt as n,_t as o,ft as p,X as q,bt as r,E as s,Rt as t,vt as u,kt as v,At as w,xt as x,St as y,Tt as z};
@@ -0,0 +1,20 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';var zlib=require('zlib'),fs$1=require('fs'),promises=require('fs/promises'),path=require('path'),promises$1=require('stream/promises'),tarStream=require('tar-stream'),url=require('url'),yaml=require('yaml'),smolToml=require('smol-toml'),stream=require('stream');var _documentCurrentScript=typeof document!=='undefined'?document.currentScript:null;var Lt=Object.defineProperty;var Jt=(e,t)=>()=>(e&&(t=e(e=0)),t);var Nt=(e,t)=>{for(var s in t)Lt(e,s,{get:t[s],enumerable:true});};var H={};Nt(H,{extractTarGz:()=>Xt,tarGzipDirectory:()=>zt});async function Yt(e){let t=[],s=async n=>{let r=n===""?e:path.join(e,n),a=await promises.readdir(r,{withFileTypes:true});a.sort((i,o)=>i.name<o.name?-1:i.name>o.name?1:0);for(let i of a){if(Wt.has(i.name))continue;let o=n===""?i.name:`${n}/${i.name}`,l=path.join(r,i.name),u=await promises.lstat(l);u.isSymbolicLink()||(u.isDirectory()?await s(o):u.isFile()&&t.push({rel:o,abs:l,mode:u.mode&73?493:420,size:u.size}));}};return await s(""),t.sort((n,r)=>n.rel<r.rel?-1:n.rel>r.rel?1:0)}async function zt(e){let t=await Yt(e),s=tarStream.pack(),n=zlib.createGzip({level:9}),r=[],a=(async()=>{for await(let o of n)r.push(Buffer.from(o));})(),i=(async()=>{for(let{rel:o,abs:l,mode:u,size:c}of t){let g=s.entry({name:o,size:c,mode:u,mtime:new Date(0),uid:0,gid:0,uname:"",gname:"",type:"file"});await promises$1.pipeline(fs$1.createReadStream(l),g);}s.finalize();})();return await Promise.all([promises$1.pipeline(s,n),i,a]),Buffer.concat(r)}async function Xt(e,t,s){let n=tarStream.extract(),r=[],a=(async()=>{for await(let i of n){let o=i.header.name,l=o.split("/").filter(c=>c!==""&&c!==".");if(o.startsWith("/")||o.includes("\\")||l.length===0||l.some(c=>c===".."))throw new Error(`refusing to extract "${o}": the path escapes the target directory`);if(l[0]!==s)throw new Error(`refusing to extract "${o}": entry outside ${s}/`);if(i.header.type==="directory"){await promises.mkdir(path.join(t,...l),{recursive:true}),i.resume();continue}if(i.header.type!=="file")throw new Error(`refusing to extract "${o}": unsupported entry type "${i.header.type}"`);let u=path.join(t,...l);await promises.mkdir(path.dirname(u),{recursive:true}),await promises$1.pipeline(i,fs$1.createWriteStream(u)),r.push(l.join("/"));}})();try{await Promise.all([promises$1.pipeline(fs$1.createReadStream(e),zlib.createGunzip(),n),a]);}catch(i){throw n.destroy(),i}return r}var Wt,W=Jt(()=>{Wt=new Set([".git",".DS_Store",".venv"]);});var be="EVOLVE_API_KEY";var Ne=process.env.EVOLVE_DASHBOARD_URL||"https://dashboard.evolvingmachines.ai";var ee=["QUEUED","RUNNING","SCORING","SCORED","SCORING_ERROR","INFRASTRUCTURE_ERROR","INDETERMINATE","CANCELLED"],te=["e2b","daytona","modal"];function ye(e){let t=e.stats?.evals??{},s=[];for(let n of Object.keys(t).sort()){let r=t[n]?.pass_at_k??{},a=[];for(let i of Object.keys(r)){let o=Number(i),l=r[i];!Number.isFinite(o)||typeof l!="number"||!Number.isFinite(l)||a.push({k:o,value:l});}a.length!==0&&(a.sort((i,o)=>i.k-o.k),s.push({evals_key:n,points:a}));}return s}var he=["trace-parsed","verifier","trace-stdout","trace-stderr","trace-atif","trajectory","agent-home"],Ue=["missing_authorization","invalid_api_key","credential_service_unavailable","rate_limited","insufficient_credits","invalid_json","invalid_input","invalid_limit","invalid_status","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","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","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 ke(e){return typeof e=="string"&&Ue.includes(e)}var I=class extends Error{status;code;param;details;retryAfterSec;requestId;constructor(t,s,n,r){super(n),this.name="EvolveApiError",this.status=t,this.code=s,r?.param!==void 0&&(this.param=r.param),r?.details!==void 0&&(this.details=r.details),r?.retryAfterSec!==void 0&&(this.retryAfterSec=r.retryAfterSec),r?.requestId!==void 0&&(this.requestId=r.requestId);}isKnownCode(){return ke(this.code)}};function Be(e,t){try{let a=JSON.parse(e)?.error?.retryAfterSec;if(typeof a=="number"&&Number.isFinite(a))return a}catch{}let s=t.headers?.get?.("retry-after");if(typeof s!="string"||s.trim()==="")return;let n=Number(s);return Number.isFinite(n)?n:void 0}async function Ke(e){let t=await e.text().catch(()=>""),s=e.headers?.get?.("x-request-id")??void 0,n=Be(t,e);try{let r=JSON.parse(t);if(r?.error&&typeof r.error=="object"){let a=typeof r.error.code=="string"?r.error.code:"unknown_error",i=typeof r.error.message=="string"?r.error.message:e.statusText;throw new I(e.status,a,i,{param:typeof r.error.param=="string"?r.error.param:void 0,details:r.error.details&&typeof r.error.details=="object"?r.error.details:void 0,retryAfterSec:n,requestId:typeof r.error.requestId=="string"?r.error.requestId:s})}}catch(r){if(r instanceof I)throw r}throw new I(e.status,"unknown_error",t||e.statusText,{retryAfterSec:n,requestId:s})}var we=class extends Error{dataset;constructor(t){super(`Dataset "${t}" has no active version`),this.name="NoActiveVersionError",this.dataset=t;}},z=class extends Error{name="GateRunningError";code="gate_running";dataset;version;gate;constructor(t,s,n,r){super(n),this.dataset=t,this.version=s,this.gate=r;}};function on(e){let t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return {status:typeof t.status=="string"?t.status:"PENDING",tasks:typeof t.tasks=="number"?t.tasks:0,unverified:typeof t.unverified=="number"?t.unverified:0,ineligible:typeof t.ineligible=="number"?t.ineligible:0}}var ln=1e3,un=3e4,cn=new Set(["COMPLETED","CANCELLED","FAILED"]),dn=new Set(["job.completed","job.cancelled","job.failed"]),mn=2e3,pn=new Set(["COMPLETED","FAILED"]);function M(e,t){let s=t?.apiKey||process.env[be];if(!s)throw new Error(`${e}() requires an API key. Set ${be} or pass { apiKey } in config.`);let n=(t?.baseUrl||process.env.EVOLVE_DASHBOARD_URL||Ne).replace(/\/$/,"");return {apiKey:s,baseUrl:n}}async function _(e,t,s){let n=await fetch(`${e.baseUrl}${t}`,{...s,headers:{Authorization:`Bearer ${e.apiKey}`,...s?.headers}});return n.ok||await Ke(n),n}function Ve(e){let t=e.indexOf("@");if(t===-1)return {name:e.trim()};let s=e.slice(0,t).trim(),n=e.slice(t+1).trim();if(!s||!n)throw new Error(`Invalid dataset ref "${e}": expected "name" or "name@version"`);return {name:s,version:n}}function He(e){return {name:e.name,version:e.version}}function We(e){let t=e.kwargs,s=Array.isArray(e.skills)?e.skills.filter(a=>typeof a=="string"):[],n=Array.isArray(e.skill_locks)?e.skill_locks:null,r=n?n.flatMap(a=>{if(!a||typeof a!="object")return [];let i=a;return typeof i.name!="string"||typeof i.digest!="string"?[]:[{name:i.name,source:typeof i.source=="string"?i.source:"",digest:i.digest,git_url:typeof i.git_url=="string"?i.git_url:null,git_commit_id:typeof i.git_commit_id=="string"?i.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:s,skill_locks:r}}function gn(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;if(typeof t.status!="string")return null;let s=t.failure&&typeof t.failure=="object"&&!Array.isArray(t.failure)?t.failure:{},n=typeof t.code=="string"?t.code:s.code,r=typeof t.message=="string"?t.message:s.message,a=fn(Array.isArray(t.failed_tasks)?t.failed_tasks:s.failed_tasks),i=typeof t.failed_task_count=="number"?t.failed_task_count:s.failed_task_count;return {status:t.status,attempts:typeof t.attempts=="number"?t.attempts:0,code:typeof n=="string"?n:null,message:typeof r=="string"?r:null,failed_tasks:a,failed_task_count:typeof i=="number"?i:a.length}}function fn(e){if(!Array.isArray(e))return [];let t=[];for(let s of e){if(!s||typeof s!="object"||Array.isArray(s))continue;let n=s;typeof n.task_name=="string"&&t.push({task_name:n.task_name,outcome:typeof n.outcome=="string"?n.outcome:null,reasons:Array.isArray(n.reasons)?n.reasons.filter(r=>typeof r=="string"):[]});}return t}function _n(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;if(typeof t.name!="string")return null;let s=Array.isArray(t.authors)?t.authors.flatMap(n=>{if(!n||typeof n!="object"||Array.isArray(n))return [];let r=n;return typeof r.name!="string"?[]:[{name:r.name,email:typeof r.email=="string"?r.email:null}]}):[];return {name:t.name,version:typeof t.version=="string"?t.version:null,description:typeof t.description=="string"?t.description:"",authors:s,keywords:Array.isArray(t.keywords)?t.keywords.filter(n=>typeof n=="string"):[],task_count:typeof t.task_count=="number"?t.task_count:null}}function bn(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 re(e){return {version:e.version,state:e.state,created_at:e.created_at,task_count:e.task_count??0,manifest:_n(e.manifest),source:bn(e.source),gate:gn(e.gate)}}function yn(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;return typeof t.outcome!="string"?null:{outcome:t.outcome,flaky:t.flaky===true,reasons:Array.isArray(t.reasons)?t.reasons.filter(s=>typeof s=="string"):[],ran_at:typeof t.ran_at=="string"?t.ran_at:null}}function hn(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,gate:yn(e.gate)}}function kn(e){return {action:e.action,type:e.type,job_id:e.job_id}}function vn(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 wn(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 ae(e){return typeof e=="number"?e:null}function P(e){let t=e.trials??{};return {id:e.id,job_name:e.job_name,status:e.status,datasets:(e.datasets??[]).map(He),agents:(e.agents??[]).map(We),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:vn(e.retry),timeout_multiplier:typeof e.timeout_multiplier=="number"?e.timeout_multiplier:1,agent_timeout_multiplier:ae(e.agent_timeout_multiplier),verifier_timeout_multiplier:ae(e.verifier_timeout_multiplier),agent_setup_timeout_multiplier:ae(e.agent_setup_timeout_multiplier),environment_build_timeout_multiplier:ae(e.environment_build_timeout_multiplier),sandbox_provider:e.sandbox_provider,counts:e.counts,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(kn),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 $(e,t){let s=e??{};return {items:Array.isArray(s.items)?s.items.map(t):[],nextCursor:s.nextCursor??null,hasMore:s.hasMore===true}}function O(e,t){let s=new URLSearchParams;e?.limit!==void 0&&s.set("limit",String(e.limit)),e?.cursor&&s.set("cursor",e.cursor);for(let[r,a]of Object.entries(t??{}))a!==void 0&&s.set(r,a);let n=s.toString();return n?`?${n}`:""}function ie(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 Sn(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 Rn(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let{from:t,to:s,reason:n}=e;return typeof t!="string"||typeof s!="string"||typeof n!="string"?null:{from:t,to:s,reason:n}}function Se(e){return {id:e.id,job_id:e.job_id,task_name:e.task_name,source:e.source,agent_info:Sn(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:ie(e.environment_setup),agent_setup:ie(e.agent_setup),agent_execution:ie(e.agent_execution),verifier:ie(e.verifier),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,max_trial_spend_usd:e.max_trial_spend_usd??null,sandbox_provider:e.sandbox_provider??null,sandbox_provider_degrade:Rn(e.sandbox_provider_degrade),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(wn):[],session_ref:e.session_ref??null,started_at:e.started_at??null,finished_at:e.finished_at??null}}function oe(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 le(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 Ye(e){let t=e??{};return {scored:t.scored??0,total:t.total??0}}function xn(e){return {id:e.id,datasets:(e.datasets??[]).map(He),status:e.status,mean_reward:e.mean_reward??null,coverage:Ye(e.coverage),cost_usd:e.cost_usd??0,agents:(e.agents||[]).map(We),started_at:e.started_at}}function An(e){return {job_id:e.job_id,status:e.status,mean_reward:e.mean_reward??null,coverage:Ye(e.coverage)}}function En(e){return {task_name:e.task_name,disagreement:e.disagreement===true,cells:(e.cells||[]).map(An)}}function Tn(e){return {seq:e.seq,type:e.type,data:e.data??{}}}function Re(e){if(e?.aborted)throw e.reason instanceof Error?e.reason:new Error("Watch aborted")}function Ge(e,t){return t?.aborted?true:e?.name==="AbortError"}function Y(e,t){return new Promise((s,n)=>{let r=setTimeout(()=>{t?.removeEventListener("abort",a),s();},e),a=()=>{clearTimeout(r),n(t?.reason instanceof Error?t.reason:new Error("Watch aborted"));};t?.addEventListener("abort",a,{once:true});})}function Pn(e){let t="",s=false;return {push(n){s&&(n="\r"+n,s=false),n.endsWith("\r")&&(n=n.slice(0,-1),s=true),t+=n.replace(/\r\n|\r/g,`
3
+ `);let r;for(;(r=t.indexOf(`
4
+
5
+ `))!==-1;){let a=t.slice(0,r);t=t.slice(r+2);let i,o,l=[];for(let u of a.split(`
6
+ `)){if(!u||u.startsWith(":"))continue;let c=u.indexOf(":"),g=c===-1?u:u.slice(0,c),d=c===-1?"":u.slice(c+1);d.startsWith(" ")&&(d=d.slice(1)),g==="id"?i=d:g==="event"?o=d:g==="data"&&l.push(d);}(i!==void 0||o!==void 0||l.length>0)&&e({id:i,event:o,data:l.join(`
7
+ `)});}}}}function L(e,t){let s,n=()=>s??=e({limit:t?.limit,cursor:t?.cursor});return {then(r,a){return n().then(r,a)},catch(r){return n().catch(r)},finally(r){return n().finally(r)},async*[Symbol.asyncIterator](){let r=t?.cursor;for(;;){let a=await e({limit:t?.limit,cursor:r});for(let i of a.items)yield i;if(!a.nextCursor)return;r=a.nextCursor;}}}}function X(e,t){let s=new FormData;for(let[n,r]of Object.entries(e))r!==void 0&&s.set(n,r);return t&&s.set("archive",new Blob([t.bytes],{type:"application/gzip"}),t.filename),s}function In(e){let t,s=()=>(t||(t=(async()=>{let n=await e.next();for(;!n.done;)n=await e.next();return n.value})()),t);return {then(n,r){return s().then(n,r)},catch(n){return s().catch(n)},finally(n){return s().finally(n)},[Symbol.asyncIterator](){return e}}}var ze="x-package-sha256",ue=class extends Error{constructor(s,n){super(`downloaded bytes do not match the digest the server stated (expected ${s}, got ${n})`);this.expected=s;this.actual=n;}name="EvolveDigestMismatchError"},ce=class extends Error{constructor(s,n){super(`download ended early: the server declared ${s} bytes and ${n} arrived`);this.expectedBytes=s;this.receivedBytes=n;}name="EvolveIncompleteDownloadError"};function Xe(e,t){let s=e.headers.get("Content-Length");if(s===null)return;let n=Number(s);if(Number.isFinite(n)&&t!==n)throw new ce(n,t)}async function Qe(e,t){let s=e.headers.get(ze);if(!s)return;let{createHash:n}=await import('crypto'),r=n("sha256").update(t).digest("hex");if(r!==s)throw new ue(s,r)}function $n(e,t){let n=(e.headers.get("Content-Disposition")||"").match(/filename="([^"]+)"/);if(!n)return t;let r=path.basename(n[1]);return r===""||r==="."||r===".."||/[/\\]/.test(r)||/[\u0000-\u001f]/.test(r)?t:r}async function Ze(e,t,s){if(!e.body)throw new Error("Download response has no body");await promises.mkdir(t,{recursive:true});let n=path.join(t,$n(e,s)),{createHash:r,randomBytes:a}=await import('crypto'),i=`${n}.${a(8).toString("hex")}.part`,o=r("sha256"),l=0,u=stream.Readable.fromWeb(e.body);u.on("data",c=>{o.update(c),l+=c.length;});try{await promises$1.pipeline(u,fs$1.createWriteStream(i));let c=e.headers.get("Content-Length");if(c!==null&&l!==Number(c))throw new ce(Number(c),l);let g=e.headers.get(ze),d=o.digest("hex");if(g&&d!==g)throw new ue(g,d);await promises.rename(i,n);}catch(c){throw await promises.rm(i,{force:true}).catch(()=>{}),c}return n}function F(e){let t=M("datasets",e);async function s(l){let u=await _(t,`/api/datasets/imports/${encodeURIComponent(l)}`);return le(await u.json())}function n(l){if(!l||typeof l!="object")return null;let u=l;return {git_url:u.git_url??null,ref:u.ref,current_commit:u.current_commit,path:u.path??null,latest_commit:u.latest_commit??null,acked_commit:u.acked_commit??null,moved:u.moved===true,behind_by:typeof u.behind_by=="number"?u.behind_by:null,checked_at:u.checked_at??null,error:u.error??null,auto_import:u.auto_import===true}}function r(l){return {name:l.name,title:l.title??null,description:l.description??null,active_version:l.active_version?re(l.active_version):null,versions:(l.versions||[]).map(re),selected_version:l.selected_version?re(l.selected_version):null,tasks:$(l.tasks,hn),upstream:n(l.upstream),created_at:l.created_at,updated_at:l.updated_at}}async function a(l,u){let c=Ve(l),g=O(u,{version:c.version}),d=await _(t,`/api/datasets/${encodeURIComponent(c.name)}${g}`);return r(await d.json())}function i(l){return {name:l.name,title:l.title??null,description:l.description??null,active_version:l.active_version?re(l.active_version):null,upstream:n(l.upstream)}}async function o(l){let u=await _(t,`/api/datasets${O(l,{search:l?.search})}`);return $(await u.json(),i)}return {list(l){return L(u=>o({...u,search:l?.search}),l)},get:a,async getActive(l,u){let c=await a(l,u);if(c.active_version===null)throw new we(l);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 publish(l){let u=l.source;if(u?.directory){if(l.name===void 0||l.version===void 0){let{existsSync:m}=await import('fs'),{join:b}=await import('path');if(!(m(b(u.directory,"dataset.toml"))||m(b(u.directory,"tasks","dataset.toml"))))throw new Error(`datasets().publish() needs ${l.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 Promise.resolve().then(()=>(W(),H)),g=await c(u.directory),d=await _(t,"/api/datasets/publish",{method:"POST",body:X({name:l.name,version:l.version},{bytes:g,filename:"corpus.tar.gz"})});return le(await d.json())}if(u&&"git_url"in u&&u.git_url){if(l.name===void 0||l.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 _(t,"/api/datasets/publish",{method:"POST",body:X({name:l.name,version:l.version,git_url:u.git_url,git_ref:u.git_ref,...u.git_path!==void 0?{git_path:u.git_path}:{}})});return le(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:s,async watchImport(l,u){let c=u?.pollIntervalMs??mn,g=null;for(;;){Re(u?.signal);let d;try{d=await s(l);}catch(m){if(m instanceof I&&(m.status===429||m.status===503)){await Y(Math.max((m.retryAfterSec??0)*1e3,c),u?.signal);continue}throw m}if(d.status!==g&&(g=d.status,u?.onStatus?.(d)),pn.has(d.status))return d;await Y(c,u?.signal);}},download:(async(l,u)=>{let c=Ve(l),g=c.version?`?version=${encodeURIComponent(c.version)}`:"",d=await _(t,`/api/datasets/${encodeURIComponent(c.name)}/download${g}`);if(u?.stream){if(!d.body)throw new Error("Package response has no body");return d.body}if(u?.to)return Ze(d,u.to,`${c.name}-corpus.tar.gz`);let m=Buffer.from(await d.arrayBuffer());return Xe(d,m.length),await Qe(d,m),m}),listImports(l){return L(async u=>{let c=new URLSearchParams;u.limit!==void 0&&c.set("limit",String(u.limit)),u.cursor!==void 0&&c.set("cursor",u.cursor),l?.status!==void 0&&c.set("status",l.status),l?.dataset!==void 0&&c.set("dataset",l.dataset);let g=c.toString()?`?${c}`:"",d=await _(t,`/api/datasets/imports${g}`);return $(await d.json(),le)},l)},async activate(l,u){let c=await _(t,`/api/datasets/${encodeURIComponent(l)}/versions/${encodeURIComponent(u)}/activate`,{method:"POST"});if(c.status===202){let g=await c.json();throw new z(l,u,typeof g.message=="string"?g.message:`Dataset "${l}" version "${u}" is still being proven by its activation gate`,on(g.gate))}return r(await c.json())},async update(l,u){let c=await _(t,`/api/datasets/${encodeURIComponent(l)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});return i(await c.json())},async delete(l){await _(t,`/api/datasets/${encodeURIComponent(l)}`,{method:"DELETE"});}}}function Q(e){let t=M("agents",e);return {async create(s){let n=await qe("agents().create()",s),r=await _(t,"/api/agents",{method:"POST",body:n});return oe(await r.json())},list(s){return L(async n=>{let r=await _(t,`/api/agents${O(n)}`);return $(await r.json(),oe)},s)},async get(s){let n=await _(t,`/api/agents/${encodeURIComponent(s)}`);return oe(await n.json())},async delete(s){await _(t,`/api/agents/${encodeURIComponent(s)}`,{method:"DELETE"});},async upsert(s,n){let r=await qe("agents().upsert()",{...n,name:s}),a=await _(t,`/api/agents/${encodeURIComponent(s)}`,{method:"PUT",body:r});return oe(await a.json())}}}async function qe(e,t){let s=typeof t.install_script=="string",n=typeof t.directory=="string";if(s&&n)throw new Error(`${e} takes EITHER an install script ({ install_script }) or a local directory ({ directory }), not both`);if(!s&&!n)throw new Error(`${e} requires either an install script ({ install_script }) or a local directory ({ directory }), plus run_command`);let r={name:t.name,run_command:t.run_command,...t.env!==void 0?{env:JSON.stringify(t.env)}:{},...s?{install_script:t.install_script}:{}};if(n){let{tarGzipDirectory:a}=await Promise.resolve().then(()=>(W(),H)),i=await a(t.directory);return X(r,{bytes:i,filename:"source.tar.gz"})}return X(r)}function ve(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 V(e){let t=M("skills",e);return {async upload(s){if(typeof s!="string"||!s.trim())throw new Error("skills().upload() requires a local skill directory path");let{tarGzipDirectory:n}=await Promise.resolve().then(()=>(W(),H)),{basename:r,resolve:a}=await import('path'),i=r(a(s)),o=await n(s),u=await(await _(t,"/api/skills",{method:"POST",body:X({name:i||void 0},{bytes:o,filename:"skill.tar.gz"})})).json();return (Array.isArray(u.skills)?u.skills:[u]).map(ve)},list(s){return L(async n=>{let r=await _(t,`/api/skills${O(n)}`);return $(await r.json(),ve)},s)},async get(s){let r=await(await _(t,`/api/skills/${encodeURIComponent(s)}`)).json();return {...ve(r),skill_md:r.skill_md??null}},async delete(s){await _(t,`/api/skills/${encodeURIComponent(s)}`,{method:"DELETE"});}}}function v(e){let t=M("jobs",e);async function s(o){let l=await _(t,`/api/jobs/${encodeURIComponent(o)}`);return P(await l.json())}async function n(o){let l=await _(t,`/api/jobs${O(o,{search:o?.search})}`);return $(await l.json(),P)}function r(o){let l=o.trials??{};return {task_name:o.task_name,source:o.source,trials:{total:l.total??0,byStatus:l.byStatus??{}},mean_reward:o.mean_reward??null,cost_usd:o.cost_usd??null}}async function a(o,l){let u=O(l,{status:l?.status?.length?l.status.join(","):void 0,dataset:l?.dataset}),c=await _(t,`/api/jobs/${encodeURIComponent(o)}/trials${u}`);return $(await c.json(),Se)}async function*i(o,l){let{onEvent:u,signal:c}=l??{},g=l?.reconnectDelayMs??ln,d=l?.maxReconnectDelayMs??un,m=null,b=false,x=false,f=g;for(;!b;){Re(c);let y;try{y=await fetch(`${t.baseUrl}/api/jobs/${encodeURIComponent(o)}/events`,{headers:{Authorization:`Bearer ${t.apiKey}`,Accept:"text/event-stream",...m!==null?{"Last-Event-ID":String(m)}:{}},signal:c});}catch(k){if(Ge(k,c))throw k;await Y(f,c),f=Math.min(f*2,d);continue}if(!y.ok){if(y.status===429||y.status>=500){let k=await y.text().catch(()=>""),T=Be(k,y)??0,j=T>0?Math.max(T*1e3,f):f;await Y(j,c),f=Math.min(f*2,d);continue}await Ke(y);}if(!y.body)throw new Error("Event stream response has no body");let w=false,U=[],Dt=Pn(k=>{let T=Number(k.id),j={seq:Number.isInteger(T)?T:-1,type:k.event||"message",data:k.data?Cn(k.data):{}};Number.isInteger(T)&&(m=T),w=true,dn.has(j.type)&&(b=true),U.push(j);}),Le=y.body.getReader(),jt=new TextDecoder;try{for(;!b;){let{done:k,value:T}=await Le.read();if(k)break;Dt.push(jt.decode(T,{stream:!0}));for(let j of U)u?.(j),yield j;U.length=0;}}catch(k){if(Ge(k,c))throw k}finally{await Le.cancel().catch(()=>{});}if(b)break;Re(c);let Je=await s(o);if(cn.has(Je.status)){if(x)return Je;x=true;continue}w&&(f=g),await Y(f,c),f=Math.min(f*2,d);}return s(o)}return {async start(o,l){let u=await _(t,"/api/jobs",{method:"POST",headers:{"Content-Type":"application/json",...l?.idempotencyKey?{"Idempotency-Key":l.idempotencyKey}:{}},body:JSON.stringify(o)});return P(await u.json())},get:s,list(o){return L(l=>n({...l,search:o?.search}),o)},trials(o,l){return L(u=>a(o,{...u,status:l?.status,dataset:l?.dataset}),l)},tasks(o,l){return L(async u=>{let c=await _(t,`/api/jobs/${encodeURIComponent(o)}/tasks${O(u)}`);return $(await c.json(),r)},l)},watch(o,l){return In(i(o,l))},async cancel(o){let l=await _(t,`/api/jobs/${encodeURIComponent(o)}/cancel`,{method:"POST"});return P(await l.json())},async compare(o){let l=o.map(encodeURIComponent).join(","),c=await(await _(t,`/api/jobs/compare?ids=${l}`)).json();return {jobs:(c.jobs||[]).map(xn),taskMatrix:(c.taskMatrix||[]).map(En)}},async resume(o,l,u){let c=await _(t,`/api/jobs/${encodeURIComponent(o)}/resume`,{method:"POST",headers:{"Content-Type":"application/json",...u?.idempotencyKey?{"Idempotency-Key":u.idempotencyKey}:{}},body:JSON.stringify(l??{})});return P(await c.json())},async retry(o,l,u){let c=await _(t,`/api/jobs/${encodeURIComponent(o)}/retry`,{method:"POST",headers:{"Content-Type":"application/json",...u?.idempotencyKey?{"Idempotency-Key":u.idempotencyKey}:{}},body:JSON.stringify(l??{})});return P(await c.json())},async regrade(o,l){let u={};l?.statuses?.length&&(u.statuses=l.statuses),l?.task_name!==void 0&&(u.task_name=l.task_name);let c=await _(t,`/api/jobs/${encodeURIComponent(o)}/regrade`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u)});return P(await c.json())},download:(async(o,l)=>{let u=await _(t,`/api/jobs/${encodeURIComponent(o)}/download`);if(l?.stream){if(!u.body)throw new Error("Download response has no body");return u.body}if(l?.to)return Ze(u,l.to,`job-${o}-results.tar.gz`);let c=Buffer.from(await u.arrayBuffer());return Xe(u,c.length),await Qe(u,c),c})}}function J(e){let t=M("trials",e);async function s(r,a){let i=await _(t,`/api/trials/${encodeURIComponent(r)}/trace${O(a)}`);return $(await i.json(),Tn)}async function n(r,a){let o=await(await _(t,`/api/trials/${encodeURIComponent(r)}/trace?stream=${a}`)).json();return a==="agent-home"?o.files??null:o.log??null}return {async get(r){let a=await _(t,`/api/trials/${encodeURIComponent(r)}`);return Se(await a.json())},trace:s,artifact:n,async*traceEvents(r,a){let i=a?.cursor;for(;;){let o=await s(r,{cursor:i,limit:a?.limit});for(let l of o.items)yield l;if(!o.nextCursor)return;i=o.nextCursor;}},async regrade(r){let a=await _(t,`/api/trials/${encodeURIComponent(r)}/regrade`,{method:"POST"});return P(await a.json())},async retry(r,a){let i=await _(t,`/api/trials/${encodeURIComponent(r)}/retry`,{method:"POST",...a?.idempotencyKey?{headers:{"Idempotency-Key":a.idempotencyKey}}:{}});return P(await i.json())},async stop(r){let i=await(await _(t,"/api/trials/stop",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({trial_ids:r})})).json();return {stopped:(i.stopped??[]).map(Se),already_terminal:i.already_terminal??[],not_found:i.not_found??[]}}}}function et(e){let t=M("auth",e);return {async status(){let n=await(await _(t,"/api/auth/status")).json(),r=n.key??{};return {user_id:n.user_id,email:n.email??null,key:{id:r.id,label:r.label??null,created_at:r.created_at,last_used_at:r.last_used_at??null}}}}}function Cn(e){try{let t=JSON.parse(e);return t&&typeof t=="object"?t:{value:t}}catch{return {raw:e}}}var p=class extends Error{constructor(t){super(t),this.name="CliUsageError";}},Oe={json:{kind:"boolean",help:"Machine-readable JSON output"},"api-key":{kind:"string",value:"<key>",help:"API key (default: $EVOLVE_API_KEY)"},"base-url":{kind:"string",value:"<url>",help:"API base URL (default: the Evolve dashboard API)"}},G={limit:{kind:"number",short:"l",value:"<n>",help:"Page size"},cursor:{kind:"string",value:"<c>",help:"Resume from a page cursor"},columns:{kind:"string",value:"<keys|all|help>",help:"Choose and order columns (comma-separated keys; 'help' lists them)"},quiet:{kind:"boolean",short:"q",help:"Print only ids, one per line (for piping)"},"no-trunc":{kind:"boolean",help:"Full cell content instead of one-line truncation"},"no-headers":{kind:"boolean",help:"Omit the header row in piped (TSV) output"}},ht={config:{kind:"string",short:"c",value:"<path>",help:"Job config file (YAML or JSON, spec vocabulary); explicit flags override its fields"},"print-config":{kind:"boolean",help:"Print the resolved job body as JSON and exit without running"},"job-name":{kind:"string",value:"<name>",help:"User-facing label (server-generated when omitted)"},dataset:{kind:"repeat",short:"d",value:"<name[@version]>",help:"Dataset to run (repeatable; bare name = active version)"},"include-task-name":{kind:"repeat",short:"i",value:"<glob>",help:"Include filter over task names, applied to every dataset (repeatable)"},"exclude-task-name":{kind:"repeat",short:"x",value:"<glob>",help:"Exclude filter over task names, applied to every dataset (repeatable)"},"n-tasks":{kind:"number",short:"l",value:"<n>",help:"Cap the task count of EACH dataset after filters"},agent:{kind:"string",short:"a",value:"<name[@version]>",help:"Agent (built-in or registered)"},model:{kind:"repeat",short:"m",value:"<name>",help:"Model (repeatable; each model is one arm)"},effort:{kind:"string",value:"<value>",help:"Reasoning effort for EVERY arm (values: GET /api/meta). Applied verbatim \u2014 an agent that cannot honor it is refused by the server, never silently skipped"},preset:{kind:"string",value:"<name>",help:"Named settings preset for EVERY arm: no-internet (vendor server-side web tools off) or pinned-context (fixed context window). Applied verbatim \u2014 an agent that cannot guarantee it is refused by the server, never silently skipped"},ak:{kind:"repeat",aliases:["agent-kwarg"],value:"key=value",help:"Agent kwarg for EVERY arm (repeatable, Harbor grammar). The delivered key is 'config': --ak 'config=<path|inline JSON>' becomes the harness's native settings file (user config is the base, platform routing on top); the server refuses unsupported kwargs and config keys touching billing/base-URL/routing/env"},skill:{kind:"repeat",aliases:["skills"],value:"<ref|path>",help:"Skill for EVERY agent arm (repeatable): skills.sh/<owner>/<repo>[/<skill>], org/repo[@ref], an https git URL, upload:<id>, name:<skill-name> (your moving name pointer, resolved server-side), or a local folder (uploaded to the platform first, then referenced)"},"agent-env":{kind:"repeat",aliases:["ae"],value:"KEY=VALUE",help:"Env for every agent run (repeatable); a pass-through slot the server owns"},"verifier-env":{kind:"repeat",aliases:["ve"],value:"KEY=VALUE",help:"Env for every verifier run (repeatable); the server honors exactly REWARDKIT_JUDGE and REWARDKIT_MODEL (rewardkit's judge override) and refuses any other key"},"n-attempts":{kind:"number",short:"k",value:"<n>",help:"Attempts per task x arm (default 1)"},"n-concurrent":{kind:"number",short:"n",value:"<n>",help:"Parallel trials (default 4)"},"max-trial-spend":{kind:"number",value:"<usd>",help:"Model-spend cap for EACH trial (default: the server's, $200)"},"max-retries":{kind:"number",short:"r",value:"<n>",help:"Max automatic retries per trial on infrastructure errors (default: the server's fleet default; 0 = off). Each attempt carries the full trial cap"},"retry-include":{kind:"repeat",value:"<exception>",help:"Exception types to retry on (repeatable; default: everything --retry-exclude admits)"},"retry-exclude":{kind:"repeat",value:"<exception>",help:"Exception types to NOT retry on (repeatable; wins over --retry-include; default: Harbor's non-retryable set)"},"timeout-multiplier":{kind:"number",value:"<x>",help:"Multiplier for task timeouts (default 1.0; > 0, server ceiling on GET /api/meta). Multiplies each task's DECLARED timeouts for this job only \u2014 the task is never rewritten"},"agent-timeout-multiplier":{kind:"number",value:"<x>",help:"Multiplier for agent execution timeout (overrides --timeout-multiplier)"},"verifier-timeout-multiplier":{kind:"number",value:"<x>",help:"Multiplier for verifier timeout (overrides --timeout-multiplier)"},"agent-setup-timeout-multiplier":{kind:"number",value:"<x>",help:"Multiplier for agent setup timeout (overrides --timeout-multiplier)"},"environment-build-timeout-multiplier":{kind:"number",value:"<x>",help:"Multiplier for environment build timeout (overrides --timeout-multiplier)"},env:{kind:"string",short:"e",value:"<provider>",help:"Sandbox provider: e2b | daytona | modal (default e2b)"},watch:{kind:"boolean",help:"Stream events until the job finishes"},quiet:{kind:"boolean",short:"q",help:"With --watch: suppress the event log, print the final block only"},yes:{kind:"boolean",short:"y",help:"Accepted for compatibility; hosted runs have no prompt to confirm"}},ge={job:{summary:"Start, follow, and derive jobs",commands:{start:{summary:"Start a job (add --watch to follow it)",flags:ht,minPositionals:0,maxPositionals:0,example:"evolve job start -d deep-swe@1.1 -a codex -m gpt-5.5 -k 2 --watch"},list:{summary:"List your jobs (newest first)",flags:{...G,search:{kind:"string",value:"<text>",help:"Free-text filter over job name and dataset names"}},minPositionals:0,maxPositionals:0,example:"evolve job list --limit 20 -q"},show:{summary:"Show one or more jobs in full (incl. pass@k, once attempts settle)",flags:{},minPositionals:1,maxPositionals:1/0,positionalUsage:"<id> [id...]",example:"evolve job show cme12ab34"},trials:{summary:"List a job's trials",flags:{...G,status:{kind:"string",value:"<s1,s2,...>",help:"Filter by trial status (e.g. INFRASTRUCTURE_ERROR)"},dataset:{kind:"string",value:"<name>",help:"Filter to one dataset's trials"}},minPositionals:1,maxPositionals:1,positionalUsage:"<id>",example:"evolve job trials cme12ab34 --status FAILED,SCORING_ERROR"},tasks:{summary:"Per-task rollup of a job",flags:{...G},minPositionals:1,maxPositionals:1,positionalUsage:"<id>",example:"evolve job tasks cme12ab34"},compare:{summary:"Compare 2-10 jobs side by side",flags:{},minPositionals:2,maxPositionals:10,positionalUsage:"<id> <id> [...]",example:"evolve job compare cme12ab34 cme56cd78"},cancel:{summary:"Request cancellation of a job",flags:{},minPositionals:1,maxPositionals:1,positionalUsage:"<id>",example:"evolve job cancel cme12ab34"},stop:{summary:"Stop one dataset's live trials without cancelling the job",flags:{dataset:{kind:"string",value:"<name>",help:"The dataset whose live trials to stop (required)"}},minPositionals:1,maxPositionals:1,positionalUsage:"<id>",example:"evolve job stop cme12ab34 --dataset deep-swe"},resume:{summary:"New linked job over a terminal job's failed or stopped trials",flags:{"filter-error-type":{kind:"repeat",short:"f",value:"<type>",help:"Failure types to resume, matched on exception_info.exception_type (repeatable; default: the standard failure set plus stopped trials)"}},minPositionals:1,maxPositionals:1,positionalUsage:"<id>",example:"evolve job resume cme12ab34 -f InfrastructureError"},retry:{summary:"New linked job re-running selected trials (all, failed-only, or named ids)",flags:{"failed-only":{kind:"boolean",help:"Only retry failed trials (SCORING_ERROR, INFRASTRUCTURE_ERROR, INDETERMINATE); stopped and scored trials are not failures"},trial:{kind:"repeat",short:"t",value:"<trial-id>",help:"Retry exactly this trial (repeatable, all-or-nothing; each must be settled, the job may still be running). Not combinable with --failed-only"}},minPositionals:1,maxPositionals:1,positionalUsage:"<id>",example:"evolve job retry cme12ab34 --failed-only"},regrade:{summary:"Verifier-only re-run of a terminal job (the result IS a job)",flags:{status:{kind:"string",value:"<s1,s2,...>",help:"Only regrade source trials in these statuses"},task:{kind:"string",value:"<name>",help:"Only regrade source trials of this task"}},minPositionals:1,maxPositionals:1,positionalUsage:"<id>",example:"evolve job regrade cme12ab34 --task tricky-task"},download:{summary:"Download the job's results, unpacked as the standard job-directory tree",flags:{"output-dir":{kind:"string",short:"o",value:"<dir>",help:"Directory to unpack into (default: current dir); the tree lands in <dir>/job-<id>/"},overwrite:{kind:"boolean",help:"Replace an existing <dir>/job-<id>/"}},minPositionals:1,maxPositionals:1,positionalUsage:"<id>",example:"evolve job download cme12ab34 -o results/"}}},trial:{summary:"Inspect, download, and act on single trials",commands:{show:{summary:"Show one trial in full detail",flags:{},minPositionals:1,maxPositionals:1,positionalUsage:"<trial-id>",example:"evolve trial show cmt90ef12"},download:{summary:"Save everything a trial recorded, or stream one artifact",flags:{"output-dir":{kind:"string",short:"o",value:"<dir>",help:"Directory to save under (default: trials/); files land in <dir>/<trial-id>/"},overwrite:{kind:"boolean",help:"Replace an existing <dir>/<trial-id>/"},stream:{kind:"string",value:"<artifact>",help:"Print ONE artifact to stdout instead of saving: trace-parsed | verifier | trace-stdout | trace-stderr | trace-atif (the ATIF trajectory) | trajectory (reserved: the harness-native session file) | agent-home"},cursor:{kind:"string",value:"<seq>",help:"With --stream trace-parsed: resume after this seq"},limit:{kind:"number",value:"<n>",help:"With --stream trace-parsed: max events per page"}},minPositionals:1,maxPositionals:1,positionalUsage:"<trial-id>",example:"evolve trial download cmt90ef12 --stream trace-stdout"},retry:{summary:"Run one settled trial again (the result IS a job)",flags:{},minPositionals:1,maxPositionals:1,positionalUsage:"<trial-id>",example:"evolve trial retry cmt90ef12"},regrade:{summary:"Verifier-only re-run of one trial (the result IS a job)",flags:{},minPositionals:1,maxPositionals:1,positionalUsage:"<trial-id>",example:"evolve trial regrade cmt90ef12"},stop:{summary:"Stop in-flight trials without cancelling their job",flags:{},minPositionals:1,maxPositionals:1/0,positionalUsage:"<trial-id> [trial-id...]",example:"evolve trial stop cmt90ef12 cmt34gh56"}}},dataset:{summary:"Browse and publish the dataset catalog",commands:{list:{summary:"List the dataset catalog",flags:{...G,search:{kind:"string",value:"<text>",help:"Free-text filter over name and description"}},minPositionals:0,maxPositionals:0,example:"evolve dataset list -q"},show:{summary:"Show one dataset (versions + tasks + providers)",flags:{limit:{kind:"number",short:"l",value:"<n>",help:"Task-list page size"},cursor:{kind:"string",value:"<c>",help:"Resume the task list from a cursor"}},minPositionals:1,maxPositionals:1,positionalUsage:"<name[@version]>",example:"evolve dataset show deep-swe@1.1"},publish:{summary:"Publish a dataset version from a git source or a local directory",flags:{git:{kind:"string",value:"<url>",help:"Git repository URL (with --ref)"},ref:{kind:"string",value:"<ref>",help:"Pinned git ref: a full 40-hex commit sha, or a tag (resolved to its commit at publish and verified at import). Branch names are refused \u2014 unpinned_git_ref (with --git)"},path:{kind:"string",value:"<subfolder>",help:"Repository subfolder holding the corpus (with --git; sparse checkout \u2014 only that folder is imported)"},dir:{kind:"string",value:"<path>",help:"Local corpus directory (tarred + uploaded)"},name:{kind:"string",value:"<dataset>",help:"Catalog dataset name to create or extend (optional with --dir when the corpus carries a dataset.toml manifest; required with --git)"},version:{kind:"string",value:"<v>",help:"Version label for the published version (optional with --dir when dataset.toml declares one; required with --git)"},watch:{kind:"boolean",help:"Poll until the publish is COMPLETED or FAILED"}},minPositionals:0,maxPositionals:0,example:"evolve dataset publish --name my-swe --version 1.0 --dir ./corpus --watch"},download:{summary:"Download the original corpus package (owner only)",flags:{"output-dir":{kind:"string",short:"o",value:"<dir>",help:"Directory to save into (default: current dir)"}},minPositionals:1,maxPositionals:1,positionalUsage:"<name[@version]>",example:"evolve dataset download my-swe@1.0 -o corpora/"},activate:{summary:"Make a READY version the dataset's active version",flags:{},minPositionals:2,maxPositionals:2,positionalUsage:"<name> <version>",example:"evolve dataset activate my-swe 1.0"}}},skill:{summary:"Upload and manage platform-stored skills",commands:{list:{summary:"List your uploaded skills (newest first)",flags:{...G},minPositionals:0,maxPositionals:0,example:"evolve skill list"},upload:{summary:"Upload a skill folder (its name becomes your moving name pointer)",flags:{},minPositionals:1,maxPositionals:1,positionalUsage:"<dir>",example:"evolve skill upload ./my-skill"},show:{summary:"Show one uploaded skill (metadata + SKILL.md)",flags:{},minPositionals:1,maxPositionals:1,positionalUsage:"<id | name:<skill-name>>",example:"evolve skill show name:my-skill"},delete:{summary:"Delete an uploaded skill record (past jobs keep their locks); refused (skill_in_use, 409) while a running job references it",flags:{},minPositionals:1,maxPositionals:1,positionalUsage:"<id>",example:"evolve skill delete 6f6f1f36-1c60-4f8e-9e2b-2a54cbb0f2aa"}}},agent:{summary:"Register and manage your own agents",commands:{list:{summary:"List your registered agents",flags:{...G},minPositionals:0,maxPositionals:0,example:"evolve agent list"},show:{summary:"Show one registered agent",flags:{},minPositionals:1,maxPositionals:1,positionalUsage:"<name>",example:"evolve agent show acme-cli"},add:{summary:"Register an agent (install script or local directory)",flags:{"install-script":{kind:"string",value:"<path>",help:"Install script file; its contents are uploaded"},dir:{kind:"string",value:"<path>",help:"Local agent directory (tarred + uploaded)"},run:{kind:"string",value:"<command>",help:"Run command, executed with sh -c (required)"},"agent-env":{kind:"repeat",aliases:["ae"],value:"KEY=VALUE",help:"Env injected at run time (repeatable)"}},minPositionals:1,maxPositionals:1,positionalUsage:"<name>",example:'evolve agent add acme-cli --install-script ./install.sh --run "acme-cli --headless"'},remove:{summary:"Delete a registered agent (past jobs keep their record)",flags:{},minPositionals:1,maxPositionals:1,positionalUsage:"<name>",example:"evolve agent remove acme-cli"}}},auth:{summary:"Identity and API keys",commands:{status:{summary:"Who am I: the caller and the API key in use",flags:{},minPositionals:0,maxPositionals:0,example:"evolve auth status"}}}},De={run:{summary:"Start a job (add --watch to follow it) \u2014 the short form of `job start`",flags:ht,minPositionals:0,maxPositionals:0,example:"evolve run -d deep-swe@1.1 -a codex -m gpt-5.5 -k 2 --watch"}},kt={jobs:"job",trials:"trial",datasets:"dataset",skills:"skill"},vt={agents:'"agents" is reserved for the managed-agents CLI (not released yet) \u2014 for eval agent arms use "evolve agent"'},wt={ls:"list"};function Nn(e,t){return `${[...t.short?[`-${t.short}`]:[],...(t.aliases??[]).map(n=>`--${n}`),`--${e}`].join(", ")}${t.value?` ${t.value}`:""}`}function Ae(e){let t=Object.entries(e);if(t.length===0)return [];let s=t.map(([r,a])=>Nn(r,a)),n=Math.min(Math.max(...s.map(r=>r.length)),36);return t.map(([,r],a)=>{let i=s[a];return i.length>n?` ${i}
8
+ ${"".padEnd(n)} ${r.help}`:` ${i.padEnd(n)} ${r.help}`})}function nt(e,t){let s=t.positionalUsage?` ${t.positionalUsage}`:"",n=Object.keys(t.flags).length>0?" [options]":"",r=[`Usage: evolve ${e}${s}${n}`,"",t.summary];return Object.keys(t.flags).length>0&&r.push("","Options:",...Ae(t.flags)),r.push("","Global options:",...Ae(Oe)),r.push("","Example:",` ${t.example}`),r.join(`
9
+ `)}function st(e){let t=ge[e],s=[`Usage: evolve ${e} <command> [options]`,"",t.summary,"","Commands:"],n=Math.max(...Object.keys(t.commands).map(r=>r.length));for(let[r,a]of Object.entries(t.commands))s.push(` ${r.padEnd(n)} ${a.summary}`);return s.push("",`Run "evolve ${e} <command> --help" for flags and an example.`),s.join(`
10
+ `)}function Ee(){let e=["evolve \u2014 Evolve hosted jobs CLI","","Usage: evolve <command> [options]","","Commands:"];for(let[t,s]of Object.entries(De))e.push(` ${t.padEnd(22)} ${s.summary}`);for(let[t,s]of Object.entries(ge)){let n=Object.keys(s.commands).join(" | ");e.push(` ${t.padEnd(22)} ${s.summary}`),e.push(` ${"".padEnd(22)} ${n}`);}return e.push(" help [command] Show help (also -h/--help on any command)","","Global options:",...Ae(Oe)," -v, --version Print the CLI version","","Example:"," evolve run -d deep-swe@1.1 -a codex -m gpt-5.5 --watch"),e.join(`
11
+ `)}var Ur=Ee();function Un(){try{return JSON.parse(fs$1.readFileSync(url.fileURLToPath(new URL("../../package.json",(typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)))),"utf-8")).version??"unknown"}catch{return "unknown"}}function Te(e,t){let s=[e.flags,Oe];for(let n of s)for(let[r,a]of Object.entries(n))if(t.long!==void 0){if(r===t.long||(a.aliases??[]).includes(t.long))return {name:r,flag:a}}else if(t.short!==void 0&&a.short===t.short)return {name:r,flag:a}}function Mn(e,t){if(t==="--help"||t==="-h")return true;if(t.startsWith("--")){let s=t.slice(2).split("=")[0];return Te(e,{long:s})!==void 0}if(t.startsWith("-")&&t.length>1){let s=t.slice(1).split("=")[0];return Te(e,{short:s})!==void 0}return false}function rt(e,t,s){let n={},r=[];for(let a=0;a<s.length;a++){let i=s[a];if(i==="--help"||i==="-h")return {command:"help",positionals:e.split(" "),flags:{}};let o,l;if(i.startsWith("--")){let m=i.slice(2),b=m.indexOf("=");b!==-1&&(l=m.slice(b+1),m=m.slice(0,b)),o={long:m};}else if(i.startsWith("-")&&i.length>1){let m=i.slice(1),b=m.indexOf("=");b!==-1&&(l=m.slice(b+1),m=m.slice(0,b)),o={short:m};}else {r.push(i);continue}let u=Te(t,o);if(!u)throw new p(`Unknown option ${i.split("=")[0]} for "${e}"`);let{name:c,flag:g}=u;if(g.kind==="boolean"){if(l!==void 0)throw new p(`Option --${c} takes no value`);n[c]=true;continue}let d=l;if(d===void 0){let m=s[a+1];if(m===void 0||Mn(t,m)){let b=m!==void 0?` (use --${c}=${m} if that is the value)`:"";throw new p(`Option --${c} requires a value${b}`)}d=m,a++;}if(g.kind==="number"){let m=Number(d);if(d.trim()===""||!Number.isFinite(m))throw new p(`Option --${c} expects a number, got "${d}"`);n[c]=m;}else if(g.kind==="repeat"){let m=n[c]??[];m.push(d),n[c]=m;}else n[c]=d;}if(r.length<t.minPositionals)throw new p(`"${e}" requires ${t.positionalUsage??`${t.minPositionals} argument(s)`}`);if(r.length>t.maxPositionals)throw new p(`"${e}" got unexpected argument "${r[t.maxPositionals]}"`);return {command:e,positionals:r,flags:n}}function Fn(e){if(e.length===0)return {command:"help",positionals:[],flags:{}};let t=e[0];if(t==="--help"||t==="-h"||t==="help")return {command:"help",positionals:e.slice(1),flags:{}};if(t==="--version"||t==="-v")return {command:"version",positionals:[],flags:{}};let s=De[t];if(s)return rt(t,s,e.slice(1));let n=vt[t];if(n)throw new p(n);let r=kt[t]??t,a=ge[r];if(!a)throw new p(`Unknown command "${t}"`);let i=e[1];if(i===void 0||i==="--help"||i==="-h")return {command:"help",positionals:[r],flags:{}};if(i.startsWith("-"))throw new p(`"${r}" requires a command (run "evolve ${r} --help")`);let o=wt[i]??i,l=a.commands[o];if(!l)throw new p(`Unknown command "${r} ${i}" (supported: ${Object.keys(a.commands).join(", ")})`);return rt(`${r} ${o}`,l,e.slice(2))}function Vn(e){return e.map(t=>typeof t=="object"&&t.tag==="tag:yaml.org,2002:bool"&&t.test?{...t,test:t.identify?.(true)?/^(?:[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/:/^(?:[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/}:t)}var Gn=/^(?:[-+]?[0-9][0-9_]*\.[0-9_]*|\.[0-9][0-9_]*)$/,qn=/^(?:[-+]?[0-9][0-9_]*\.[0-9_]*|\.[0-9][0-9_]*)[eE][-+][0-9]+$/;function Bn(e){return e.map(t=>typeof t!="object"||t.tag!=="tag:yaml.org,2002:float"||!t.test?t:t.test.test("1.5e+3")?{...t,test:qn}:t.test.test("1.5")?{...t,test:Gn}:t)}var Kn=/^[-+]?(?:0|[1-9][0-9_]*)$/,Hn=/^[-+]?[1-9][0-9_]*(?::[0-5]?[0-9])+$/;function Wn(e){return e.map(t=>typeof t!="object"||t.tag!=="tag:yaml.org,2002:int"||!t.test?t:t.test.test("1:00")?{...t,test:Hn}:t.test.test("19")?{...t,test:Kn}:t)}function Mr(e,t){return St(e,t).value}function St(e,t){let s=new yaml.LineCounter,n=yaml.parseDocument(e,{version:"1.1",schema:"yaml-1.1",resolveKnownTags:false,lineCounter:s,customTags:o=>Wn(Bn(Vn(o)))}),r=n.errors[0]??n.warnings[0];if(r){let o=r.linePos?.[0]?.line??1,l=r.code==="MULTIPLE_DOCS"?"multi-document YAML is not supported here \u2014 one config per file":r.message.replace(/ at line \d+, column \d+:[\s\S]*$/,"");throw new p(`${t}:${o}: ${l}`)}n.options.logLevel="silent";let a;try{a=n.toJS()??{};}catch(o){throw new p(`${t}: ${o.message}`)}return {value:a,locate:o=>{let u=n.getIn(o,true)?.range?.[0];return u===void 0?void 0:s.linePos(u).line}}}var Yn=["../../spec/openapi.yaml","../../../../spec/openapi.yaml"],de;function zn(){if(de)return de;let e=[];for(let t of Yn){let s=url.fileURLToPath(new URL(t,(typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))));if(e.push(s),!fs$1.existsSync(s))continue;let r=yaml.parse(fs$1.readFileSync(s,"utf-8"))?.components?.schemas,a=r?.JobCreate;if(!r||!a||typeof a!="object")throw new Error(`${s} carries no components.schemas.JobCreate \u2014 the contract this CLI validates -c against`);return de={root:a,components:r},de}throw new Error(`spec/openapi.yaml not found (tried: ${e.join(", ")}) \u2014 the package ships it; reinstall the SDK`)}function Rt(e){let t=e.type;return typeof t=="string"?[t]:Array.isArray(t)?t.filter(s=>typeof s=="string"):[]}function je(e,t,s){let n=e.$ref;if(typeof n!="string")return {schema:e,specName:s};let r=n.replace("#/components/schemas/",""),a=t[r];if(!a)throw new Error(`spec/openapi.yaml: unresolvable $ref "${n}"`);return je(a,t,r)}function Xn(e){return e.length===1&&typeof e[0]=="string"?`"${e[0]}"`:e.map((t,s)=>typeof t=="number"?`[${t}]`:s===0?t:`.${t}`).join("")}function xt(e,t){let s=t.locate?.(e),n=`${t.source}${s!==void 0?`:${s}`:""}`;return e.length===0?n:`${Xn(e)} in ${n}`}function S(e,t,s,n){throw new p(`--config: ${xt(e,t)} ${s} [spec: ${n}]`)}function Qn(e){for(let t=e.length-1;t>=0;t--)if(typeof e[t]=="string")return e[t];return "value"}function Zn(e,t){if(!e)return "a list";let s=je(e,t.components,""),n=Rt(s.schema);return n.includes("string")?"a list of strings":n.includes("object")?"a list of objects":"a list"}function me(e,t,s,n,r,a=false){let{schema:i,specName:o}=je(t,r.components,n),l=Rt(i),u=c=>o?`${o}.${c}`:c;if(e===null){if(l.includes("null"))return;S(s,r,`must be a ${l[0]??"value"}, not null`,o);}if(l.includes("object")){let c=q(i.additionalProperties)?i.additionalProperties:void 0;if(!q(e)){let d=c&&!i.properties?`must be a map of KEY: "value" pairs, not ${N(e)}`:`must be an object like {${es(i)}: "..."}, not ${N(e)}`;S(s,r,d,o);}let g=q(i.properties)?i.properties:void 0;if(g){if(!a&&Array.isArray(i.required))for(let d of i.required)typeof d=="string"&&e[d]===void 0&&S(s,r,`is missing the required key "${d}"`,o);for(let d of Object.keys(e))if(g[d]===void 0&&!c)throw new p(`--config: unknown key "${d}" in ${xt([...s,d],r)} (allowed: ${Object.keys(g).join(", ")}) [spec: ${o}]`);for(let[d,m]of Object.entries(g)){let b=e[d];b!==void 0&&me(b,m,[...s,d],u(d),r);}}if(c)for(let[d,m]of Object.entries(e))g?.[d]===void 0&&me(m,c,[...s,d],o,r);return}if(l.includes("array")){let c=q(i.items)?i.items:void 0;Array.isArray(e)||S(s,r,`must be ${Zn(c,r)}, not ${N(e)}`,o),typeof i.minItems=="number"&&e.length<i.minItems&&S(s,r,`needs at least ${i.minItems} ${i.minItems===1?"entry":"entries"}`,o),typeof i.maxItems=="number"&&e.length>i.maxItems&&S(s,r,`takes at most ${i.maxItems} entries`,o),c&&e.forEach((g,d)=>me(g,c,[...s,d],o,r));return}if(Array.isArray(i.enum)){i.enum.includes(e)||S(s,r,`must be one of: ${i.enum.join(", ")}`,o);return}if(l.includes("string")){typeof e!="string"&&S(s,r,`must be a string, not ${N(e)} \u2014 quote it (${Qn(s)}: "...")`,o),typeof i.maxLength=="number"&&e.length>i.maxLength&&S(s,r,`must be at most ${i.maxLength} characters (got ${e.length})`,o);return}if(l.includes("integer")||l.includes("number")){let c=l.includes("integer");(typeof e!="number"||c&&!Number.isInteger(e))&&S(s,r,`must be ${c?"an integer":"a number"}, not ${N(e)}`,o),typeof i.minimum=="number"&&e<i.minimum&&S(s,r,`must be at least ${i.minimum}`,o),typeof i.maximum=="number"&&e>i.maximum&&S(s,r,`must be at most ${i.maximum}`,o);return}l.includes("boolean")&&typeof e!="boolean"&&S(s,r,`must be a boolean, not ${N(e)}`,o);}function es(e){let t=Array.isArray(e.required)?e.required[0]:void 0;return typeof t=="string"?t:(q(e.properties)?Object.keys(e.properties):[])[0]??"name"}function ts(e,t,s){let{root:n,components:r}=zn();me(e,n,[],"JobCreate",{source:t,locate:s,components:r},true);}function N(e){return e===null?"null":Array.isArray(e)?"a list":typeof e=="object"?`a ${e.constructor?.name??"object"}`:`a ${typeof e}`}function q(e){if(typeof e!="object"||e===null||Array.isArray(e))return false;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Pe(e,t,s,n=new WeakSet){if(!(e===null||typeof e=="string"||typeof e=="boolean")){if(typeof e=="number"){if(Number.isFinite(e))return;throw new p(`--config: ${t} in ${s} is ${Number.isNaN(e)?".nan":"infinite"} \u2014 a JSON body carries finite numbers only`)}if(Array.isArray(e)||q(e)){if(n.has(e))throw new p(`--config: ${t} in ${s} is an alias of a value that contains it \u2014 a JSON body cannot carry a cycle`);if(n.add(e),Array.isArray(e))e.forEach((r,a)=>Pe(r,`${t}[${a}]`,s,n));else for(let[r,a]of Object.entries(e))Pe(a,`${t}.${r}`,s,n);n.delete(e);return}throw new p(`--config: ${t} in ${s} resolved to ${N(e)}, which a JSON body cannot carry \u2014 quote the value to keep it text`)}}function ns(e,t){let s;try{s=t(e);}catch(i){throw new p(`--config: cannot read ${e}: ${i.message}`)}let n,r;if(e.endsWith(".json"))try{n=JSON.parse(s);}catch(i){throw new p(`--config: ${e} is not valid JSON: ${i.message}`)}else ({value:n,locate:r}=St(s,e));if(!n||typeof n!="object"||Array.isArray(n))throw new p(`--config: ${e} must contain a JSON/YAML object`);let a=n;for(let[i,o]of Object.entries(a))Pe(o,i,e);return ts(a,e,r),n}function at(e,t){let s=e.indexOf("@");if(s===-1)return {name:e};let n=e.slice(0,s),r=e.slice(s+1);if(!n||!r)throw new p(`Invalid ${t} "${e}": expected name or name@version`);return {name:n,version:r}}function ss(e){let t=e.trim();try{return JSON.parse(t)}catch{return t==="True"?true:t==="False"?false:t==="None"?null:t}}function rs(e,t=s=>fs$1.readFileSync(s,"utf-8")){let s={};for(let n of e){let r=n.indexOf("=");if(r<=0)throw new p(`Invalid --ak "${n}": expected key=value`);let a=n.slice(0,r).trim(),i=ss(n.slice(r+1));a==="config"&&typeof i=="string"&&(i=as(i,t)),s[a]=i;}return s}function as(e,t){let s;try{s=t(e);}catch(r){throw new p(`--ak config: cannot read ${e}: ${r.message}`)}let n;if(e.endsWith(".toml"))try{n=smolToml.parse(s);}catch(r){throw new p(`--ak config: ${e} is not valid TOML: ${r.message}`)}else if(e.endsWith(".json"))try{n=JSON.parse(s);}catch(r){throw new p(`--ak config: ${e} is not valid JSON: ${r.message}`)}else try{n=JSON.parse(s);}catch{try{n=smolToml.parse(s);}catch{throw new p(`--ak config: ${e} parses as neither JSON nor TOML; use a .json or .toml settings file`)}}if(!n||typeof n!="object"||Array.isArray(n))throw new p(`--ak config: ${e} must contain a settings object`);return n}function Ie(e,t){let s={};for(let n of e){let r=n.indexOf("=");if(r<=0)throw new p(`Invalid ${t} "${n}": expected KEY=VALUE`);s[n.slice(0,r)]=n.slice(r+1);}return s}function is(e,t=s=>fs$1.readFileSync(s,"utf-8")){let s=e.flags,n=typeof s.config=="string"?ns(s.config,t):{},r;if(s.dataset!==void 0)r=s.dataset.map(f=>{let y=at(f,"--dataset");return {name:y.name,...y.version?{version:y.version}:{}}});else if(Array.isArray(n.datasets)&&n.datasets.length>0)r=n.datasets.map(f=>({...f}));else throw new p(`"${e.command}" requires -d/--dataset (or datasets in --config)`);if(s["include-task-name"]!==void 0)for(let f of r)f.task_names=s["include-task-name"];if(s["exclude-task-name"]!==void 0)for(let f of r)f.exclude_task_names=s["exclude-task-name"];if(s["n-tasks"]!==void 0)for(let f of r)f.n_tasks=s["n-tasks"];let a;if(s.agent!==void 0||s.model!==void 0){if(s.agent===void 0)throw new p("-m/--model requires -a/--agent");if(s.model===void 0)throw new p("-a/--agent requires at least one -m/--model (the server applies no model default)");let f=at(String(s.agent),"--agent");a=s.model.map(y=>({name:f.name,model_name:y,...f.version?{version:f.version}:{}}));}else if(Array.isArray(n.agents)&&n.agents.length>0)a=n.agents.map(f=>({...f}));else throw new p(`"${e.command}" requires -a/--agent and -m/--model (or agents in --config)`);if(s.effort!==void 0&&(a=a.map(f=>({...f,reasoning_effort:s.effort}))),s.ak!==void 0){let f=rs(s.ak,t);a=a.map(y=>({...y,kwargs:{...y.kwargs??{},...f}}));}s.preset!==void 0&&(a=a.map(f=>({...f,preset:s.preset}))),s.skill!==void 0&&(a=a.map(f=>({...f,skills:[...s.skill]})));let o=s["agent-env"]!==void 0?Ie(s["agent-env"],"--agent-env"):n.agent_env,l=s["verifier-env"]!==void 0?Ie(s["verifier-env"],"--verifier-env"):n.verifier_env,u=s["job-name"]!==void 0?String(s["job-name"]):n.job_name,c=s["n-attempts"]!==void 0?s["n-attempts"]:n.n_attempts,g=s["n-concurrent"]!==void 0?s["n-concurrent"]:n.n_concurrent_trials,d=s["max-trial-spend"]!==void 0?s["max-trial-spend"]:n.max_trial_spend_usd;if(s.env!==void 0&&!te.includes(String(s.env)))throw new p(`-e/--env must be one of: ${te.join(", ")}`);let m=s.env!==void 0?s.env:n.sandbox_provider,b={...n.retry??{}};s["max-retries"]!==void 0&&(b.max_retries=s["max-retries"]),s["retry-include"]!==void 0&&(b.include_exceptions=s["retry-include"]),s["retry-exclude"]!==void 0&&(b.exclude_exceptions=s["retry-exclude"]);let x={};for(let[f,y]of [["timeout-multiplier","timeout_multiplier"],["agent-timeout-multiplier","agent_timeout_multiplier"],["verifier-timeout-multiplier","verifier_timeout_multiplier"],["agent-setup-timeout-multiplier","agent_setup_timeout_multiplier"],["environment-build-timeout-multiplier","environment_build_timeout_multiplier"]]){let w=s[f]!==void 0?s[f]:n[y];w!==void 0&&(x[y]=w);}return {...u!==void 0?{job_name:u}:{},datasets:r,agents:a,...c!==void 0?{n_attempts:c}:{},...g!==void 0?{n_concurrent_trials:g}:{},...d!==void 0?{max_trial_spend_usd:d}:{},...m!==void 0?{sandbox_provider:m}:{},...Object.keys(b).length>0?{retry:b}:{},...x,...o!==void 0?{agent_env:o}:{},...l!==void 0?{verifier_env:l}:{}}}function os(e){let t=e.flags,s=typeof t.dir=="string",n=typeof t.git=="string"||typeof t.ref=="string"||typeof t.path=="string";if(s&&n)throw new p('"dataset publish" takes EITHER --dir OR --git/--ref/--path, not both');if(s)return {source:{directory:t.dir},...typeof t.name=="string"?{name:t.name}:{},...typeof t.version=="string"?{version:t.version}:{}};for(let r of ["git","ref","name","version"])if(typeof t[r]!="string"){let a=r==="git"||r==="ref"?" (or --dir for a local corpus directory)":" (a git source cannot take it from dataset.toml \u2014 the repository is only cloned after the publish is accepted)";throw new p(`"dataset publish" requires --${r}${a}`)}return {source:{git_url:t.git,git_ref:t.ref,...typeof t.path=="string"?{git_path:t.path}:{}},name:t.name,version:t.version}}function ls(e,t=s=>fs$1.readFileSync(s,"utf-8")){let s=e.flags,n=typeof s.dir=="string",r=typeof s["install-script"]=="string";if(n&&r)throw new p('"agent add" takes EITHER --dir OR --install-script, not both');if(!n&&!r)throw new p('"agent add" requires --install-script (or --dir for a local agent directory)');if(typeof s.run!="string")throw new p('"agent add" requires --run');let a=Ie(s["agent-env"]??[],"--agent-env");return {name:e.positionals[0],...n?{directory:s.dir}:{install_script:t(s["install-script"])},run_command:s.run,...Object.keys(a).length>0?{env:a}:{}}}var us={out:e=>process.stdout.write(e+`
12
+ `),err:e=>process.stderr.write(e+`
13
+ `),tty:process.stdout.isTTY===true&&process.env.TERM!=="dumb"};function R(e){if(e.length===0)return [];let t=[];for(let s of e)s.forEach((n,r)=>{t[r]=Math.max(t[r]??0,n.length);});return e.map(s=>s.map((n,r)=>n.padEnd(t[r])).join(" ").trimEnd())}function A(e){return typeof e=="number"?`$${e.toFixed(2)}`:"-"}function pe(e){let t=`${e.name}:${e.model_name}`;return e.version?`${t}:${e.version}`:t}function fe(e){return e.map(t=>`${t.name}@${t.version}`).join(", ")||"-"}function _e(e,t){return e.length>t?e.slice(0,t-1)+"\u2026":e}function xe(e){return e.replace(/[\t\n\r]+/g," ")}function B(e,t,s,n,r,a){if(e.flags.quiet===true){for(let l of s)t.out(a(l));return}let i=cs(e,n,r);if(t.tty===true){let l=e.flags["no-trunc"]===true,u=[i.map(c=>c.header)];for(let c of s)u.push(i.map(g=>l?xe(g.cell(c)):_e(xe(g.cell(c)),60)));for(let c of R(u))t.out(c);}else {e.flags["no-headers"]!==true&&t.out(i.map(l=>l.header).join(" "));for(let l of s)t.out(i.map(u=>xe(u.cell(l))).join(" "));}}function cs(e,t,s){let n=e.flags.columns;if(n===void 0)return s.map(a=>t.find(i=>i.key===a));if(n==="all")return t;let r=n.split(",").map(a=>a.trim()).filter(Boolean);if(r.length===0)throw new p("--columns got an empty column list");return r.map(a=>{let i=t.find(o=>o.key===a);if(!i)throw new p(`Unknown column "${a}" (available: ${t.map(o=>o.key).join(", ")}, or "all")`);return i})}function K(e,t,s){if(e.flags.columns!=="help")return false;for(let n of s)t.out(n.key);return true}function C(e){let t=[["id",e.id],["status",e.status],["datasets",fe(e.datasets)]];t.push(["agents",e.agents.map(pe).join(", ")]);for(let n of e.agents){n.skills.length>0&&t.push(["skills",`${pe(n)}: ${n.skills.join(", ")}`]);for(let r of n.skill_locks??[])t.push(["skill lock",`${r.name} @ ${r.git_commit_id?r.git_commit_id.slice(0,12):r.digest.slice(0,19)}`]);}t.push(["size",`${e.counts.agents} agent(s) x ${e.counts.tasks} task(s) = ${e.n_total_trials} trial(s)`]),t.push(["attempts/task",String(e.n_attempts)]),t.push(["concurrency",String(e.n_concurrent_trials)]),t.push(["max spend/trial",A(e.max_trial_spend_usd)]),t.push(["worst case",A(e.worst_case_spend_usd)]),t.push(["retries",`${e.retry.max_retries}/trial on infrastructure errors`+((e.stats.n_retries??0)>0?` (${e.stats.n_retries} used)`:"")]);{let r=[["agent",e.agent_timeout_multiplier],["verifier",e.verifier_timeout_multiplier],["agent setup",e.agent_setup_timeout_multiplier],["environment build",e.environment_build_timeout_multiplier]].filter(([,a])=>a!=null);(e.timeout_multiplier!==1||r.length>0)&&t.push(["timeouts",`x${e.timeout_multiplier}`+(r.length>0?` (${r.map(([a,i])=>`${a} x${i}`).join(", ")})`:"")]);}t.push(["provider",e.sandbox_provider]),t.push(["spent",A(e.stats.cost_usd)]),e.stats.gpu_cost_usd!=null&&t.push(["gpu compute (est.)",`$${e.stats.gpu_cost_usd.toFixed(4)}`]),e.stats.judge_cost_usd!=null&&e.stats.judge_cost_usd>0&&t.push(["spent (judge)",A(e.stats.judge_cost_usd)]);let s=Object.entries(e.trials.byStatus).filter(([,n])=>n>0).map(([n,r])=>`${n} ${r}`).join(" \xB7 ");s&&t.push(["trials",s]);for(let n of e.source_jobs)t.push([n.action==="regrade"?"regrade of":n.action==="retry"?"retry of":"resume of",n.job_id]);return e.idempotent_replay&&t.push(["note","idempotent replay of an existing job"]),e.failure&&t.push(["failure",`${e.failure.code}: ${e.failure.message}`]),t.push(["started",e.started_at]),t.push(["updated",e.updated_at]),[...R(t),...ds(e)]}function ds(e){let t=ye(e);if(t.length===0)return [];let s=t.map(n=>[` ${n.evals_key}`,n.points.map(r=>`pass@${r.k} ${r.value.toFixed(3)}`).join(" ")]);return ["","pass@k",...R(s)]}var it=[{key:"id",header:"ID",cell:e=>e.id},{key:"name",header:"NAME",cell:e=>e.job_name??"-"},{key:"status",header:"STATUS",cell:e=>e.status},{key:"datasets",header:"DATASETS",cell:e=>fe(e.datasets)},{key:"agents",header:"AGENTS",cell:e=>e.agents.map(pe).join(", ")},{key:"trials",header:"TRIALS",cell:e=>String(e.trials.total)},{key:"spent",header:"SPENT",cell:e=>A(e.stats.cost_usd)},{key:"started",header:"STARTED",cell:e=>e.started_at}],ms=["id","status","datasets","trials","spent","started"],ot=[{key:"task",header:"TASK",cell:e=>e.task_name},{key:"agent",header:"AGENT",cell:e=>pe({name:e.agent_info.name,model_name:e.agent_info.model_info.name,version:e.agent_info.version,reasoning_effort:e.agent_info.reasoning_effort??null})},{key:"attempt",header:"ATTEMPT",cell:e=>String(e.attempt)},{key:"status",header:"STATUS",cell:e=>e.status},{key:"reward",header:"REWARD",cell:e=>e.reward!==null?String(e.reward):"-"},{key:"spent",header:"SPENT",cell:e=>A(e.agent_result?.cost_usd)},{key:"gpu",header:"GPU (EST)",cell:e=>e.gpu_cost?.estimate_usd!=null?`$${e.gpu_cost.estimate_usd.toFixed(4)}`:"-"},{key:"id",header:"TRIAL ID",cell:e=>e.id}],ps=["task","agent","attempt","status","reward","spent","id"],lt=[{key:"task",header:"TASK",cell:e=>e.task_name},{key:"source",header:"DATASET",cell:e=>e.source},{key:"trials",header:"TRIALS",cell:e=>String(e.trials.total)},{key:"statuses",header:"STATUSES",cell:e=>Object.entries(e.trials.byStatus).filter(([,t])=>t>0).map(([t,s])=>`${t} ${s}`).join(" \xB7 ")||"-"},{key:"reward",header:"MEAN REWARD",cell:e=>$e(e.mean_reward)},{key:"spent",header:"SPENT",cell:e=>A(e.cost_usd)}],gs=["task","source","trials","statuses","reward","spent"],ut=[{key:"name",header:"NAME",cell:e=>e.name},{key:"active",header:"ACTIVE",cell:e=>e.active_version?.version??"-"},{key:"state",header:"STATE",cell:e=>e.active_version?.state??"-"},{key:"tasks",header:"TASKS",cell:e=>e.active_version?String(e.active_version.task_count):"-"},{key:"title",header:"TITLE",cell:e=>e.title??"-"}],fs=["name","active","state","tasks","title"];function _s(e){return e.length>19?`${e.slice(0,19)}\u2026`:e}function At(e){return e<1024?`${e}B`:e<1024*1024?`${(e/1024).toFixed(1)}KB`:`${(e/(1024*1024)).toFixed(1)}MB`}var ct=[{key:"name",header:"NAME",cell:e=>e.name},{key:"id",header:"ID",cell:e=>e.id},{key:"digest",header:"DIGEST",cell:e=>_s(e.digest)},{key:"size",header:"SIZE",cell:e=>At(e.size_bytes)},{key:"created",header:"CREATED",cell:e=>e.created_at},{key:"description",header:"DESCRIPTION",cell:e=>e.description??"-"},{key:"ref",header:"REF",cell:e=>e.ref}],bs=["name","id","digest","size","created"],dt=[{key:"name",header:"NAME",cell:e=>e.name},{key:"source",header:"SOURCE",cell:e=>e.source},{key:"run",header:"RUN COMMAND",cell:e=>e.run_command},{key:"updated",header:"UPDATED",cell:e=>e.updated_at}],ys=["name","source","run","updated"];function hs(e){let t=[["trial id",e.id],["job",e.job_id],["task",e.task_name],["dataset",e.source],["agent",`${e.agent_info.name}:${e.agent_info.model_info.name}`],["attempt",String(e.attempt)],["status",e.status],["reward",e.reward!==null?String(e.reward):"-"]],s=e.verifier_result?.rewards;if(s&&Object.keys(s).length>0&&t.push(["rewards",Object.entries(s).map(([n,r])=>`${n}=${r}`).join(" \xB7 ")]),t.push(["spent",A(e.agent_result?.cost_usd)]),e.judge_result&&t.push(["spent (judge)",A(e.judge_result.cost_usd)]),(e.status==="RUNNING"||e.status==="SCORING")&&e.live_spent_usd!==null){let n=e.live_spend_at?` as of ${e.live_spend_at}`:"";t.push(["spent (live)",`at least $${e.live_spent_usd.toFixed(4)}${n}`]);}if(e.attempt_phase&&t.push(["phase",e.attempt_phase]),e.sandbox_provider&&t.push(["provider",e.sandbox_provider]),e.sandbox_provider_degrade){let n=e.sandbox_provider_degrade;t.push(["provider degrade",`${n.from} \u2192 ${n.to}: ${n.reason}`]);}if(e.gpu_cost){let n=e.gpu_cost;if(n.estimate_usd!=null){let r=n.gpu_type??n.declared_gpu_type,a=n.duration_sec!=null?`${Math.round(n.duration_sec)}s`:"unmeasured",i=`rate card v${n.rate_card.version}${n.rate_card.source?`, ${n.rate_card.source} ${n.rate_card.source_date??""}`.trimEnd():""}`;t.push(["gpu compute (est.)",`$${n.estimate_usd.toFixed(4)} \u2014 ${r} x${n.gpu_count}, ${a} on ${n.provider} (${i})`]);}else t.push(["gpu compute (est.)",`not priced \u2014 ${n.unpriced_reason??"no reason recorded"}`]);}if(e.sandbox_id&&t.push(["sandbox",e.sandbox_id]),e.verifier_environment_mode&&t.push(["verifier",e.verifier_environment_mode]),e.verifier_sandbox_id&&t.push(["verifier sandbox",e.verifier_sandbox_id]),e.agent_info.version&&t.push(["agent version",e.agent_info.version]),e.exception_info&&(t.push(["failure type",e.exception_info.exception_type]),t.push(["failure detail",e.exception_info.exception_message])),e.n_retries>0){t.push(["auto-retries",String(e.n_retries)]);for(let n of e.retries)t.push([`attempt ${n.attempt_number}`,`${n.exception_info.exception_type} \xB7 spent ${A(n.cost_usd)}`+(n.settled_at?` \xB7 settled ${n.settled_at}`:"")]);}return e.session_ref&&t.push(["session",e.session_ref]),e.started_at&&t.push(["started",e.started_at]),e.finished_at&&t.push(["finished",e.finished_at]),R(t)}function Et(e){let t=[["name",e.name],["source",e.source],["run command",e.run_command]],s=Object.keys(e.env??{});return s.length>0&&t.push(["env",s.sort().join(", ")]),t.push(["created",e.created_at]),t.push(["updated",e.updated_at]),R(t)}var Tt=["e2b","daytona","modal"];function ks(e){return Tt.filter(t=>e?.[t]!==void 0).map(t=>{let s=e[t];return s.ok?s.degrades_to?`${t} \u2192${s.degrades_to}`:`${t} ok`:`${t} NO`}).join(" \xB7 ")}function vs(e){let t=e.gpus??0;if(t<=0)return null;let s=e.gpu_types&&e.gpu_types.length>0?e.gpu_types.join("|"):"any GPU";return `${t}x ${s}`}function $e(e){return e!==null?String(Math.round(e*1e3)/1e3):"-"}function ws(e){let t=_e(JSON.stringify(e.data??{}),140);return `#${String(e.seq).padStart(4)} ${e.type.padEnd(26)} ${t}`.trimEnd()}function Pt(e){let t=e.failures?.length?` (${e.failures.length} task failure${e.failures.length===1?"":"s"})`:"";return `${e.message}${t}`}function mt(e){let t=[["id",e.id],["status",e.status]];e.name!==void 0&&t.push(["dataset",e.name]),e.version!==void 0&&t.push(["version",e.version]),e.task_count!==void 0&&t.push(["tasks",String(e.task_count)]);for(let s of e.warnings)t.push(["warning",s.message??s.code]);if(e.failure){t.push(["failure",Pt(e.failure)]);for(let s of e.failure.failures??[])t.push([` ${s.task_name}`,s.error]);}return R(t)}function Ss(e){let t=[];return e.task_count!==void 0&&t.push(`tasks=${e.task_count}`),e.failure&&t.push(_e(Pt(e.failure),140)),`status ${e.status.padEnd(12)} ${t.join(" ")}`.trimEnd()}function Rs(e){let t={...e.data??{}},s=[];typeof t.trial_id=="string"&&s.push(t.trial_id),typeof t.task_name=="string"&&s.push(t.task_name),typeof t.status=="string"&&s.push(t.status),typeof t.reward=="number"&&s.push(`reward=${t.reward}`);let n=new Set(["trial_id","task_name","status","reward"]);for(let[a,i]of Object.entries(t))n.has(a)||s.push(`${a}=${typeof i=="object"?JSON.stringify(i):String(i)}`);let r=_e(s.join(" "),140);return `#${String(e.seq).padStart(4)} ${e.type.padEnd(26)} ${r}`.trimEnd()}function h(e){let t={};return typeof e.flags["api-key"]=="string"&&(t.apiKey=e.flags["api-key"]),typeof e.flags["base-url"]=="string"&&(t.baseUrl=e.flags["base-url"]),t}var xs=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,As=/^[0-9a-f][0-9a-f-]{7,34}$/i,pt=8,gt=new WeakMap;function Es(e){let t=gt.get(e);if(t)return t;let s=(async()=>{let n=v(h(e)),r=[],a;do{let i=await n.list({limit:100,...a?{cursor:a}:{}});for(let o of i.items)r.push(o.id);a=i.nextCursor??void 0;}while(a);return r})();return gt.set(e,s),s}async function E(e,t){if(t===void 0||xs.test(t))return t;if(/^[0-9a-f][0-9a-f-]*$/i.test(t)&&t.length<pt)throw new p(`"${t}" is too short to name a job \u2014 id prefixes need at least ${pt} characters`);if(!As.test(t))return t;let s=t.toLowerCase(),n=new Set;for(let a of await Es(e))a.startsWith(s)&&n.add(a);let r=[...n];if(r.length===1)return r[0];throw r.length===0?new p(`no job id starts with "${t}"`):new p(`"${t}" is ambiguous \u2014 it matches ${r.length} jobs: ${r.slice(0,5).join(", ")}${r.length>5?", \u2026":""}`)}function D(e){return {...e.flags.limit!==void 0?{limit:e.flags.limit}:{},...e.flags.cursor!==void 0?{cursor:String(e.flags.cursor)}:{}}}function It(e){if(e.flags.status===void 0)return;let t=String(e.flags.status).split(",").map(n=>n.trim()).filter(Boolean);if(t.length===0)throw new p("--status got an empty status list");let s=t.filter(n=>!ee.includes(n));if(s.length>0)throw new p(`--status must name trial statuses (${ee.join(", ")}); got: ${s.join(", ")}`);return t}function Ts(e){return e.status==="COMPLETED"?0:e.status==="FAILED"||e.status==="CANCELLED"?1:0}function Ps(e){return e.startsWith("./")||e.startsWith("../")||e.startsWith("/")||e.startsWith("~")}async function Is(e,t,s){let n=new Set;for(let i of e.agents)for(let o of i.skills??[])Ps(o)&&n.add(o);if(n.size===0)return e;let r=V(h(t)),a=new Map;for(let i of n){let o=await r.upload(i);if(a.set(i,o.map(l=>l.ref)),t.flags.json!==true)for(let l of o)s.err(`Uploaded skill ${l.name} (${l.ref}, ${l.digest.slice(0,19)}\u2026)`);}return {...e,agents:e.agents.map(i=>({...i,...i.skills!==void 0&&i.skills!==null?{skills:i.skills.flatMap(o=>a.get(o)??[o])}:{}}))}}async function ft(e,t){let s=is(e);if(e.flags["print-config"]===true)return t.out(JSON.stringify(s,null,2)),0;let n=e.flags.json===true,r=e.flags.watch===true,a=e.flags.quiet===true,i=v(h(e)),o=await i.start(await Is(s,e,t));if(!r){if(n)t.out(JSON.stringify(o));else {for(let u of C(o))t.out(u);t.out(""),t.out(`Follow it with: evolve job show ${o.id}`);}return 0}n?t.out(JSON.stringify({kind:"job.created",job:o})):t.out(`Job ${o.id} (${fe(o.datasets)}) ${o.status} \u2014 watching\u2026`);let l=await i.watch(o.id,{onEvent:u=>{a||t.out(n?JSON.stringify({kind:"event",...u}):Rs(u));}});if(n)t.out(JSON.stringify({kind:"job.final",job:l}));else {t.out("");for(let u of C(l))t.out(u);}return Ts(l)}async function $s(e,t){if(K(e,t,it))return 0;let n=await v(h(e)).list({...D(e),...e.flags.search!==void 0?{search:String(e.flags.search)}:{}});return e.flags.json===true?(t.out(JSON.stringify(n)),0):n.items.length===0?(e.flags.quiet!==true&&t.out("No jobs."),0):(B(e,t,n.items,it,ms,r=>r.id),n.nextCursor&&t.tty===true&&e.flags.quiet!==true&&t.out(`
14
+ More: evolve job list --cursor ${n.nextCursor}`),0)}async function Cs(e,t){let s=v(h(e)),n=[];for(let r of e.positionals)n.push(await s.get(await E(e,r)));return e.flags.json===true?(t.out(JSON.stringify(n.length===1?n[0]:n)),0):(n.forEach((r,a)=>{a>0&&t.out("");for(let i of C(r))t.out(i);}),0)}async function Os(e,t){if(K(e,t,ot))return 0;let s=v(h(e)),n=It(e),r=e.flags.dataset,a=await s.trials(await E(e,e.positionals[0]),{...n!==void 0?{status:n}:{},...r!==void 0?{dataset:r}:{},...D(e)});return e.flags.json===true?(t.out(JSON.stringify(a)),0):a.items.length===0?(e.flags.quiet!==true&&t.out("No trials."),0):(B(e,t,a.items,ot,ps,i=>i.id),t.tty===true&&e.flags.quiet!==true&&(t.out(`
15
+ ${a.items.length} trial(s) shown`),a.nextCursor&&t.out(`More: evolve job trials ${e.positionals[0]} --cursor ${a.nextCursor}`)),0)}async function Ds(e,t){if(K(e,t,lt))return 0;let n=await v(h(e)).tasks(await E(e,e.positionals[0]),D(e));return e.flags.json===true?(t.out(JSON.stringify(n)),0):n.items.length===0?(e.flags.quiet!==true&&t.out("No tasks."),0):(B(e,t,n.items,lt,gs,r=>r.task_name),n.nextCursor&&t.tty===true&&e.flags.quiet!==true&&t.out(`
16
+ More: evolve job tasks ${e.positionals[0]} --cursor ${n.nextCursor}`),0)}function js(e){let t=[],s=[["ID","DATASETS","STATUS","MEAN REWARD","COVERAGE","SPENT"]];for(let n of e.jobs)s.push([n.id,fe(n.datasets),n.status,$e(n.mean_reward),`${n.coverage.scored}/${n.coverage.total}`,A(n.cost_usd)]);if(t.push(...R(s)),e.taskMatrix.length>0){t.push("","Task matrix (disagreements first; columns in the order above):");let n=[["TASK","DIFF",...e.jobs.map((a,i)=>`JOB ${i+1}`)]],r=e.jobs.map(a=>a.id);for(let a of e.taskMatrix){let i=new Map(a.cells.map(o=>[o.job_id,o]));n.push([a.task_name,a.disagreement?"!":"",...r.map(o=>{let l=i.get(o);return l?l.mean_reward!==null?`${l.status} ${$e(l.mean_reward)}`:l.status:"-"})]);}t.push(...R(n));}return t}async function Ls(e,t){let s=v(h(e)),n=[];for(let a of e.positionals)n.push(await E(e,a));let r=await s.compare(n);if(e.flags.json===true)t.out(JSON.stringify(r));else for(let a of js(r))t.out(a);return 0}async function Js(e,t){let n=await v(h(e)).cancel(await E(e,e.positionals[0]));if(e.flags.json===true)t.out(JSON.stringify(n));else for(let r of C(n))t.out(r);return 0}async function Ns(e,t){let s=e.flags.dataset;if(!s)throw new p("job stop needs --dataset <name> (to stop the whole job, use: evolve job cancel <id>)");let n=v(h(e)),r=await n.get(await E(e,e.positionals[0])),a=r.datasets.map(c=>c.name);if(!a.includes(s))throw new Error(`job ${r.id} does not run dataset ${s}; its datasets: ${a.join(", ")}`);let i=[];for await(let c of n.trials(r.id,{dataset:s}))i.push(c.id);if(i.length===0)return e.flags.json===true?t.out(JSON.stringify({stopped:[],already_terminal:[],not_found:[]})):t.out(`No trials in ${s}.`),0;let o=J(h(e)),l={stopped:[],already_terminal:[],not_found:[]},u=0;try{for(let c=0;c<i.length;c+=100){let g=i.slice(c,c+100),d=await o.stop(g);u+=g.length,l.stopped.push(...d.stopped),l.already_terminal.push(...d.already_terminal),l.not_found.push(...d.not_found);}}catch(c){throw _t(l,s,i.length,u,e,t),c}return _t(l,s,i.length,u,e,t),0}function _t(e,t,s,n,r,a){let i=s-n;if(r.flags.json===true){a.out(JSON.stringify(i>0?{...e,partial:true,unreported:i}:e));return}for(let o of e.stopped)a.out(`stopped ${o.id} (${o.task_name}) ${o.status}`);for(let o of e.already_terminal)a.out(`already terminal ${o}`);for(let o of e.not_found)a.out(`not found ${o}`);a.out(`${e.stopped.length} stopped, ${e.already_terminal.length} already terminal, ${e.not_found.length} not found (${t})`),i>0&&a.out(`PARTIAL: ${i} of ${s} trials have no report \u2014 no answer came back for trials ${n+1}-${Math.min(n+100,s)}; rerun the same command to finish the rest.`);}async function Us(e,t){let s=v(h(e)),n=e.flags["filter-error-type"],r=await s.resume(await E(e,e.positionals[0]),n!==void 0?{filter_error_types:n}:void 0);if(e.flags.json===true)t.out(JSON.stringify(r));else {for(let a of C(r))t.out(a);t.out(""),t.out(`Follow it with: evolve job show ${r.id}`);}return 0}async function Ms(e,t){let s=e.flags.trial,n=e.flags["failed-only"]===true;if(s!==void 0&&n)throw new p('"job retry" takes EITHER -t/--trial OR --failed-only, not both \u2014 explicit ids are already a selection');let r={};s!==void 0&&(r.trial_ids=s),n&&(r.failed_only=true);let a=await v(h(e)).retry(await E(e,e.positionals[0]),r);if(e.flags.json===true)t.out(JSON.stringify(a));else {for(let i of C(a))t.out(i);t.out(""),t.out(`Follow it with: evolve job show ${a.id}`);}return 0}async function Fs(e,t){let s=v(h(e)),n={},r=It(e);r!==void 0&&(n.statuses=r),e.flags.task!==void 0&&(n.task_name=String(e.flags.task));let a=await s.regrade(await E(e,e.positionals[0]),n);if(e.flags.json===true)t.out(JSON.stringify(a));else {for(let i of C(a))t.out(i);t.out(""),t.out(`Follow it with: evolve job show ${a.id}`);}return 0}async function Vs(e,t){let s=v(h(e)),n=await E(e,e.positionals[0]),{join:r}=await import('path'),a=e.flags["output-dir"]??process.cwd(),i=`job-${n}`,o=r(a,i);if(fs$1.existsSync(o)&&e.flags.overwrite!==true)throw new Error(`${o} already exists (pass --overwrite to replace it)`);let{mkdtemp:l,rm:u}=await import('fs/promises'),{tmpdir:c}=await import('os'),{extractTarGz:g}=await Promise.resolve().then(()=>(W(),H)),d=await l(r(c(),"evolve-job-download-"));try{let m=await s.download(n,{to:d});e.flags.overwrite===!0&&await u(o,{recursive:!0,force:!0});let b;try{b=await g(m,a,i);}catch(x){throw await u(o,{recursive:!0,force:!0}).catch(()=>{}),x}return e.flags.json===!0?t.out(JSON.stringify({path:o,files:b.length})):t.out(`Saved ${o} (${b.length} files)`),0}finally{await u(d,{recursive:true,force:true}).catch(()=>{});}}async function Gs(e,t){let n=await J(h(e)).get(e.positionals[0]);if(e.flags.json===true)t.out(JSON.stringify(n));else for(let r of hs(n))t.out(r);return 0}var bt=he;async function qs(e,t){let s=J(h(e)),n=e.positionals[0],r=e.flags.json===true,a=e.flags.stream;if(a!==void 0&&(e.flags["output-dir"]!==void 0||e.flags.overwrite===true))throw new p('"trial download" takes EITHER --stream OR -o/--overwrite, not both');if((a===void 0||a!=="trace-parsed")&&(e.flags.cursor!==void 0||e.flags.limit!==void 0))throw new p("--cursor/--limit page the parsed events; they apply only to --stream trace-parsed");if(a!==void 0){if(!bt.includes(a))throw new p(`--stream must be one of: ${bt.join(", ")}`);if(a==="trace-parsed"){let y=0;for await(let w of s.traceEvents(n,D(e)))t.out(r?JSON.stringify(w):ws(w)),y+=1;return !r&&y===0&&t.out("No trace events."),0}if(a==="agent-home"){let y=await s.artifact(n,a);if(y===null)return t.out(r?JSON.stringify({files:null}):`No ${a} content was stored for this trial.`),0;if(r)t.out(JSON.stringify({files:y}));else for(let[w,U]of Object.entries(y))t.out(`===== ${w} (${Buffer.byteLength(U,"utf8")} bytes) =====`),t.out(U);return 0}let f=await s.artifact(n,a);return f===null?(t.out(r?JSON.stringify({log:null}):`No ${a} log was stored for this trial.`),0):(t.out(r?JSON.stringify({log:f}):f),0)}let{mkdir:i,writeFile:o}=await import('fs/promises'),{join:l,dirname:u}=await import('path'),c=l(e.flags["output-dir"]??"trials",n);if(fs$1.existsSync(c)&&e.flags.overwrite!==true)throw new Error(`${c} already exists (pass --overwrite to replace it)`);await i(c,{recursive:true});let g=[],d=f=>{g.push(f),r||t.out(f);},m=[];for await(let f of s.traceEvents(n))m.push(JSON.stringify(f));await o(l(c,"trace-parsed.jsonl"),m.join(`
17
+ `)+(m.length?`
18
+ `:"")),d(`trace-parsed.jsonl (${m.length} events)`);let b=await s.artifact(n,"trace-atif");b!==null&&(await o(l(c,"trace-atif.json"),b),d(`trace-atif.json (${Buffer.byteLength(b,"utf8")} bytes)`));for(let f of ["verifier","trace-stdout","trace-stderr"]){let y=await s.artifact(n,f);y!==null&&(await o(l(c,`${f}.log`),y),d(`${f}.log (${Buffer.byteLength(y,"utf8")} bytes)`));}let x=await s.artifact(n,"agent-home");if(x!==null){for(let[f,y]of Object.entries(x)){let w=l(c,"agent-home",...f.split("/").filter(Boolean));await i(u(w),{recursive:true}),await o(w,y);}d(`agent-home/ (${Object.keys(x).length} files)`);}return r?t.out(JSON.stringify({path:c,saved:g})):t.out(`Saved ${c}`),0}async function Bs(e,t){let s=await J(h(e)).retry(e.positionals[0]);if(e.flags.json===true)t.out(JSON.stringify(s));else {for(let n of C(s))t.out(n);t.out(""),t.out(`Follow it with: evolve job show ${s.id}`);}return 0}async function Ks(e,t){let s=await J(h(e)).regrade(e.positionals[0]);if(e.flags.json===true)t.out(JSON.stringify(s));else {for(let n of C(s))t.out(n);t.out(""),t.out(`Follow it with: evolve job show ${s.id}`);}return 0}async function Hs(e,t){let n=await J(h(e)).stop(e.positionals);if(e.flags.json===true)return t.out(JSON.stringify(n)),0;for(let r of n.stopped)t.out(`stopped ${r.id} (${r.task_name}) ${r.status}`);for(let r of n.already_terminal)t.out(`already terminal ${r}`);for(let r of n.not_found)t.out(`not found ${r}`);return 0}function $t(e){let t=R([["name",e.name],["title",e.title??"-"],["description",e.description??"-"],["active version",e.active_version?.version??"-"]]),s=e.selected_version?.source??e.active_version?.source??null;if(s){let r=s.ref===s.commit?"":` @ ${s.ref}`;t.push(`source: ${s.git_url??"?"}${r} (commit ${s.commit.slice(0,12)})`),s.path&&t.push(` subfolder: ${s.path}`);}else if(e.upstream){let r=e.upstream,a=r.ref===r.current_commit?"":` @ ${r.ref}`;t.push(`source: ${r.git_url??"?"}${a} (commit ${r.current_commit.slice(0,12)})`),r.path&&t.push(` subfolder: ${r.path}`);}let n=e.active_version?.manifest;if(n&&(t.push(`manifest: ${n.name}${n.version?`@${n.version}`:""}`+(n.task_count!==null?` (${n.task_count} tasks pinned)`:"")),n.authors.length>0&&t.push(` authors: ${n.authors.map(r=>r.email?`${r.name} <${r.email}>`:r.name).join(", ")}`),n.keywords.length>0&&t.push(` keywords: ${n.keywords.join(", ")}`)),e.versions&&e.versions.length>0){t.push("");let r=e.versions.some(o=>o.gate!=null),a=e.versions.some(o=>o.source!=null),i=[["VERSION","STATE","TASKS","CREATED",...a?["COMMIT"]:[],...r?["GATE"]:[]]];for(let o of e.versions)i.push([o.version,o.state,String(o.task_count),o.created_at??"-",...a?[o.source?o.source.commit.slice(0,12):"-"]:[],...r?[o.gate?.status??"-"]:[]]);t.push(...R(i));for(let o of e.versions)if(o.gate?.status==="FAILED"){let l=o.gate.message??o.gate.code??"no reason reported";t.push(`version ${o.version} activation gate FAILED: ${l}`);for(let u of o.gate.failed_tasks){let c=u.reasons.length>0?u.reasons.join("; "):u.outcome??"no reason reported";t.push(` ${u.task_name}: ${c}`);}o.gate.failed_task_count>o.gate.failed_tasks.length&&t.push(` \u2026 and ${o.gate.failed_task_count-o.gate.failed_tasks.length} more (${o.gate.failed_task_count} ineligible tasks in total)`);}}if(e.tasks&&e.tasks.items.length>0){t.push("",`Tasks (version ${e.selected_version?.version??"?"}):`);let r=e.tasks.items.some(o=>(o.gpus??0)>0),a=[["TASK","AGENT TIMEOUT","VERIFIER TIMEOUT",...r?["GPU"]:[],"PROVIDERS"]];for(let o of e.tasks.items)a.push([o.task_name,`${o.agent_timeout_sec}s`,`${o.verifier_timeout_sec}s`,...r?[vs(o)??"-"]:[],ks(o.providers)]);t.push(...R(a)),e.tasks.nextCursor&&t.push(`More tasks: evolve dataset show ${e.name} --cursor ${e.tasks.nextCursor}`);let i=new Map;for(let o of e.tasks.items)for(let l of Tt){let u=o.providers?.[l];if(u){if(!u.ok)i.has(`${l}:${u.reason}`)||i.set(`${l}:${u.reason}`,`${l}: ${u.reason}`);else if(u.degrades_to&&u.reason){let c=`${l}:degrade:${u.reason}`;i.has(c)||i.set(c,`${l}: runs on ${u.degrades_to} \u2014 ${u.reason}`);}}}if(i.size>0){t.push("","Provider limitations:");for(let o of i.values())t.push(` ${o}`);}}return t}function Ct(e){let t=[];for(let s of e){if(!s.upstream?.moved)continue;let n=s.active_version?`@${s.active_version.version}`:"",r=s.upstream.latest_commit??s.upstream.ref,a=s.upstream.git_url??"<url>",i=s.upstream.path?` --path ${s.upstream.path}`:"";t.push(`${s.name}${n} \xB7 upstream ${s.upstream.ref} moved \u2014 run: evolve dataset publish --name ${s.name} --version <new-version> --git ${a} --ref ${r}${i}`);}return t}async function Ws(e,t){if(K(e,t,ut))return 0;let n=await F(h(e)).list({...D(e),...e.flags.search!==void 0?{search:String(e.flags.search)}:{}});if(e.flags.json===true)return t.out(JSON.stringify(n)),0;if(n.items.length===0)return e.flags.quiet!==true&&t.out("No datasets."),0;if(B(e,t,n.items,ut,fs,r=>r.name),e.flags.quiet!==true)for(let r of Ct(n.items))t.out(r);return 0}async function Ys(e,t){let n=await F(h(e)).get(e.positionals[0],D(e));if(e.flags.json===true)t.out(JSON.stringify(n));else {for(let r of $t(n))t.out(r);for(let r of Ct([n]))t.out(r);}return 0}async function zs(e,t){let s=e.flags.json===true,n=F(h(e)),r=os(e),a=await n.publish(r);if(e.flags.watch!==true){if(s)t.out(JSON.stringify(a));else {for(let o of mt(a))t.out(o);t.out(""),t.out(`Follow it with: evolve dataset show ${a.name}`);}return 0}s?t.out(JSON.stringify({kind:"import.created",datasetImport:a})):t.out(`Publish ${a.id} (${a.name}) ${a.status} \u2014 watching\u2026`);let i=await n.watchImport(a.id,{onStatus:o=>{t.out(s?JSON.stringify({kind:"import.status",datasetImport:o}):Ss(o));}});if(s)t.out(JSON.stringify({kind:"import.final",datasetImport:i}));else {t.out("");for(let o of mt(i))t.out(o);}return i.status==="FAILED"?1:0}async function Xs(e,t){let n=await F(h(e)).download(e.positionals[0],{to:e.flags["output-dir"]??process.cwd()});return e.flags.json===true?t.out(JSON.stringify({path:n})):t.out(`Saved ${n}`),0}async function Qs(e,t){let s=F(h(e)),[n,r]=e.positionals,a;try{a=await s.activate(n,r);}catch(i){if(i instanceof z)return e.flags.json===true?t.out(JSON.stringify({kind:"gate.running",code:i.code,message:i.message,dataset:i.dataset,version:i.version,gate:i.gate})):(t.out(`Not yet: ${i.message}`),t.out(`Gate ${i.gate.status}: ${i.gate.tasks} task(s), ${i.gate.unverified} unverified, ${i.gate.ineligible} ineligible so far.`),t.out(`Follow it with: evolve dataset show ${n} \u2014 a gate that passes activates the version itself.`)),1;throw i}if(e.flags.json===true)t.out(JSON.stringify(a));else for(let i of $t(a))t.out(i);return 0}function Ot(e){let t=[["name",e.name],["id",e.id],["ref",e.ref],["digest",e.digest],["size",At(e.size_bytes)]];return e.description&&t.push(["description",e.description]),t.push(["created",e.created_at]),R(t)}async function Zs(e,t){if(K(e,t,ct))return 0;let n=await V(h(e)).list(D(e));return e.flags.json===true?(t.out(JSON.stringify(n)),0):n.items.length===0?(e.flags.quiet!==true&&t.out("No uploaded skills."),0):(B(e,t,n.items,ct,bs,r=>r.id),n.nextCursor&&t.tty===true&&e.flags.quiet!==true&&t.out(`
19
+ More: evolve skill list --cursor ${n.nextCursor}`),0)}async function er(e,t){let n=await V(h(e)).upload(e.positionals[0]);return e.flags.json===true?(t.out(JSON.stringify(n.length===1?n[0]:n)),0):(n.forEach((r,a)=>{a>0&&t.out("");for(let i of Ot(r))t.out(i);}),t.out(""),t.out(`Use it with: evolve run --skill name:${n[0].name} (moving pointer) or --skill ${n[0].ref} (this exact content)`),0)}async function tr(e,t){let s=await V(h(e)).get(e.positionals[0]);if(e.flags.json===true)return t.out(JSON.stringify(s)),0;for(let n of Ot(s))t.out(n);return s.skill_md&&(t.out(""),t.out(s.skill_md)),0}async function nr(e,t){let s=e.positionals[0];return await V(h(e)).delete(s),e.flags.json===true?t.out(JSON.stringify({id:s,deleted:true})):t.out(`Deleted skill ${s}`),0}async function sr(e,t){if(K(e,t,dt))return 0;let n=await Q(h(e)).list(D(e));return e.flags.json===true?(t.out(JSON.stringify(n)),0):n.items.length===0?(e.flags.quiet!==true&&t.out("No registered agents."),0):(B(e,t,n.items,dt,ys,r=>r.name),0)}async function rr(e,t){let n=await Q(h(e)).get(e.positionals[0]);if(e.flags.json===true)t.out(JSON.stringify(n));else for(let r of Et(n))t.out(r);return 0}async function ar(e,t){let n=await Q(h(e)).create(ls(e));if(e.flags.json===true)t.out(JSON.stringify(n));else {for(let r of Et(n))t.out(r);t.out(""),t.out(`Use it with: evolve run -d <dataset> -a ${n.name} -m <model>`);}return 0}async function ir(e,t){let s=Q(h(e)),n=e.positionals[0];return await s.delete(n),e.flags.json===true?t.out(JSON.stringify({name:n,deleted:true})):t.out(`Deleted agent ${n}`),0}function or(e){let t=[["user",e.user_id],["email",e.email??"-"],["key",e.key.id]];return e.key.label&&t.push(["key label",e.key.label]),t.push(["key created",e.key.created_at]),e.key.last_used_at&&t.push(["key last used",e.key.last_used_at]),R(t)}async function lr(e,t){let s=await et(h(e)).status();if(e.flags.json===true)t.out(JSON.stringify(s));else for(let n of or(s))t.out(n);return 0}function ur(e){if(e.length===0)return {text:Ee(),code:0};let t=De[e[0]];if(t)return {text:nt(e[0],t),code:0};let s=vt[e[0]];if(s)return {text:s,code:0};let n=kt[e[0]]??e[0],r=ge[n];if(!r)return {text:Ee(),code:0};if(e.length===1)return {text:st(n),code:0};let a=wt[e[1]]??e[1],i=r.commands[a];return i?{text:nt(`${n} ${a}`,i),code:0}:{text:st(n),code:0}}var cr={run:ft,"job start":ft,"job list":$s,"job show":Cs,"job trials":Os,"job tasks":Ds,"job compare":Ls,"job cancel":Js,"job stop":Ns,"job resume":Us,"job retry":Ms,"job regrade":Fs,"job download":Vs,"trial show":Gs,"trial download":qs,"trial retry":Bs,"trial regrade":Ks,"trial stop":Hs,"dataset list":Ws,"dataset show":Ys,"dataset publish":zs,"dataset download":Xs,"dataset activate":Qs,"skill list":Zs,"skill upload":er,"skill show":tr,"skill delete":nr,"agent list":sr,"agent show":rr,"agent add":ar,"agent remove":ir,"auth status":lr};function dr(e){return e instanceof I?{code:e.code,message:e.message,...e.param!==void 0?{param:e.param}:{},...e.details!==void 0?{details:e.details}:{},...e.retryAfterSec!==void 0?{retryAfterSec:e.retryAfterSec}:{},...e.requestId!==void 0?{request_id:e.requestId}:{}}:{message:e instanceof Error?e.message:String(e)}}async function mr(e,t=us){let s;try{s=Fn(e);}catch(n){if(n instanceof p)return t.err(`Error: ${n.message}`),t.err('Run "evolve help" for usage.'),2;throw n}if(s.command==="help"){let{text:n,code:r}=ur(s.positionals);return t.out(n),r}if(s.command==="version")return t.out(Un()),0;try{let n=cr[s.command];return n?await n(s,t):(t.err(`Error: unknown command "${s.command}"`),2)}catch(n){if(n instanceof p)return t.err(`Error: ${n.message}`),t.err(`Run "evolve ${s.command} --help" for usage.`),2;if(s.flags.json===true&&t.out(JSON.stringify({error:dr(n)})),n instanceof I&&n.status===429){let r=n.retryAfterSec!==void 0?`retry in ${n.retryAfterSec}s`:"retry shortly";return t.err(`Error: rate limited by the server \u2014 ${r}.`),1}return t.err(`Error: ${n.message}`),1}}var pr=(()=>{let e=process.argv[1];if(!e)return false;let t=s=>{try{return (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href))===url.pathToFileURL(s).href}catch{return false}};if(t(e))return true;try{return t(fs$1.realpathSync(e))}catch{return false}})();pr&&mr(process.argv.slice(2)).then(e=>{process.exitCode=e;},e=>{process.stderr.write(`Error: ${e?.message??e}
20
+ `),process.exitCode=1;});exports.CliUsageError=p;exports.USAGE=Ur;exports.buildAgentInput=ls;exports.buildJobInput=is;exports.buildPublishInput=os;exports.eventLine=Rs;exports.importStatusLine=Ss;exports.parseAgentKwargs=rs;exports.parseArgs=Fn;exports.parseEnvPairs=Ie;exports.parseYamlConfig=Mr;exports.parseYamlConfigLocated=St;exports.runCli=mr;exports.traceEventLine=ws;exports.trialDetailLines=hs;
@@ -0,0 +1,126 @@
1
+ #!/usr/bin/env node
2
+ import { Z as JobCreate, aB as PublishDatasetInput, aH as AgentInput, a7 as Trial, al as TraceEvent, az as DatasetImport, an as JobEvent } from '../types-6PL1THem.cjs';
3
+
4
+ /**
5
+ * evolve — the CLI for Evolve hosted datasets & jobs.
6
+ *
7
+ * Noun-verb grammar over the hosted client: `evolve <noun> <verb>`, plus
8
+ * first-class top-level commands that need no noun — today that is `run`,
9
+ * which takes `job start`'s flags and is spelled, helped and dispatched as a
10
+ * command in its own right (Harbor registers their `run` the same way, as the
11
+ * `job start` function bound at the top level: cli/main.py:164). Singular
12
+ * nouns are canonical; `job`/`trial`/`dataset`/`skill` also answer to their
13
+ * plurals as hidden aliases, but `agents` does NOT — that word is reserved for
14
+ * the managed-agents CLI and refuses with the reason. The CLI speaks ONLY
15
+ * through the SDK clients (datasets() / agents() / jobs() / trials() /
16
+ * skills() / auth()) — no raw HTTP lives here.
17
+ *
18
+ * Output: human tables on a TTY, tab-separated rows when piped, --json for
19
+ * the rendered machine shape (NDJSON for --watch event streams), -q for
20
+ * ids-only lists. Exit codes: 0 success (watch: job COMPLETED / publish
21
+ * COMPLETED), 1 runtime/API failure (watch: FAILED or CANCELLED), 2 usage
22
+ * error.
23
+ */
24
+
25
+ /** Usage-level error: bad command line, not a runtime failure. Exit code 2. */
26
+ declare class CliUsageError extends Error {
27
+ constructor(message: string);
28
+ }
29
+ declare const USAGE: string;
30
+ interface Invocation {
31
+ /** Canonical "<group> <verb>", or "help" / "version". */
32
+ command: string;
33
+ positionals: string[];
34
+ flags: Record<string, string | number | boolean | string[]>;
35
+ }
36
+ declare function parseArgs(argv: string[]): Invocation;
37
+ /**
38
+ * -c reads real YAML through the standard `yaml` package — the hand-rolled
39
+ * subset reader is retired. PyYAML's reading is the contract, so the schema is
40
+ * YAML 1.1 (`yes`/`on` are booleans, `012` is octal, a flow mapping is a whole
41
+ * sequence item) with two carve-outs: the 1.1 spec's bare `y`/`n` booleans,
42
+ * which PyYAML never adopted — `n: 3` keeps its key — and the 1.1 spec's
43
+ * number shapes PyYAML never adopted either, where a float needs a dot and a
44
+ * signed exponent and an integer may not be zero-padded, so `e3`, `1e3`, `08`
45
+ * and `0:0` stay the strings a caller wrote. The schema is PINNED, not
46
+ * merely defaulted: PyYAML's resolver has no mode but 1.1 and reads a file the
47
+ * same way whatever its `%YAML` directive says, while this library lets an
48
+ * explicit `%YAML 1.2` swap in the 1.2 core schema. One file, one reading.
49
+ * Three refusals sit on top of the library: a second document, an unresolvable
50
+ * tag (both PyYAML refusals too), and a duplicate key — PyYAML silently keeps
51
+ * the last value, and that silence is exactly the corruption a config file
52
+ * cannot afford. Every refusal names its `source` and carries `:line` wherever
53
+ * the parser places the problem — the library's alias-bomb guard fires at
54
+ * resolution, after parsing, and has no position to give. An empty or
55
+ * comment-only file is an empty object.
56
+ */
57
+ declare function parseYamlConfig(text: string, source: string): unknown;
58
+ /** A path into the parsed config: object keys and list indices, root first. */
59
+ type ConfigPath = (string | number)[];
60
+ /**
61
+ * `parseYamlConfig` plus a `locate` that answers "what line does this path
62
+ * start on", so a schema refusal can point at the file the way a parse
63
+ * refusal already does. JSON configs have no locator — JSON.parse keeps no
64
+ * positions — and every message treats the line as optional for that reason.
65
+ */
66
+ declare function parseYamlConfigLocated(text: string, source: string): {
67
+ value: unknown;
68
+ locate: (path: ConfigPath) => number | undefined;
69
+ };
70
+ /**
71
+ * Parse repeatable --ak key=value pairs into the wire's agents[].kwargs
72
+ * object. The `config` key gets the channel's one client-side mechanic: a
73
+ * string value is a LOCAL settings file (the server never reads a client
74
+ * path), resolved here to its parsed content — JSON or TOML by extension,
75
+ * with a both-ways attempt for anything else. Every other key rides verbatim;
76
+ * acceptance is the server's.
77
+ */
78
+ declare function parseAgentKwargs(pairs: string[], read?: (path: string) => string): Record<string, unknown>;
79
+ /** Parse repeatable KEY=VALUE pairs into an env map. */
80
+ declare function parseEnvPairs(pairs: string[], flag: string): Record<string, string>;
81
+ /**
82
+ * Build the POST /api/jobs body from a parsed `job start` / `run` invocation:
83
+ * -c loads a base config in the spec's own vocabulary, then every explicitly
84
+ * passed flag overrides the corresponding field. -i/-x/-l are stamped onto
85
+ * EVERY dataset selector — per-selector filters with one flag grammar, so a
86
+ * glob that matches nothing in one dataset simply filters nothing there.
87
+ */
88
+ declare function buildJobInput(inv: Invocation, read?: (path: string) => string): JobCreate;
89
+ /**
90
+ * Build the datasets().publish() input from a parsed `dataset publish`
91
+ * invocation. `--name`/`--version` are optional with `--dir`: a corpus
92
+ * carrying a dataset.toml manifest supplies them server-side (Harbor's
93
+ * dataset layout), and the SDK refuses before uploading when neither the
94
+ * flags nor a manifest exist. A git source always requires both — its
95
+ * manifest is only readable after the server clones it.
96
+ */
97
+ declare function buildPublishInput(inv: Invocation): PublishDatasetInput;
98
+ /**
99
+ * Build the agents().create() input from a parsed `agent add` invocation.
100
+ * `--install-script` names a FILE; its contents are what the SDK uploads.
101
+ */
102
+ declare function buildAgentInput(inv: Invocation, readScript?: (path: string) => string): AgentInput;
103
+ interface CliIO {
104
+ out(line: string): void;
105
+ err(line: string): void;
106
+ /**
107
+ * True when stdout is an interactive terminal. Drives the table-vs-TSV
108
+ * split on list commands; TERM=dumb counts as non-interactive. Defaults to
109
+ * false when absent so redirected output always gets machine-safe rows.
110
+ */
111
+ tty?: boolean;
112
+ }
113
+ /**
114
+ * Full-detail rendering of one trial — evolve trial show. Exported for
115
+ * tests, like the other line renderers.
116
+ */
117
+ declare function trialDetailLines(run: Trial): string[];
118
+ /** One trace event line — evolve trial download --stream trace-parsed. */
119
+ declare function traceEventLine(event: TraceEvent): string;
120
+ /** Compact one-line rendering of one publish status change for --watch. */
121
+ declare function importStatusLine(job: DatasetImport): string;
122
+ /** Compact one-line rendering of one SSE event for --watch. */
123
+ declare function eventLine(event: JobEvent): string;
124
+ declare function runCli(argv: string[], io?: CliIO): Promise<number>;
125
+
126
+ export { type CliIO, CliUsageError, type Invocation, USAGE, buildAgentInput, buildJobInput, buildPublishInput, eventLine, importStatusLine, parseAgentKwargs, parseArgs, parseEnvPairs, parseYamlConfig, parseYamlConfigLocated, runCli, traceEventLine, trialDetailLines };