evolve-sdk 0.0.55.dev1192__tar.gz → 0.0.55.dev1201__tar.gz
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.
- {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1201}/PKG-INFO +1 -1
- {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1201}/bridge/dist/bridge.bundle.cjs +2 -2
- {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1201}/evolve/__init__.py +1 -1
- {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1201}/evolve/hosted.py +57 -13
- {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1201}/evolve_sdk.egg-info/PKG-INFO +1 -1
- {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1201}/pyproject.toml +1 -1
- {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1201}/LICENSE +0 -0
- {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1201}/MANIFEST.in +0 -0
- {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1201}/README.md +0 -0
- {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1201}/bridge/__init__.py +0 -0
- {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1201}/evolve/_http.py +0 -0
- {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1201}/evolve/agent.py +0 -0
- {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1201}/evolve/bridge.py +0 -0
- {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1201}/evolve/browser_credentials.py +0 -0
- {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1201}/evolve/browser_profiles.py +0 -0
- {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1201}/evolve/config.py +0 -0
- {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1201}/evolve/integrations.py +0 -0
- {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1201}/evolve/managed_secrets.py +0 -0
- {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1201}/evolve/pipeline/__init__.py +0 -0
- {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1201}/evolve/pipeline/pipeline.py +0 -0
- {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1201}/evolve/pipeline/types.py +0 -0
- {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1201}/evolve/prompts/__init__.py +0 -0
- {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1201}/evolve/prompts/agent_md/judge.md +0 -0
- {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1201}/evolve/prompts/agent_md/reduce.md +0 -0
- {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1201}/evolve/prompts/agent_md/verify.md +0 -0
- {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1201}/evolve/prompts/user/judge.md +0 -0
- {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1201}/evolve/prompts/user/retry_feedback.md +0 -0
- {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1201}/evolve/prompts/user/verify.md +0 -0
- {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1201}/evolve/py.typed +0 -0
- {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1201}/evolve/results.py +0 -0
- {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1201}/evolve/retry.py +0 -0
- {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1201}/evolve/schema.py +0 -0
- {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1201}/evolve/sessions_client.py +0 -0
- {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1201}/evolve/storage_client.py +0 -0
- {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1201}/evolve/swarm/__init__.py +0 -0
- {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1201}/evolve/swarm/results.py +0 -0
- {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1201}/evolve/swarm/swarm.py +0 -0
- {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1201}/evolve/swarm/types.py +0 -0
- {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1201}/evolve/utils.py +0 -0
- {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1201}/evolve_sdk.egg-info/SOURCES.txt +0 -0
- {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1201}/evolve_sdk.egg-info/dependency_links.txt +0 -0
- {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1201}/evolve_sdk.egg-info/requires.txt +0 -0
- {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1201}/evolve_sdk.egg-info/top_level.txt +0 -0
- {evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1201}/setup.cfg +0 -0
|
@@ -675,7 +675,7 @@ if __name__ == "__main__":
|
|
|
675
675
|
]))`;continue}else if(r[c]==="$"){a+=`($|(?=[\r
|
|
676
676
|
]))`;continue}}if(n.s&&r[c]==="."){a+=s?`${r[c]}\r
|
|
677
677
|
`:`[${r[c]}\r
|
|
678
|
-
]`;continue}a+=r[c],r[c]==="\\"?i=!0:s&&r[c]==="]"?s=!1:!s&&r[c]==="["&&(s=!0)}try{new RegExp(a)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return a}function UA(e,t){if(t.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),t.target==="openApi3"&&e.keyType?._def.typeName===Ue.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((r,a)=>({...r,[a]:gt(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",a]})??Jr(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let n={type:"object",additionalProperties:gt(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return n;if(e.keyType?._def.typeName===Ue.ZodString&&e.keyType._def.checks?.length){let{type:r,...a}=DA(e.keyType._def,t);return{...n,propertyNames:a}}else{if(e.keyType?._def.typeName===Ue.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===Ue.ZodBranded&&e.keyType._def.type._def.typeName===Ue.ZodString&&e.keyType._def.type._def.checks?.length){let{type:r,...a}=MA(e.keyType._def,t);return{...n,propertyNames:a}}}return n}function ire(e,t){if(t.mapStrategy==="record")return UA(e,t);let n=gt(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Jr(t),r=gt(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Jr(t);return{type:"array",maxItems:125,items:{type:"array",items:[n,r],minItems:2,maxItems:2}}}function are(e){let t=e.values,r=Object.keys(e.values).filter(i=>typeof t[t[i]]!="number").map(i=>t[i]),a=Array.from(new Set(r.map(i=>typeof i)));return{type:a.length===1?a[0]==="string"?"string":"number":["string","number"],enum:r}}function sre(e){return e.target==="openAi"?void 0:{not:Jr({...e,currentPath:[...e.currentPath,"not"]})}}function ore(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var UI={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function lre(e,t){if(t.target==="openApi3")return cre(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(r=>r._def.typeName in UI&&(!r._def.checks||!r._def.checks.length))){let r=n.reduce((a,i)=>{let s=UI[i._def.typeName];return s&&!a.includes(s)?[...a,s]:a},[]);return{type:r.length>1?r:r[0]}}else if(n.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){let r=n.reduce((a,i)=>{let s=typeof i._def.value;switch(s){case"string":case"number":case"boolean":return[...a,s];case"bigint":return[...a,"integer"];case"object":if(i._def.value===null)return[...a,"null"];case"symbol":case"undefined":case"function":default:return a}},[]);if(r.length===n.length){let a=r.filter((i,s,o)=>o.indexOf(i)===s);return{type:a.length>1?a:a[0],enum:n.reduce((i,s)=>i.includes(s._def.value)?i:[...i,s._def.value],[])}}}else if(n.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((r,a)=>[...r,...a._def.values.filter(i=>!r.includes(i))],[])};return cre(e,t)}var cre=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((r,a)=>gt(r._def,{...t,currentPath:[...t.currentPath,"anyOf",`${a}`]})).filter(r=>!!r&&(!t.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return n.length?{anyOf:n}:void 0};function ure(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target==="openApi3"?{type:UI[e.innerType._def.typeName],nullable:!0}:{type:[UI[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){let r=gt(e.innerType._def,{...t,currentPath:[...t.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let n=gt(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function dre(e,t){let n={type:"number"};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case"int":n.type="integer",CL(n,"type",r.message,t);break;case"min":t.target==="jsonSchema7"?r.inclusive?yn(n,"minimum",r.value,r.message,t):yn(n,"exclusiveMinimum",r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),yn(n,"minimum",r.value,r.message,t));break;case"max":t.target==="jsonSchema7"?r.inclusive?yn(n,"maximum",r.value,r.message,t):yn(n,"exclusiveMaximum",r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),yn(n,"maximum",r.value,r.message,t));break;case"multipleOf":yn(n,"multipleOf",r.value,r.message,t);break}return n}function fre(e,t){let n=t.target==="openAi",r={type:"object",properties:{}},a=[],i=e.shape();for(let o in i){let c=i[o];if(c===void 0||c._def===void 0)continue;let l=ist(c);l&&n&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),l=!1);let u=gt(c._def,{...t,currentPath:[...t.currentPath,"properties",o],propertyPath:[...t.currentPath,"properties",o]});u!==void 0&&(r.properties[o]=u,l||a.push(o))}a.length&&(r.required=a);let s=rst(e,t);return s!==void 0&&(r.additionalProperties=s),r}function rst(e,t){if(e.catchall._def.typeName!=="ZodNever")return gt(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function ist(e){try{return e.isOptional()}catch{return!0}}var pre=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return gt(e.innerType._def,t);let n=gt(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return n?{anyOf:[{not:Jr(t)},n]}:Jr(t)};var hre=(e,t)=>{if(t.pipeStrategy==="input")return gt(e.in._def,t);if(t.pipeStrategy==="output")return gt(e.out._def,t);let n=gt(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),r=gt(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,r].filter(a=>a!==void 0)}};function mre(e,t){return gt(e.type._def,t)}function gre(e,t){let r={type:"array",uniqueItems:!0,items:gt(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&yn(r,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&yn(r,"maxItems",e.maxSize.value,e.maxSize.message,t),r}function yre(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((n,r)=>gt(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:gt(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((n,r)=>gt(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}function vre(e){return{not:Jr(e)}}function bre(e){return Jr(e)}var Sre=(e,t)=>gt(e.innerType._def,t);var _re=(e,t,n)=>{switch(t){case Ue.ZodString:return DA(e,n);case Ue.ZodNumber:return dre(e,n);case Ue.ZodObject:return fre(e,n);case Ue.ZodBigInt:return Yne(e,n);case Ue.ZodBoolean:return Kne();case Ue.ZodDate:return UL(e,n);case Ue.ZodUndefined:return vre(n);case Ue.ZodNull:return ore(n);case Ue.ZodArray:return jne(e,n);case Ue.ZodUnion:case Ue.ZodDiscriminatedUnion:return lre(e,n);case Ue.ZodIntersection:return tre(e,n);case Ue.ZodTuple:return yre(e,n);case Ue.ZodRecord:return UA(e,n);case Ue.ZodLiteral:return nre(e,n);case Ue.ZodEnum:return ere(e);case Ue.ZodNativeEnum:return are(e);case Ue.ZodNullable:return ure(e,n);case Ue.ZodOptional:return pre(e,n);case Ue.ZodMap:return ire(e,n);case Ue.ZodSet:return gre(e,n);case Ue.ZodLazy:return()=>e.getter()._def;case Ue.ZodPromise:return mre(e,n);case Ue.ZodNaN:case Ue.ZodNever:return sre(n);case Ue.ZodEffects:return Qne(e,n);case Ue.ZodAny:return Jr(n);case Ue.ZodUnknown:return bre(n);case Ue.ZodDefault:return Zne(e,n);case Ue.ZodBranded:return MA(e,n);case Ue.ZodReadonly:return Sre(e,n);case Ue.ZodCatch:return Xne(e,n);case Ue.ZodPipeline:return hre(e,n);case Ue.ZodFunction:case Ue.ZodVoid:case Ue.ZodSymbol:return;default:return(r=>{})(t)}};function gt(e,t,n=!1){let r=t.seen.get(e);if(t.override){let o=t.override?.(e,t,r,n);if(o!==Mne)return o}if(r&&!n){let o=ast(r,t);if(o!==void 0)return o}let a={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,a);let i=_re(e,e.typeName,t),s=typeof i=="function"?gt(i(),t):i;if(s&&sst(e,t,s),t.postProcess){let o=t.postProcess(s,e,t);return a.jsonSchema=s,o}return a.jsonSchema=s,s}var ast=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:OA(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((n,r)=>t.currentPath[r]===n)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),Jr(t)):t.$refStrategy==="seen"?Jr(t):void 0}},sst=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n);var wre=(e,t)=>{let n=Une(t),r=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[l,u])=>({...c,[l]:gt(u._def,{...n,currentPath:[...n.basePath,n.definitionPath,l]},!0)??Jr(n)}),{}):void 0,a=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,i=gt(e._def,a===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,a]},!1)??Jr(n),s=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;s!==void 0&&(i.title=s),n.flags.hasReferencedOpenAiAnyType&&(r||(r={}),r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:n.$refStrategy==="relative"?"1":[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join("/")}}));let o=a===void 0?r?{...i,[n.definitionPath]:r}:i:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,a].join("/"),[n.definitionPath]:{...r,[a]:i}};return n.target==="jsonSchema7"?o.$schema="http://json-schema.org/draft-07/schema#":(n.target==="jsonSchema2019-09"||n.target==="openAi")&&(o.$schema="https://json-schema.org/draft/2019-09/schema#"),n.target==="openAi"&&("anyOf"in o||"oneOf"in o||"allOf"in o||"type"in o&&Array.isArray(o.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),o};var Ire=wre;var rf=Ve(require("fs"),1),AXe=require("fs");rE();FT();tB();var $Ke=["no-internet","pinned-context"],w5t={strict:{coerceTypes:!1,removeAdditional:!1,useDefaults:!1,allErrors:!0},loose:{coerceTypes:"array",removeAdditional:!1,useDefaults:!0,allErrors:!0}};var zKe=2e5;function I5t(e,t){return t??Vp[e]?.defaultReasoningEffort}function uB(e){return e!=="off"&&e!=="none"&&e!=="minimal"&&e!=="no-thinking"}function PXe(e){if(!(e==="off"||e==="none"||e==="no-thinking"))return!e||e==="thinking"||e==="medium"?"medium":e==="low"||e==="minimal"?"minimal":e==="xhigh"?"max":e}function x5t(e){let t=PXe(e);return t?` --variant ${t} --thinking`:""}var Vp={claude:{image:"evolve-all",apiKeyEnv:"ANTHROPIC_API_KEY",effortSupport:"level",oauthEnv:"CLAUDE_CODE_OAUTH_TOKEN",baseUrlEnv:"ANTHROPIC_BASE_URL",customHeadersEnv:"ANTHROPIC_CUSTOM_HEADERS",defaultModel:"opus",defaultReasoningEffort:"high",models:[{alias:"fable",modelId:"claude-fable-5",description:"Highest capability, long-horizon agentic work"},{alias:"opus",modelId:"claude-opus-5",description:"Complex reasoning, R&D, architecting"},{alias:"sonnet",modelId:"claude-sonnet-5",description:"Daily coding, features, tests"},{alias:"haiku",modelId:"claude-haiku-4-5-20251001",description:"Quick tasks, syntax correction"},{alias:"opus[1m]",modelId:"opus[1m]",description:"Complex reasoning with 1M context window"},{alias:"sonnet[1m]",modelId:"sonnet[1m]",description:"Daily coding with 1M context window"},{alias:"glm-5.3",modelId:"glm-5.3",description:"Zhipu GLM-5.3 via the Evolve gateway"},{alias:"glm-5.3-flash",modelId:"glm-5.3-flash",description:"Zhipu GLM-5.3 Flash via the Evolve gateway"},{alias:"deepseek-v4-flash-vision",modelId:"deepseek-v4-flash-vision",description:"DeepSeek V4 Flash Vision (Fireworks) via the Evolve gateway"}],systemPromptFile:"CLAUDE.md",mcpConfig:{settingsDir:"~/.claude",filename:"settings.json",format:"json",projectConfig:!0},nativeConfig:{format:"json",path:"~/.claude/evolve-user-settings.json",delivery:"settings-flag"},presets:{"no-internet":{configStamp:{permissions:{deny:["WebSearch","WebFetch"]}}},"pinned-context":{configStamp:{autoCompactEnabled:!0,autoCompactWindow:zKe}}},skillsConfig:{targetDir:"~/.claude/skills"},buildCommand:({prompt:e,model:t,isResume:n,reasoningEffort:r,nativeConfigPath:a})=>{let i=n?"--continue ":"",s=r?` --effort ${r}`:"",o=a?` --settings ${a}`:"";return`echo "${e}" | claude -p ${i}--model ${t}${s}${o} --output-format stream-json --verbose --dangerously-skip-permissions`}},codex:{image:"evolve-all",apiKeyEnv:"OPENAI_API_KEY",oauthEnv:"CODEX_OAUTH_FILE_PATH",effortSupport:"level",oauthFileName:"auth.json",baseUrlEnv:"OPENAI_BASE_URL",defaultModel:"gpt-5.6-sol",defaultReasoningEffort:"high",models:[{alias:"gpt-5.6-sol",modelId:"gpt-5.6-sol",description:"Newest frontier flagship"},{alias:"gpt-5.6-terra",modelId:"gpt-5.6-terra",description:"Balances intelligence and cost"},{alias:"gpt-5.6-luna",modelId:"gpt-5.6-luna",description:"High-volume, cost-sensitive tier"},{alias:"gpt-5.5",modelId:"gpt-5.5",description:"Previous frontier model"},{alias:"gpt-5.3-codex",modelId:"gpt-5.3-codex",description:"Industry-leading code-optimized"}],systemPromptFile:"AGENTS.md",mcpConfig:{settingsDir:"~/.codex",filename:"config.toml",format:"toml"},nativeConfig:{format:"toml",path:"~/.codex/config.toml",delivery:"base-file"},presets:{"no-internet":{commandFlags:" -c web_search=disabled"},"pinned-context":{commandFlags:` -c model_context_window=${zKe}`}},skillsConfig:{targetDir:"~/.codex/skills"},spendTrackingEnvs:{sessionTagEnv:"EVOLVE_LITELLM_CUSTOMER_ID",runTagEnv:"EVOLVE_LITELLM_TAGS"},setupCommand:`printf '%s\\n' "$OPENAI_API_KEY" | codex login --with-api-key`,buildCommand:({prompt:e,model:t,isResume:n,reasoningEffort:r,presetFlags:a})=>{let i=r?` -c model_reasoning_effort="${r}"`:"";return`printf '%s' "${e}" | codex exec --model ${t}${i}${a??""} --dangerously-bypass-approvals-and-sandbox --skip-git-repo-check --json${n?" resume --last":""}`}},gemini:{image:"evolve-all",apiKeyEnv:"GEMINI_API_KEY",effortSupport:"none",oauthEnv:"GEMINI_OAUTH_FILE_PATH",oauthFileName:"oauth_creds.json",oauthActivationEnv:{key:"GOOGLE_GENAI_USE_GCA",value:"true"},baseUrlEnv:"GOOGLE_GEMINI_BASE_URL",defaultModel:"gemini-3.5-flash",models:[{alias:"gemini-3.5-flash",modelId:"gemini-3.5-flash",description:"Latest flash the stable gemini CLI serves: coding + agentic planning"},{alias:"gemini-3.5-flash-lite",modelId:"gemini-3.5-flash-lite",description:"Most cost-effective 3.5-class model"},{alias:"gemini-3.1-pro-preview",modelId:"gemini-3.1-pro-preview",description:"Latest pro, complex agentic + coding"}],systemPromptFile:"GEMINI.md",mcpConfig:{settingsDir:"~/.gemini",filename:"settings.json",format:"json"},skillsConfig:{targetDir:"~/.gemini/skills"},customHeadersEnv:"GEMINI_CLI_CUSTOM_HEADERS",customHeadersFormat:"comma",gatewayPath:"/gemini",buildCommand:({prompt:e,model:t,isResume:n})=>`gemini ${n?"--resume latest ":""}--prompt ${yO(e)} --model ${t} --yolo --output-format stream-json`},qwen:{image:"evolve-all",apiKeyEnv:"OPENAI_API_KEY",baseUrlEnv:"OPENAI_BASE_URL",effortSupport:"binary",defaultModel:"qwen3.7-max",defaultReasoningEffort:"thinking",models:[{alias:"qwen3.7-max",modelId:"qwen3.7-max",description:"Strongest reasoning and coding option"},{alias:"qwen3.7-plus",modelId:"qwen3.7-plus",description:"Latest balanced Qwen Cloud recommendation"},{alias:"qwen3.6-flash",modelId:"qwen3.6-flash",description:"Fast and cost-effective option"}],systemPromptFile:"QWEN.md",mcpConfig:{settingsDir:"~/.qwen",filename:"settings.json",format:"json"},skillsConfig:{targetDir:"~/.qwen/skills"},spendTrackingJsonConfig:{headersPath:"model.generationConfig.customHeaders"},gatewayModelAliases:{"qwen3.7-max":"dashscope/qwen3.7-max","qwen3.7-plus":"dashscope/qwen3.7-plus","qwen3.6-flash":"dashscope/qwen3.6-flash"},defaultBaseUrl:"https://dashscope-intl.aliyuncs.com/compatible-mode/v1",buildCommand:({prompt:e,model:t,isResume:n,isDirectMode:r})=>{let a=n?"--continue ":"",i=r||t.startsWith("dashscope/")?t:`dashscope/${t}`;return`qwen "${e}" ${a}--auth-type openai --model ${i} --yolo --output-format stream-json`}},kimi:{image:"evolve-all",apiKeyEnv:"KIMI_API_KEY",effortSupport:"level",baseUrlEnv:"KIMI_BASE_URL",defaultModel:"kimi-k3",defaultReasoningEffort:"max",models:[{alias:"kimi-k3",modelId:"moonshot/kimi-k3",description:"Latest flagship: 1M context, always-on thinking",maxContextSize:1048576},{alias:"kimi-k2.7-code",modelId:"moonshot/kimi-k2.7-code",description:"Latest coding-specialized standard model"},{alias:"kimi-k3-raptor",modelId:"kimi-k3-raptor",description:"Evolve-managed Kimi K3 Raptor route for latency-sensitive agent runs",maxContextSize:1048576},{alias:"kimi-k2p7-code-raptor",modelId:"kimi-k2p7-code-raptor",description:"Evolve-managed Kimi K2.7 Code Raptor route for latency-sensitive agent runs"}],systemPromptFile:"AGENTS.md",mcpConfig:{settingsDir:"~/.kimi-code",filename:"mcp.json",format:"json"},skillsConfig:{targetDir:"~/.kimi-code/skills"},defaultBaseUrl:"https://api.moonshot.ai/v1",spendTrackingTomlProvider:{configPath:"~/.kimi-code/config.toml",providerName:"evolve-gateway",modelName:"evolve-default",maxContextSize:262144},checkpointExcludes:[".kimi-code/config.toml"],gatewayModelAliases:{"kimi-k3":"moonshot/kimi-k3","kimi-k2.7-code":"moonshot/kimi-k2.7-code","kimi-k3-raptor":"kimi-k3-raptor","kimi-k2p7-code-raptor":"kimi-k2p7-code-raptor"},buildCommand:({prompt:e,isResume:t,reasoningEffort:n,homeDir:r=qp})=>{let a=t?"--continue ":"",i=yO(e),s=`--config-file ${r}/.kimi-code/config.toml`,o=`$(if [ -f ${r}/.kimi-code/mcp.json ]; then printf ' --mcp-config-file ${r}/.kimi-code/mcp.json'; fi)`,c=uB(n)?"":" --no-thinking";return`if kimi --help 2>&1 | grep -q -- '--print'; then kimi --print ${a}${s}${o}${c} -p ${i} --output-format stream-json; else kimi ${a}-p ${i} --output-format stream-json; fi`}},opencode:{image:"evolve-all",apiKeyEnv:"OPENROUTER_API_KEY",effortSupport:"level",baseUrlEnv:"OPENAI_BASE_URL",defaultModel:"openrouter/anthropic/claude-opus-5",defaultReasoningEffort:"high",providerEnvMap:{openrouter:{keyEnv:"OPENROUTER_API_KEY"}},gatewayConfigEnv:"OPENCODE_CONFIG_CONTENT",models:[{alias:"openrouter/anthropic/claude-fable-5",modelId:"openrouter/anthropic/claude-fable-5",description:"Anthropic Fable via OpenRouter"},{alias:"openrouter/anthropic/claude-opus-5",modelId:"openrouter/anthropic/claude-opus-5",description:"Anthropic Opus 5 via OpenRouter"},{alias:"openrouter/anthropic/claude-sonnet-5",modelId:"openrouter/anthropic/claude-sonnet-5",description:"Anthropic Sonnet 5 via OpenRouter"},{alias:"openrouter/anthropic/claude-haiku-4.5",modelId:"openrouter/anthropic/claude-haiku-4.5",description:"Anthropic Haiku via OpenRouter"},{alias:"openrouter/openai/gpt-5.6-sol",modelId:"openrouter/openai/gpt-5.6-sol",description:"OpenAI GPT-5.6 Sol via OpenRouter"},{alias:"openrouter/openai/gpt-5.6-terra",modelId:"openrouter/openai/gpt-5.6-terra",description:"OpenAI GPT-5.6 Terra via OpenRouter"},{alias:"openrouter/openai/gpt-5.6-luna",modelId:"openrouter/openai/gpt-5.6-luna",description:"OpenAI GPT-5.6 Luna via OpenRouter"},{alias:"openrouter/google/gemini-3.6-flash",modelId:"openrouter/google/gemini-3.6-flash",description:"Gemini 3.6 Flash via OpenRouter"},{alias:"openrouter/qwen/qwen3.7-max",modelId:"openrouter/qwen/qwen3.7-max",description:"Qwen 3.7 Max via OpenRouter"},{alias:"openrouter/moonshotai/kimi-k3",modelId:"openrouter/moonshotai/kimi-k3",description:"Kimi K3 via OpenRouter"},{alias:"openrouter/z-ai/glm-5.3",modelId:"openrouter/z-ai/glm-5.3",description:"Zhipu GLM-5.3 via OpenRouter"},{alias:"openrouter/z-ai/glm-5.3-flash",modelId:"openrouter/z-ai/glm-5.3-flash",description:"Zhipu GLM-5.3 Flash (OpenRouter id; the Evolve gateway serves it from Fireworks)"}],systemPromptFile:"AGENTS.md",mcpConfig:{settingsDir:".",filename:"opencode.json",format:"json"},skillsConfig:{targetDir:"~/.agents/skills"},checkpointDirs:["~/.local/share/opencode","~/.config/opencode","~/.local/state/opencode"],buildCommand:({prompt:e,model:t,isResume:n,isDirectMode:r,isExternalGateway:a,reasoningEffort:i})=>{let s=n?"--continue ":"",o=x5t(i);if(a)return`OPENCODE_PERMISSION='{"*":"allow"}' opencode run ${s}--model litellm/${t} --format json${o} "${e}" < /dev/null`;let c=t.startsWith("openrouter/")?t:`openrouter/${t}`;return r?`OPENCODE_PERMISSION='{"*":"allow"}' opencode run ${s}--model ${c} --format json${o} "${e}" < /dev/null`:`OPENCODE_PERMISSION='{"*":"allow"}' opencode run ${s}--model litellm/${c} --format json${o} "${e}" < /dev/null`}},droid:{image:"evolve-all",apiKeyEnv:"FACTORY_API_KEY",effortSupport:"level",defaultModel:"claude-opus-5",defaultReasoningEffort:"high",models:[{alias:"claude-fable-5",modelId:"claude-fable-5",description:"Factory-managed Claude Fable 5"},{alias:"claude-opus-5",modelId:"claude-opus-5",description:"Factory-managed Claude Opus 5"},{alias:"claude-sonnet-5",modelId:"claude-sonnet-5",description:"Factory-managed Claude Sonnet 5"},{alias:"claude-haiku-4-5",modelId:"claude-haiku-4-5-20251001",description:"Factory-managed Claude Haiku 4.5"},{alias:"gpt-5.6-sol",modelId:"gpt-5.6-sol",description:"Factory-managed GPT-5.6 Sol"},{alias:"gpt-5.6-terra",modelId:"gpt-5.6-terra",description:"Factory-managed GPT-5.6 Terra"},{alias:"gpt-5.6-luna",modelId:"gpt-5.6-luna",description:"Factory-managed GPT-5.6 Luna"},{alias:"gemini-3.6-flash",modelId:"gemini-3.6-flash",description:"Factory-managed Gemini 3.6 Flash"},{alias:"qwen3.7-max",modelId:"qwen3.7-max",description:"Qwen 3.7 Max via the Evolve gateway"},{alias:"kimi-k3",modelId:"kimi-k3",description:"Factory-managed Droid Core Kimi K3"},{alias:"glm-5.3",modelId:"glm-5.3",description:"Zhipu GLM-5.3 via the Evolve gateway"},{alias:"glm-5.3-flash",modelId:"glm-5.3-flash",description:"Zhipu GLM-5.3 Flash via the Evolve gateway"}],systemPromptFile:"AGENTS.md",mcpConfig:{settingsDir:"~/.factory",filename:"mcp.json",format:"json"},skillsConfig:{targetDir:"~/.factory/skills"},skipApiKeyEnvInGateway:!0,gatewayModelAliases:{"kimi-k3":"moonshot/kimi-k3","glm-5.3":"openrouter/z-ai/glm-5.3","qwen3.7-max":"dashscope/qwen3.7-max"},droidGatewaySettings:{settingsPath:"~/.factory/evolve-settings.json",displayName:"Evolve Gateway",provider:"generic-chat-completion-api",maxOutputTokens:32768},checkpointDirs:["~/.factory"],buildCommand:({prompt:e,model:t,isResume:n,sessionId:r,reasoningEffort:a,isDirectMode:i,isExternalGateway:s,homeDir:o=qp})=>{let c=!i||s,l=c?`--settings ${o}/.factory/evolve-settings.json `:"",u=c?"custom:Evolve-Gateway-0":t,d=a?` --reasoning-effort ${a}`:"",f=n&&r?`--session-id ${yO(r)} `:"";return`printf '%s' ${yO(e)} | droid ${l}exec ${f}--skip-permissions-unsafe --cwd ${o}/workspace --output-format stream-json --model ${yO(u)}${d}`}}};function xv(e){let t=Vp[e];if(!t)throw new Error(`Unknown agent type: ${e}`);return t}function E5t(e){return e in Vp}function Fp(e,t=qp){return e.replace(/^~/,t)}function yO(e){return`'${e.replace(/'/g,"'\\''")}'`}function Yw(e,t=qp){let n=xv(e);return`${Fp(n.mcpConfig.settingsDir,t)}/${n.mcpConfig.filename}`}function Kw(e,t=qp){let n=xv(e);return Fp(n.mcpConfig.settingsDir,t)}function Ev(e){if(e instanceof Error){let t=e.message.toLowerCase();return t.includes("not found")||t.includes("enoent")||t.includes("no such file")||t.includes("does not exist")}return!1}function RXe(e,t){let n=[t.command,t.url].filter(Boolean);if(n.length===0)throw new Error(`MCP server "${e}" must specify command or url`);if(n.length>1)throw new Error(`MCP server "${e}" cannot specify both command and url`)}function gB(e){for(let[t,n]of Object.entries(e))RXe(t,n)}function EO(e){return e.type?e.type:e.command?"stdio":"sse"}function T5t(e){let t=EO(e);return{...e,type:t}}function k5t(e){let{type:t,url:n,...r}=e;return EO(e)==="http"&&n?{httpUrl:n,...r}:n?{url:n,...r}:r}function O5t(e){return{type:EO(e),...e}}function A5t(e){let{type:t,...n}=e;return n.command?{...n,transport:"stdio"}:n.url&&(t==="http"||t==="sse")?{...n,transport:t}:n}function P5t(e){let t=EO(e),{type:n,httpHeaders:r,envHttpHeaders:a,bearerTokenEnvVar:i,envVars:s,...o}=e;if(t==="stdio"&&e.command)return{type:"stdio",...o};if(e.url){let c={...o,type:t==="sse"?"sse":"http",url:e.url},l=e.headers??r;return l&&Object.keys(l).length>0&&(c.headers=l),c}return{type:t==="stdio"?"stdio":"http",...o}}async function UZ(e,t,n,r,a){gB(n);let i=Kw(t,a),s=Yw(t,a);await e.files.makeDir(i);let o={};try{let l=await e.files.read(s);typeof l=="string"&&(o=JSON.parse(l))}catch(l){if(!Ev(l))throw l}let c=Object.fromEntries(Object.entries(n).map(([l,u])=>[l,r(u)]));await e.files.write(s,JSON.stringify({...o,mcpServers:c},null,2))}async function R5t(e,t,n,r){gB(n);let a=Kw("claude",r),i=Yw("claude",r),s=Object.fromEntries(Object.entries(n).map(([c,l])=>[c,O5t(l)]));await e.files.write(`${t}/.mcp.json`,JSON.stringify({mcpServers:s},null,2)),await e.files.makeDir(a);let o={};try{let c=await e.files.read(i);typeof c=="string"&&(o=JSON.parse(c))}catch(c){if(!Ev(c))throw c}o.enableAllProjectMcpServers=!0,await e.files.write(i,JSON.stringify(o,null,2))}async function C5t(e,t,n){await UZ(e,"gemini",t,T5t,n)}async function N5t(e,t,n){await UZ(e,"qwen",t,k5t,n)}async function GKe(e,t,n,r,a){let i=Kw(t,a),s=Yw(t,a);await e.files.makeDir(i);let o={};try{let f=await e.files.read(s);typeof f=="string"&&(o=JSON.parse(f))}catch(f){if(!Ev(f))throw f}let c=n.split("."),l=o;for(let f=0;f<c.length-1;f++){let p=c[f];(typeof l[p]!="object"||l[p]===null)&&(l[p]={}),l=l[p]}let u=c[c.length-1],d=typeof l[u]=="object"&&l[u]!==null?l[u]:{};l[u]={...d,...r},await e.files.write(s,JSON.stringify(o,null,2))}async function M5t(e,t,n){let r=Kw("qwen",n),a=Yw("qwen",n);await e.files.makeDir(r);let i={};try{let l=await e.files.read(a);typeof l=="string"&&(i=JSON.parse(l))}catch(l){if(!Ev(l))throw l}let s=i.model??{},o=s.generationConfig??{},c=o.extra_body??{};i.model={...s,generationConfig:{...o,extra_body:{...c,enable_thinking:t}}},await e.files.write(a,JSON.stringify(i,null,2))}async function D5t(e,t,n){await UZ(e,"kimi",t,A5t,n)}async function U5t(e,t,n){gB(n);let r=`${t}/.factory`,a=`${r}/mcp.json`;await e.files.makeDir(r);let i={};try{let o=await e.files.read(a);typeof o=="string"&&(i=JSON.parse(o))}catch(o){if(!Ev(o))throw o}let s=Object.fromEntries(Object.entries(n).map(([o,c])=>[o,P5t(c)]));await e.files.write(a,JSON.stringify({...i,mcpServers:s},null,2))}async function B5t(e,t,n,r){let a=Fp(t.settingsPath,r),i=a.slice(0,a.lastIndexOf("/"));await e.files.makeDir(i);let s={cloudSessionSync:!1,customModels:[{model:t.model,displayName:t.displayName,baseUrl:t.baseUrl,apiKey:`\${${t.apiKeyEnv}}`,provider:t.provider,...t.maxOutputTokens!==void 0&&{maxOutputTokens:t.maxOutputTokens},extraHeaders:n}]};await e.files.write(a,JSON.stringify(s,null,2))}async function F5t(e,t,n){gB(n);let r=`${t}/opencode.json`,a={};try{let s=await e.files.read(r);typeof s=="string"&&(a=JSON.parse(s))}catch(s){if(!Ev(s))throw s}let i=Object.fromEntries(Object.entries(n).map(([s,o])=>[s,L5t(o)]));await e.files.write(r,JSON.stringify({...a,mcp:i},null,2))}function L5t(e){let t=EO(e);if(t==="stdio"&&e.command){let n={type:"local",command:e.args?[e.command,...e.args]:[e.command]};return e.env&&Object.keys(e.env).length>0&&(n.environment=e.env),n}if(e.url){let n={type:"remote",url:e.url};return e.headers&&Object.keys(e.headers).length>0&&(n.headers=e.headers),n}return{type:t==="stdio"?"local":"remote",...e}}function OZ(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function CXe(e,t,n){let r=e[t];if(r===void 0)return{};let a=OZ(r);if(!a){let i=Array.isArray(r)?"an array":`a ${typeof r}`;throw new Error(`Refusing to rewrite "${t}" in ${n}: expected a TOML table, found ${i}`)}return a}function AZ(e,t){if(e===t)return!0;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((i,s)=>AZ(i,t[s]));let n=OZ(e),r=OZ(t);if(!n||!r)return!1;let a=Object.keys(n);return a.length===Object.keys(r).length&&a.every(i=>i in r&&AZ(n[i],r[i]))}async function NXe(e,t){let n="";try{let r=await e.files.read(t);typeof r=="string"&&(n=r)}catch(r){if(!Ev(r))throw r;return{}}if(!n.trim())return{};try{return Bm(n)}catch(r){throw new Error(`Failed to parse TOML at ${t}: ${r.message}`)}}async function BZ(e,t,n){await e.files.write(t,Wv(n).trimEnd()+`
|
|
678
|
+
]`;continue}a+=r[c],r[c]==="\\"?i=!0:s&&r[c]==="]"?s=!1:!s&&r[c]==="["&&(s=!0)}try{new RegExp(a)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return a}function UA(e,t){if(t.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),t.target==="openApi3"&&e.keyType?._def.typeName===Ue.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((r,a)=>({...r,[a]:gt(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",a]})??Jr(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let n={type:"object",additionalProperties:gt(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return n;if(e.keyType?._def.typeName===Ue.ZodString&&e.keyType._def.checks?.length){let{type:r,...a}=DA(e.keyType._def,t);return{...n,propertyNames:a}}else{if(e.keyType?._def.typeName===Ue.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===Ue.ZodBranded&&e.keyType._def.type._def.typeName===Ue.ZodString&&e.keyType._def.type._def.checks?.length){let{type:r,...a}=MA(e.keyType._def,t);return{...n,propertyNames:a}}}return n}function ire(e,t){if(t.mapStrategy==="record")return UA(e,t);let n=gt(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||Jr(t),r=gt(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||Jr(t);return{type:"array",maxItems:125,items:{type:"array",items:[n,r],minItems:2,maxItems:2}}}function are(e){let t=e.values,r=Object.keys(e.values).filter(i=>typeof t[t[i]]!="number").map(i=>t[i]),a=Array.from(new Set(r.map(i=>typeof i)));return{type:a.length===1?a[0]==="string"?"string":"number":["string","number"],enum:r}}function sre(e){return e.target==="openAi"?void 0:{not:Jr({...e,currentPath:[...e.currentPath,"not"]})}}function ore(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var UI={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function lre(e,t){if(t.target==="openApi3")return cre(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(r=>r._def.typeName in UI&&(!r._def.checks||!r._def.checks.length))){let r=n.reduce((a,i)=>{let s=UI[i._def.typeName];return s&&!a.includes(s)?[...a,s]:a},[]);return{type:r.length>1?r:r[0]}}else if(n.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){let r=n.reduce((a,i)=>{let s=typeof i._def.value;switch(s){case"string":case"number":case"boolean":return[...a,s];case"bigint":return[...a,"integer"];case"object":if(i._def.value===null)return[...a,"null"];case"symbol":case"undefined":case"function":default:return a}},[]);if(r.length===n.length){let a=r.filter((i,s,o)=>o.indexOf(i)===s);return{type:a.length>1?a:a[0],enum:n.reduce((i,s)=>i.includes(s._def.value)?i:[...i,s._def.value],[])}}}else if(n.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((r,a)=>[...r,...a._def.values.filter(i=>!r.includes(i))],[])};return cre(e,t)}var cre=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((r,a)=>gt(r._def,{...t,currentPath:[...t.currentPath,"anyOf",`${a}`]})).filter(r=>!!r&&(!t.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return n.length?{anyOf:n}:void 0};function ure(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target==="openApi3"?{type:UI[e.innerType._def.typeName],nullable:!0}:{type:[UI[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){let r=gt(e.innerType._def,{...t,currentPath:[...t.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let n=gt(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function dre(e,t){let n={type:"number"};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case"int":n.type="integer",CL(n,"type",r.message,t);break;case"min":t.target==="jsonSchema7"?r.inclusive?yn(n,"minimum",r.value,r.message,t):yn(n,"exclusiveMinimum",r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),yn(n,"minimum",r.value,r.message,t));break;case"max":t.target==="jsonSchema7"?r.inclusive?yn(n,"maximum",r.value,r.message,t):yn(n,"exclusiveMaximum",r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),yn(n,"maximum",r.value,r.message,t));break;case"multipleOf":yn(n,"multipleOf",r.value,r.message,t);break}return n}function fre(e,t){let n=t.target==="openAi",r={type:"object",properties:{}},a=[],i=e.shape();for(let o in i){let c=i[o];if(c===void 0||c._def===void 0)continue;let l=ist(c);l&&n&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),l=!1);let u=gt(c._def,{...t,currentPath:[...t.currentPath,"properties",o],propertyPath:[...t.currentPath,"properties",o]});u!==void 0&&(r.properties[o]=u,l||a.push(o))}a.length&&(r.required=a);let s=rst(e,t);return s!==void 0&&(r.additionalProperties=s),r}function rst(e,t){if(e.catchall._def.typeName!=="ZodNever")return gt(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function ist(e){try{return e.isOptional()}catch{return!0}}var pre=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return gt(e.innerType._def,t);let n=gt(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return n?{anyOf:[{not:Jr(t)},n]}:Jr(t)};var hre=(e,t)=>{if(t.pipeStrategy==="input")return gt(e.in._def,t);if(t.pipeStrategy==="output")return gt(e.out._def,t);let n=gt(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),r=gt(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,r].filter(a=>a!==void 0)}};function mre(e,t){return gt(e.type._def,t)}function gre(e,t){let r={type:"array",uniqueItems:!0,items:gt(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&yn(r,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&yn(r,"maxItems",e.maxSize.value,e.maxSize.message,t),r}function yre(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((n,r)=>gt(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:gt(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((n,r)=>gt(n._def,{...t,currentPath:[...t.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}function vre(e){return{not:Jr(e)}}function bre(e){return Jr(e)}var Sre=(e,t)=>gt(e.innerType._def,t);var _re=(e,t,n)=>{switch(t){case Ue.ZodString:return DA(e,n);case Ue.ZodNumber:return dre(e,n);case Ue.ZodObject:return fre(e,n);case Ue.ZodBigInt:return Yne(e,n);case Ue.ZodBoolean:return Kne();case Ue.ZodDate:return UL(e,n);case Ue.ZodUndefined:return vre(n);case Ue.ZodNull:return ore(n);case Ue.ZodArray:return jne(e,n);case Ue.ZodUnion:case Ue.ZodDiscriminatedUnion:return lre(e,n);case Ue.ZodIntersection:return tre(e,n);case Ue.ZodTuple:return yre(e,n);case Ue.ZodRecord:return UA(e,n);case Ue.ZodLiteral:return nre(e,n);case Ue.ZodEnum:return ere(e);case Ue.ZodNativeEnum:return are(e);case Ue.ZodNullable:return ure(e,n);case Ue.ZodOptional:return pre(e,n);case Ue.ZodMap:return ire(e,n);case Ue.ZodSet:return gre(e,n);case Ue.ZodLazy:return()=>e.getter()._def;case Ue.ZodPromise:return mre(e,n);case Ue.ZodNaN:case Ue.ZodNever:return sre(n);case Ue.ZodEffects:return Qne(e,n);case Ue.ZodAny:return Jr(n);case Ue.ZodUnknown:return bre(n);case Ue.ZodDefault:return Zne(e,n);case Ue.ZodBranded:return MA(e,n);case Ue.ZodReadonly:return Sre(e,n);case Ue.ZodCatch:return Xne(e,n);case Ue.ZodPipeline:return hre(e,n);case Ue.ZodFunction:case Ue.ZodVoid:case Ue.ZodSymbol:return;default:return(r=>{})(t)}};function gt(e,t,n=!1){let r=t.seen.get(e);if(t.override){let o=t.override?.(e,t,r,n);if(o!==Mne)return o}if(r&&!n){let o=ast(r,t);if(o!==void 0)return o}let a={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,a);let i=_re(e,e.typeName,t),s=typeof i=="function"?gt(i(),t):i;if(s&&sst(e,t,s),t.postProcess){let o=t.postProcess(s,e,t);return a.jsonSchema=s,o}return a.jsonSchema=s,s}var ast=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:OA(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((n,r)=>t.currentPath[r]===n)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),Jr(t)):t.$refStrategy==="seen"?Jr(t):void 0}},sst=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n);var wre=(e,t)=>{let n=Une(t),r=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((c,[l,u])=>({...c,[l]:gt(u._def,{...n,currentPath:[...n.basePath,n.definitionPath,l]},!0)??Jr(n)}),{}):void 0,a=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,i=gt(e._def,a===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,a]},!1)??Jr(n),s=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.name:void 0;s!==void 0&&(i.title=s),n.flags.hasReferencedOpenAiAnyType&&(r||(r={}),r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:n.$refStrategy==="relative"?"1":[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join("/")}}));let o=a===void 0?r?{...i,[n.definitionPath]:r}:i:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,a].join("/"),[n.definitionPath]:{...r,[a]:i}};return n.target==="jsonSchema7"?o.$schema="http://json-schema.org/draft-07/schema#":(n.target==="jsonSchema2019-09"||n.target==="openAi")&&(o.$schema="https://json-schema.org/draft/2019-09/schema#"),n.target==="openAi"&&("anyOf"in o||"oneOf"in o||"allOf"in o||"type"in o&&Array.isArray(o.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),o};var Ire=wre;var rf=Ve(require("fs"),1),AXe=require("fs");rE();FT();tB();var $Ke=["no-internet","pinned-context"],w5t={strict:{coerceTypes:!1,removeAdditional:!1,useDefaults:!1,allErrors:!0},loose:{coerceTypes:"array",removeAdditional:!1,useDefaults:!0,allErrors:!0}};var zKe=2e5;function I5t(e,t){return t??Vp[e]?.defaultReasoningEffort}function uB(e){return e!=="off"&&e!=="none"&&e!=="minimal"&&e!=="no-thinking"}function PXe(e){if(!(e==="off"||e==="none"||e==="no-thinking"))return!e||e==="thinking"||e==="medium"?"medium":e==="low"||e==="minimal"?"minimal":e==="xhigh"?"max":e}function x5t(e){let t=PXe(e);return t?` --variant ${t} --thinking`:""}var Vp={claude:{image:"evolve-all",apiKeyEnv:"ANTHROPIC_API_KEY",effortSupport:"level",oauthEnv:"CLAUDE_CODE_OAUTH_TOKEN",baseUrlEnv:"ANTHROPIC_BASE_URL",customHeadersEnv:"ANTHROPIC_CUSTOM_HEADERS",defaultModel:"opus",defaultReasoningEffort:"high",models:[{alias:"fable",modelId:"claude-fable-5",description:"Highest capability, long-horizon agentic work"},{alias:"opus",modelId:"claude-opus-5",description:"Complex reasoning, R&D, architecting"},{alias:"sonnet",modelId:"claude-sonnet-5",description:"Daily coding, features, tests"},{alias:"haiku",modelId:"claude-haiku-4-5-20251001",description:"Quick tasks, syntax correction"},{alias:"opus[1m]",modelId:"opus[1m]",description:"Complex reasoning with 1M context window"},{alias:"sonnet[1m]",modelId:"sonnet[1m]",description:"Daily coding with 1M context window"},{alias:"glm-5.3",modelId:"glm-5.3",description:"Zhipu GLM-5.3 via the Evolve gateway"},{alias:"glm-5.3-flash",modelId:"glm-5.3-flash",description:"Zhipu GLM-5.3 Flash via the Evolve gateway"},{alias:"deepseek-flash",modelId:"deepseek-flash",description:"DeepSeek V4.1 Flash (Fireworks) via the Evolve gateway"}],systemPromptFile:"CLAUDE.md",mcpConfig:{settingsDir:"~/.claude",filename:"settings.json",format:"json",projectConfig:!0},nativeConfig:{format:"json",path:"~/.claude/evolve-user-settings.json",delivery:"settings-flag"},presets:{"no-internet":{configStamp:{permissions:{deny:["WebSearch","WebFetch"]}}},"pinned-context":{configStamp:{autoCompactEnabled:!0,autoCompactWindow:zKe}}},skillsConfig:{targetDir:"~/.claude/skills"},buildCommand:({prompt:e,model:t,isResume:n,reasoningEffort:r,nativeConfigPath:a})=>{let i=n?"--continue ":"",s=r?` --effort ${r}`:"",o=a?` --settings ${a}`:"";return`echo "${e}" | claude -p ${i}--model ${t}${s}${o} --output-format stream-json --verbose --dangerously-skip-permissions`}},codex:{image:"evolve-all",apiKeyEnv:"OPENAI_API_KEY",oauthEnv:"CODEX_OAUTH_FILE_PATH",effortSupport:"level",oauthFileName:"auth.json",baseUrlEnv:"OPENAI_BASE_URL",defaultModel:"gpt-5.6-sol",defaultReasoningEffort:"high",models:[{alias:"gpt-5.6-sol",modelId:"gpt-5.6-sol",description:"Newest frontier flagship"},{alias:"gpt-5.6-terra",modelId:"gpt-5.6-terra",description:"Balances intelligence and cost"},{alias:"gpt-5.6-luna",modelId:"gpt-5.6-luna",description:"High-volume, cost-sensitive tier"},{alias:"gpt-5.5",modelId:"gpt-5.5",description:"Previous frontier model"},{alias:"gpt-5.3-codex",modelId:"gpt-5.3-codex",description:"Industry-leading code-optimized"}],systemPromptFile:"AGENTS.md",mcpConfig:{settingsDir:"~/.codex",filename:"config.toml",format:"toml"},nativeConfig:{format:"toml",path:"~/.codex/config.toml",delivery:"base-file"},presets:{"no-internet":{commandFlags:" -c web_search=disabled"},"pinned-context":{commandFlags:` -c model_context_window=${zKe}`}},skillsConfig:{targetDir:"~/.codex/skills"},spendTrackingEnvs:{sessionTagEnv:"EVOLVE_LITELLM_CUSTOMER_ID",runTagEnv:"EVOLVE_LITELLM_TAGS"},setupCommand:`printf '%s\\n' "$OPENAI_API_KEY" | codex login --with-api-key`,buildCommand:({prompt:e,model:t,isResume:n,reasoningEffort:r,presetFlags:a})=>{let i=r?` -c model_reasoning_effort="${r}"`:"";return`printf '%s' "${e}" | codex exec --model ${t}${i}${a??""} --dangerously-bypass-approvals-and-sandbox --skip-git-repo-check --json${n?" resume --last":""}`}},gemini:{image:"evolve-all",apiKeyEnv:"GEMINI_API_KEY",effortSupport:"none",oauthEnv:"GEMINI_OAUTH_FILE_PATH",oauthFileName:"oauth_creds.json",oauthActivationEnv:{key:"GOOGLE_GENAI_USE_GCA",value:"true"},baseUrlEnv:"GOOGLE_GEMINI_BASE_URL",defaultModel:"gemini-3.5-flash",models:[{alias:"gemini-3.5-flash",modelId:"gemini-3.5-flash",description:"Latest flash the stable gemini CLI serves: coding + agentic planning"},{alias:"gemini-3.5-flash-lite",modelId:"gemini-3.5-flash-lite",description:"Most cost-effective 3.5-class model"},{alias:"gemini-3.1-pro-preview",modelId:"gemini-3.1-pro-preview",description:"Latest pro, complex agentic + coding"}],systemPromptFile:"GEMINI.md",mcpConfig:{settingsDir:"~/.gemini",filename:"settings.json",format:"json"},skillsConfig:{targetDir:"~/.gemini/skills"},customHeadersEnv:"GEMINI_CLI_CUSTOM_HEADERS",customHeadersFormat:"comma",gatewayPath:"/gemini",buildCommand:({prompt:e,model:t,isResume:n})=>`gemini ${n?"--resume latest ":""}--prompt ${yO(e)} --model ${t} --yolo --output-format stream-json`},qwen:{image:"evolve-all",apiKeyEnv:"OPENAI_API_KEY",baseUrlEnv:"OPENAI_BASE_URL",effortSupport:"binary",defaultModel:"qwen3.7-max",defaultReasoningEffort:"thinking",models:[{alias:"qwen3.7-max",modelId:"qwen3.7-max",description:"Strongest reasoning and coding option"},{alias:"qwen3.7-plus",modelId:"qwen3.7-plus",description:"Latest balanced Qwen Cloud recommendation"},{alias:"qwen3.6-flash",modelId:"qwen3.6-flash",description:"Fast and cost-effective option"}],systemPromptFile:"QWEN.md",mcpConfig:{settingsDir:"~/.qwen",filename:"settings.json",format:"json"},skillsConfig:{targetDir:"~/.qwen/skills"},spendTrackingJsonConfig:{headersPath:"model.generationConfig.customHeaders"},gatewayModelAliases:{"qwen3.7-max":"dashscope/qwen3.7-max","qwen3.7-plus":"dashscope/qwen3.7-plus","qwen3.6-flash":"dashscope/qwen3.6-flash"},defaultBaseUrl:"https://dashscope-intl.aliyuncs.com/compatible-mode/v1",buildCommand:({prompt:e,model:t,isResume:n,isDirectMode:r})=>{let a=n?"--continue ":"",i=r||t.startsWith("dashscope/")?t:`dashscope/${t}`;return`qwen "${e}" ${a}--auth-type openai --model ${i} --yolo --output-format stream-json`}},kimi:{image:"evolve-all",apiKeyEnv:"KIMI_API_KEY",effortSupport:"level",baseUrlEnv:"KIMI_BASE_URL",defaultModel:"kimi-k3",defaultReasoningEffort:"max",models:[{alias:"kimi-k3",modelId:"moonshot/kimi-k3",description:"Latest flagship: 1M context, always-on thinking",maxContextSize:1048576},{alias:"kimi-k2.7-code",modelId:"moonshot/kimi-k2.7-code",description:"Latest coding-specialized standard model"},{alias:"kimi-k3-raptor",modelId:"kimi-k3-raptor",description:"Evolve-managed Kimi K3 Raptor route for latency-sensitive agent runs",maxContextSize:1048576},{alias:"kimi-k2p7-code-raptor",modelId:"kimi-k2p7-code-raptor",description:"Evolve-managed Kimi K2.7 Code Raptor route for latency-sensitive agent runs"}],systemPromptFile:"AGENTS.md",mcpConfig:{settingsDir:"~/.kimi-code",filename:"mcp.json",format:"json"},skillsConfig:{targetDir:"~/.kimi-code/skills"},defaultBaseUrl:"https://api.moonshot.ai/v1",spendTrackingTomlProvider:{configPath:"~/.kimi-code/config.toml",providerName:"evolve-gateway",modelName:"evolve-default",maxContextSize:262144},checkpointExcludes:[".kimi-code/config.toml"],gatewayModelAliases:{"kimi-k3":"moonshot/kimi-k3","kimi-k2.7-code":"moonshot/kimi-k2.7-code","kimi-k3-raptor":"kimi-k3-raptor","kimi-k2p7-code-raptor":"kimi-k2p7-code-raptor"},buildCommand:({prompt:e,isResume:t,reasoningEffort:n,homeDir:r=qp})=>{let a=t?"--continue ":"",i=yO(e),s=`--config-file ${r}/.kimi-code/config.toml`,o=`$(if [ -f ${r}/.kimi-code/mcp.json ]; then printf ' --mcp-config-file ${r}/.kimi-code/mcp.json'; fi)`,c=uB(n)?"":" --no-thinking";return`if kimi --help 2>&1 | grep -q -- '--print'; then kimi --print ${a}${s}${o}${c} -p ${i} --output-format stream-json; else kimi ${a}-p ${i} --output-format stream-json; fi`}},opencode:{image:"evolve-all",apiKeyEnv:"OPENROUTER_API_KEY",effortSupport:"level",baseUrlEnv:"OPENAI_BASE_URL",defaultModel:"openrouter/anthropic/claude-opus-5",defaultReasoningEffort:"high",providerEnvMap:{openrouter:{keyEnv:"OPENROUTER_API_KEY"}},gatewayConfigEnv:"OPENCODE_CONFIG_CONTENT",models:[{alias:"openrouter/anthropic/claude-fable-5",modelId:"openrouter/anthropic/claude-fable-5",description:"Anthropic Fable via OpenRouter"},{alias:"openrouter/anthropic/claude-opus-5",modelId:"openrouter/anthropic/claude-opus-5",description:"Anthropic Opus 5 via OpenRouter"},{alias:"openrouter/anthropic/claude-sonnet-5",modelId:"openrouter/anthropic/claude-sonnet-5",description:"Anthropic Sonnet 5 via OpenRouter"},{alias:"openrouter/anthropic/claude-haiku-4.5",modelId:"openrouter/anthropic/claude-haiku-4.5",description:"Anthropic Haiku via OpenRouter"},{alias:"openrouter/openai/gpt-5.6-sol",modelId:"openrouter/openai/gpt-5.6-sol",description:"OpenAI GPT-5.6 Sol via OpenRouter"},{alias:"openrouter/openai/gpt-5.6-terra",modelId:"openrouter/openai/gpt-5.6-terra",description:"OpenAI GPT-5.6 Terra via OpenRouter"},{alias:"openrouter/openai/gpt-5.6-luna",modelId:"openrouter/openai/gpt-5.6-luna",description:"OpenAI GPT-5.6 Luna via OpenRouter"},{alias:"openrouter/google/gemini-3.6-flash",modelId:"openrouter/google/gemini-3.6-flash",description:"Gemini 3.6 Flash via OpenRouter"},{alias:"openrouter/qwen/qwen3.7-max",modelId:"openrouter/qwen/qwen3.7-max",description:"Qwen 3.7 Max via OpenRouter"},{alias:"openrouter/moonshotai/kimi-k3",modelId:"openrouter/moonshotai/kimi-k3",description:"Kimi K3 via OpenRouter"},{alias:"openrouter/z-ai/glm-5.3",modelId:"openrouter/z-ai/glm-5.3",description:"Zhipu GLM-5.3 via OpenRouter"},{alias:"openrouter/z-ai/glm-5.3-flash",modelId:"openrouter/z-ai/glm-5.3-flash",description:"Zhipu GLM-5.3 Flash (OpenRouter id; the Evolve gateway serves it from Fireworks)"}],systemPromptFile:"AGENTS.md",mcpConfig:{settingsDir:".",filename:"opencode.json",format:"json"},skillsConfig:{targetDir:"~/.agents/skills"},checkpointDirs:["~/.local/share/opencode","~/.config/opencode","~/.local/state/opencode"],buildCommand:({prompt:e,model:t,isResume:n,isDirectMode:r,isExternalGateway:a,reasoningEffort:i})=>{let s=n?"--continue ":"",o=x5t(i);if(a)return`OPENCODE_PERMISSION='{"*":"allow"}' opencode run ${s}--model litellm/${t} --format json${o} "${e}" < /dev/null`;let c=t.startsWith("openrouter/")?t:`openrouter/${t}`;return r?`OPENCODE_PERMISSION='{"*":"allow"}' opencode run ${s}--model ${c} --format json${o} "${e}" < /dev/null`:`OPENCODE_PERMISSION='{"*":"allow"}' opencode run ${s}--model litellm/${c} --format json${o} "${e}" < /dev/null`}},droid:{image:"evolve-all",apiKeyEnv:"FACTORY_API_KEY",effortSupport:"level",defaultModel:"claude-opus-5",defaultReasoningEffort:"high",models:[{alias:"claude-fable-5",modelId:"claude-fable-5",description:"Factory-managed Claude Fable 5"},{alias:"claude-opus-5",modelId:"claude-opus-5",description:"Factory-managed Claude Opus 5"},{alias:"claude-sonnet-5",modelId:"claude-sonnet-5",description:"Factory-managed Claude Sonnet 5"},{alias:"claude-haiku-4-5",modelId:"claude-haiku-4-5-20251001",description:"Factory-managed Claude Haiku 4.5"},{alias:"gpt-5.6-sol",modelId:"gpt-5.6-sol",description:"Factory-managed GPT-5.6 Sol"},{alias:"gpt-5.6-terra",modelId:"gpt-5.6-terra",description:"Factory-managed GPT-5.6 Terra"},{alias:"gpt-5.6-luna",modelId:"gpt-5.6-luna",description:"Factory-managed GPT-5.6 Luna"},{alias:"gemini-3.6-flash",modelId:"gemini-3.6-flash",description:"Factory-managed Gemini 3.6 Flash"},{alias:"qwen3.7-max",modelId:"qwen3.7-max",description:"Qwen 3.7 Max via the Evolve gateway"},{alias:"kimi-k3",modelId:"kimi-k3",description:"Factory-managed Droid Core Kimi K3"},{alias:"glm-5.3",modelId:"glm-5.3",description:"Zhipu GLM-5.3 via the Evolve gateway"},{alias:"glm-5.3-flash",modelId:"glm-5.3-flash",description:"Zhipu GLM-5.3 Flash via the Evolve gateway"}],systemPromptFile:"AGENTS.md",mcpConfig:{settingsDir:"~/.factory",filename:"mcp.json",format:"json"},skillsConfig:{targetDir:"~/.factory/skills"},skipApiKeyEnvInGateway:!0,gatewayModelAliases:{"kimi-k3":"moonshot/kimi-k3","glm-5.3":"openrouter/z-ai/glm-5.3","qwen3.7-max":"dashscope/qwen3.7-max"},droidGatewaySettings:{settingsPath:"~/.factory/evolve-settings.json",displayName:"Evolve Gateway",provider:"generic-chat-completion-api",maxOutputTokens:32768},checkpointDirs:["~/.factory"],buildCommand:({prompt:e,model:t,isResume:n,sessionId:r,reasoningEffort:a,isDirectMode:i,isExternalGateway:s,homeDir:o=qp})=>{let c=!i||s,l=c?`--settings ${o}/.factory/evolve-settings.json `:"",u=c?"custom:Evolve-Gateway-0":t,d=a?` --reasoning-effort ${a}`:"",f=n&&r?`--session-id ${yO(r)} `:"";return`printf '%s' ${yO(e)} | droid ${l}exec ${f}--skip-permissions-unsafe --cwd ${o}/workspace --output-format stream-json --model ${yO(u)}${d}`}}};function xv(e){let t=Vp[e];if(!t)throw new Error(`Unknown agent type: ${e}`);return t}function E5t(e){return e in Vp}function Fp(e,t=qp){return e.replace(/^~/,t)}function yO(e){return`'${e.replace(/'/g,"'\\''")}'`}function Yw(e,t=qp){let n=xv(e);return`${Fp(n.mcpConfig.settingsDir,t)}/${n.mcpConfig.filename}`}function Kw(e,t=qp){let n=xv(e);return Fp(n.mcpConfig.settingsDir,t)}function Ev(e){if(e instanceof Error){let t=e.message.toLowerCase();return t.includes("not found")||t.includes("enoent")||t.includes("no such file")||t.includes("does not exist")}return!1}function RXe(e,t){let n=[t.command,t.url].filter(Boolean);if(n.length===0)throw new Error(`MCP server "${e}" must specify command or url`);if(n.length>1)throw new Error(`MCP server "${e}" cannot specify both command and url`)}function gB(e){for(let[t,n]of Object.entries(e))RXe(t,n)}function EO(e){return e.type?e.type:e.command?"stdio":"sse"}function T5t(e){let t=EO(e);return{...e,type:t}}function k5t(e){let{type:t,url:n,...r}=e;return EO(e)==="http"&&n?{httpUrl:n,...r}:n?{url:n,...r}:r}function O5t(e){return{type:EO(e),...e}}function A5t(e){let{type:t,...n}=e;return n.command?{...n,transport:"stdio"}:n.url&&(t==="http"||t==="sse")?{...n,transport:t}:n}function P5t(e){let t=EO(e),{type:n,httpHeaders:r,envHttpHeaders:a,bearerTokenEnvVar:i,envVars:s,...o}=e;if(t==="stdio"&&e.command)return{type:"stdio",...o};if(e.url){let c={...o,type:t==="sse"?"sse":"http",url:e.url},l=e.headers??r;return l&&Object.keys(l).length>0&&(c.headers=l),c}return{type:t==="stdio"?"stdio":"http",...o}}async function UZ(e,t,n,r,a){gB(n);let i=Kw(t,a),s=Yw(t,a);await e.files.makeDir(i);let o={};try{let l=await e.files.read(s);typeof l=="string"&&(o=JSON.parse(l))}catch(l){if(!Ev(l))throw l}let c=Object.fromEntries(Object.entries(n).map(([l,u])=>[l,r(u)]));await e.files.write(s,JSON.stringify({...o,mcpServers:c},null,2))}async function R5t(e,t,n,r){gB(n);let a=Kw("claude",r),i=Yw("claude",r),s=Object.fromEntries(Object.entries(n).map(([c,l])=>[c,O5t(l)]));await e.files.write(`${t}/.mcp.json`,JSON.stringify({mcpServers:s},null,2)),await e.files.makeDir(a);let o={};try{let c=await e.files.read(i);typeof c=="string"&&(o=JSON.parse(c))}catch(c){if(!Ev(c))throw c}o.enableAllProjectMcpServers=!0,await e.files.write(i,JSON.stringify(o,null,2))}async function C5t(e,t,n){await UZ(e,"gemini",t,T5t,n)}async function N5t(e,t,n){await UZ(e,"qwen",t,k5t,n)}async function GKe(e,t,n,r,a){let i=Kw(t,a),s=Yw(t,a);await e.files.makeDir(i);let o={};try{let f=await e.files.read(s);typeof f=="string"&&(o=JSON.parse(f))}catch(f){if(!Ev(f))throw f}let c=n.split("."),l=o;for(let f=0;f<c.length-1;f++){let p=c[f];(typeof l[p]!="object"||l[p]===null)&&(l[p]={}),l=l[p]}let u=c[c.length-1],d=typeof l[u]=="object"&&l[u]!==null?l[u]:{};l[u]={...d,...r},await e.files.write(s,JSON.stringify(o,null,2))}async function M5t(e,t,n){let r=Kw("qwen",n),a=Yw("qwen",n);await e.files.makeDir(r);let i={};try{let l=await e.files.read(a);typeof l=="string"&&(i=JSON.parse(l))}catch(l){if(!Ev(l))throw l}let s=i.model??{},o=s.generationConfig??{},c=o.extra_body??{};i.model={...s,generationConfig:{...o,extra_body:{...c,enable_thinking:t}}},await e.files.write(a,JSON.stringify(i,null,2))}async function D5t(e,t,n){await UZ(e,"kimi",t,A5t,n)}async function U5t(e,t,n){gB(n);let r=`${t}/.factory`,a=`${r}/mcp.json`;await e.files.makeDir(r);let i={};try{let o=await e.files.read(a);typeof o=="string"&&(i=JSON.parse(o))}catch(o){if(!Ev(o))throw o}let s=Object.fromEntries(Object.entries(n).map(([o,c])=>[o,P5t(c)]));await e.files.write(a,JSON.stringify({...i,mcpServers:s},null,2))}async function B5t(e,t,n,r){let a=Fp(t.settingsPath,r),i=a.slice(0,a.lastIndexOf("/"));await e.files.makeDir(i);let s={cloudSessionSync:!1,customModels:[{model:t.model,displayName:t.displayName,baseUrl:t.baseUrl,apiKey:`\${${t.apiKeyEnv}}`,provider:t.provider,...t.maxOutputTokens!==void 0&&{maxOutputTokens:t.maxOutputTokens},extraHeaders:n}]};await e.files.write(a,JSON.stringify(s,null,2))}async function F5t(e,t,n){gB(n);let r=`${t}/opencode.json`,a={};try{let s=await e.files.read(r);typeof s=="string"&&(a=JSON.parse(s))}catch(s){if(!Ev(s))throw s}let i=Object.fromEntries(Object.entries(n).map(([s,o])=>[s,L5t(o)]));await e.files.write(r,JSON.stringify({...a,mcp:i},null,2))}function L5t(e){let t=EO(e);if(t==="stdio"&&e.command){let n={type:"local",command:e.args?[e.command,...e.args]:[e.command]};return e.env&&Object.keys(e.env).length>0&&(n.environment=e.env),n}if(e.url){let n={type:"remote",url:e.url};return e.headers&&Object.keys(e.headers).length>0&&(n.headers=e.headers),n}return{type:t==="stdio"?"local":"remote",...e}}function OZ(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function CXe(e,t,n){let r=e[t];if(r===void 0)return{};let a=OZ(r);if(!a){let i=Array.isArray(r)?"an array":`a ${typeof r}`;throw new Error(`Refusing to rewrite "${t}" in ${n}: expected a TOML table, found ${i}`)}return a}function AZ(e,t){if(e===t)return!0;if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((i,s)=>AZ(i,t[s]));let n=OZ(e),r=OZ(t);if(!n||!r)return!1;let a=Object.keys(n);return a.length===Object.keys(r).length&&a.every(i=>i in r&&AZ(n[i],r[i]))}async function NXe(e,t){let n="";try{let r=await e.files.read(t);typeof r=="string"&&(n=r)}catch(r){if(!Ev(r))throw r;return{}}if(!n.trim())return{};try{return Bm(n)}catch(r){throw new Error(`Failed to parse TOML at ${t}: ${r.message}`)}}async function BZ(e,t,n){await e.files.write(t,Wv(n).trimEnd()+`
|
|
679
679
|
`)}function V5t(e,t){let n={},r=t.type??(t.command?"stdio":"http");if(r==="http"||r==="sse"||t.url){if(!t.url)throw new Error(`MCP server "${e}" is missing url for ${r} transport`);n.url=t.url,t.bearerTokenEnvVar&&(n.bearer_token_env_var=t.bearerTokenEnvVar);let a=t.httpHeaders??t.headers;a&&Object.keys(a).length>0&&(n.http_headers=a),t.envHttpHeaders&&Object.keys(t.envHttpHeaders).length>0&&(n.env_http_headers=t.envHttpHeaders)}else n.command=t.command,t.args&&t.args.length>0&&(n.args=t.args),t.cwd&&(n.cwd=t.cwd);return t.env&&Object.keys(t.env).length>0&&(n.env=t.env),t.envVars&&t.envVars.length>0&&(n.env_vars=t.envVars),n}async function q5t(e,t,n){for(let[o,c]of Object.entries(t))RXe(o,c);let r=Kw("codex",n),a=Yw("codex",n);await e.files.makeDir(r);let i=await NXe(e,a);i.experimental_use_rmcp_client===void 0&&(i.experimental_use_rmcp_client=!0);let s=CXe(i,"mcp_servers",a);i.mcp_servers=s;for(let[o,c]of Object.entries(t))s[o]===void 0&&(s[o]=V5t(o,c));await BZ(e,a,i)}async function JKe(e,t,n,r={},a){let i=Kw("codex",a),s=Yw("codex",a);await e.files.makeDir(i);let o=await NXe(e,s),c={...n?{[Wu]:n.sessionTagEnv,[$p]:n.runTagEnv}:{},...r},l={name:"Evolve Gateway",base_url:t,env_key:"OPENAI_API_KEY",wire_api:"responses",...Object.keys(c).length>0?{env_http_headers:c}:{}},u=CXe(o,"model_providers",s);o.model_provider==="evolve-gateway"&&AZ(u["evolve-gateway"],l)||(o.model_provider="evolve-gateway",u["evolve-gateway"]=l,o.model_providers=u,await BZ(e,s,o))}async function $5t(e,t,n,r,a){let i=Fp(t.configPath,a),s=i.slice(0,i.lastIndexOf("/"));await e.files.makeDir(s);let o={default_model:t.modelName,default_thinking:r.defaultThinking,default_permission_mode:"auto",thinking:{mode:r.defaultThinking?"on":"off",...r.defaultThinking&&r.thinkingEffort?{effort:r.thinkingEffort}:{}},providers:{[t.providerName]:{type:"kimi",base_url:r.baseUrl,api_key:r.apiKey,custom_headers:n}},models:{[t.modelName]:{provider:t.providerName,model:r.model,max_context_size:t.maxContextSize,capabilities:["image_in","thinking"]}}};await BZ(e,i,o)}async function z5t(e,t,n,r,a){if(!(!r||Object.keys(r).length===0))switch(e){case"claude":await R5t(t,n,r,a);break;case"codex":await q5t(t,r,a);break;case"gemini":await C5t(t,r,a);break;case"qwen":await N5t(t,r,a);break;case"kimi":await D5t(t,r,a);break;case"opencode":await F5t(t,n,r);break;case"droid":await U5t(t,n,r);break;default:throw new Error(`Unknown agent type for MCP config: ${e}`)}}function Gu(e,t){for(let n of e)if(typeof n=="string"&&n.length>0)return n;try{let n=JSON.stringify(t);if(typeof n=="string"&&n.length>0)return n}catch{}return String(t)}function iB(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function PZ(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e,n=iB(t.input_tokens),r=iB(t.output_tokens),a=iB(t.cache_read_input_tokens),i=iB(t.cache_creation_input_tokens),s={};(n!==void 0||a!==void 0||i!==void 0)&&(s.promptTokens=(n??0)+(a??0)+(i??0)),r!==void 0&&(s.completionTokens=r),a!==void 0&&(s.cachedTokens=a);let o={};for(let[c,l]of Object.entries(t))c==="input_tokens"||c==="output_tokens"||l!=null&&(o[c]=l);return Object.keys(o).length>0&&(s.extra=o),s}function yB(e){if(typeof e=="string"&&e.length>0&&!Number.isNaN(Date.parse(e)))return e;if(typeof e=="number"&&Number.isFinite(e))return new Date(e).toISOString()}function G5t(){let e={};return function(c){let l;try{l=JSON.parse(c)}catch{return null}if(l._meta||l._prompt)return null;let u=l.session_id;switch(l.type){case"system":return null;case"assistant":{let d=n(l.message?.content,"assistant")??[],f=PZ(l.message?.usage);return f&&d.push({sessionUpdate:"usage",scope:"call",usage:f}),t(d,l,u)}case"user":{let d=l.message?.content;if(typeof d=="string"||Array.isArray(d)&&d.length===1&&d[0].type==="text")return null;let f=l.tool_use_result??l.toolUseResult;return t(n(d,"user",f),l,u)}case"result":{let d=[],f=typeof l.total_cost_usd=="number"&&Number.isFinite(l.total_cost_usd)?l.total_cost_usd:void 0,p=PZ(l.usage)??(f!==void 0?{}:null);if(p&&(f!==void 0&&(p.costUsd=f),d.push({sessionUpdate:"usage",scope:"run",usage:p})),l.is_error===!0){let m=(Array.isArray(l.errors)?l.errors:[]).filter(y=>typeof y=="string"&&y.length>0).join(`
|
|
680
680
|
`);d.push({sessionUpdate:"error",message:Gu([m,l.result,l.subtype],l),fatal:!0})}return t(d,l,u)}default:return null}};function t(c,l,u){if(!c||c.length===0)return null;let d=l.message,f=yB(l.timestamp),p=typeof d?.model=="string"&&d.model?d.model:void 0,m=typeof d?.id=="string"&&d.id?d.id:void 0,y=typeof l.parent_tool_use_id=="string"&&l.parent_tool_use_id?l.parent_tool_use_id:void 0,b={};for(let v of["stop_reason","stop_sequence","requestId"]){let S=d?.[v];S!=null&&(b[v]=S)}return c.map(v=>({sessionId:u,update:v,...f!==void 0?{timestamp:f}:{},...p!==void 0?{model:p}:{},...m!==void 0?{messageId:m}:{},...y!==void 0?{parentToolCallId:y}:{},...Object.keys(b).length>0?{extra:b}:{}}))}function n(c,l,u){if(typeof c=="string")return l==="user"?null:[{sessionUpdate:"agent_message_chunk",content:{type:"text",text:c}}];if(!c||!Array.isArray(c))return null;let d=[];for(let f of c){let p=null;switch(f.type){case"text":case"text_delta":if(l==="user")break;p={sessionUpdate:"agent_message_chunk",content:{type:"text",text:f.text}};break;case"image":if(l==="user")break;p={sessionUpdate:"agent_message_chunk",content:{type:"image",data:f.source?.type==="base64"?f.source.data:"",mimeType:f.source?.type==="base64"?f.source.media_type:"",uri:f.source?.type==="url"?f.source.url:void 0}};break;case"thinking":case"thinking_delta":p={sessionUpdate:"agent_thought_chunk",content:{type:"text",text:f.thinking}};break;case"tool_use":case"server_tool_use":case"mcp_tool_use":{if(e[f.id]=f,f.name==="TodoWrite")Array.isArray(f.input?.todos)&&(p={sessionUpdate:"plan",entries:o(f.input)});else{let m=r(f);p={sessionUpdate:"tool_call",toolCallId:f.id,status:"pending",...m,toolName:f.name}}break}case"tool_result":case"tool_search_tool_result":case"web_fetch_tool_result":case"web_search_tool_result":case"code_execution_tool_result":case"bash_code_execution_tool_result":case"text_editor_code_execution_tool_result":case"mcp_tool_result":{let m=e[f.tool_use_id];if(!m||(delete e[f.tool_use_id],m.name==="TodoWrite"))break;p={sessionUpdate:"tool_call_update",toolCallId:f.tool_use_id,status:"is_error"in f&&f.is_error?"failed":"completed",...a(f,m),...u!=null?{rawOutput:u}:{}};break}}p&&d.push(p)}return d.length>0?d:null}function r(c){let l=c.name,u=c.input||{};switch(l){case"Task":return{title:u.description||"Task",kind:"think",content:u.prompt?[{type:"content",content:{type:"text",text:u.prompt}}]:[],rawInput:u};case"NotebookRead":return{title:u.notebook_path?`Read Notebook ${u.notebook_path}`:"Read Notebook",kind:"read",content:[],locations:u.notebook_path?[{path:u.notebook_path}]:[],rawInput:u};case"NotebookEdit":return{title:u.notebook_path?`Edit Notebook ${u.notebook_path}`:"Edit Notebook",kind:"edit",content:u.new_source?[{type:"content",content:{type:"text",text:u.new_source}}]:[],locations:u.notebook_path?[{path:u.notebook_path}]:[],rawInput:u};case"Bash":return{title:u.command?"`"+u.command.replaceAll("`","\\`")+"`":"Terminal",kind:"execute",content:u.description?[{type:"content",content:{type:"text",text:u.description}}]:[],rawInput:u};case"BashOutput":return{title:"Tail Logs",kind:"execute",content:[],rawInput:u};case"KillShell":return{title:"Kill Process",kind:"execute",content:[],rawInput:u};case"Read":{let d="";return u.limit?d=" ("+((u.offset??0)+1)+" - "+((u.offset??0)+u.limit)+")":u.offset&&(d=" (from line "+(u.offset+1)+")"),{title:"Read "+(u.file_path??"File")+d,kind:"read",content:[],locations:u.file_path?[{path:u.file_path,line:u.offset??0}]:[],rawInput:u}}case"LS":return{title:u.path?`List \`${u.path}\` directory`:"List current directory",kind:"search",content:[],locations:[],rawInput:u};case"Edit":{let d=u.file_path;return{title:d?`Edit \`${d}\``:"Edit",kind:"edit",content:d?[{type:"diff",path:d,oldText:u.old_string??null,newText:u.new_string??""}]:[],locations:d?[{path:d}]:[],rawInput:u}}case"Write":return{title:u.file_path?`Write ${u.file_path}`:"Write",kind:"edit",content:u.file_path?[{type:"diff",path:u.file_path,oldText:null,newText:u.content??""}]:[],locations:u.file_path?[{path:u.file_path}]:[],rawInput:u};case"Glob":{let d="Find";return u.path&&(d+=` \`${u.path}\``),u.pattern&&(d+=` \`${u.pattern}\``),{title:d,kind:"search",content:[],locations:u.path?[{path:u.path}]:[],rawInput:u}}case"Grep":{let d="grep";return u["-i"]&&(d+=" -i"),u["-n"]&&(d+=" -n"),u["-A"]!==void 0&&(d+=` -A ${u["-A"]}`),u["-B"]!==void 0&&(d+=` -B ${u["-B"]}`),u["-C"]!==void 0&&(d+=` -C ${u["-C"]}`),u.output_mode==="files_with_matches"?d+=" -l":u.output_mode==="count"&&(d+=" -c"),u.head_limit!==void 0&&(d+=` | head -${u.head_limit}`),u.glob&&(d+=` --include="${u.glob}"`),u.type&&(d+=` --type=${u.type}`),u.multiline&&(d+=" -P"),d+=` "${u.pattern??""}"`,u.path&&(d+=` ${u.path}`),{title:d,kind:"search",content:[],rawInput:u}}case"WebFetch":return{title:u.url?`Fetch ${u.url}`:"Fetch",kind:"fetch",content:u.prompt?[{type:"content",content:{type:"text",text:u.prompt}}]:[],rawInput:u};case"WebSearch":{let d=`"${u.query??""}"`;return u.allowed_domains?.length>0&&(d+=` (allowed: ${u.allowed_domains.join(", ")})`),u.blocked_domains?.length>0&&(d+=` (blocked: ${u.blocked_domains.join(", ")})`),{title:d,kind:"fetch",content:[],rawInput:u}}case"TodoWrite":return{title:Array.isArray(u.todos)?`Update TODOs: ${u.todos.map(d=>d.content).join(", ")}`:"Update TODOs",kind:"think",content:[],rawInput:u};case"ExitPlanMode":return{title:"Ready to code?",kind:"switch_mode",content:u.plan?[{type:"content",content:{type:"text",text:u.plan}}]:[],rawInput:u};default:if(l?.startsWith("mcp__")){let d=l.split("__"),f=d[1]||"mcp",p=d.slice(2).join("__")||l;return{title:`${f}: ${p}`,kind:"other",content:[],rawInput:u}}return{title:l||"Unknown Tool",kind:"other",content:[],rawInput:u}}}function a(c,l){return l?.name==="ExitPlanMode"?{title:"Exited Plan Mode"}:i(c.content)}function i(c){return Array.isArray(c)&&c.length>0?{content:c.map(l=>({type:"content",content:s(l)}))}:typeof c=="string"&&c.length>0?{content:[{type:"content",content:{type:"text",text:c}}]}:{}}function s(c){if(c.type==="text")return{type:"text",text:c.text};if(c.type==="image"){if(c.data&&c.mimeType)return{type:"image",data:c.data,mimeType:c.mimeType};if(c.source?.type==="base64")return{type:"image",data:c.source.data||"",mimeType:c.source.media_type||""};if(c.source?.type==="url")return{type:"image",data:"",mimeType:"",uri:c.source.url}}return c}function o(c){return c.todos.map(l=>({content:l.content,status:l.status||"pending",priority:"medium"}))}}function J5t(){let e;return function(c){let l;try{l=JSON.parse(c)}catch{return null}if(l._meta||l._prompt)return null;let u=[];switch(l.type){case"thread.started":return typeof l.thread_id=="string"&&l.thread_id&&(e=l.thread_id),null;case"turn.started":return null;case"turn.completed":{let d=t(l.usage);if(!d)return null;u.push({update:{sessionUpdate:"usage",scope:"run",usage:d}});break}case"error":{let d=Gu([l.message],l);u.push({update:{sessionUpdate:"error",message:d,fatal:!1}});break}case"turn.failed":{let d=Gu([l.error?.message],l.error??l);u.push({update:{sessionUpdate:"error",message:d,fatal:!0}});break}case"item.started":{let d=l.item;if(!d)return null;let f=n(d);f&&u.push({update:f});break}case"item.updated":{let d=l.item;if(!d)return null;let f=r(d);f&&u.push({update:f});break}case"item.completed":{let d=l.item;if(!d)return null;let f=a(d);f&&u.push({update:f});break}default:return null}return u.length===0?null:e===void 0?u:u.map(d=>({sessionId:e,...d}))};function t(c){if(!c||typeof c!="object"||Array.isArray(c))return null;let l=c,u=b=>typeof b=="number"&&Number.isFinite(b)?b:void 0,d={},f=u(l.input_tokens),p=u(l.output_tokens),m=u(l.cached_input_tokens);f!==void 0&&(d.promptTokens=f),p!==void 0&&(d.completionTokens=p),m!==void 0&&(d.cachedTokens=m);let y={};for(let[b,v]of Object.entries(l))b==="input_tokens"||b==="output_tokens"||b==="cached_input_tokens"||v!=null&&(y[b]=v);return Object.keys(y).length>0&&(d.extra=y),d}function n(c){let l=c.id;switch(c.type){case"mcp_tool_call":return`${c.server}${c.tool}`,{sessionUpdate:"tool_call",toolCallId:l,title:`${c.server}: ${c.tool}`,toolName:`mcp__${c.server}__${c.tool}`,kind:"other",status:"in_progress",rawInput:c.arguments,content:[]};case"command_execution":return c.command,{sessionUpdate:"tool_call",toolCallId:l,title:c.command?`\`${c.command}\``:"Execute Command",toolName:"command_execution",kind:"execute",status:"in_progress",rawInput:{command:c.command},content:[]};case"web_search":return c.query,{sessionUpdate:"tool_call",toolCallId:l,title:`Search: ${c.query??""}`,toolName:"web_search",kind:"fetch",status:"in_progress",content:[]};case"todo_list":return{sessionUpdate:"plan",entries:o(c.items)};default:return null}}function r(c){return c.type==="todo_list"?{sessionUpdate:"plan",entries:o(c.items)}:null}function a(c){let l=c.id;switch(c.type){case"error":return{sessionUpdate:"error",message:Gu([c.message],c),fatal:!1};case"reasoning":return{sessionUpdate:"agent_thought_chunk",content:{type:"text",text:c.text??c.summary?.join(`
|
|
681
681
|
`)??c.content?.join(`
|
|
@@ -899,7 +899,7 @@ PY`,{timeoutMs:1e4})).exitCode!==0)throw new Error("Managed secret egress proxy
|
|
|
899
899
|
`);f=T.pop()??"";for(let k of T){if(!k.trim())continue;let O=p(k);if(this.captureDroidSession(k,O),this.sessionLogger?.writeEventParsed(k,O),t?.onStdout?.(k+`
|
|
900
900
|
`),O&&t?.onContent)for(let R of O)t.onContent(R)}},y=I=>{t?.onStderr?.(I)},b=await c.commands.spawn(l,{cwd:this.workingDir,timeoutMs:r,envs:d,onStdout:m,onStderr:y}),v=this.beginOperation("run",b,t,"run_start");if(this.hasRun=!0,a)return this.watchBackgroundOperation(v,"run",b,t,c),{sandboxId:c.sandboxId,sessionId:this.managedBrowserSession?.sessionId,browser:this.browserResponseInfo(),runId:u,exitCode:0,stdout:`Background process started with ID ${b.processId}`,stderr:""};let S;try{S=await b.wait()}catch(I){throw this.interruptedOperations.delete(v),this.finalizeOperation(v,t,"run_failed","error"),I}if(this.interruptedOperations.delete(v)||S.exitCode===130?this.finalizeOperation(v,t,"run_interrupted","interrupted"):S.exitCode===0?this.finalizeOperation(v,t,"run_complete","idle"):this.finalizeOperation(v,t,"run_failed","error"),f.trim()){let I=p(f);if(this.captureDroidSession(f,I),this.sessionLogger?.writeEventParsed(f,I),t?.onStdout?.(f+`
|
|
901
901
|
`),I&&t?.onContent)for(let T of I)t.onContent(T)}await this.writeDroidSessionState(c),this.sessionLogger&&!a&&await this.flushSessionLoggerWithTimeout();let w;if(this.storage&&!a&&S.exitCode===0)try{w=await cXe(c,this.storage,this.agentConfig.type,this.workingDir,{tag:this.sessionTag,model:this.agentConfig.model||this.registry.defaultModel,workspaceMode:this.options.workspaceMode||"knowledge",comment:i,parentId:this.lastCheckpointId}),this.lastCheckpointId=w.id}catch(I){console.warn(`[Evolve] Auto-checkpoint failed: ${I.message}`)}return{sandboxId:c.sandboxId,sessionId:this.managedBrowserSession?.sessionId,browser:this.browserResponseInfo(),runId:u,exitCode:S.exitCode,stdout:S.stdout,stderr:S.stderr,checkpoint:w}}async executeCommand(e,t={},n){let{timeoutMs:r=FO,background:a=!1}=t;if(this.activeCommand)throw new Error("Agent is already running. Call interrupt(), wait for the active/background command to finish, or create a new Evolve instance.");let i=await this.getSandbox(n);this.credentialsSealed||await this.ensureProviderRuntimeToken(),this.lastRunTimestamp=Date.now(),this.requiresPreRunDashboardIngest()&&(this.ensureSessionLogger(i),this.sessionLogger?.writePrompt(e),await this.flushSessionLoggerWithTimeout());let s="",o="",c=m=>{s+=m,n?.onStdout?.(m)},l=m=>{o+=m,n?.onStderr?.(m)},u=this.credentialsSealed?{}:this.buildProviderRuntimeProcessEnvs(),d=await i.commands.spawn(e,{cwd:this.workingDir,timeoutMs:r,envs:Object.keys(u).length>0?u:void 0,onStdout:c,onStderr:l}),f=this.beginOperation("command",d,n,"command_start");if(a)return this.watchBackgroundOperation(f,"command",d,n),{sandboxId:i.sandboxId,sessionId:this.managedBrowserSession?.sessionId,browser:this.browserResponseInfo(),exitCode:0,stdout:`Background process started with ID ${d.processId}`,stderr:""};let p;try{p=await d.wait()}catch(m){throw this.interruptedOperations.delete(f),this.finalizeOperation(f,n,"command_failed","error"),m}return this.interruptedOperations.delete(f)||p.exitCode===130?this.finalizeOperation(f,n,"command_interrupted","interrupted"):p.exitCode===0?this.finalizeOperation(f,n,"command_complete","idle"):this.finalizeOperation(f,n,"command_failed","error"),{sandboxId:i.sandboxId,sessionId:this.managedBrowserSession?.sessionId,browser:this.browserResponseInfo(),exitCode:p.exitCode,stdout:s||p.stdout||"",stderr:o||p.stderr||""}}async sealCredentials(){if(!this.credentialsSealed){if(!this.sandbox)throw new Error("No active sandbox. Call run() or executeCommand() first.");if(this.activeCommand)throw new Error("Cannot seal credentials while a process is running.");if(this.agentConfig.isDirectMode&&!this.agentConfig.externalGateway)throw new Error("Credential sealing requires gateway mode; direct provider credentials cannot be revoked by Evolve");if([this.options.secrets&&Object.keys(this.options.secrets).length>0,this.options.sandboxCreateOptions?.envs&&Object.keys(this.options.sandboxCreateOptions.envs).length>0,this.options.managedSecrets,this.options.integrations,this.options.mcpServers&&Object.keys(this.options.mcpServers).length>0,this.options.managedBrowser,this.options.browserCredentials].some(Boolean))throw new Error("Credential sealing requires a credential-minimal sandbox: omit secrets, managed secrets, integrations, MCP servers, and browser credentials");if(this.agentConfig.externalGateway){await this.agentConfig.externalGateway.revoke(),this.credentialsSealed=!0;return}if(!this.providerRuntimeToken||!this.options.providerRouting)throw new Error("Cannot seal credentials: no active provider runtime token to revoke. Without a gateway-issued runtime token the sandbox may hold credentials Evolve cannot revoke, so sealing would be a false guarantee.");await this.closeProviderRuntimeToken(!0),this.credentialsSealed=!0}}isSealed(){return this.credentialsSealed}async collectArtifacts(e){if(!this.credentialsSealed)throw new Error("Call sealCredentials() before collecting artifacts.");if(!this.sandbox)throw new Error("No active sandbox.");if(this.activeCommand)throw new Error("Cannot collect artifacts while a process is running.");return f9t(this.sandbox,this.workingDir,e)}async uploadContext(e){let t=await this.getSandbox();await this.uploadContextFiles(t,e)}async uploadFiles(e){let t=await this.getSandbox();await this.uploadWorkspaceFiles(t,e)}async uploadFileFromPath(e,t){let n=await this.getSandbox(),r=e.startsWith("/")?e:`${this.workingDir}/${e}`,a=r.substring(0,r.lastIndexOf("/"));if(a&&await n.commands.run(`mkdir -p ${a}`,{timeoutMs:3e4}),n.files.writeFromPath){await n.files.writeFromPath(r,t);return}let{readFile:i}=await import("fs/promises");await n.files.write(r,await i(t))}async getOutputFiles(e=!1){let t=await this.getSandbox(),n=`${this.workingDir}/output`,r=e?"":"-maxdepth 1",a=(await t.commands.run(`find ${n} ${r} -type f -exec stat -c '%n|%Z' {} \\; 2>/dev/null || true`,{timeoutMs:3e4})).stdout.split(`
|
|
902
|
-
`).filter(Boolean),i=this.lastRunTimestamp?Math.floor(this.lastRunTimestamp/1e3)-2:0,s=[],o=`${n}/`;for(let f of a){let[p,m]=f.split("|");if(!p||!m)continue;let y=parseInt(m,10);i>0&&y<i||s.push(p)}let c={},l=await Promise.all(s.map(async f=>{try{let p=await t.files.read(f);return{relativePath:f.startsWith(o)?f.slice(o.length):f.split("/").pop()||f,content:p}}catch{return null}}));for(let f of l)f&&(c[f.relativePath]=f.content);if(!this.zodSchema&&!this.jsonSchema)return{files:c,data:null};let u=c["result.json"];if(!u)return{files:c,data:null,error:"Schema provided but agent did not create output/result.json"};let d=typeof u=="string"?u:new TextDecoder().decode(u);try{let f=JSON.parse(d);if(this.zodSchema){let p=this.zodSchema.safeParse(f);return p.success?{files:c,data:p.data}:{files:c,data:null,error:`Schema validation failed: ${p.error.message}`,rawData:d}}if(this.compiledValidator){if(this.compiledValidator(f))return{files:c,data:f};{let p=this.compiledValidator.errors?.map(m=>`${m.instancePath} ${m.message}`).join(", ")||"Unknown validation error";return{files:c,data:null,error:`Schema validation failed: ${p}`,rawData:d}}}return{files:c,data:null}}catch(f){return{files:c,data:null,error:`Failed to parse result.json: ${f.message}`,rawData:d}}}async checkpoint(e){if(!this.storage)throw new Error("Storage not configured. Call .withStorage().");if(!this.sandbox)throw new Error("No active sandbox. Call run() first.");let t=await cXe(this.sandbox,this.storage,this.agentConfig.type,this.workingDir,{tag:this.sessionTag,model:this.agentConfig.model||this.registry.defaultModel,workspaceMode:this.options.workspaceMode||"knowledge",comment:e?.comment,parentId:this.lastCheckpointId});return this.lastCheckpointId=t.id,t}getSession(){return this.sandbox?.sandboxId||this.options.sandboxId||null}async setSession(e){if(this.credentialsSealed)throw new Error("Agent credentials are sealed and this Evolve instance cannot switch sandboxes");if(this.options.managedSecrets)throw new Error("setSession() cannot be used with managed secrets; managed secret grants are sandbox-scoped.");if(this.options.sandboxCreateOptions?.user)throw new Error("setSession() cannot be used with a configured sandbox user; the user cannot be enforced on an existing sandbox.");if(this.activeCommand&&!await this.interrupt())throw new Error("Cannot switch session while an active process is running and could not be interrupted.");await this.rotateSession(),await this.closeProviderRuntimeToken(),await this.closeManagedSecretRuntimeToken(),await this.closeManagedBrowserSession(),this.options.sandboxId=e,this.sandbox=void 0,this.interruptedOperations.clear(),this.invalidateActiveOperation(),this.sandboxState="ready",this.agentState="idle",this.hasRun=!0,this.lastCheckpointId=void 0}async pause(e){this.sandbox&&(this.activeCommand&&await this.interrupt(e),await this.sandbox.pause(),this.sandboxState="paused",this.agentState="idle",this.emitLifecycle(e,"sandbox_pause"))}async resume(e){this.sandbox&&this.options.sandboxProvider&&(this.sandbox=await this.options.sandboxProvider.connect(this.sandbox.sandboxId),this.sandboxState="ready",this.agentState="idle",this.emitLifecycle(e,"sandbox_resume"))}async interrupt(e){if(!this.activeCommand&&!this.activeProcessId)return!1;let t=this.activeOperationId,n=this.activeOperationKind,r=!1;try{this.activeCommand?r=await this.activeCommand.kill():this.sandbox&&this.activeProcessId&&(r=await this.sandbox.commands.kill(this.activeProcessId))}catch{r=!1}if(!r)return this.sandboxState="running",this.agentState="running",!1;t!==null&&this.interruptedOperations.add(t),this.invalidateActiveOperation(),this.sandboxState="ready",this.agentState="interrupted";let a=n==="run"?"run_interrupted":"command_interrupted";return this.emitLifecycle(e,a),r}status(){let e=this.browserRuntimeInfo();return{sandboxId:this.getSession(),sandbox:this.sandboxState,agent:this.agentState,activeProcessId:this.activeProcessId,hasRun:this.hasRun,timestamp:new Date().toISOString(),...e?{browser:e}:{}}}async kill(e){await this.rotateSession();let t;try{this.activeCommand&&await this.interrupt(e),this.sandbox&&(await this.sandbox.kill(),this.sandbox=void 0)}catch(n){t=n}finally{await this.closeProviderRuntimeToken(),await this.closeManagedSecretRuntimeToken(),await this.closeManagedBrowserSession()}if(t)throw t;this.options.sandboxId=void 0,this.interruptedOperations.clear(),this.invalidateActiveOperation(),this.sandboxState="stopped",this.agentState="idle",this.hasRun=!1,this.lastCheckpointId=void 0,this.emitLifecycle(e,"sandbox_killed")}async getHost(e){return(await this.getSandbox()).getHost(e)}getAgentType(){return this.agentConfig.type}getSessionTag(){return!this.sandbox&&!this.sessionLogger?null:this.sessionTag}getSessionTimestamp(){return this.sessionLogger?.getTimestamp()||null}async flushObservability(){await this.sessionLogger?.flush()}async rotateSession(){let e=!!this.sessionLogger;this.sessionLogger&&(await this.sessionLogger.close(),this.sessionLogger=void 0),e&&(this.previousSessionTag=this.sessionTag),this.sessionTag=wXe(this.options.sessionTagPrefix||"evolve")}async fetchSpend(e){if(this.agentConfig.isDirectMode)throw new Error("Cost tracking requires gateway mode (set EVOLVE_API_KEY).");let t=this.agentConfig.apiKey;if(!t)throw new Error("Cost tracking requires an API key.");let n=process.env.EVOLVE_DASHBOARD_URL||ia,r=await fetch(`${n}/api/sessions/spend?${e}`,{headers:{Authorization:`Bearer ${t}`},signal:AbortSignal.timeout(1e4)});if(!r.ok){let a=await r.text().catch(()=>"");throw new Error(`Spend query failed (${r.status}): ${a}`)}return r}resolveSpendTag(){if(this.sandbox||this.sessionLogger)return this.sessionTag;if(this.previousSessionTag)return this.previousSessionTag;throw new Error("No session to query. Call run() first.")}normalizeRunCost(e,t){return{...e,asOf:e.asOf??t.asOf,isComplete:e.isComplete??t.isComplete,truncated:e.truncated??t.truncated}}normalizeSessionCost(e){let t={asOf:e.asOf,isComplete:e.isComplete,truncated:e.truncated};return{...e,runs:e.runs.map(n=>this.normalizeRunCost(n,t))}}async getSessionCost(){let e=this.resolveSpendTag(),t=new URLSearchParams({tag:e}),n=await(await this.fetchSpend(t)).json();return this.normalizeSessionCost(n)}async getRunCost(e){let t=this.resolveSpendTag();if("runId"in e){let i=new URLSearchParams({tag:t,runId:e.runId}),s=await(await this.fetchSpend(i)).json();return this.normalizeRunCost(s,{asOf:new Date().toISOString(),isComplete:!1,truncated:!1})}let n=await this.getSessionCost(),r=e.index>0?e.index-1:n.runs.length+e.index,a=n.runs[r];if(!a)throw new Error(`Run index ${e.index} out of range. Session has ${n.runs.length} run(s).`);return a}};function v9t(e){return(e||process.env.EVOLVE_DASHBOARD_URL||ia).replace(/\/$/,"")}function b9t(e){let t=e||process.env.EVOLVE_API_KEY;if(!t)throw new Error("Browser profiles require EVOLVE_API_KEY or an explicit apiKey");return t}async function S9t(e){return await e.text().catch(()=>"")}async function EXe(e,t,n={}){let r=await fetch(`${v9t(e?.dashboardUrl)}${t}`,{...n,headers:{Authorization:`Bearer ${b9t(e?.apiKey)}`,accept:"application/json",...n.body?{"content-type":"application/json"}:{},...n.headers||{}}});if(!r.ok)throw new Error(`Browser profiles request failed (${r.status}): ${await S9t(r)}`);return r.status===204?{}:await r.json()}var _9t=class{constructor(e={}){this.config=e}toMetadata(e){return{id:e.id,profile:e.profile,createdAt:e.createdAt||e.created_at||"",updatedAt:e.updatedAt||e.updated_at||"",lastUsedAt:e.lastUsedAt??e.last_used_at??null}}async list(){return{profiles:(await EXe(this.config,"/api/browser-profiles")).profiles.map(e=>this.toMetadata(e))}}async delete(e){return await EXe(this.config,"/api/browser-profiles",{method:"DELETE",body:JSON.stringify(e)})}};function w9t(e={}){return new _9t(e)}var Tv=class extends kXe.EventEmitter{config={};agent;fallbackSandboxState="stopped";fallbackAgentState="idle";fallbackHasRun=!1;constructor(){super()}on(e,t){return super.on(e,t)}off(e,t){return super.off(e,t)}emit(e,...t){return super.emit(e,...t)}withAgent(e){return e&&(zXe(e),jXe(e),this.config.agent=e,this._cachedGatewayOverrides=null),this}withSandbox(e){return this.config.sandbox=e,this}withSandboxCreateOptions(e){return this.config.sandboxCreateOptions={...e,envs:e.envs?{...e.envs}:void 0,metadata:e.metadata?{...e.metadata}:void 0},this}withWorkingDirectory(e){return this.config.workingDirectory=e,this}withWorkspaceMode(e){return this.config.workspaceMode=e,this}withSecrets(e){return this.config.secrets={...this.config.secrets,...e},this}withManagedSecrets(e){return this.config.managedSecrets=e,this}withSession(e){return this.config.sandboxId=e,this.agent||(this.fallbackSandboxState="ready",this.fallbackAgentState="idle",this.fallbackHasRun=!0),this}withSystemPrompt(e){return this.config.systemPrompt=e,this}withContext(e){return this.config.context={...this.config.context,...e},this}withFiles(e){return this.config.files={...this.config.files,...e},this}withMcpServers(e){return this.config.mcpServers={...this.config.mcpServers,...e},this}withBrowser(e={provider:"agent-browser",remote:!0}){return e===!1?delete this.config.browser:this.config.browser=e,this}withBrowserCredentials(e={}){return this.config.browserCredentials=e,this}withPlugins(e){let t=Array.isArray(e)?e:[e];return this.config.plugins=[...this.config.plugins??[],...t],this}withSkills(e){return this.config.skills=e,this}withSchema(e,t){return this.config.schema=e,t&&(vB(e)?console.warn("[Evolve] schemaOptions ignored for Zod schemas - use .passthrough(), .strip(), z.coerce instead"):this.config.schemaOptions=t),this}withSessionTagPrefix(e){return this.config.sessionTagPrefix=e,this}withObservability(e){return this.config.observability={...this.config.observability,...e},this}withIntegrations(e){return this.config.integrations=e,this}withStorage(e){return this.config.storage=e||{},this}static integrations=IYt;static browserCredentials=t9t;static browserProfiles=w9t;static managedSecrets=CB;async initializeAgent(){let e=tXe(this.config.agent),t=xv(e.type);if(this.config.integrations&&e.isDirectMode)throw new Error("withIntegrations() is available only in gateway mode with EVOLVE_API_KEY");if(this.config.managedSecrets&&e.isDirectMode)throw new Error("withManagedSecrets() is available only in gateway mode with EVOLVE_API_KEY");if(this.config.managedSecrets&&this.config.sandboxId)throw new Error("withManagedSecrets() cannot be used with withSession(); managed secret grants are sandbox-scoped.");let n=RQ(this.config.managedSecrets,t);if(n&&this.config.sandbox&&!DZ(this.config.sandbox))throw new Error("withManagedSecrets() requires an Evolve-managed sandbox; remove withSandbox() or pass a managed sandbox provider.");let r=this.config.sandbox??(n?await qZ(e.apiKey):await $jt()),a={},i,s,o=this.config.skills,c;if(this.config.browser){let d=JYt(this.config.browser);if(c=d,d.provider==="browser-use"){if(e.isDirectMode)throw new Error('withBrowser("browser-use") requires gateway mode. Use apiKey/EVOLVE_API_KEY instead of providerApiKey/direct mode.');a=bQ(e.apiKey)}if((d.provider==="actionbook"||d.provider==="agent-browser")&&d.managed){if(e.isDirectMode)throw new Error(`Managed browser provider "${d.provider}" requires gateway mode. Use apiKey/EVOLVE_API_KEY instead of providerApiKey/direct mode.`);i=d.provider==="actionbook"?oYt:cYt,s={provider:d.provider,apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||ia,...d.profile?{profile:d.profile}:{}}}if(d.profile&&!d.managed)throw new Error('withBrowser({ profile }) requires managed remote browser mode. Use .withBrowser({ profile }) or .withBrowser({ provider: "agent-browser", remote: true, profile }).')}if(this.config.browserCredentials!==void 0){if(this.config.sandboxId)throw new Error("withBrowserCredentials() cannot be used with withSession(); browser login tokens are run-scoped.");if(e.isDirectMode)throw new Error("withBrowserCredentials() requires gateway mode. Use apiKey/EVOLVE_API_KEY instead of providerApiKey/direct mode.");if(!c||c.provider!=="agent-browser"||!c.managed)throw new Error('withBrowserCredentials() requires .withBrowser() or .withBrowser({ provider: "agent-browser", remote: true }).');if(this.config.mcpServers?.["browser-login"])throw new Error('withBrowserCredentials() reserves the "browser-login" MCP server name.')}let l=this.config.storage!==void 0?XXe(this.config.storage,!e.isDirectMode,ia,e.isDirectMode?void 0:e.apiKey):void 0,u={sandboxProvider:r,sandboxCreateOptions:this.config.sandboxCreateOptions,secrets:this.config.secrets,managedSecrets:n?{secrets:n,apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||ia}:void 0,sandboxId:this.config.sandboxId,workingDirectory:this.config.workingDirectory,workspaceMode:this.config.workspaceMode,systemPrompt:this.config.systemPrompt,context:this.config.context,files:this.config.files,mcpServers:{...a,...this.config.mcpServers},browserPrompt:i,managedBrowser:s,browserCredentials:this.config.browserCredentials!==void 0?{apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||ia,config:this.config.browserCredentials}:void 0,plugins:this.config.plugins,skills:o,schema:this.config.schema,schemaOptions:this.config.schemaOptions,sessionTagPrefix:this.config.sessionTagPrefix,observability:this.config.observability,integrations:this.config.integrations?{...this.config.integrations,apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||ia}:void 0,providerRouting:e.isDirectMode?void 0:{apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||ia},storage:l};this.agent=new y9t(e,u)}createStreamCallbacks(){let e=this.listenerCount("stdout")>0,t=this.listenerCount("stderr")>0,n=this.listenerCount("content")>0,r=this.listenerCount("lifecycle")>0;return{onStdout:e?a=>this.emit("stdout",a):void 0,onStderr:t?a=>this.emit("stderr",a):void 0,onContent:n?a=>this.emit("content",a):void 0,onLifecycle:r?a=>this.emit("lifecycle",a):void 0}}emitLifecycleFromStatus(e){if(this.listenerCount("lifecycle")===0)return;let t=this.status();this.emit("lifecycle",{sandboxId:t.sandboxId,sandbox:t.sandbox,agent:t.agent,timestamp:new Date().toISOString(),reason:e,...t.browser?{browser:t.browser}:{}})}async run({prompt:e,timeoutMs:t,background:n,from:r,checkpointComment:a,resume:i}){if(r&&this.config.sandboxId)throw new Error("Cannot use 'from' with 'withSession()' \u2014 restore requires a fresh sandbox.");this.agent||await this.initializeAgent();let s=this.createStreamCallbacks();return this.agent.run({prompt:e,timeoutMs:t,background:n,from:r,checkpointComment:a,resume:i},s)}async executeCommand(e,t={}){this.agent||await this.initializeAgent();let n=this.createStreamCallbacks();return this.agent.executeCommand(e,t,n)}async prepareSandbox(){this.agent||await this.initializeAgent();let e=this.createStreamCallbacks();return(await this.agent.getSandbox(e)).sandboxId}async updateNetwork(e){if(!this.agent)throw new Error("No sandbox yet. Call prepareSandbox(), run() or executeCommand() before updateNetwork().");let t=await this.agent.getSandbox(this.createStreamCallbacks());if(typeof t.updateNetwork!="function")throw new Error(`The ${this.config.sandbox?.providerType??"configured"} sandbox provider cannot change network policy after start. Create the sandbox with the policy it needs for its whole lifetime, or use a provider that supports runtime changes.`);await t.updateNetwork(e)}async sealCredentials(){if(!this.agent)throw new Error("Agent not initialized. Call run() or executeCommand() first.");await this.agent.sealCredentials()}isSealed(){return this.agent?.isSealed()??!1}resolvedSkills(){return this.agent?.resolvedSkills()??[]}async collectArtifacts(e){if(!this.agent)throw new Error("Agent not initialized. Call run() or executeCommand() first.");return this.agent.collectArtifacts(e)}async interrupt(){if(!this.agent)return!1;let e=this.createStreamCallbacks();return this.agent.interrupt(e)}async uploadContext(e){return this.agent||await this.initializeAgent(),this.agent.uploadContext(e)}async uploadFiles(e){return this.agent||await this.initializeAgent(),this.agent.uploadFiles(e)}async uploadFileFromPath(e,t){return this.agent||await this.initializeAgent(),this.agent.uploadFileFromPath(e,t)}async getOutputFiles(e=!1){if(!this.agent)throw new Error("Agent not initialized. Call run() first.");return this.agent.getOutputFiles(e)}async checkpoint(e){if(!this.agent)throw new Error("Agent not initialized. Call run() first.");return this.agent.checkpoint(e)}_cachedGatewayOverrides=null;resolveGatewayOverrides(){if(this._cachedGatewayOverrides!==null)return this._cachedGatewayOverrides||void 0;try{let e=tXe(this.config.agent);if(!e.isDirectMode)return this._cachedGatewayOverrides={gatewayUrl:ia,gatewayApiKey:e.apiKey},this._cachedGatewayOverrides}catch{}this._cachedGatewayOverrides=void 0}async listCheckpoints(e){if(this.config.storage===void 0)throw new Error("Storage not configured. Call .withStorage().");return hXe(this.config.storage,this.resolveGatewayOverrides()||{}).listCheckpoints(e)}storage(){if(this.config.storage===void 0)throw new Error("Storage not configured. Call .withStorage().");return hXe(this.config.storage,this.resolveGatewayOverrides()||{})}getSession(){return this.agent?this.agent.getSession():this.config.sandboxId??null}async setSession(e){if(this.config.managedSecrets)throw new Error("setSession() cannot be used with withManagedSecrets(); managed secret grants are sandbox-scoped.");this.agent?await this.agent.setSession(e):(this.fallbackSandboxState="ready",this.fallbackAgentState="idle",this.fallbackHasRun=!0),this.config.sandboxId=e}status(){return this.agent?this.agent.status():{sandboxId:this.config.sandboxId??null,sandbox:this.fallbackSandboxState,agent:this.fallbackAgentState,activeProcessId:null,hasRun:this.fallbackHasRun,timestamp:new Date().toISOString()}}async pause(){if(this.agent){let e=this.createStreamCallbacks();await this.agent.pause(e);return}this.config.sandboxId&&this.config.sandbox&&(await(await this.config.sandbox.connect(this.config.sandboxId)).pause(),this.fallbackSandboxState="paused",this.fallbackAgentState="idle",this.emitLifecycleFromStatus("sandbox_pause"))}async resume(){if(this.agent){let e=this.createStreamCallbacks();await this.agent.resume(e);return}this.config.sandboxId&&this.config.sandbox&&(await this.config.sandbox.connect(this.config.sandboxId),this.fallbackSandboxState="ready",this.fallbackAgentState="idle",this.emitLifecycleFromStatus("sandbox_resume"))}async kill(){if(this.agent){let e=this.createStreamCallbacks();await this.agent.kill(e),this.config.sandboxId=void 0,this.fallbackSandboxState="stopped",this.fallbackAgentState="idle",this.fallbackHasRun=!1;return}this.config.sandboxId&&this.config.sandbox&&(await(await this.config.sandbox.connect(this.config.sandboxId)).kill(),this.fallbackSandboxState="stopped",this.fallbackAgentState="idle",this.fallbackHasRun=!1,this.emitLifecycleFromStatus("sandbox_killed"),this.config.sandboxId=void 0)}async getHost(e){return this.agent||await this.initializeAgent(),this.agent.getHost(e)}getSessionTag(){return this.agent?.getSessionTag()||null}getSessionTimestamp(){return this.agent?.getSessionTimestamp()||null}async flushObservability(){await this.agent?.flushObservability()}async getSessionCost(){if(!this.agent)throw new Error("No agent initialized. Call run() first.");return this.agent.getSessionCost()}async getRunCost(e){if(!this.agent)throw new Error("No agent initialized. Call run() first.");return this.agent.getRunCost(e)}},I9t=class{permits;queue=[];constructor(e){if(e<1)throw new Error("Semaphore max must be >= 1");this.permits=e}async use(e){await this.acquire();try{return await e()}finally{this.release()}}acquire(){return this.permits>0?(this.permits--,Promise.resolve()):new Promise(e=>this.queue.push(e))}release(){this.queue.length>0?this.queue.shift()():this.permits++}},_O=Symbol.for("evolve.SwarmResult"),TXe=class yZe extends Array{get success(){return this.filter(t=>t.status==="success")}get filtered(){return this.filter(t=>t.status==="filtered")}get error(){return this.filter(t=>t.status==="error")}static from(t){let n=new yZe;return n.push(...t),n}},EOn=class pB{config;semaphore;constructor(t={}){let n=t.concurrency??SQ;if(n>AB)throw new Error(`concurrency=${n} exceeds max ${AB}. For higher parallelism, scale horizontally with multiple processes.`);this.config={agent:t.agent,sandbox:t.sandbox,tag:t.tag??"swarm",concurrency:n,timeoutMs:t.timeoutMs??FO,workspaceMode:t.workspaceMode??"knowledge",retry:t.retry,mcpServers:t.mcpServers,skills:t.skills,integrations:t.integrations},this.semaphore=new I9t(this.config.concurrency)}async map(t){let{items:n,prompt:r,bestOf:a,verify:i}=t,s=t.retry??this.config.retry,o=this.generateOperationId(),c=t.timeoutMs??this.config.timeoutMs;if(a&&i)throw new Error("map() cannot use both bestOf and verify options simultaneously");let l=await Promise.all(n.map((u,d)=>a?this.executeMapItemWithBestOf(u,r,d,o,t,c,s):i?this.executeMapItemWithVerify(u,r,d,o,t,c,s):s?Mp(f=>this.executeMapItem(u,r,d,o,t,c,f),s,d):this.executeMapItem(u,r,d,o,t,c)));return TXe.from(l)}async filter(t){let{items:n,prompt:r,condition:a,verify:i}=t,s=t.retry??this.config.retry,o=this.generateOperationId(),c=t.timeoutMs??this.config.timeoutMs,l=await Promise.all(n.map((d,f)=>i?this.executeFilterItemWithVerify(d,r,f,o,t,c,s):s?Mp(p=>this.executeFilterItem(d,r,f,o,t,c,p),s,f):this.executeFilterItem(d,r,f,o,t,c))),u=[];for(let d of l)if(d.status==="error")u.push(d);else if(d.data!==null)try{a(d.data)?u.push(d):u.push({...d,status:"filtered"})}catch(f){u.push({...d,status:"error",data:null,error:`Condition function threw: ${f.message}`})}return TXe.from(u)}async reduce(t){let{items:n,prompt:r,verify:a}=t,i=t.retry??this.config.retry,s=this.generateOperationId(),o=t.timeoutMs??this.config.timeoutMs,c=[],l=[];n.forEach((I,T)=>{c.push(this.getFiles(I)),l.push(this.getIndex(I,T))});let u={};c.forEach((I,T)=>{Object.entries(I).forEach(([k,O])=>{u[`item_${l[T]}/${k}`]=O})});let d=wZ(u),f=Iv(pYt,{fileTree:d}),p=t.systemPrompt?`${f}
|
|
902
|
+
`).filter(Boolean),i=this.lastRunTimestamp?Math.floor(this.lastRunTimestamp/1e3)-2:0,s=[],o=`${n}/`;for(let f of a){let[p,m]=f.split("|");if(!p||!m)continue;let y=parseInt(m,10);i>0&&y<i||s.push(p)}let c={},l=await Promise.all(s.map(async f=>{try{let p=await t.files.read(f);return{relativePath:f.startsWith(o)?f.slice(o.length):f.split("/").pop()||f,content:p}}catch{return null}}));for(let f of l)f&&(c[f.relativePath]=f.content);if(!this.zodSchema&&!this.jsonSchema)return{files:c,data:null};let u=c["result.json"];if(!u)return{files:c,data:null,error:"Schema provided but agent did not create output/result.json"};let d=typeof u=="string"?u:new TextDecoder().decode(u);try{let f=JSON.parse(d);if(this.zodSchema){let p=this.zodSchema.safeParse(f);return p.success?{files:c,data:p.data}:{files:c,data:null,error:`Schema validation failed: ${p.error.message}`,rawData:d}}if(this.compiledValidator){if(this.compiledValidator(f))return{files:c,data:f};{let p=this.compiledValidator.errors?.map(m=>`${m.instancePath} ${m.message}`).join(", ")||"Unknown validation error";return{files:c,data:null,error:`Schema validation failed: ${p}`,rawData:d}}}return{files:c,data:null}}catch(f){return{files:c,data:null,error:`Failed to parse result.json: ${f.message}`,rawData:d}}}async checkpoint(e){if(!this.storage)throw new Error("Storage not configured. Call .withStorage().");if(!this.sandbox)throw new Error("No active sandbox. Call run() first.");let t=await cXe(this.sandbox,this.storage,this.agentConfig.type,this.workingDir,{tag:this.sessionTag,model:this.agentConfig.model||this.registry.defaultModel,workspaceMode:this.options.workspaceMode||"knowledge",comment:e?.comment,parentId:this.lastCheckpointId});return this.lastCheckpointId=t.id,t}getSession(){return this.sandbox?.sandboxId||this.options.sandboxId||null}async setSession(e){if(this.credentialsSealed)throw new Error("Agent credentials are sealed and this Evolve instance cannot switch sandboxes");if(this.options.managedSecrets)throw new Error("setSession() cannot be used with managed secrets; managed secret grants are sandbox-scoped.");if(this.options.sandboxCreateOptions?.user)throw new Error("setSession() cannot be used with a configured sandbox user; the user cannot be enforced on an existing sandbox.");if(this.activeCommand&&!await this.interrupt())throw new Error("Cannot switch session while an active process is running and could not be interrupted.");await this.rotateSession(),await this.closeProviderRuntimeToken(),await this.closeManagedSecretRuntimeToken(),await this.closeManagedBrowserSession(),this.options.sandboxId=e,this.sandbox=void 0,this.interruptedOperations.clear(),this.invalidateActiveOperation(),this.sandboxState="ready",this.agentState="idle",this.hasRun=!0,this.lastCheckpointId=void 0}async pause(e){this.sandbox&&(this.activeCommand&&await this.interrupt(e),await this.sandbox.pause(),this.sandboxState="paused",this.agentState="idle",this.emitLifecycle(e,"sandbox_pause"))}async resume(e){this.sandbox&&this.options.sandboxProvider&&(this.sandbox=await this.options.sandboxProvider.connect(this.sandbox.sandboxId),this.sandboxState="ready",this.agentState="idle",this.emitLifecycle(e,"sandbox_resume"))}async interrupt(e){if(!this.activeCommand&&!this.activeProcessId)return!1;let t=this.activeOperationId,n=this.activeOperationKind,r=!1;try{this.activeCommand?r=await this.activeCommand.kill():this.sandbox&&this.activeProcessId&&(r=await this.sandbox.commands.kill(this.activeProcessId))}catch{r=!1}if(!r)return this.sandboxState="running",this.agentState="running",!1;t!==null&&this.interruptedOperations.add(t),this.invalidateActiveOperation(),this.sandboxState="ready",this.agentState="interrupted";let a=n==="run"?"run_interrupted":"command_interrupted";return this.emitLifecycle(e,a),r}status(){let e=this.browserRuntimeInfo();return{sandboxId:this.getSession(),sandbox:this.sandboxState,agent:this.agentState,activeProcessId:this.activeProcessId,hasRun:this.hasRun,timestamp:new Date().toISOString(),...e?{browser:e}:{}}}async kill(e){await this.rotateSession();let t;try{this.activeCommand&&await this.interrupt(e),this.sandbox&&(await this.sandbox.kill(),this.sandbox=void 0)}catch(n){t=n}finally{await this.closeProviderRuntimeToken(),await this.closeManagedSecretRuntimeToken(),await this.closeManagedBrowserSession()}if(t)throw t;this.options.sandboxId=void 0,this.interruptedOperations.clear(),this.invalidateActiveOperation(),this.sandboxState="stopped",this.agentState="idle",this.hasRun=!1,this.lastCheckpointId=void 0,this.emitLifecycle(e,"sandbox_killed")}async getHost(e){return(await this.getSandbox()).getHost(e)}getAgentType(){return this.agentConfig.type}getSessionTag(){return!this.sandbox&&!this.sessionLogger?null:this.sessionTag}getSessionTimestamp(){return this.sessionLogger?.getTimestamp()||null}async flushObservability(){await this.sessionLogger?.flush()}async rotateSession(){let e=!!this.sessionLogger;this.sessionLogger&&(await this.sessionLogger.close(),this.sessionLogger=void 0),e&&(this.previousSessionTag=this.sessionTag),this.sessionTag=wXe(this.options.sessionTagPrefix||"evolve")}async fetchSpend(e){if(this.agentConfig.isDirectMode)throw new Error("Cost tracking requires gateway mode (set EVOLVE_API_KEY).");let t=this.agentConfig.apiKey;if(!t)throw new Error("Cost tracking requires an API key.");let n=process.env.EVOLVE_DASHBOARD_URL||ia,r=await fetch(`${n}/api/sessions/spend?${e}`,{headers:{Authorization:`Bearer ${t}`},signal:AbortSignal.timeout(1e4)});if(!r.ok){let a=await r.text().catch(()=>"");throw new Error(`Spend query failed (${r.status}): ${a}`)}return r}resolveSpendTag(){if(this.sandbox||this.sessionLogger)return this.sessionTag;if(this.previousSessionTag)return this.previousSessionTag;throw new Error("No session to query. Call run() first.")}normalizeRunCost(e,t){return{...e,asOf:e.asOf??t.asOf,isComplete:e.isComplete??t.isComplete,truncated:e.truncated??t.truncated}}normalizeSessionCost(e){let t={asOf:e.asOf,isComplete:e.isComplete,truncated:e.truncated};return{...e,runs:e.runs.map(n=>this.normalizeRunCost(n,t))}}async getSessionCost(){let e=this.resolveSpendTag(),t=new URLSearchParams({tag:e}),n=await(await this.fetchSpend(t)).json();return this.normalizeSessionCost(n)}async getRunCost(e){let t=this.resolveSpendTag();if("runId"in e){let i=new URLSearchParams({tag:t,runId:e.runId}),s=await(await this.fetchSpend(i)).json();return this.normalizeRunCost(s,{asOf:new Date().toISOString(),isComplete:!1,truncated:!1})}let n=await this.getSessionCost(),r=e.index>0?e.index-1:n.runs.length+e.index,a=n.runs[r];if(!a)throw new Error(`Run index ${e.index} out of range. Session has ${n.runs.length} run(s).`);return a}};function v9t(e){return(e||process.env.EVOLVE_DASHBOARD_URL||ia).replace(/\/$/,"")}function b9t(e){let t=e||process.env.EVOLVE_API_KEY;if(!t)throw new Error("Browser profiles require EVOLVE_API_KEY or an explicit apiKey");return t}async function S9t(e){return await e.text().catch(()=>"")}async function EXe(e,t,n={}){let r=await fetch(`${v9t(e?.dashboardUrl)}${t}`,{...n,headers:{Authorization:`Bearer ${b9t(e?.apiKey)}`,accept:"application/json",...n.body?{"content-type":"application/json"}:{},...n.headers||{}}});if(!r.ok)throw new Error(`Browser profiles request failed (${r.status}): ${await S9t(r)}`);return r.status===204?{}:await r.json()}var _9t=class{constructor(e={}){this.config=e}toMetadata(e){return{id:e.id,profile:e.profile,createdAt:e.createdAt||e.created_at||"",updatedAt:e.updatedAt||e.updated_at||"",lastUsedAt:e.lastUsedAt??e.last_used_at??null}}async list(){return{profiles:(await EXe(this.config,"/api/browser-profiles")).profiles.map(e=>this.toMetadata(e))}}async delete(e){return await EXe(this.config,"/api/browser-profiles",{method:"DELETE",body:JSON.stringify(e)})}};function w9t(e={}){return new _9t(e)}var Tv=class extends kXe.EventEmitter{config={};agent;fallbackSandboxState="stopped";fallbackAgentState="idle";fallbackHasRun=!1;constructor(){super()}on(e,t){return super.on(e,t)}off(e,t){return super.off(e,t)}emit(e,...t){return super.emit(e,...t)}withAgent(e){return e&&(zXe(e),jXe(e),this.config.agent=e,this._cachedGatewayOverrides=null),this}withSandbox(e){return this.config.sandbox=e,this}withSandboxCreateOptions(e){return this.config.sandboxCreateOptions={...e,envs:e.envs?{...e.envs}:void 0,metadata:e.metadata?{...e.metadata}:void 0},this}withWorkingDirectory(e){return this.config.workingDirectory=e,this}withWorkspaceMode(e){return this.config.workspaceMode=e,this}withSecrets(e){return this.config.secrets={...this.config.secrets,...e},this}withManagedSecrets(e){return this.config.managedSecrets=e,this}withSession(e){return this.config.sandboxId=e,this.agent||(this.fallbackSandboxState="ready",this.fallbackAgentState="idle",this.fallbackHasRun=!0),this}withSystemPrompt(e){return this.config.systemPrompt=e,this}withContext(e){return this.config.context={...this.config.context,...e},this}withFiles(e){return this.config.files={...this.config.files,...e},this}withMcpServers(e){return this.config.mcpServers={...this.config.mcpServers,...e},this}withBrowser(e={provider:"agent-browser",remote:!0}){return e===!1?delete this.config.browser:this.config.browser=e,this}withBrowserCredentials(e={}){return this.config.browserCredentials=e,this}withPlugins(e){let t=Array.isArray(e)?e:[e];return this.config.plugins=[...this.config.plugins??[],...t],this}withSkills(e){return this.config.skills=e,this}withSchema(e,t){return this.config.schema=e,t&&(vB(e)?console.warn("[Evolve] schemaOptions ignored for Zod schemas - use .passthrough(), .strip(), z.coerce instead"):this.config.schemaOptions=t),this}withSessionTagPrefix(e){return this.config.sessionTagPrefix=e,this}withObservability(e){return this.config.observability={...this.config.observability,...e},this}withIntegrations(e){return this.config.integrations=e,this}withStorage(e){return this.config.storage=e||{},this}static integrations=IYt;static browserCredentials=t9t;static browserProfiles=w9t;static managedSecrets=CB;async initializeAgent(){let e=tXe(this.config.agent),t=xv(e.type);if(this.config.integrations&&e.isDirectMode)throw new Error("withIntegrations() is available only in gateway mode with EVOLVE_API_KEY");if(this.config.managedSecrets&&e.isDirectMode)throw new Error("withManagedSecrets() is available only in gateway mode with EVOLVE_API_KEY");if(this.config.managedSecrets&&this.config.sandboxId)throw new Error("withManagedSecrets() cannot be used with withSession(); managed secret grants are sandbox-scoped.");let n=RQ(this.config.managedSecrets,t);if(n&&this.config.sandbox&&!DZ(this.config.sandbox))throw new Error("withManagedSecrets() requires an Evolve-managed sandbox; remove withSandbox() or pass a managed sandbox provider.");let r=this.config.sandbox??(n?await qZ(e.apiKey):await $jt()),a={},i,s,o=this.config.skills,c;if(this.config.browser){let d=JYt(this.config.browser);if(c=d,d.provider==="browser-use"){if(e.isDirectMode)throw new Error('withBrowser("browser-use") requires gateway mode. Use apiKey/EVOLVE_API_KEY instead of providerApiKey/direct mode.');a=bQ(e.apiKey)}if((d.provider==="actionbook"||d.provider==="agent-browser")&&d.managed){if(e.isDirectMode)throw new Error(`Managed browser provider "${d.provider}" requires gateway mode. Use apiKey/EVOLVE_API_KEY instead of providerApiKey/direct mode.`);i=d.provider==="actionbook"?oYt:cYt,s={provider:d.provider,apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||ia,...d.profile?{profile:d.profile}:{}}}if(d.profile&&!d.managed)throw new Error('withBrowser({ profile }) requires managed remote browser mode. Use .withBrowser({ profile }) or .withBrowser({ provider: "agent-browser", remote: true, profile }).')}if(this.config.browserCredentials!==void 0){if(this.config.sandboxId)throw new Error("withBrowserCredentials() cannot be used with withSession(); browser login tokens are run-scoped.");if(e.isDirectMode)throw new Error("withBrowserCredentials() requires gateway mode. Use apiKey/EVOLVE_API_KEY instead of providerApiKey/direct mode.");if(!c||c.provider!=="agent-browser"||!c.managed)throw new Error('withBrowserCredentials() requires .withBrowser() or .withBrowser({ provider: "agent-browser", remote: true }).');if(this.config.mcpServers?.["browser-login"])throw new Error('withBrowserCredentials() reserves the "browser-login" MCP server name.')}let l=this.config.storage!==void 0?XXe(this.config.storage,!e.isDirectMode,ia,e.isDirectMode?void 0:e.apiKey):void 0,u={sandboxProvider:r,sandboxCreateOptions:this.config.sandboxCreateOptions,secrets:this.config.secrets,managedSecrets:n?{secrets:n,apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||ia}:void 0,sandboxId:this.config.sandboxId,workingDirectory:this.config.workingDirectory,workspaceMode:this.config.workspaceMode,systemPrompt:this.config.systemPrompt,context:this.config.context,files:this.config.files,mcpServers:{...a,...this.config.mcpServers},browserPrompt:i,managedBrowser:s,browserCredentials:this.config.browserCredentials!==void 0?{apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||ia,config:this.config.browserCredentials}:void 0,plugins:this.config.plugins,skills:o,schema:this.config.schema,schemaOptions:this.config.schemaOptions,sessionTagPrefix:this.config.sessionTagPrefix,observability:this.config.observability,integrations:this.config.integrations?{...this.config.integrations,apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||ia}:void 0,providerRouting:e.isDirectMode?void 0:{apiKey:e.apiKey,dashboardUrl:process.env.EVOLVE_DASHBOARD_URL||ia},storage:l};this.agent=new y9t(e,u)}createStreamCallbacks(){let e=this.listenerCount("stdout")>0,t=this.listenerCount("stderr")>0,n=this.listenerCount("content")>0,r=this.listenerCount("lifecycle")>0;return{onStdout:e?a=>this.emit("stdout",a):void 0,onStderr:t?a=>this.emit("stderr",a):void 0,onContent:n?a=>this.emit("content",a):void 0,onLifecycle:r?a=>this.emit("lifecycle",a):void 0}}emitLifecycleFromStatus(e){if(this.listenerCount("lifecycle")===0)return;let t=this.status();this.emit("lifecycle",{sandboxId:t.sandboxId,sandbox:t.sandbox,agent:t.agent,timestamp:new Date().toISOString(),reason:e,...t.browser?{browser:t.browser}:{}})}async run({prompt:e,timeoutMs:t,background:n,from:r,checkpointComment:a,resume:i}){if(r&&this.config.sandboxId)throw new Error("Cannot use 'from' with 'withSession()' \u2014 restore requires a fresh sandbox.");this.agent||await this.initializeAgent();let s=this.createStreamCallbacks();return this.agent.run({prompt:e,timeoutMs:t,background:n,from:r,checkpointComment:a,resume:i},s)}async executeCommand(e,t={}){this.agent||await this.initializeAgent();let n=this.createStreamCallbacks();return this.agent.executeCommand(e,t,n)}async prepareSandbox(){this.agent||await this.initializeAgent();let e=this.createStreamCallbacks();return(await this.agent.getSandbox(e)).sandboxId}async updateNetwork(e){if(!this.agent)throw new Error("No sandbox yet. Call prepareSandbox(), run() or executeCommand() before updateNetwork().");let t=await this.agent.getSandbox(this.createStreamCallbacks());if(typeof t.updateNetwork!="function")throw new Error(`The ${this.config.sandbox?.providerType??"configured"} sandbox provider cannot change network policy after start. Create the sandbox with the policy it needs for its whole lifetime, or use a provider that supports runtime changes.`);await t.updateNetwork(e)}async sealCredentials(){if(!this.agent)throw new Error("Agent not initialized. Call run() or executeCommand() first.");await this.agent.sealCredentials()}isSealed(){return this.agent?.isSealed()??!1}resolvedSkills(){return this.agent?.resolvedSkills()??[]}async collectArtifacts(e){if(!this.agent)throw new Error("Agent not initialized. Call run() or executeCommand() first.");return this.agent.collectArtifacts(e)}async interrupt(){if(!this.agent)return!1;let e=this.createStreamCallbacks();return this.agent.interrupt(e)}async uploadContext(e){return this.agent||await this.initializeAgent(),this.agent.uploadContext(e)}async uploadFiles(e){return this.agent||await this.initializeAgent(),this.agent.uploadFiles(e)}async uploadFileFromPath(e,t){return this.agent||await this.initializeAgent(),this.agent.uploadFileFromPath(e,t)}async getOutputFiles(e=!1){if(!this.agent)throw new Error("Agent not initialized. Call run() first.");return this.agent.getOutputFiles(e)}async checkpoint(e){if(!this.agent)throw new Error("Agent not initialized. Call run() first.");return this.agent.checkpoint(e)}_cachedGatewayOverrides=null;resolveGatewayOverrides(){if(this._cachedGatewayOverrides!==null)return this._cachedGatewayOverrides||void 0;try{let e=tXe(this.config.agent);if(!e.isDirectMode)return this._cachedGatewayOverrides={gatewayUrl:ia,gatewayApiKey:e.apiKey},this._cachedGatewayOverrides}catch{}this._cachedGatewayOverrides=void 0}async listCheckpoints(e){if(this.config.storage===void 0)throw new Error("Storage not configured. Call .withStorage().");return hXe(this.config.storage,this.resolveGatewayOverrides()||{}).listCheckpoints(e)}storage(){if(this.config.storage===void 0)throw new Error("Storage not configured. Call .withStorage().");return hXe(this.config.storage,this.resolveGatewayOverrides()||{})}getSession(){return this.agent?this.agent.getSession():this.config.sandboxId??null}async setSession(e){if(this.config.managedSecrets)throw new Error("setSession() cannot be used with withManagedSecrets(); managed secret grants are sandbox-scoped.");this.agent?await this.agent.setSession(e):(this.fallbackSandboxState="ready",this.fallbackAgentState="idle",this.fallbackHasRun=!0),this.config.sandboxId=e}status(){return this.agent?this.agent.status():{sandboxId:this.config.sandboxId??null,sandbox:this.fallbackSandboxState,agent:this.fallbackAgentState,activeProcessId:null,hasRun:this.fallbackHasRun,timestamp:new Date().toISOString()}}async pause(){if(this.agent){let e=this.createStreamCallbacks();await this.agent.pause(e);return}this.config.sandboxId&&this.config.sandbox&&(await(await this.config.sandbox.connect(this.config.sandboxId)).pause(),this.fallbackSandboxState="paused",this.fallbackAgentState="idle",this.emitLifecycleFromStatus("sandbox_pause"))}async resume(){if(this.agent){let e=this.createStreamCallbacks();await this.agent.resume(e);return}this.config.sandboxId&&this.config.sandbox&&(await this.config.sandbox.connect(this.config.sandboxId),this.fallbackSandboxState="ready",this.fallbackAgentState="idle",this.emitLifecycleFromStatus("sandbox_resume"))}async kill(){if(this.agent){let e=this.createStreamCallbacks();await this.agent.kill(e),this.config.sandboxId=void 0,this.fallbackSandboxState="stopped",this.fallbackAgentState="idle",this.fallbackHasRun=!1;return}this.config.sandboxId&&this.config.sandbox&&(await(await this.config.sandbox.connect(this.config.sandboxId)).kill(),this.fallbackSandboxState="stopped",this.fallbackAgentState="idle",this.fallbackHasRun=!1,this.emitLifecycleFromStatus("sandbox_killed"),this.config.sandboxId=void 0)}async getHost(e){return this.agent||await this.initializeAgent(),this.agent.getHost(e)}getSessionTag(){return this.agent?.getSessionTag()||null}getSessionTimestamp(){return this.agent?.getSessionTimestamp()||null}async flushObservability(){await this.agent?.flushObservability()}async getSessionCost(){if(!this.agent)throw new Error("No agent initialized. Call run() first.");return this.agent.getSessionCost()}async getRunCost(e){if(!this.agent)throw new Error("No agent initialized. Call run() first.");return this.agent.getRunCost(e)}},I9t=class{permits;queue=[];constructor(e){if(e<1)throw new Error("Semaphore max must be >= 1");this.permits=e}async use(e){await this.acquire();try{return await e()}finally{this.release()}}acquire(){return this.permits>0?(this.permits--,Promise.resolve()):new Promise(e=>this.queue.push(e))}release(){this.queue.length>0?this.queue.shift()():this.permits++}},_O=Symbol.for("evolve.SwarmResult"),TXe=class yZe extends Array{get success(){return this.filter(t=>t.status==="success")}get filtered(){return this.filter(t=>t.status==="filtered")}get error(){return this.filter(t=>t.status==="error")}static from(t){let n=new yZe;return n.push(...t),n}},kOn=class pB{config;semaphore;constructor(t={}){let n=t.concurrency??SQ;if(n>AB)throw new Error(`concurrency=${n} exceeds max ${AB}. For higher parallelism, scale horizontally with multiple processes.`);this.config={agent:t.agent,sandbox:t.sandbox,tag:t.tag??"swarm",concurrency:n,timeoutMs:t.timeoutMs??FO,workspaceMode:t.workspaceMode??"knowledge",retry:t.retry,mcpServers:t.mcpServers,skills:t.skills,integrations:t.integrations},this.semaphore=new I9t(this.config.concurrency)}async map(t){let{items:n,prompt:r,bestOf:a,verify:i}=t,s=t.retry??this.config.retry,o=this.generateOperationId(),c=t.timeoutMs??this.config.timeoutMs;if(a&&i)throw new Error("map() cannot use both bestOf and verify options simultaneously");let l=await Promise.all(n.map((u,d)=>a?this.executeMapItemWithBestOf(u,r,d,o,t,c,s):i?this.executeMapItemWithVerify(u,r,d,o,t,c,s):s?Mp(f=>this.executeMapItem(u,r,d,o,t,c,f),s,d):this.executeMapItem(u,r,d,o,t,c)));return TXe.from(l)}async filter(t){let{items:n,prompt:r,condition:a,verify:i}=t,s=t.retry??this.config.retry,o=this.generateOperationId(),c=t.timeoutMs??this.config.timeoutMs,l=await Promise.all(n.map((d,f)=>i?this.executeFilterItemWithVerify(d,r,f,o,t,c,s):s?Mp(p=>this.executeFilterItem(d,r,f,o,t,c,p),s,f):this.executeFilterItem(d,r,f,o,t,c))),u=[];for(let d of l)if(d.status==="error")u.push(d);else if(d.data!==null)try{a(d.data)?u.push(d):u.push({...d,status:"filtered"})}catch(f){u.push({...d,status:"error",data:null,error:`Condition function threw: ${f.message}`})}return TXe.from(u)}async reduce(t){let{items:n,prompt:r,verify:a}=t,i=t.retry??this.config.retry,s=this.generateOperationId(),o=t.timeoutMs??this.config.timeoutMs,c=[],l=[];n.forEach((I,T)=>{c.push(this.getFiles(I)),l.push(this.getIndex(I,T))});let u={};c.forEach((I,T)=>{Object.entries(I).forEach(([k,O])=>{u[`item_${l[T]}/${k}`]=O})});let d=wZ(u),f=Iv(pYt,{fileTree:d}),p=t.systemPrompt?`${f}
|
|
903
903
|
|
|
904
904
|
${t.systemPrompt}`:f,m=(I,T,k)=>({operationId:s,operation:"reduce",tag:I.tag,sandboxId:I.sandboxId,swarmName:this.config.tag,operationName:t.name,inputCount:n.length,inputIndices:l,errorRetry:T,verifyRetry:k,...this.pipelineContextToMeta(t._pipelineContext)}),y=t.mcpServers??this.config.mcpServers,b=t.skills??this.config.skills,v=t.integrations??this.config.integrations,S=async(I,T,k,O)=>{let R=await this.semaphore.use(()=>this.execute(u,I,{systemPrompt:p,schema:t.schema,schemaOptions:t.schemaOptions,agent:t.agent,mcpServers:y,skills:b,integrations:v,tagPrefix:T,timeoutMs:o,observability:{swarmName:this.config.tag,operationName:t.name,operationId:s,operation:"reduce",role:"worker",errorRetry:k,verifyRetry:O&&O>1?O-1:void 0,...this.pipelineContextToObservability(t._pipelineContext)}})),B=m(R,k,O&&O>1?O-1:void 0);return R.error?{status:"error",data:null,files:R.files,meta:B,error:R.error,rawData:R.rawData}:{status:"success",data:R.data,files:R.files,meta:B}},w=`${this.config.tag}-reduce`;return a?this.runWithVerification((I,T,k)=>S(I,T,void 0,k),{originalPrompt:r,inputFiles:u,verifyConfig:a,timeoutMs:o,systemPrompt:p,schema:t.schema,mcpServers:y,skills:b,integrations:v,operationId:s,baseTag:w,retry:i,operation:"reduce",_pipelineContext:t._pipelineContext}):i?Mp(I=>{let T=I>1?I-1:void 0,k=T?`${w}-er${T}`:w;return S(r,k,T)},i):S(r,w)}async bestOf(t){let{item:n,prompt:r,config:a}=t,i=t.retry??this.config.retry,s=a.n??a.taskAgents?.length;if(s===void 0)throw new Error("bestOf requires n or taskAgents");if(s<2)throw new Error("bestOf requires n >= 2");let o=this.generateOperationId(),c=t.timeoutMs??this.config.timeoutMs,l=this.getFiles(n),u=a.mcpServers??this.config.mcpServers,d=a.judgeMcpServers??a.mcpServers??this.config.mcpServers,f=a.skills??this.config.skills,p=a.judgeSkills??a.skills??this.config.skills,m=a.integrations??this.config.integrations,y=a.judgeIntegrations??a.integrations??this.config.integrations,b=await Promise.all(Array.from({length:s},async(T,k)=>{let O=i?await Mp(R=>this.executeBestOfCandidate({inputFiles:l,prompt:r,candidateIndex:k,operationId:o,config:a,systemPrompt:t.systemPrompt,schema:t.schema,schemaOptions:t.schemaOptions,mcpServers:u,skills:f,integrations:m,timeoutMs:c,attempt:R}),i,k):await this.executeBestOfCandidate({inputFiles:l,prompt:r,candidateIndex:k,operationId:o,config:a,systemPrompt:t.systemPrompt,schema:t.schema,schemaOptions:t.schemaOptions,mcpServers:u,skills:f,integrations:m,timeoutMs:c});return a.onCandidateComplete?.(0,k,O.status==="success"?"success":"error"),O})),v=i?await Mp(T=>this.executeBestOfJudge({inputFiles:l,taskPrompt:r,candidates:b,config:a,timeoutMs:c,operationId:o,systemPrompt:t.systemPrompt,schema:t.schema,schemaOptions:t.schemaOptions,mcpServers:d,skills:p,integrations:y,attempt:T}),{...i,retryOn:void 0},0):await this.executeBestOfJudge({inputFiles:l,taskPrompt:r,candidates:b,config:a,timeoutMs:c,operationId:o,systemPrompt:t.systemPrompt,schema:t.schema,schemaOptions:t.schemaOptions,mcpServers:d,skills:p,integrations:y}),S=b.findIndex(T=>T.status==="success"),w=v.decision?.winner??(S>=0?S:0);a.onJudgeComplete?.(0,w,v.decision?.reasoning??"Judge failed to provide reasoning");let I={operationId:o,operation:"bestof-judge",tag:v.tag,sandboxId:v.sandboxId,swarmName:this.config.tag,operationName:t.name,candidateCount:s};return{winner:b[w]??b[0],winnerIndex:w,judgeReasoning:v.decision?.reasoning??"Judge failed to provide reasoning",judgeMeta:I,candidates:b}}async execute(t,n,r){let a=null,i="",s=r.tagPrefix,o={},c=null,l,u,d={...this.config.agent,...r.agent};try{a=new Tv().withAgent(d).withSandbox(this.config.sandbox).withWorkspaceMode(this.config.workspaceMode).withSessionTagPrefix(r.tagPrefix),r.schema&&a.withSchema(r.schema,r.schemaOptions),r.systemPrompt&&a.withSystemPrompt(r.systemPrompt),r.mcpServers&&a.withMcpServers(r.mcpServers),r.skills?.length&&a.withSkills(r.skills),r.integrations&&a.withIntegrations(r.integrations),r.observability&&a.withObservability(r.observability),Object.keys(t).length>0&&a.withContext(t);let f=await a.run({prompt:n,timeoutMs:r.timeoutMs});i=f.sandboxId,s=a.getSessionTag()??r.tagPrefix;let p=null;try{p=await a.getOutputFiles(!0),o=p.files}catch{}f.exitCode!==0?l=`Agent exited with code ${f.exitCode}`:r.schema?p?(c=p.data,p.error&&(l=p.error),p.rawData&&(u=p.rawData)):l="Failed to read output files from sandbox":c=o}catch(f){if(l=f.message,a){s=a.getSessionTag()??r.tagPrefix;try{o=(await a.getOutputFiles(!0)).files}catch{}}}finally{a&&await a.kill().catch(()=>{})}return{files:o,data:c,tag:s,sandboxId:i,error:l,rawData:u}}async executeMapItem(t,n,r,a,i,s,o=1){let c=this.getFiles(t),l=o>1?`${this.config.tag}-map-${r}-er${o-1}`:`${this.config.tag}-map-${r}`,u=this.evaluatePrompt(n,c,r);if(u instanceof Error)return this.buildErrorResult(`Prompt function threw: ${u.message}`,{operationId:a,operation:"map",tag:l,sandboxId:"",itemIndex:r});let d=i.mcpServers??this.config.mcpServers,f=i.skills??this.config.skills,p=i.integrations??this.config.integrations,m=await this.semaphore.use(()=>this.execute(c,u,{systemPrompt:i.systemPrompt,schema:i.schema,schemaOptions:i.schemaOptions,agent:i.agent,mcpServers:d,skills:f,integrations:p,tagPrefix:l,timeoutMs:s,observability:{swarmName:this.config.tag,operationName:i.name,operationId:a,operation:"map",itemIndex:r,role:"worker",errorRetry:o>1?o-1:void 0,...this.pipelineContextToObservability(i._pipelineContext)}})),y={operationId:a,operation:"map",tag:m.tag,sandboxId:m.sandboxId,swarmName:this.config.tag,operationName:i.name,itemIndex:r,errorRetry:o>1?o-1:void 0,...this.pipelineContextToMeta(i._pipelineContext)};return this.buildResult(m,y)}async executeMapItemWithVerify(t,n,r,a,i,s,o){let c=this.getFiles(t),l=`${this.config.tag}-map-${r}`,u=i.verify,d=i.mcpServers??this.config.mcpServers,f=i.skills??this.config.skills,p=i.integrations??this.config.integrations,m=this.evaluatePrompt(n,c,r);if(m instanceof Error)return this.buildErrorResult(`Prompt function threw: ${m.message}`,{operationId:a,operation:"map",tag:l,sandboxId:"",itemIndex:r});let y=async(b,v,S)=>{let w=await this.semaphore.use(()=>this.execute(c,b,{systemPrompt:i.systemPrompt,schema:i.schema,schemaOptions:i.schemaOptions,agent:i.agent,mcpServers:d,skills:f,integrations:p,tagPrefix:v,timeoutMs:s,observability:{swarmName:this.config.tag,operationName:i.name,operationId:a,operation:"map",itemIndex:r,role:"worker",verifyRetry:S&&S>1?S-1:void 0,...this.pipelineContextToObservability(i._pipelineContext)}})),I={operationId:a,operation:"map",tag:w.tag,sandboxId:w.sandboxId,swarmName:this.config.tag,operationName:i.name,itemIndex:r,verifyRetry:S&&S>1?S-1:void 0,...this.pipelineContextToMeta(i._pipelineContext)};return this.buildResult(w,I)};return this.runWithVerification(y,{originalPrompt:m,inputFiles:c,verifyConfig:u,timeoutMs:s,systemPrompt:i.systemPrompt,schema:i.schema,mcpServers:d,skills:f,integrations:p,operationId:a,baseTag:l,retry:o,itemIndex:r,operation:"map",_pipelineContext:i._pipelineContext})}async executeMapItemWithBestOf(t,n,r,a,i,s,o){let c=this.getFiles(t),l=`${this.config.tag}-map-${r}`,u=this.evaluatePrompt(n,c,r);if(u instanceof Error)return this.buildErrorResult(`Prompt function threw: ${u.message}`,{operationId:a,operation:"map",tag:l,sandboxId:"",itemIndex:r});let d=i.bestOf,f=d.n??d.taskAgents?.length;if(f===void 0||f<2)return this.buildErrorResult("bestOf requires n >= 2 or taskAgents with at least 2 elements",{operationId:a,operation:"map",tag:l,sandboxId:"",itemIndex:r});let p=i.mcpServers??this.config.mcpServers,m=d.mcpServers??p,y=d.judgeMcpServers??d.mcpServers??p,b=i.skills??this.config.skills,v=d.skills??b,S=d.judgeSkills??d.skills??b,w=i.integrations??this.config.integrations,I=d.integrations??w,T=d.judgeIntegrations??d.integrations??w,k=await Promise.all(Array.from({length:f},async(Pe,ee)=>{let E=o?await Mp(G=>this.executeBestOfCandidate({inputFiles:c,prompt:u,candidateIndex:ee,operationId:a,config:d,systemPrompt:i.systemPrompt,schema:i.schema,schemaOptions:i.schemaOptions,mcpServers:m,skills:v,integrations:I,timeoutMs:s,parentIndex:r,attempt:G,_pipelineContext:i._pipelineContext}),o,ee):await this.executeBestOfCandidate({inputFiles:c,prompt:u,candidateIndex:ee,operationId:a,config:d,systemPrompt:i.systemPrompt,schema:i.schema,schemaOptions:i.schemaOptions,mcpServers:m,skills:v,integrations:I,timeoutMs:s,parentIndex:r,_pipelineContext:i._pipelineContext});return d.onCandidateComplete?.(r,ee,E.status==="success"?"success":"error"),E})),O=o?await Mp(Pe=>this.executeBestOfJudge({inputFiles:c,taskPrompt:u,candidates:k,config:d,timeoutMs:s,operationId:a,systemPrompt:i.systemPrompt,schema:i.schema,schemaOptions:i.schemaOptions,mcpServers:y,skills:S,integrations:T,parentIndex:r,attempt:Pe,_pipelineContext:i._pipelineContext}),{...o,retryOn:void 0},0):await this.executeBestOfJudge({inputFiles:c,taskPrompt:u,candidates:k,config:d,timeoutMs:s,operationId:a,systemPrompt:i.systemPrompt,schema:i.schema,schemaOptions:i.schemaOptions,mcpServers:y,skills:S,integrations:T,parentIndex:r,_pipelineContext:i._pipelineContext}),R=k.findIndex(Pe=>Pe.status==="success"),B=O.decision?.winner??(R>=0?R:0),V=k[B]??k[0];d.onJudgeComplete?.(r,B,O.decision?.reasoning??"Judge failed to provide reasoning");let L={operationId:a,operation:"bestof-judge",tag:O.tag,sandboxId:O.sandboxId,swarmName:this.config.tag,operationName:i.name,candidateCount:f,...this.pipelineContextToMeta(i._pipelineContext)};return{...V,meta:{...V.meta,operation:"map",swarmName:this.config.tag,operationName:i.name,itemIndex:r,...this.pipelineContextToMeta(i._pipelineContext)},bestOf:{winnerIndex:B,judgeReasoning:O.decision?.reasoning??"Judge failed to provide reasoning",judgeMeta:L,candidates:k}}}async executeFilterItem(t,n,r,a,i,s,o=1){let c=this.getFiles(t),l=o>1?`${this.config.tag}-filter-${r}-er${o-1}`:`${this.config.tag}-filter-${r}`,u=i.mcpServers??this.config.mcpServers,d=i.skills??this.config.skills,f=i.integrations??this.config.integrations,p=await this.semaphore.use(()=>this.execute(c,n,{systemPrompt:i.systemPrompt,schema:i.schema,schemaOptions:i.schemaOptions,agent:i.agent,mcpServers:u,skills:d,integrations:f,tagPrefix:l,timeoutMs:s,observability:{swarmName:this.config.tag,operationName:i.name,operationId:a,operation:"filter",itemIndex:r,role:"worker",errorRetry:o>1?o-1:void 0,...this.pipelineContextToObservability(i._pipelineContext)}})),m={operationId:a,operation:"filter",tag:p.tag,sandboxId:p.sandboxId,swarmName:this.config.tag,operationName:i.name,itemIndex:r,errorRetry:o>1?o-1:void 0,...this.pipelineContextToMeta(i._pipelineContext)};return this.buildResult(p,m,c)}async executeFilterItemWithVerify(t,n,r,a,i,s,o){let c=this.getFiles(t),l=`${this.config.tag}-filter-${r}`,u=i.verify,d=i.mcpServers??this.config.mcpServers,f=i.skills??this.config.skills,p=i.integrations??this.config.integrations,m=async(y,b,v)=>{let S=await this.semaphore.use(()=>this.execute(c,y,{systemPrompt:i.systemPrompt,schema:i.schema,schemaOptions:i.schemaOptions,agent:i.agent,mcpServers:d,skills:f,integrations:p,tagPrefix:b,timeoutMs:s,observability:{swarmName:this.config.tag,operationName:i.name,operationId:a,operation:"filter",itemIndex:r,role:"worker",verifyRetry:v&&v>1?v-1:void 0,...this.pipelineContextToObservability(i._pipelineContext)}})),w={operationId:a,operation:"filter",tag:S.tag,sandboxId:S.sandboxId,swarmName:this.config.tag,operationName:i.name,itemIndex:r,verifyRetry:v&&v>1?v-1:void 0,...this.pipelineContextToMeta(i._pipelineContext)};return this.buildResult(S,w,c)};return this.runWithVerification(m,{originalPrompt:n,inputFiles:c,verifyConfig:u,timeoutMs:s,systemPrompt:i.systemPrompt,schema:i.schema,mcpServers:d,skills:f,integrations:p,operationId:a,baseTag:l,retry:o,itemIndex:r,operation:"filter",_pipelineContext:i._pipelineContext})}async executeBestOfCandidate(t){let{inputFiles:n,prompt:r,candidateIndex:a,operationId:i,config:s,timeoutMs:o,parentIndex:c,attempt:l=1,_pipelineContext:u}=t,d=c!==void 0?`${this.config.tag}-map-${c}-bestof-cand-${a}`:`${this.config.tag}-bestof-cand-${a}`,f=l>1?`${d}-er${l-1}`:d,p=await this.semaphore.use(()=>this.execute(n,r,{systemPrompt:t.systemPrompt,schema:t.schema,schemaOptions:t.schemaOptions,agent:s.taskAgents?.[a],mcpServers:t.mcpServers,skills:t.skills,integrations:t.integrations,tagPrefix:f,timeoutMs:o,observability:{swarmName:this.config.tag,operationId:i,operation:"map",itemIndex:c,role:"candidate",candidateIndex:a,errorRetry:l>1?l-1:void 0,...this.pipelineContextToObservability(u)}})),m={operationId:i,operation:"bestof-cand",tag:p.tag,sandboxId:p.sandboxId,swarmName:this.config.tag,itemIndex:a,errorRetry:l>1?l-1:void 0,candidateIndex:a,...this.pipelineContextToMeta(u)};return this.buildResult(p,m)}buildJudgeContext(t){let n=this.buildEvaluatorContext({inputFiles:t.inputFiles,taskPrompt:t.taskPrompt,systemPrompt:t.systemPrompt,schema:t.schema});return t.candidates.forEach((r,a)=>{r.status==="error"&&(n[`candidate_${a}/_failed.txt`]=`STATUS: FAILED
|
|
905
905
|
|
|
@@ -1561,7 +1561,7 @@ class AnalyzeConfigInput(TypedDict, total=False):
|
|
|
1561
1561
|
#: at max — the effort its published scores use; a recorded deviation
|
|
1562
1562
|
#: from Harbor's claude-haiku-4-5 default — analysis is input-dominated,
|
|
1563
1563
|
#: and this is the roster's intelligence-per-input-dollar pick at its
|
|
1564
|
-
#: published effort; deepseek-
|
|
1564
|
+
#: published effort; deepseek-flash and haiku stay as
|
|
1565
1565
|
#: alternatives, glm-5.3 to escalate).
|
|
1566
1566
|
#: Same vocabulary as ``agents[].model_name``: either advertised
|
|
1567
1567
|
#: spelling is accepted and stored as given (the default is the roster
|
|
@@ -1595,7 +1595,7 @@ class AnalyzeConfigInput(TypedDict, total=False):
|
|
|
1595
1595
|
#: default applies (``analyze['models'][i]['default_reasoning_effort']``:
|
|
1596
1596
|
#: max on glm-5.3-flash, the default model — the platform's ruling
|
|
1597
1597
|
#: 2026-09-08, the effort its published scores use; high on
|
|
1598
|
-
#: deepseek-
|
|
1598
|
+
#: deepseek-flash — DeepSeek's own default; the claude harness
|
|
1599
1599
|
#: default elsewhere). Always passed to the analyzer explicitly and
|
|
1600
1600
|
#: recorded on the analysis (``TrialAnalysis['reasoning_effort']``). A
|
|
1601
1601
|
#: hosted extension: Harbor's analyze has no effort option.
|
|
@@ -1838,13 +1838,20 @@ class CheckConfigInput(TypedDict, total=False):
|
|
|
1838
1838
|
|
|
1839
1839
|
|
|
1840
1840
|
class CheckSource(TypedDict):
|
|
1841
|
-
"""What was checked
|
|
1842
|
-
|
|
1841
|
+
"""What was checked, by identity (spec ``CheckSource``) — two forms told
|
|
1842
|
+
apart by ``type``: ``'archive'`` (the uploaded tar's sha256 and compressed
|
|
1843
|
+
``bytes``; ``dataset`` None) or ``'dataset'`` (the resolved
|
|
1844
|
+
``name@version`` in ``dataset`` and the sha256 of the version's retained
|
|
1845
|
+
task package; ``bytes`` None — a package's size is not a recorded fact,
|
|
1846
|
+
so the wire invents none)."""
|
|
1847
|
+
#: ``'archive'`` or ``'dataset'``.
|
|
1843
1848
|
type: str
|
|
1844
|
-
#: SHA-256 of the archive as uploaded.
|
|
1849
|
+
#: SHA-256 of the archive as uploaded, or of the version's retained task package.
|
|
1845
1850
|
sha256: str
|
|
1846
|
-
#: The archive's compressed size.
|
|
1847
|
-
bytes: int
|
|
1851
|
+
#: The archive's compressed size on the archive form; None on the dataset form.
|
|
1852
|
+
bytes: Optional[int]
|
|
1853
|
+
#: The resolved ``name@version`` on the dataset form; None on the archive form.
|
|
1854
|
+
dataset: Optional[str]
|
|
1848
1855
|
|
|
1849
1856
|
|
|
1850
1857
|
class TaskCheck(TypedDict):
|
|
@@ -2463,6 +2470,10 @@ class JobTaskRollup:
|
|
|
2463
2470
|
mean_reward: Optional[float]
|
|
2464
2471
|
#: Measured spend across the task's settled trials.
|
|
2465
2472
|
cost_usd: Optional[float]
|
|
2473
|
+
#: The task's LATEST quality check among the checks you may read that ran
|
|
2474
|
+
#: on a dataset version this job spans (``checks().create(dataset=...)``);
|
|
2475
|
+
#: None = never checked. The job page's CHECK tab reads it.
|
|
2476
|
+
check: Optional[TaskCheck]
|
|
2466
2477
|
|
|
2467
2478
|
|
|
2468
2479
|
@dataclass
|
|
@@ -3730,6 +3741,8 @@ def _map_job_task_rollup(data: Dict[str, Any]) -> JobTaskRollup:
|
|
|
3730
3741
|
trials=_map_trial_tally(data.get('trials')),
|
|
3731
3742
|
mean_reward=float(mean_reward) if isinstance(mean_reward, (int, float)) else None,
|
|
3732
3743
|
cost_usd=float(cost_usd) if isinstance(cost_usd, (int, float)) else None,
|
|
3744
|
+
# The wire's TaskCheck or None, passed through: the row IS the answer.
|
|
3745
|
+
check=cast(TaskCheck, data['check']) if isinstance(data.get('check'), dict) else None,
|
|
3733
3746
|
)
|
|
3734
3747
|
|
|
3735
3748
|
|
|
@@ -7302,7 +7315,7 @@ class JobsClient:
|
|
|
7302
7315
|
``reasoning_effort`` is the arms' effort vocabulary applied to the
|
|
7303
7316
|
analyzer (``meta().analyze['reasoning_efforts']``); omitted, the
|
|
7304
7317
|
per-model default applies (max on glm-5.3-flash, high on
|
|
7305
|
-
deepseek-
|
|
7318
|
+
deepseek-flash, the claude harness default elsewhere) —
|
|
7306
7319
|
the effort is always passed explicitly and recorded on each
|
|
7307
7320
|
analysis.
|
|
7308
7321
|
Every argument omitted means the defaults: glm-5.3-flash at max
|
|
@@ -8146,8 +8159,9 @@ class ChecksClient:
|
|
|
8146
8159
|
|
|
8147
8160
|
async def create(
|
|
8148
8161
|
self,
|
|
8149
|
-
directory: str,
|
|
8162
|
+
directory: Optional[str] = None,
|
|
8150
8163
|
*,
|
|
8164
|
+
dataset: Optional[str] = None,
|
|
8151
8165
|
model_name: Optional[str] = None,
|
|
8152
8166
|
rubric: Optional[Rubric] = None,
|
|
8153
8167
|
prompt: Optional[str] = None,
|
|
@@ -8162,10 +8176,16 @@ class ChecksClient:
|
|
|
8162
8176
|
"""Check task quality against a rubric — Harbor's ``harbor check
|
|
8163
8177
|
<PATH>`` (their cli/analyze.py:84-207), hosted.
|
|
8164
8178
|
|
|
8165
|
-
``directory``
|
|
8166
|
-
task directories, tarred and streamed from disk
|
|
8167
|
-
as Harbor's PATH is (their checker.py:125-130 refuses
|
|
8168
|
-
no ready-packed archive form
|
|
8179
|
+
ONE source: ``directory`` — Harbor's PATH: one task directory, or a
|
|
8180
|
+
directory of task directories, tarred and streamed from disk, a
|
|
8181
|
+
directory only, as Harbor's PATH is (their checker.py:125-130 refuses
|
|
8182
|
+
anything else; no ready-packed archive form) — or ``dataset``, a
|
|
8183
|
+
PUBLISHED dataset (``'name'`` for its active version, or
|
|
8184
|
+
``'name@version'``), the hosted form and a recorded deviation: Harbor's
|
|
8185
|
+
check takes a local path only; here the checker reads the version's
|
|
8186
|
+
retained task package, nothing is uploaded, and the job page's CHECK
|
|
8187
|
+
tab lists these checks by task. Both or neither is a ``ValueError``
|
|
8188
|
+
at the keyboard. Which task directories are checked is
|
|
8169
8189
|
Harbor's own resolution (checker.py:
|
|
8170
8190
|
116-141): the root when it is a task directory (task.toml +
|
|
8171
8191
|
environment/ + instruction.md + tests/), else every top-level
|
|
@@ -8194,7 +8214,21 @@ class ChecksClient:
|
|
|
8194
8214
|
``limits['uploads']['check_archive_bytes']``),
|
|
8195
8215
|
``too_many_concurrent_check_uploads`` (the server is already
|
|
8196
8216
|
spooling its bound of check archives — retry when one finishes).
|
|
8217
|
+
The dataset form resolves under the job-create door's own refusals:
|
|
8218
|
+
``dataset_not_found`` (404), ``dataset_version_not_found`` (404),
|
|
8219
|
+
``no_active_version`` (400), ``version_not_ready`` (409), and
|
|
8220
|
+
``invalid_input`` on ``dataset`` (400) for a version whose task
|
|
8221
|
+
package was not retained.
|
|
8222
|
+
|
|
8223
|
+
Each task's result (``results[i]['id']``) is also a run of its own,
|
|
8224
|
+
read like an analysis run — the checker's transcript, raw streams,
|
|
8225
|
+
agent home and ``check-result.json``; those reads ride the
|
|
8226
|
+
dashboard's traces feed (not on the contract) and are
|
|
8227
|
+
TypeScript-and-CLI today: ``evolve check trace`` and ``evolve check
|
|
8228
|
+
download``.
|
|
8197
8229
|
"""
|
|
8230
|
+
if (directory is None) == (dataset is None):
|
|
8231
|
+
raise ValueError('checks().create() takes exactly one source: directory or dataset')
|
|
8198
8232
|
knobs: Dict[str, Any] = {}
|
|
8199
8233
|
if model_name is not None:
|
|
8200
8234
|
knobs['model_name'] = model_name
|
|
@@ -8218,6 +8252,16 @@ class ChecksClient:
|
|
|
8218
8252
|
# sent before the archive so the server rules it before a byte of
|
|
8219
8253
|
# the upload — the analyze door's acceptance, under ``check.*``.
|
|
8220
8254
|
fields: Dict[str, Optional[str]] = {'config': json.dumps(knobs)}
|
|
8255
|
+
if dataset is not None:
|
|
8256
|
+
# THE DATASET FORM: no archive travels — the ``dataset`` part
|
|
8257
|
+
# names the published version (the metadata-only multipart body
|
|
8258
|
+
# every no-archive route takes).
|
|
8259
|
+
if dataset.strip() == '':
|
|
8260
|
+
raise ValueError('checks().create(): dataset must be "name" or "name@version"')
|
|
8261
|
+
body, content_type = _multipart_body({**fields, 'dataset': dataset.strip()})
|
|
8262
|
+
raw = await self._http.request_upload('/api/checks', body, {'Content-Type': content_type})
|
|
8263
|
+
return _map_check(raw)
|
|
8264
|
+
assert directory is not None
|
|
8221
8265
|
path = os.path.abspath(directory)
|
|
8222
8266
|
# Harbor's own first refusal: "Path '{path}' does not exist"
|
|
8223
8267
|
# (checker.py:66-67), at the keyboard, before any tar.
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1201}/evolve/prompts/user/retry_feedback.md
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{evolve_sdk-0.0.55.dev1192 → evolve_sdk-0.0.55.dev1201}/evolve_sdk.egg-info/dependency_links.txt
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|