jeo-code 0.12.17 → 0.12.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -9,6 +9,12 @@ The README mirrors the latest 5 entries — regenerate with `bun run changelog:s
9
9
 
10
10
  ## [Unreleased]
11
11
 
12
+ ## [0.12.18] - 2026-11-04
13
+
14
+ ### Changed
15
+ - **Session model follows the login** — a session opens on the configured default model, and only when the stored login can actually serve it (the provider has a live credential and, for built-in providers, the credential serves that specific model; ChatGPT OAuth serves only Codex ids). When it cannot, the session starts on the first authenticated model from recents, then role tiers, and prints a one-line notice naming the provider to log in to. The fallback is session-local; the saved default is never rewritten, and an explicit `--model`/`--model-role`/`--provider` pin still wins.
16
+ - **Resume opens on the default too** — `--resume`, `--resume-interactive` and `/session resume` no longer restore the model saved in the session header; a resumed session opens on the same default as a new one. `/model` and the picker still switch the model for the running session.
17
+
12
18
  ## [0.12.17] - 2026-11-04
13
19
 
14
20
  ### Fixed
@@ -2694,7 +2700,8 @@ _Initial release._
2694
2700
  ### Added
2695
2701
  - Initial jeo-code agent and CLI.
2696
2702
 
2697
- [Unreleased]: https://github.com/akillness/jeo-code/compare/v0.12.17...HEAD
2703
+ [Unreleased]: https://github.com/akillness/jeo-code/compare/v0.12.18...HEAD
2704
+ [0.12.18]: https://github.com/akillness/jeo-code/releases/tag/v0.12.18
2698
2705
  [0.12.17]: https://github.com/akillness/jeo-code/releases/tag/v0.12.17
2699
2706
  [0.12.16]: https://github.com/akillness/jeo-code/releases/tag/v0.12.16
2700
2707
  [0.12.6]: https://github.com/akillness/jeo-code/releases/tag/v0.12.6
package/README.ja.md CHANGED
@@ -447,10 +447,10 @@ CI は `.github/workflows/npm-publish.yml` で公開します — GitHub リリ
447
447
 
448
448
  <!-- CHANGELOG:START (auto-generated from CHANGELOG.md — run `bun run changelog:sync`) -->
449
449
  - **[Unreleased]**
450
+ - **[0.12.18]** (2026-11-04)
450
451
  - **[0.12.17]** (2026-11-04)
451
452
  - **[0.12.16]** (2026-11-04)
452
453
  - **[0.12.15]** (2026-11-03)
453
- - **[0.12.14]** (2026-11-03)
454
454
 
455
455
  See [CHANGELOG.md](CHANGELOG.md) for the full history.
456
456
  <!-- CHANGELOG:END -->
package/README.ko.md CHANGED
@@ -502,10 +502,10 @@ CI는 `.github/workflows/npm-publish.yml`로 배포합니다 — GitHub 릴리
502
502
 
503
503
  <!-- CHANGELOG:START (auto-generated from CHANGELOG.md — run `bun run changelog:sync`) -->
504
504
  - **[Unreleased]**
505
+ - **[0.12.18]** (2026-11-04)
505
506
  - **[0.12.17]** (2026-11-04)
506
507
  - **[0.12.16]** (2026-11-04)
507
508
  - **[0.12.15]** (2026-11-03)
508
- - **[0.12.14]** (2026-11-03)
509
509
 
510
510
  See [CHANGELOG.md](CHANGELOG.md) for the full history.
511
511
  <!-- CHANGELOG:END -->
package/README.md CHANGED
@@ -491,10 +491,10 @@ Huge thanks to [gajae-code](https://github.com/Yeachan-Heo/gajae-code) for the i
491
491
 
492
492
  <!-- CHANGELOG:START (auto-generated from CHANGELOG.md — run `bun run changelog:sync`) -->
493
493
  - **[Unreleased]**
494
+ - **[0.12.18]** (2026-11-04)
494
495
  - **[0.12.17]** (2026-11-04)
495
496
  - **[0.12.16]** (2026-11-04)
496
497
  - **[0.12.15]** (2026-11-03)
497
- - **[0.12.14]** (2026-11-03)
498
498
 
499
499
  See [CHANGELOG.md](CHANGELOG.md) for the full history.
500
500
  <!-- CHANGELOG:END -->
package/README.zh.md CHANGED
@@ -445,10 +445,10 @@ CI 通过 `.github/workflows/npm-publish.yml` 发布 — GitHub 发布 release
445
445
 
446
446
  <!-- CHANGELOG:START (auto-generated from CHANGELOG.md — run `bun run changelog:sync`) -->
447
447
  - **[Unreleased]**
448
+ - **[0.12.18]** (2026-11-04)
448
449
  - **[0.12.17]** (2026-11-04)
449
450
  - **[0.12.16]** (2026-11-04)
450
451
  - **[0.12.15]** (2026-11-03)
451
- - **[0.12.14]** (2026-11-03)
452
452
 
453
453
  See [CHANGELOG.md](CHANGELOG.md) for the full history.
454
454
  <!-- CHANGELOG:END -->
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jeo-code",
3
- "version": "0.12.17",
3
+ "version": "0.12.18",
4
4
  "description": "Clean, highly optimized AI coding agent using spec-first loop",
5
5
  "type": "module",
6
6
 
@@ -62,7 +62,7 @@ button:hover{background:#1b1c27}
62
62
  <script>__SCRIPT__</script>
63
63
  </body></html>`});async function NhG(G,Z){let b=await fetch(G,{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify(Z),signal:AbortSignal.timeout(30000)}),Y=await b.text();if(!b.ok)throw Error(`Anthropic OAuth request failed (HTTP ${b.status}): ${Y}`);try{return JSON.parse(Y)}catch{throw Error(`Anthropic OAuth returned invalid JSON: ${Y}`)}}function YhG(G){let Z=G.account?.uuid,b=G.account?.email_address;return{access:G.access_token,refresh:G.refresh_token,expires:Date.now()+G.expires_in*1000-300000,accountId:typeof Z==="string"&&Z?Z:void 0,email:typeof b==="string"&&b?b:void 0}}async function saI(G){return new VhG(G).login()}async function iaI(G){let Z=await NhG(WhG,{grant_type:"refresh_token",client_id:faI,refresh_token:G});return{...YhG(Z),refresh:Z.refresh_token||G}}var TEZ=(G)=>atob(G),faI,SEZ="https://claude.ai/oauth/authorize",WhG="https://api.anthropic.com/v1/oauth/token",nEZ=54545,qEZ="/callback",PEZ="org:create_api_key user:profile user:inference",VhG;var taI=KW(()=>{lr();faI=TEZ("OWQxYzI1MGEtZTYxYi00NGQ5LTg4ZWQtNTk0NGQxOTYyZjVl");VhG=class VhG extends $z{#I="";constructor(G){super(G,{preferredPort:nEZ,callbackPath:qEZ})}async generateAuthUrl(G,Z){let b=await TdI();this.#I=b.verifier;let Y=new URLSearchParams({code:"true",client_id:faI,response_type:"code",redirect_uri:Z,scope:PEZ,code_challenge:b.challenge,code_challenge_method:"S256",state:G});return{url:`${SEZ}?${Y.toString()}`,instructions:"Approve in your browser. If it cannot reach this machine, paste the final redirect URL or code when prompted."}}async exchangeToken(G,Z,b){let Y=G,V=Z,X=G.indexOf("#");if(X>=0){Y=G.slice(0,X);let Q=G.slice(X+1);if(Q)V=Q}let R=await NhG(WhG,{grant_type:"authorization_code",client_id:faI,code:Y,state:V,redirect_uri:b,code_verifier:this.#I});return YhG(R)}}});function Z5Z(G){try{let Z=G.split(".");if(Z.length!==3)return null;return JSON.parse(Buffer.from(Z[1]??"","base64").toString("utf-8"))}catch{return null}}function RhG(G){let Z=Z5Z(G),b=Z?.[fEZ]?.chatgpt_account_id,Y=Z?.[sEZ]?.email?.trim?.().toLowerCase?.();return{accountId:typeof b==="string"&&b?b:void 0,email:typeof Y==="string"&&Y?Y:void 0}}async function FhG(G,Z,b){let Y=await fetch(XhG,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:qdI,code:G,code_verifier:Z,redirect_uri:b}),signal:AbortSignal.timeout(ndI)});if(!Y.ok)throw Error(`OpenAI token exchange failed (HTTP ${Y.status}): ${await Y.text()}`);let V=await Y.json();if(!V.access_token||!V.refresh_token||typeof V.expires_in!=="number")throw Error("OpenAI token response missing required fields");let{accountId:X,email:R}=RhG(V.access_token);if(!X)throw Error("Failed to extract accountId from token");return{access:V.access_token,refresh:V.refresh_token,expires:Date.now()+V.expires_in*1000-300000,accountId:X,email:R}}async function raI(G){try{return await new dhG(G).login()}catch(Z){if(Z instanceof SdI)return G.onProgress?.(`Port ${oaI} is busy \u2014 falling back to device-code login.`),l5Z(G);throw Z}}async function l5Z(G){G.onProgress?.("Initiating device authorization\u2026");let Z=await fetch(iEZ,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({client_id:qdI}),signal:AbortSignal.timeout(ndI)});if(!Z.ok)throw Error(`Device authorization initiation failed: ${Z.status}`);let b=await Z.json();if(!b.device_auth_id||!b.user_code)throw Error("Device authorization response missing required fields");let Y=b.user_code,V=(typeof b.interval==="number"?b.interval:parseInt(String(b.interval??"5"),10)||5)*1000+I5Z;G.onAuth?.({url:rEZ,instructions:`Enter code: ${Y}`}),G.onProgress?.(`Waiting for browser authorization (code: ${Y})\u2026`);for(let X=0;X<G5Z;X++){if(await Bun.sleep(X===0?Math.min(V,eEZ):V),G.signal?.aborted)throw Error("Device authorization cancelled");let R=await fetch(tEZ,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({device_auth_id:b.device_auth_id,user_code:Y}),signal:AbortSignal.timeout(ndI)});if(R.status===403||R.status===404)continue;if(!R.ok)throw Error(`Device token polling failed: ${R.status}`);let Q=await R.json();if(!Q.authorization_code||!Q.code_verifier)throw Error("Device token response missing authorization_code or code_verifier");return G.onProgress?.("Exchanging authorization code for tokens\u2026"),FhG(Q.authorization_code,Q.code_verifier,oEZ)}throw Error("Device authorization timed out \u2014 user did not complete login in time")}async function eaI(G){let Z=await fetch(XhG,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:G,client_id:qdI}),signal:AbortSignal.timeout(ndI)});if(!Z.ok)throw Error(`OpenAI token refresh failed (HTTP ${Z.status}): ${await Z.text()}`);let b=await Z.json();if(!b.access_token||typeof b.expires_in!=="number")throw Error("OpenAI refresh response missing required fields");let{accountId:Y,email:V}=RhG(b.access_token);return{access:b.access_token,refresh:b.refresh_token||G,expires:Date.now()+b.expires_in*1000-300000,accountId:Y,email:V}}var qdI="app_EMoamEEZ73f0CkXaXp7hrann",$EZ="https://auth.openai.com/oauth/authorize",XhG="https://auth.openai.com/oauth/token",oaI=1455,chG="/auth/callback",_EZ="openid profile email offline_access",ndI=15000,fEZ="https://api.openai.com/auth",sEZ="https://api.openai.com/profile",iEZ="https://auth.openai.com/api/accounts/deviceauth/usercode",tEZ="https://auth.openai.com/api/accounts/deviceauth/token",oEZ="https://auth.openai.com/deviceauth/callback",rEZ="https://auth.openai.com/codex/device",eEZ=5000,I5Z=3000,G5Z=120,dhG;var IxI=KW(()=>{lr();dhG=class dhG extends $z{#I="";constructor(G){super(G,{preferredPort:oaI,callbackPath:chG,redirectUri:`http://localhost:${oaI}${chG}`})}async generateAuthUrl(G,Z){let b=await TdI();this.#I=b.verifier;let Y=new URLSearchParams({response_type:"code",client_id:qdI,redirect_uri:Z,scope:_EZ,code_challenge:b.challenge,code_challenge_method:"S256",state:G,id_token_add_organizations:"true",codex_cli_simplified_flow:"true",originator:"codex_cli_rs"});return{url:`${$EZ}?${Y.toString()}`,instructions:"Complete login in your browser."}}async exchangeToken(G,Z,b){return FhG(G,this.#I,b)}}});var mhG={};X3(mhG,{discoverGoogleProjectId:()=>aK,ANTIGRAVITY_DISCOVERY_METADATA:()=>br});function W5Z(G,Z){let b=AbortSignal.timeout(Z);if(!G)return b;return typeof AbortSignal.any==="function"?AbortSignal.any([G,b]):b}function QhG(G){if(typeof G==="string"&&G.length>0)return G;if(G&&typeof G==="object"&&typeof G.id==="string"&&G.id.length>0)return G.id;return}function N5Z(G){if(!G||G.length===0)return"legacy-tier";return G.find((b)=>b.isDefault&&typeof b.id==="string"&&b.id.length>0)?.id??"legacy-tier"}function Y5Z(G){if(!G||typeof G!=="object"||!("error"in G))return!1;let Z=G.error?.details;return Array.isArray(Z)&&Z.some((b)=>b.reason==="SECURITY_POLICY_VIOLATED")}async function aK(G,Z={}){let b=Z.fetchImpl??fetch,Y=Z.sleep??((x)=>new Promise((S)=>setTimeout(S,x))),V=Z.env??process.env,X=Z.maxPollAttempts??5,R=V.GOOGLE_CLOUD_PROJECT||V.GOOGLE_CLOUD_PROJECT_ID||void 0,Q=Z.metadata??b5Z,H=Z.requestTimeoutMs??30000,w=()=>W5Z(Z.signal,H),C={authorization:`Bearer ${G}`,"content-type":"application/json",...Z.extraHeaders??{}};Z.onProgress?.("Checking for an existing Cloud Code Assist project\u2026");let A=await b("https://cloudcode-pa.googleapis.com/v1internal:loadCodeAssist",{method:"POST",headers:C,body:JSON.stringify({cloudaicompanionProject:R,metadata:{...Q,duetProject:R}}),signal:w()}),y;if(!A.ok){let x;try{x=await A.clone().json()}catch{x=void 0}if(Y5Z(x))y={currentTier:{id:"standard-tier"}};else throw Error(`loadCodeAssist failed (HTTP ${A.status}): ${await A.text()}`)}else y=await A.json();if(y.currentTier){let x=QhG(y.cloudaicompanionProject)??R;if(x)return x;if(!Z.alwaysOnboard)throw Error(GxI)}let k=N5Z(y.allowedTiers)||"free-tier";if(!Z.alwaysOnboard&&k!=="free-tier"&&k!=="legacy-tier"&&!R)throw Error(GxI);Z.onProgress?.("Provisioning a Cloud Code Assist project (one-time, may take a moment)\u2026");let p={tierId:k,metadata:{...Q}};if(R&&k!=="free-tier")p.cloudaicompanionProject=R,p.metadata.duetProject=R;let O=await b("https://cloudcode-pa.googleapis.com/v1internal:onboardUser",{method:"POST",headers:C,body:JSON.stringify(p),signal:w()});if(!O.ok)throw Error(`onboardUser failed (HTTP ${O.status}): ${await O.text()}`);let K=await O.json();for(let x=1;!K.done&&K.name&&x<=X;x++){Z.onProgress?.(`Waiting for project provisioning (attempt ${x}/${X})\u2026`),await Y(2000);let S=await b(`https://cloudcode-pa.googleapis.com/v1internal/${K.name}`,{method:"GET",headers:C,signal:w()});if(!S.ok)throw Error(`Polling onboardUser operation failed (HTTP ${S.status}).`);K=await S.json()}let a=QhG(K.response?.cloudaicompanionProject)??R;if(a)return a;throw Error(`Cloud Code Assist did not return a provisioned project id${K.done?"":` after ${X} attempts`}. ${GxI}`)}var b5Z,br,GxI="This Google account requires an explicit project: set GOOGLE_CLOUD_PROJECT or GOOGLE_CLOUD_PROJECT_ID (see https://goo.gle/gemini-cli-auth-docs#workspace-gca), then retry.";var Wr=KW(()=>{b5Z=Object.freeze({ideType:"IDE_UNSPECIFIED",platform:"PLATFORM_UNSPECIFIED",pluginType:"GEMINI"}),br=Object.freeze({ideType:"ANTIGRAVITY",platform:"PLATFORM_UNSPECIFIED",pluginType:"GEMINI"})});async function*ZxI(G,Z){let b=G.getReader(),Y=new TextDecoder("utf-8"),V="",X=0;try{while(!0){let{done:Q,value:H}=await b.read();if(Q)break;if(H&&H.length>0)Z?.();V+=Y.decode(H,{stream:!0});let w;while((w=V.indexOf(`
64
64
  `,X))!==-1){let C=V.slice(X,w),A=C.endsWith("\r")?C.slice(0,-1):C;if(A!=="")yield A;X=w+1}if(X>0)V=V.slice(X),X=0}V+=Y.decode();let R;while((R=V.indexOf(`
65
- `,X))!==-1){let Q=V.slice(X,R),H=Q.endsWith("\r")?Q.slice(0,-1):Q;if(H!=="")yield H;X=R+1}if(X<V.length){let Q=V.slice(X),H=Q.endsWith("\r")?Q.slice(0,-1):Q;if(H!=="")yield H}}finally{await b.cancel().catch(()=>{})}}async function*sv(G,Z){for await(let b of ZxI(G,Z))if(b.startsWith("data:")){let Y=b.slice(5);if(Y.startsWith(" "))Y=Y.slice(1);if(Y!=="[DONE]")yield Y}}function _z(G,Z){if(G instanceof xK)return new xK(Z,G.status,G.detail,G.context,G.retryAfterMs);if(G instanceof Uw)return new Uw(Z,G.rawMessage,G.code,G.status);return G}function lxI(G){if(!G)return;let Z=G.trim(),b=Number(Z);if(Number.isFinite(b))return Math.max(0,b*1000);let Y=Date.parse(Z);if(!Number.isNaN(Y))return Math.max(0,Y-Date.now());return}function bxI(G){if(!G)return;let Z=G.match(/"retryDelay"\s*:\s*"?([\d.]+)s/i)||G.match(/retry in ([\d.]+)\s*s/i);if(!Z)return;let b=Number(Z[1]);return Number.isFinite(b)?Math.max(0,b*1000):void 0}async function PdI(G,Z){let b=await G(!1);if(b.ok)return b;let Y=await b.clone().text().catch(()=>"");return Z(b.status,Y)?G(!0):b}async function n1(G,Z,b){let Y=await Z.text().catch(()=>""),V=lxI(Z.headers.get("retry-after"))??bxI(Y);return new xK(G,Z.status,Y,b,V)}var xK,Uw;var WA=KW(()=>{xK=class xK extends Error{status;provider;retryAfterMs;detail;context;constructor(G,Z,b,Y,V){super(`${G} request failed (HTTP ${Z})${Y?` ${Y}`:""}: ${b}`);this.name="ProviderHttpError",this.status=Z,this.provider=G,this.retryAfterMs=V,this.detail=b,this.context=Y}};Uw=class Uw extends Error{status;provider;code;rawMessage;constructor(G,Z,b,Y){super(`${G} stream failed${b?` (${b})`:""}: ${Z}`);this.name="ProviderStreamError",this.status=Y??(b==="rate_limit_exceeded"?429:500),this.provider=G,this.code=b,this.rawMessage=Z}}});function l5(G){return WxI(G,new WeakMap)}function WxI(G,Z){if(typeof G==="string")return G.toWellFormed();if(!G||typeof G!=="object")return G;let b=Z.get(G);if(b!==void 0)return b;if(Array.isArray(G)){let V=[];Z.set(G,V);for(let X of G)V.push(WxI(X,Z));return V}let Y={};Z.set(G,Y);for(let[V,X]of Object.entries(G))Y[V.toWellFormed()]=WxI(X,Z);return Y}var khG={};X3(khG,{resolveAntigravityProjectId:()=>$dI,getAntigravityUserAgent:()=>qp,antigravityRequest:()=>phG,antigravityAdapter:()=>_dI});import{randomUUID as V5Z}from"crypto";function X5Z(G){switch(G){case"low":return 4000;case"medium":return 1e4;case"high":return 24000;default:return}}function qp(){let G=process.env.PI_AI_ANTIGRAVITY_VERSION||"2.23.1",Z=process.platform==="win32"?"windows":process.platform,b=process.arch==="x64"?"amd64":process.arch==="ia32"?"386":process.arch;return`antigravity/hub/${G} ${Z}/${b}`}function LhG(G){return G.replace(/^antigravity\//,"")}function AhG(G){let Z=LhG(G.model);if(Z.toLowerCase().includes("claude")){let b=X5Z(G.reasoningEffort);return b===void 0?void 0:{includeThoughts:!0,thinkingBudget:b}}return fdI(Z,G.reasoningEffort)}function F5Z(G){let Z=AhG(G);return Z!==void 0&&(("thinkingLevel"in Z)||Z.thinkingBudget>0)}function uhG(G){if(G.kind==="oauth"&&G.projectId)return G.projectId;return process.env.GOOGLE_CLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT_ID||void 0}async function $dI(G,Z={}){if(G.kind!=="oauth")throw Error("Antigravity provider requires Google/Gemini CLI OAuth credentials. Run `jeo auth login gemini`.");let b=uhG(G);if(b)return b;let Y=HhG.get(G.token);if(Y)return Y;let V=Z.discover??(async(Q)=>{let{discoverGoogleProjectId:H,ANTIGRAVITY_DISCOVERY_METADATA:w}=await Promise.resolve().then(() => (Wr(),mhG));return H(Q,{metadata:{...w},extraHeaders:{"User-Agent":qp()},alwaysOnboard:!0,signal:Z.signal})}),X;try{X=await V(G.token)}catch(Q){throw Error(`Antigravity project auto-discovery failed: ${Q?.message??Q}. Set GOOGLE_CLOUD_PROJECT(_ID) or re-run \`jeo auth login gemini\`.`)}HhG.set(G.token,X);let R=Z.persist??(async(Q)=>{let H=G.provider==="antigravity"?"antigravity":"gemini";await C3((w)=>{let C=w.oauth?.[H];if(!C||typeof C==="string"||C.access!==G.token||C.projectId)return{};return{oauth:{...w.oauth,[H]:{...C,projectId:Q}}}})});try{await R(X)}catch{}return X}function d5Z(G){let Z=[];for(let b of G){if(b.role==="system")continue;let Y=b.role==="assistant"?"model":"user",V=[...b.images?.map((R)=>({inlineData:{mimeType:R.mediaType,data:R.data}}))??[],{text:b.content}],X=Z[Z.length-1];if(X&&X.role===Y)X.parts.push(...V);else Z.push({role:Y,parts:V})}return Z}function Q5Z(G){let Z=G.find((Y)=>Y.role==="user")?.content??`${Date.now()}`,b=0n;for(let Y of new TextEncoder().encode(Z))b=b*131n+BigInt(Y)&(1n<<63n)-1n;return`-${b.toString()}`}function phG(G,Z,b,Y=yhG,V){if(b.kind!=="oauth")throw Error("Antigravity provider requires Google/Gemini CLI OAuth credentials.");let X=V??uhG(b);if(!X)throw Error("Antigravity needs a Google Cloud projectId and auto-discovery has not run yet. Set GOOGLE_CLOUD_PROJECT(_ID) or re-run `jeo auth login gemini`.");let R=LhG(Z.model),Q=Z.systemPrompt??G.find((p)=>p.role==="system")?.content,H={};if(Z.temperature!==void 0)H.temperature=Z.temperature;let w=R.toLowerCase().includes("claude");if(w)H.maxOutputTokens=Z.maxTokens??4000;let C=AhG(Z),A=w&&C!==void 0;if(C!==void 0){if(H.thinkingConfig=C,A&&"thinkingBudget"in C)H.maxOutputTokens=Math.max(Z.maxTokens??4000,C.thinkingBudget+1024)}let y={contents:d5Z(G),sessionId:Q5Z(G)};if(Q)y.systemInstruction={role:"user",parts:[{text:Q}]};if(Object.keys(H).length>0)y.generationConfig=H;if(Z.tools?.length)y.tools=[{functionDeclarations:Z.tools.map((p)=>({name:p.name,description:p.description,parameters:p.parameters}))}],y.toolConfig={functionCallingConfig:{mode:"AUTO"}};let k=JSON.stringify(l5({project:X,model:R,request:y,requestType:"agent",userAgent:"antigravity",requestId:`agent-${V5Z()}`}));return{url:`${Y}/v1internal:streamGenerateContent?alt=sse`,headers:{authorization:`Bearer ${b.token}`,"content-type":"application/json",accept:"text/event-stream","User-Agent":qp(),...A?{"anthropic-beta":"interleaved-thinking-2025-05-14"}:{}},body:k}}function hhG(G){let Z=G.error;if(!Z)return;throw new Uw("Antigravity",Z.message??"unknown error",Z.status,Z.code)}function JhG(G){let Z=G.response?.candidates?.[0]?.finishReason;if(Z&&Z!=="STOP")return`finishReason=${Z}`;return}function whG(G){return G.response?.candidates?.[0]?.content?.parts?.filter((Z)=>!Z.thought).map((Z)=>Z.text??"").join("")??""}function EhG(G){return G.response?.candidates?.[0]?.content?.parts?.filter((Z)=>Z.thought).map((Z)=>Z.text??"").join("")??""}function vhG(G){let Z=G.response?.candidates?.[0]?.content?.parts??[],b=[];for(let Y of Z)if(Y.functionCall&&typeof Y.functionCall.name==="string")b.push({tool:Y.functionCall.name,arguments:Y.functionCall.args??{}});return b}async function ChG(G,Z,b){let Y=await $dI(b,{signal:Z.signal}),V;for(let X of R5Z){let{url:R,headers:Q,body:H}=phG(G,Z,b,X,Y),w=await fetch(R,{method:"POST",headers:Q,body:H,signal:Z.signal});if(w.ok)return w;if(V=w,w.status!==404&&w.status!==503)break}throw await n1("Antigravity",V)}var yhG="https://daily-cloudcode-pa.googleapis.com",c5Z="https://daily-cloudcode-pa.sandbox.googleapis.com",R5Z,HhG,_dI;var KK=KW(()=>{WA();vK();Nr();nh();R5Z=[yhG,c5Z];HhG=new Map;_dI={name:"antigravity",supportsNativeTools:!0,async call(G,Z,b){let Y=await ChG(G,Z,b);if(!Y.body)return"";let V="",X,R,Q=!1,H=[];for await(let C of sv(Y.body)){let A;try{A=JSON.parse(C)}catch{continue}hhG(A);let y=EhG(A);if(y)Z.onReasoning?.(y);let k=whG(A);if(k)V+=k;if(R=JhG(A)??R,A.response?.candidates?.[0]?.finishReason)Q=!0;if(H.push(...vhG(A)),A.response?.usageMetadata)X=A.response.usageMetadata}if(X)Z.onUsage?.({inputTokens:X.promptTokenCount,outputTokens:(X.candidatesTokenCount??0)+(X.thoughtsTokenCount??0)});if(R&&(V||H.length))throw Error(`Antigravity Cloud Code Assist response incomplete (${R}).`);if(!Q&&(V||H.length))throw Error("Antigravity Cloud Code Assist response incomplete (missing finishReason).");let w=r4(H);if(w)return w;if(!V)throw Error(`Antigravity Cloud Code Assist returned no content${R?` (${R})`:""}.`);return V},async*stream(G,Z,b){let Y=await ChG(G,Z,b);if(!Y.body)return;if(F5Z(Z))Z.onReasoningStart?.();let V=!1,X,R,Q=!1,H=[];for await(let C of sv(Y.body,Z.onStreamActivity)){let A;try{A=JSON.parse(C)}catch{continue}hhG(A);let y=EhG(A);if(y)Z.onReasoning?.(y);let k=whG(A);if(k)V=!0,yield k;if(R=JhG(A)??R,A.response?.candidates?.[0]?.finishReason)Q=!0;if(H.push(...vhG(A)),A.response?.usageMetadata)X=A.response.usageMetadata}if(X)Z.onUsage?.({inputTokens:X.promptTokenCount,outputTokens:(X.candidatesTokenCount??0)+(X.thoughtsTokenCount??0)});if(R&&(V||H.length))throw Error(`Antigravity Cloud Code Assist response incomplete (${R}).`);if(!Q&&(V||H.length))throw Error("Antigravity Cloud Code Assist response incomplete (missing finishReason).");let w=r4(H);if(w)V=!0,yield w;if(!V)throw Error(`Antigravity Cloud Code Assist returned no content${R?` (${R})`:""}.`)}}});function m5Z(G,Z,b){let Y=G.toLowerCase(),V=Y.match(/gemini-(\d+)(?:\.(\d+))?/),X=V?Number(V[1]):0,R=V?Number(V[2]??0):0;if(!(X>=3||X===2&&R>=5||/flash-latest|pro-latest/.test(Y)))return;let H=Y.includes("pro")?128:0,w=Z??BhG(Y),C;switch(w){case"low":C=4096;break;case"medium":C=8192;break;case"high":C=16384;break;case"xhigh":C=24575;break;default:C=H}if(typeof b==="number")C=Math.min(C,Math.max(H,b-1024));return C}function BhG(G){return G.includes("-high")?"high":G.includes("-medium")?"medium":G.includes("-low")?"low":G.includes("thinking")?"medium":void 0}function H5Z(G){let Z=G.toLowerCase().match(/gemini-(\d+)(?:\.(\d+))?/);return!!Z&&Number(Z[1])===3}function h5Z(G){switch(G){case"low":return"LOW";case"medium":return"MEDIUM";case"high":case"xhigh":return"HIGH";default:return"MEDIUM"}}function fdI(G,Z,b){if(H5Z(G)){let V=Z??BhG(G.toLowerCase());if(V===void 0)return;return{includeThoughts:!0,thinkingLevel:h5Z(V)}}let Y=m5Z(G,Z,b);return Y===void 0?void 0:{includeThoughts:!0,thinkingBudget:Y}}function OhG(G){let Z=G.model.replace(/^(google|gemini)\//,""),b=fdI(Z,G.reasoningEffort,G.maxTokens);return b!==void 0&&(("thinkingLevel"in b)||b.thinkingBudget>0)}function zhG(G,Z,b){return b&&!!G.toolUse?.length&&!!G.reasoningArtifacts?.some((Y)=>Y.provider==="gemini"&&Y.model===Z&&!!Y.thoughtSignature)}function MhG(G,Z,b=!1){let V=Z.model.replace(/^(google|gemini)\//,"");if(!V||V.startsWith("claude-"))V="gemini-2.0-flash";let X=Z.systemPrompt??G.find((y)=>y.role==="system")?.content,R=fdI(V,Z.reasoningEffort,Z.maxTokens),Q=R!==void 0&&!b,H=G.filter((y)=>y.role!=="system"),w=[];H.forEach((y,k)=>{let p=y.role==="assistant"?"model":"user",O;if(y.role==="assistant"&&zhG(y,Z.model,Q)){let a=y.reasoningArtifacts.find((x)=>x.provider==="gemini"&&x.model===Z.model&&x.thoughtSignature)?.thoughtSignature;O=y.toolUse.map((x,S)=>{let n={functionCall:{name:x.tool,args:x.arguments}};if(S===0&&a)n.thoughtSignature=a;return n})}else if(y.role==="user"&&y.toolResults?.length&&k>0&&H[k-1].role==="assistant"&&zhG(H[k-1],Z.model,Q)){let a=H[k-1].toolUse??[];if(O=y.toolResults.map((x)=>({functionResponse:{name:a.find((S)=>S.id===x.id)?.tool??"tool",response:{output:x.output}}})),y.toolResultExtra)O.push({text:y.toolResultExtra})}else O=[...y.images?.map((a)=>({inlineData:{mimeType:a.mediaType,data:a.data}}))??[],{text:y.content}];let K=w[w.length-1];if(K&&K.role===p)K.parts.push(...O);else w.push({role:p,parts:O})});let C={temperature:Z.temperature??0.2,maxOutputTokens:Z.maxTokens??4000};if(Z.jsonMode&&!Z.tools?.length)C.responseMimeType="application/json";if(R!==void 0){if(C.thinkingConfig=R,"thinkingBudget"in R&&R.thinkingBudget>0)C.maxOutputTokens=Math.min((Z.maxTokens??4000)+R.thinkingBudget,65536)}let A={contents:w,generationConfig:C};if(X)A.systemInstruction={parts:[{text:X}]};if(Z.tools?.length)A.tools=[{functionDeclarations:Z.tools.map((y)=>({name:y.name,description:y.description,parameters:y.parameters}))}],A.toolConfig={functionCallingConfig:{mode:"AUTO"}};return{geminiModel:V,payload:A}}function ghG(G,Z,b,Y,V=!1){let{geminiModel:X,payload:R}=MhG(G,Z,V),Q=b.kind==="oauth"?b.token:void 0,H=b.kind==="api_key"?b.token:void 0,w=`https://generativelanguage.googleapis.com/v1beta/models/${encodeURIComponent(X)}:${Y}`,C=Y==="streamGenerateContent"?"alt=sse":"";if(!Q)w+=`?${C?C+"&":""}key=${encodeURIComponent(H??"")}`;else if(C)w+=`?${C}`;let A=Q?{"content-type":"application/json",authorization:`Bearer ${Q}`}:{"content-type":"application/json"};return{url:w,headers:A,body:JSON.stringify(l5(R))}}function cxI(G){return{"User-Agent":`GeminiCLI/${$V("GEMINI_CLI_VERSION")||"0.49.0"}/${G??"gemini-2.5-flash"} (${process.platform}; ${process.arch}; terminal)`,"Client-Metadata":"ideType=IDE_UNSPECIFIED,platform=PLATFORM_UNSPECIFIED,pluginType=GEMINI"}}function w5Z(G,Z,b,Y,V=!1){let{geminiModel:X,payload:R}=MhG(G,Z,V);return{url:`${J5Z}/v1internal:streamGenerateContent?alt=sse`,headers:{authorization:`Bearer ${b}`,"content-type":"application/json",accept:"text/event-stream",...cxI(X)},body:JSON.stringify(l5({project:Y,model:X,request:R}))}}function NxI(G,Z){return PdI((b)=>{let Y=G(b);return fetch(Y.url,{method:"POST",headers:Y.headers,body:Y.body,signal:Z})},(b,Y)=>b===400&&/thoughtsignature|thought_signature|functioncall|function_call|signature/i.test(Y))}function sdI(G){return G.candidates?.[0]?.content?.parts?.filter((Z)=>!Z.thought).map((Z)=>Z.text??"").join("")??""}function ahG(G){return G.candidates?.[0]?.content?.parts?.filter((Z)=>Z.thought).map((Z)=>Z.text??"").join("")??""}function YxI(G,Z,b){for(let Y of G.candidates?.[0]?.content?.parts??[]){let V=Y.thoughtSignature;if(V&&!b.has(V))b.add(V),Z.onReasoningArtifact?.({provider:"gemini",model:Z.model,thoughtSignature:V})}}function idI(G){let Z=G.candidates?.[0]?.content?.parts??[],b=[];for(let Y of Z)if(Y.functionCall&&typeof Y.functionCall.name==="string")b.push({tool:Y.functionCall.name,arguments:Y.functionCall.args??{}});return b}function VxI(G){let Z=G.promptFeedback?.blockReason;if(Z)return`blockReason=${Z}`;let b=G.candidates?.[0]?.finishReason;if(b==="MAX_TOKENS")return"finishReason=MAX_TOKENS \u2014 output budget exhausted before any text; raise maxTokens or lower the thinking level";if(b&&b!=="STOP")return`finishReason=${b}`;return}function xhG(G,Z){if(!Z)return;throw new Uw(G,Z.message??"unknown error",Z.status,Z.code)}async function*UhG(G,Z,b){let{resolveAntigravityProjectId:Y}=await Promise.resolve().then(() => (KK(),khG)),V=await Y(b,{signal:Z.signal}),X=await NxI((k)=>w5Z(G,Z,b.token,V,k),Z.signal);if(!X.ok)throw await n1("Gemini (Cloud Code Assist)",X);if(!X.body)return;if(OhG(Z))Z.onReasoningStart?.();let R,Q=!1,H,w=!1,C=[],A=new Set;for await(let k of sv(X.body,Z.onStreamActivity)){let p;try{p=JSON.parse(k)}catch{continue}xhG("Gemini (Cloud Code Assist)",p.error);let O=p.response;if(!O)continue;let K=ahG(O);if(K)Z.onReasoning?.(K);YxI(O,Z,A);let a=sdI(O);if(a)Q=!0,yield a;if(H=VxI(O)??H,O.candidates?.[0]?.finishReason)w=!0;if(O.usageMetadata)R=O.usageMetadata;C.push(...idI(O))}if(H&&(Q||C.length))throw Error(`Gemini (Cloud Code Assist) response incomplete (${H.replace(" before any text","")}).`);if(!w&&(Q||C.length))throw Error("Gemini (Cloud Code Assist) response incomplete (missing finishReason).");let y=r4(C);if(y)Q=!0,yield y;if(!Q)throw Error(`Gemini (Cloud Code Assist) returned no content${H?` (${H})`:""}.`);if(R)Z.onUsage?.({inputTokens:R.promptTokenCount,outputTokens:(R.candidatesTokenCount??0)+(R.thoughtsTokenCount??0)})}var J5Z="https://cloudcode-pa.googleapis.com",XxI;var Nr=KW(()=>{WA();vK();XxI={name:"gemini",supportsNativeTools:!0,async call(G,Z,b){if(b.kind==="oauth"){let H="";for await(let w of UhG(G,Z,b))H+=w;return H}let Y=await NxI((H)=>ghG(G,Z,b,"generateContent",H),Z.signal);if(!Y.ok)throw await n1("Gemini",Y);let V=await Y.json();if(YxI(V,Z,new Set),V.usageMetadata)Z.onUsage?.({inputTokens:V.usageMetadata.promptTokenCount,outputTokens:V.usageMetadata.candidatesTokenCount});let X=VxI(V);if(X){let H=!!sdI(V)||idI(V).length>0;throw Error(H?`Gemini response incomplete (${X.replace(" before any text","")}).`:`Gemini returned no content (${X}).`)}let R=r4(idI(V));if(R)return R;return sdI(V)},async*stream(G,Z,b){if(b.kind==="oauth"){yield*UhG(G,Z,b);return}let Y=await NxI((A)=>ghG(G,Z,b,"streamGenerateContent",A),Z.signal);if(!Y.ok)throw await n1("Gemini",Y,"(stream)");if(!Y.body)return;if(OhG(Z))Z.onReasoningStart?.();let V,X,R=!1,Q=!1,H=[],w=new Set;for await(let A of sv(Y.body,Z.onStreamActivity)){let y;try{y=JSON.parse(A)}catch{continue}xhG("Gemini",y.error);let k=ahG(y);if(k)Z.onReasoning?.(k);YxI(y,Z,w);let p=sdI(y);if(p)Q=!0,yield p;if(X=VxI(y)??X,y.candidates?.[0]?.finishReason)R=!0;if(y.usageMetadata)V=y.usageMetadata;H.push(...idI(y))}if(X){if(Q||H.length)throw Error(`Gemini response incomplete (${X.replace(" before any text","")}).`);throw Error(`Gemini returned no content (${X}).`)}if(!R&&(Q||H.length))throw Error("Gemini response incomplete (missing finishReason).");let C=r4(H);if(C)yield C;if(V)Z.onUsage?.({inputTokens:V.promptTokenCount,outputTokens:V.candidatesTokenCount})}}});function E5Z(G,Z={}){return aK(G,{extraHeaders:cxI(),onProgress:Z.onProgress})}function jhG(G=process.env){return G.GEMINI_OAUTH_CLIENT_SECRET||KhG(v5Z)}async function u5Z(G){try{let Z=await fetch("https://www.googleapis.com/oauth2/v1/userinfo?alt=json",{headers:{authorization:`Bearer ${G}`}});if(Z.ok)return(await Z.json()).email}catch{}return}async function FxI(G){return new ThG(G).login()}async function dxI(G){let Z=await fetch(DhG,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:RxI,client_secret:jhG(),refresh_token:G,grant_type:"refresh_token"})});if(!Z.ok)throw Error(`Google token refresh failed (HTTP ${Z.status}): ${await Z.text()}`);let b=await Z.json();return{access:b.access_token,refresh:b.refresh_token||G,expires:Date.now()+b.expires_in*1000-300000}}var KhG=(G)=>atob(G),RxI,v5Z,C5Z="https://accounts.google.com/o/oauth2/v2/auth",DhG="https://oauth2.googleapis.com/token",y5Z=8085,L5Z="/oauth2callback",A5Z,ThG;var QxI=KW(()=>{lr();Wr();Nr();RxI=KhG(["NjgxMjU1ODA5Mzk1","LW9vOGZ0Mm9wcmRy","bnA5ZTNhcWY2YXYz","aG1kaWIxMzVqLmFw","cHMuZ29vZ2xldXNl","cmNvbnRlbnQuY29t"].join("")),v5Z=["R09DU1BYLTR1SGdN","UG0tMW83U2stZ2VW","NkN1NWNsWEZzeGw="].join("");A5Z=["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/userinfo.email","https://www.googleapis.com/auth/userinfo.profile"];ThG=class ThG extends $z{constructor(G){super(G,{preferredPort:y5Z,callbackPath:L5Z})}async generateAuthUrl(G,Z){let b=new URLSearchParams({client_id:RxI,response_type:"code",redirect_uri:Z,scope:A5Z.join(" "),state:G,access_type:"offline",prompt:"consent"});return{url:`${C5Z}?${b.toString()}`,instructions:"Complete the sign-in in your browser."}}async exchangeToken(G,Z,b){let Y=await fetch(DhG,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:RxI,client_secret:jhG(),code:G,grant_type:"authorization_code",redirect_uri:b})});if(!Y.ok)throw Error(`Google token exchange failed (HTTP ${Y.status}): ${await Y.text()}`);let V=await Y.json();if(!V.refresh_token)throw Error("No refresh token received from Google. Try again with prompt=consent.");let X=await u5Z(V.access_token),R=process.env.GOOGLE_CLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT_ID||void 0;if(!R)try{R=await E5Z(V.access_token)}catch{R=void 0}return{access:V.access_token,refresh:V.refresh_token,expires:Date.now()+V.expires_in*1000-300000,email:X,projectId:R}}}});function HxI(G=process.env){return G.ANTIGRAVITY_OAUTH_CLIENT_SECRET||ShG(p5Z)}function qhG(G,Z={}){return aK(G,{metadata:{...br},extraHeaders:{"User-Agent":qp()},alwaysOnboard:!0,onProgress:Z.onProgress})}async function B5Z(G){try{let Z=await fetch("https://www.googleapis.com/oauth2/v1/userinfo?alt=json",{headers:{authorization:`Bearer ${G}`}});if(Z.ok)return(await Z.json()).email}catch{}return}async function hxI(G){return new PhG(G).login()}async function JxI(G){let Z=await fetch(nhG,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:mxI,client_secret:HxI(),refresh_token:G,grant_type:"refresh_token"})});if(!Z.ok)throw Error(`Antigravity token refresh failed (HTTP ${Z.status}): ${await Z.text()}`);let b=await Z.json();return{access:b.access_token,refresh:b.refresh_token||G,expires:Date.now()+b.expires_in*1000-300000}}var ShG=(G)=>atob(G),mxI,p5Z,k5Z="https://accounts.google.com/o/oauth2/v2/auth",nhG="https://oauth2.googleapis.com/token",z5Z=51121,g5Z="/oauth-callback",U5Z,PhG;var wxI=KW(()=>{lr();Wr();KK();mxI=ShG(["MTA3MTAwNjA2MDU5MS10","bWhzc2luMmgyMWxjcmUy","MzV2dG9sb2poNGc0MDNl","cC5hcHBzLmdvb2dsZXVz","ZXJjb250ZW50LmNvbQ=="].join("")),p5Z=["R09DU1BYLUs1OEZX","UjQ4NkxkTEoxbUxC","OHNYQzR6NnFEQWY="].join("");U5Z=["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/userinfo.email","https://www.googleapis.com/auth/userinfo.profile","https://www.googleapis.com/auth/cclog","https://www.googleapis.com/auth/experimentsandconfigs"];PhG=class PhG extends $z{constructor(G){super(G,{preferredPort:z5Z,callbackPath:g5Z})}async generateAuthUrl(G,Z){let b=new URLSearchParams({client_id:mxI,response_type:"code",redirect_uri:Z,scope:U5Z.join(" "),state:G,access_type:"offline",prompt:"consent"});return{url:`${k5Z}?${b.toString()}`,instructions:"Complete the Antigravity sign-in in your browser."}}async exchangeToken(G,Z,b){let Y=await fetch(nhG,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:mxI,client_secret:HxI(),code:G,grant_type:"authorization_code",redirect_uri:b})});if(!Y.ok)throw Error(`Antigravity token exchange failed (HTTP ${Y.status}): ${await Y.text()}`);let V=await Y.json();if(!V.refresh_token)throw Error("No refresh token received from Google. Try again with prompt=consent.");let X=await B5Z(V.access_token),R=process.env.GOOGLE_CLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT_ID||void 0;if(!R)try{R=await qhG(V.access_token)}catch{R=void 0}return{access:V.access_token,refresh:V.refresh_token,expires:Date.now()+V.expires_in*1000-300000,email:X,projectId:R}}}});var Yr;var ExI=KW(()=>{Yr={name:"jeo-code",version:"0.12.17",description:"Clean, highly optimized AI coding agent using spec-first loop",type:"module",main:"src/cli.ts",bin:{jeo:"src/cli.ts"},files:["src","scripts/install.sh","scripts/uninstall.sh","tsconfig.json","CHANGELOG.md","README.md","README.ko.md","README.ja.md","README.zh.md"],engines:{bun:">=1.3.14"},repository:{type:"git",url:"git+https://github.com/akillness/jeo-code.git"},homepage:"https://github.com/akillness/jeo-code#readme",bugs:{url:"https://github.com/akillness/jeo-code/issues"},keywords:["ai","coding-agent","bun","cli","spec-first","jeo"],publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},license:"MIT",scripts:{start:"bun src/cli.ts",typecheck:"tsc -p tsconfig.json --noEmit",build:"bun scripts/build-sandbox-worker.ts && bun build src/cli.ts --compile --keep-names --external chromium-bidi --no-compile-autoload-dotenv --outfile dist/jeo","build:binaries":"bun scripts/ci-release-build-binaries.ts","build:win":"bun scripts/ci-release-build-binaries.ts --targets win32-x64","pack:check":"bun scripts/check-package.ts","publish:npm":"npm publish --access public --registry https://registry.npmjs.org/","changelog:sync":"bun scripts/sync-changelog.ts",test:"bun test","build:hands":"bun scripts/build-sandbox-worker.ts","verify:sandbox":"bun scripts/verify-sandbox-isolation.ts","verify:browser":"bun scripts/verify-browser.ts","verify:discord":"bun scripts/verify-discord-integration.ts","verify:tmux":"bash scripts/tmux-verify.sh","dev:link":"bun scripts/dev-link.ts link","dev:doctor":"bun scripts/dev-link.ts doctor"},dependencies:{zod:"^3.24.1",chalk:"^5.3.0","js-tiktoken":"^1.0.21",typescript:"^5.6.3",playwright:"^1.61.0"},devDependencies:{"@types/bun":"^1.1.14",ws:"^8.21.0"},packageManager:"pnpm@10.33.4+sha512.1c67b3b359b2d408119ba1ed289f34b8fc3c6873412bec6fd264fbdc82489e510fcbecb9ce9d22dae7f3b76269d8441046014bdca53b9979cd7a561ad631b800"}});import*as $hG from"crypto";import*as $6 from"fs";import*as e4 from"os";import*as yxI from"path";function AxI(){return process.env.KIMI_CODE_OAUTH_HOST||process.env.KIMI_OAUTH_HOST||M5Z}function vxI(G,Z,b){return[G,Z,b].filter(Boolean).join(" ").trim()}function D5Z(){let G=e4.platform(),Z=e4.release(),b=e4.arch();if(G==="darwin")return vxI("macOS",Z,b);if(G==="win32")return vxI("Windows",Z,b);return vxI(G==="linux"?"Linux":G,Z,b)}function T5Z(){let G=$V("CONFIG_DIR")||yxI.join(e4.homedir(),".jeo"),Z=yxI.join(G,a5Z),b=CxI.get(Z);if(b)return b;try{let V=$6.readFileSync(Z,"utf-8").trim();if(V)return CxI.set(Z,V),V}catch(V){if(V?.code!=="ENOENT")throw V}let Y=$hG.randomUUID().replace(/-/g,"");return $6.mkdirSync(G,{recursive:!0,mode:448}),$6.writeFileSync(Z,`${Y}
65
+ `,X))!==-1){let Q=V.slice(X,R),H=Q.endsWith("\r")?Q.slice(0,-1):Q;if(H!=="")yield H;X=R+1}if(X<V.length){let Q=V.slice(X),H=Q.endsWith("\r")?Q.slice(0,-1):Q;if(H!=="")yield H}}finally{await b.cancel().catch(()=>{})}}async function*sv(G,Z){for await(let b of ZxI(G,Z))if(b.startsWith("data:")){let Y=b.slice(5);if(Y.startsWith(" "))Y=Y.slice(1);if(Y!=="[DONE]")yield Y}}function _z(G,Z){if(G instanceof xK)return new xK(Z,G.status,G.detail,G.context,G.retryAfterMs);if(G instanceof Uw)return new Uw(Z,G.rawMessage,G.code,G.status);return G}function lxI(G){if(!G)return;let Z=G.trim(),b=Number(Z);if(Number.isFinite(b))return Math.max(0,b*1000);let Y=Date.parse(Z);if(!Number.isNaN(Y))return Math.max(0,Y-Date.now());return}function bxI(G){if(!G)return;let Z=G.match(/"retryDelay"\s*:\s*"?([\d.]+)s/i)||G.match(/retry in ([\d.]+)\s*s/i);if(!Z)return;let b=Number(Z[1]);return Number.isFinite(b)?Math.max(0,b*1000):void 0}async function PdI(G,Z){let b=await G(!1);if(b.ok)return b;let Y=await b.clone().text().catch(()=>"");return Z(b.status,Y)?G(!0):b}async function n1(G,Z,b){let Y=await Z.text().catch(()=>""),V=lxI(Z.headers.get("retry-after"))??bxI(Y);return new xK(G,Z.status,Y,b,V)}var xK,Uw;var WA=KW(()=>{xK=class xK extends Error{status;provider;retryAfterMs;detail;context;constructor(G,Z,b,Y,V){super(`${G} request failed (HTTP ${Z})${Y?` ${Y}`:""}: ${b}`);this.name="ProviderHttpError",this.status=Z,this.provider=G,this.retryAfterMs=V,this.detail=b,this.context=Y}};Uw=class Uw extends Error{status;provider;code;rawMessage;constructor(G,Z,b,Y){super(`${G} stream failed${b?` (${b})`:""}: ${Z}`);this.name="ProviderStreamError",this.status=Y??(b==="rate_limit_exceeded"?429:500),this.provider=G,this.code=b,this.rawMessage=Z}}});function l5(G){return WxI(G,new WeakMap)}function WxI(G,Z){if(typeof G==="string")return G.toWellFormed();if(!G||typeof G!=="object")return G;let b=Z.get(G);if(b!==void 0)return b;if(Array.isArray(G)){let V=[];Z.set(G,V);for(let X of G)V.push(WxI(X,Z));return V}let Y={};Z.set(G,Y);for(let[V,X]of Object.entries(G))Y[V.toWellFormed()]=WxI(X,Z);return Y}var khG={};X3(khG,{resolveAntigravityProjectId:()=>$dI,getAntigravityUserAgent:()=>qp,antigravityRequest:()=>phG,antigravityAdapter:()=>_dI});import{randomUUID as V5Z}from"crypto";function X5Z(G){switch(G){case"low":return 4000;case"medium":return 1e4;case"high":return 24000;default:return}}function qp(){let G=process.env.PI_AI_ANTIGRAVITY_VERSION||"2.23.1",Z=process.platform==="win32"?"windows":process.platform,b=process.arch==="x64"?"amd64":process.arch==="ia32"?"386":process.arch;return`antigravity/hub/${G} ${Z}/${b}`}function LhG(G){return G.replace(/^antigravity\//,"")}function AhG(G){let Z=LhG(G.model);if(Z.toLowerCase().includes("claude")){let b=X5Z(G.reasoningEffort);return b===void 0?void 0:{includeThoughts:!0,thinkingBudget:b}}return fdI(Z,G.reasoningEffort)}function F5Z(G){let Z=AhG(G);return Z!==void 0&&(("thinkingLevel"in Z)||Z.thinkingBudget>0)}function uhG(G){if(G.kind==="oauth"&&G.projectId)return G.projectId;return process.env.GOOGLE_CLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT_ID||void 0}async function $dI(G,Z={}){if(G.kind!=="oauth")throw Error("Antigravity provider requires Google/Gemini CLI OAuth credentials. Run `jeo auth login gemini`.");let b=uhG(G);if(b)return b;let Y=HhG.get(G.token);if(Y)return Y;let V=Z.discover??(async(Q)=>{let{discoverGoogleProjectId:H,ANTIGRAVITY_DISCOVERY_METADATA:w}=await Promise.resolve().then(() => (Wr(),mhG));return H(Q,{metadata:{...w},extraHeaders:{"User-Agent":qp()},alwaysOnboard:!0,signal:Z.signal})}),X;try{X=await V(G.token)}catch(Q){throw Error(`Antigravity project auto-discovery failed: ${Q?.message??Q}. Set GOOGLE_CLOUD_PROJECT(_ID) or re-run \`jeo auth login gemini\`.`)}HhG.set(G.token,X);let R=Z.persist??(async(Q)=>{let H=G.provider==="antigravity"?"antigravity":"gemini";await C3((w)=>{let C=w.oauth?.[H];if(!C||typeof C==="string"||C.access!==G.token||C.projectId)return{};return{oauth:{...w.oauth,[H]:{...C,projectId:Q}}}})});try{await R(X)}catch{}return X}function d5Z(G){let Z=[];for(let b of G){if(b.role==="system")continue;let Y=b.role==="assistant"?"model":"user",V=[...b.images?.map((R)=>({inlineData:{mimeType:R.mediaType,data:R.data}}))??[],{text:b.content}],X=Z[Z.length-1];if(X&&X.role===Y)X.parts.push(...V);else Z.push({role:Y,parts:V})}return Z}function Q5Z(G){let Z=G.find((Y)=>Y.role==="user")?.content??`${Date.now()}`,b=0n;for(let Y of new TextEncoder().encode(Z))b=b*131n+BigInt(Y)&(1n<<63n)-1n;return`-${b.toString()}`}function phG(G,Z,b,Y=yhG,V){if(b.kind!=="oauth")throw Error("Antigravity provider requires Google/Gemini CLI OAuth credentials.");let X=V??uhG(b);if(!X)throw Error("Antigravity needs a Google Cloud projectId and auto-discovery has not run yet. Set GOOGLE_CLOUD_PROJECT(_ID) or re-run `jeo auth login gemini`.");let R=LhG(Z.model),Q=Z.systemPrompt??G.find((p)=>p.role==="system")?.content,H={};if(Z.temperature!==void 0)H.temperature=Z.temperature;let w=R.toLowerCase().includes("claude");if(w)H.maxOutputTokens=Z.maxTokens??4000;let C=AhG(Z),A=w&&C!==void 0;if(C!==void 0){if(H.thinkingConfig=C,A&&"thinkingBudget"in C)H.maxOutputTokens=Math.max(Z.maxTokens??4000,C.thinkingBudget+1024)}let y={contents:d5Z(G),sessionId:Q5Z(G)};if(Q)y.systemInstruction={role:"user",parts:[{text:Q}]};if(Object.keys(H).length>0)y.generationConfig=H;if(Z.tools?.length)y.tools=[{functionDeclarations:Z.tools.map((p)=>({name:p.name,description:p.description,parameters:p.parameters}))}],y.toolConfig={functionCallingConfig:{mode:"AUTO"}};let k=JSON.stringify(l5({project:X,model:R,request:y,requestType:"agent",userAgent:"antigravity",requestId:`agent-${V5Z()}`}));return{url:`${Y}/v1internal:streamGenerateContent?alt=sse`,headers:{authorization:`Bearer ${b.token}`,"content-type":"application/json",accept:"text/event-stream","User-Agent":qp(),...A?{"anthropic-beta":"interleaved-thinking-2025-05-14"}:{}},body:k}}function hhG(G){let Z=G.error;if(!Z)return;throw new Uw("Antigravity",Z.message??"unknown error",Z.status,Z.code)}function JhG(G){let Z=G.response?.candidates?.[0]?.finishReason;if(Z&&Z!=="STOP")return`finishReason=${Z}`;return}function whG(G){return G.response?.candidates?.[0]?.content?.parts?.filter((Z)=>!Z.thought).map((Z)=>Z.text??"").join("")??""}function EhG(G){return G.response?.candidates?.[0]?.content?.parts?.filter((Z)=>Z.thought).map((Z)=>Z.text??"").join("")??""}function vhG(G){let Z=G.response?.candidates?.[0]?.content?.parts??[],b=[];for(let Y of Z)if(Y.functionCall&&typeof Y.functionCall.name==="string")b.push({tool:Y.functionCall.name,arguments:Y.functionCall.args??{}});return b}async function ChG(G,Z,b){let Y=await $dI(b,{signal:Z.signal}),V;for(let X of R5Z){let{url:R,headers:Q,body:H}=phG(G,Z,b,X,Y),w=await fetch(R,{method:"POST",headers:Q,body:H,signal:Z.signal});if(w.ok)return w;if(V=w,w.status!==404&&w.status!==503)break}throw await n1("Antigravity",V)}var yhG="https://daily-cloudcode-pa.googleapis.com",c5Z="https://daily-cloudcode-pa.sandbox.googleapis.com",R5Z,HhG,_dI;var KK=KW(()=>{WA();vK();Nr();nh();R5Z=[yhG,c5Z];HhG=new Map;_dI={name:"antigravity",supportsNativeTools:!0,async call(G,Z,b){let Y=await ChG(G,Z,b);if(!Y.body)return"";let V="",X,R,Q=!1,H=[];for await(let C of sv(Y.body)){let A;try{A=JSON.parse(C)}catch{continue}hhG(A);let y=EhG(A);if(y)Z.onReasoning?.(y);let k=whG(A);if(k)V+=k;if(R=JhG(A)??R,A.response?.candidates?.[0]?.finishReason)Q=!0;if(H.push(...vhG(A)),A.response?.usageMetadata)X=A.response.usageMetadata}if(X)Z.onUsage?.({inputTokens:X.promptTokenCount,outputTokens:(X.candidatesTokenCount??0)+(X.thoughtsTokenCount??0)});if(R&&(V||H.length))throw Error(`Antigravity Cloud Code Assist response incomplete (${R}).`);if(!Q&&(V||H.length))throw Error("Antigravity Cloud Code Assist response incomplete (missing finishReason).");let w=r4(H);if(w)return w;if(!V)throw Error(`Antigravity Cloud Code Assist returned no content${R?` (${R})`:""}.`);return V},async*stream(G,Z,b){let Y=await ChG(G,Z,b);if(!Y.body)return;if(F5Z(Z))Z.onReasoningStart?.();let V=!1,X,R,Q=!1,H=[];for await(let C of sv(Y.body,Z.onStreamActivity)){let A;try{A=JSON.parse(C)}catch{continue}hhG(A);let y=EhG(A);if(y)Z.onReasoning?.(y);let k=whG(A);if(k)V=!0,yield k;if(R=JhG(A)??R,A.response?.candidates?.[0]?.finishReason)Q=!0;if(H.push(...vhG(A)),A.response?.usageMetadata)X=A.response.usageMetadata}if(X)Z.onUsage?.({inputTokens:X.promptTokenCount,outputTokens:(X.candidatesTokenCount??0)+(X.thoughtsTokenCount??0)});if(R&&(V||H.length))throw Error(`Antigravity Cloud Code Assist response incomplete (${R}).`);if(!Q&&(V||H.length))throw Error("Antigravity Cloud Code Assist response incomplete (missing finishReason).");let w=r4(H);if(w)V=!0,yield w;if(!V)throw Error(`Antigravity Cloud Code Assist returned no content${R?` (${R})`:""}.`)}}});function m5Z(G,Z,b){let Y=G.toLowerCase(),V=Y.match(/gemini-(\d+)(?:\.(\d+))?/),X=V?Number(V[1]):0,R=V?Number(V[2]??0):0;if(!(X>=3||X===2&&R>=5||/flash-latest|pro-latest/.test(Y)))return;let H=Y.includes("pro")?128:0,w=Z??BhG(Y),C;switch(w){case"low":C=4096;break;case"medium":C=8192;break;case"high":C=16384;break;case"xhigh":C=24575;break;default:C=H}if(typeof b==="number")C=Math.min(C,Math.max(H,b-1024));return C}function BhG(G){return G.includes("-high")?"high":G.includes("-medium")?"medium":G.includes("-low")?"low":G.includes("thinking")?"medium":void 0}function H5Z(G){let Z=G.toLowerCase().match(/gemini-(\d+)(?:\.(\d+))?/);return!!Z&&Number(Z[1])===3}function h5Z(G){switch(G){case"low":return"LOW";case"medium":return"MEDIUM";case"high":case"xhigh":return"HIGH";default:return"MEDIUM"}}function fdI(G,Z,b){if(H5Z(G)){let V=Z??BhG(G.toLowerCase());if(V===void 0)return;return{includeThoughts:!0,thinkingLevel:h5Z(V)}}let Y=m5Z(G,Z,b);return Y===void 0?void 0:{includeThoughts:!0,thinkingBudget:Y}}function OhG(G){let Z=G.model.replace(/^(google|gemini)\//,""),b=fdI(Z,G.reasoningEffort,G.maxTokens);return b!==void 0&&(("thinkingLevel"in b)||b.thinkingBudget>0)}function zhG(G,Z,b){return b&&!!G.toolUse?.length&&!!G.reasoningArtifacts?.some((Y)=>Y.provider==="gemini"&&Y.model===Z&&!!Y.thoughtSignature)}function MhG(G,Z,b=!1){let V=Z.model.replace(/^(google|gemini)\//,"");if(!V||V.startsWith("claude-"))V="gemini-2.0-flash";let X=Z.systemPrompt??G.find((y)=>y.role==="system")?.content,R=fdI(V,Z.reasoningEffort,Z.maxTokens),Q=R!==void 0&&!b,H=G.filter((y)=>y.role!=="system"),w=[];H.forEach((y,k)=>{let p=y.role==="assistant"?"model":"user",O;if(y.role==="assistant"&&zhG(y,Z.model,Q)){let a=y.reasoningArtifacts.find((x)=>x.provider==="gemini"&&x.model===Z.model&&x.thoughtSignature)?.thoughtSignature;O=y.toolUse.map((x,S)=>{let n={functionCall:{name:x.tool,args:x.arguments}};if(S===0&&a)n.thoughtSignature=a;return n})}else if(y.role==="user"&&y.toolResults?.length&&k>0&&H[k-1].role==="assistant"&&zhG(H[k-1],Z.model,Q)){let a=H[k-1].toolUse??[];if(O=y.toolResults.map((x)=>({functionResponse:{name:a.find((S)=>S.id===x.id)?.tool??"tool",response:{output:x.output}}})),y.toolResultExtra)O.push({text:y.toolResultExtra})}else O=[...y.images?.map((a)=>({inlineData:{mimeType:a.mediaType,data:a.data}}))??[],{text:y.content}];let K=w[w.length-1];if(K&&K.role===p)K.parts.push(...O);else w.push({role:p,parts:O})});let C={temperature:Z.temperature??0.2,maxOutputTokens:Z.maxTokens??4000};if(Z.jsonMode&&!Z.tools?.length)C.responseMimeType="application/json";if(R!==void 0){if(C.thinkingConfig=R,"thinkingBudget"in R&&R.thinkingBudget>0)C.maxOutputTokens=Math.min((Z.maxTokens??4000)+R.thinkingBudget,65536)}let A={contents:w,generationConfig:C};if(X)A.systemInstruction={parts:[{text:X}]};if(Z.tools?.length)A.tools=[{functionDeclarations:Z.tools.map((y)=>({name:y.name,description:y.description,parameters:y.parameters}))}],A.toolConfig={functionCallingConfig:{mode:"AUTO"}};return{geminiModel:V,payload:A}}function ghG(G,Z,b,Y,V=!1){let{geminiModel:X,payload:R}=MhG(G,Z,V),Q=b.kind==="oauth"?b.token:void 0,H=b.kind==="api_key"?b.token:void 0,w=`https://generativelanguage.googleapis.com/v1beta/models/${encodeURIComponent(X)}:${Y}`,C=Y==="streamGenerateContent"?"alt=sse":"";if(!Q)w+=`?${C?C+"&":""}key=${encodeURIComponent(H??"")}`;else if(C)w+=`?${C}`;let A=Q?{"content-type":"application/json",authorization:`Bearer ${Q}`}:{"content-type":"application/json"};return{url:w,headers:A,body:JSON.stringify(l5(R))}}function cxI(G){return{"User-Agent":`GeminiCLI/${$V("GEMINI_CLI_VERSION")||"0.49.0"}/${G??"gemini-2.5-flash"} (${process.platform}; ${process.arch}; terminal)`,"Client-Metadata":"ideType=IDE_UNSPECIFIED,platform=PLATFORM_UNSPECIFIED,pluginType=GEMINI"}}function w5Z(G,Z,b,Y,V=!1){let{geminiModel:X,payload:R}=MhG(G,Z,V);return{url:`${J5Z}/v1internal:streamGenerateContent?alt=sse`,headers:{authorization:`Bearer ${b}`,"content-type":"application/json",accept:"text/event-stream",...cxI(X)},body:JSON.stringify(l5({project:Y,model:X,request:R}))}}function NxI(G,Z){return PdI((b)=>{let Y=G(b);return fetch(Y.url,{method:"POST",headers:Y.headers,body:Y.body,signal:Z})},(b,Y)=>b===400&&/thoughtsignature|thought_signature|functioncall|function_call|signature/i.test(Y))}function sdI(G){return G.candidates?.[0]?.content?.parts?.filter((Z)=>!Z.thought).map((Z)=>Z.text??"").join("")??""}function ahG(G){return G.candidates?.[0]?.content?.parts?.filter((Z)=>Z.thought).map((Z)=>Z.text??"").join("")??""}function YxI(G,Z,b){for(let Y of G.candidates?.[0]?.content?.parts??[]){let V=Y.thoughtSignature;if(V&&!b.has(V))b.add(V),Z.onReasoningArtifact?.({provider:"gemini",model:Z.model,thoughtSignature:V})}}function idI(G){let Z=G.candidates?.[0]?.content?.parts??[],b=[];for(let Y of Z)if(Y.functionCall&&typeof Y.functionCall.name==="string")b.push({tool:Y.functionCall.name,arguments:Y.functionCall.args??{}});return b}function VxI(G){let Z=G.promptFeedback?.blockReason;if(Z)return`blockReason=${Z}`;let b=G.candidates?.[0]?.finishReason;if(b==="MAX_TOKENS")return"finishReason=MAX_TOKENS \u2014 output budget exhausted before any text; raise maxTokens or lower the thinking level";if(b&&b!=="STOP")return`finishReason=${b}`;return}function xhG(G,Z){if(!Z)return;throw new Uw(G,Z.message??"unknown error",Z.status,Z.code)}async function*UhG(G,Z,b){let{resolveAntigravityProjectId:Y}=await Promise.resolve().then(() => (KK(),khG)),V=await Y(b,{signal:Z.signal}),X=await NxI((k)=>w5Z(G,Z,b.token,V,k),Z.signal);if(!X.ok)throw await n1("Gemini (Cloud Code Assist)",X);if(!X.body)return;if(OhG(Z))Z.onReasoningStart?.();let R,Q=!1,H,w=!1,C=[],A=new Set;for await(let k of sv(X.body,Z.onStreamActivity)){let p;try{p=JSON.parse(k)}catch{continue}xhG("Gemini (Cloud Code Assist)",p.error);let O=p.response;if(!O)continue;let K=ahG(O);if(K)Z.onReasoning?.(K);YxI(O,Z,A);let a=sdI(O);if(a)Q=!0,yield a;if(H=VxI(O)??H,O.candidates?.[0]?.finishReason)w=!0;if(O.usageMetadata)R=O.usageMetadata;C.push(...idI(O))}if(H&&(Q||C.length))throw Error(`Gemini (Cloud Code Assist) response incomplete (${H.replace(" before any text","")}).`);if(!w&&(Q||C.length))throw Error("Gemini (Cloud Code Assist) response incomplete (missing finishReason).");let y=r4(C);if(y)Q=!0,yield y;if(!Q)throw Error(`Gemini (Cloud Code Assist) returned no content${H?` (${H})`:""}.`);if(R)Z.onUsage?.({inputTokens:R.promptTokenCount,outputTokens:(R.candidatesTokenCount??0)+(R.thoughtsTokenCount??0)})}var J5Z="https://cloudcode-pa.googleapis.com",XxI;var Nr=KW(()=>{WA();vK();XxI={name:"gemini",supportsNativeTools:!0,async call(G,Z,b){if(b.kind==="oauth"){let H="";for await(let w of UhG(G,Z,b))H+=w;return H}let Y=await NxI((H)=>ghG(G,Z,b,"generateContent",H),Z.signal);if(!Y.ok)throw await n1("Gemini",Y);let V=await Y.json();if(YxI(V,Z,new Set),V.usageMetadata)Z.onUsage?.({inputTokens:V.usageMetadata.promptTokenCount,outputTokens:V.usageMetadata.candidatesTokenCount});let X=VxI(V);if(X){let H=!!sdI(V)||idI(V).length>0;throw Error(H?`Gemini response incomplete (${X.replace(" before any text","")}).`:`Gemini returned no content (${X}).`)}let R=r4(idI(V));if(R)return R;return sdI(V)},async*stream(G,Z,b){if(b.kind==="oauth"){yield*UhG(G,Z,b);return}let Y=await NxI((A)=>ghG(G,Z,b,"streamGenerateContent",A),Z.signal);if(!Y.ok)throw await n1("Gemini",Y,"(stream)");if(!Y.body)return;if(OhG(Z))Z.onReasoningStart?.();let V,X,R=!1,Q=!1,H=[],w=new Set;for await(let A of sv(Y.body,Z.onStreamActivity)){let y;try{y=JSON.parse(A)}catch{continue}xhG("Gemini",y.error);let k=ahG(y);if(k)Z.onReasoning?.(k);YxI(y,Z,w);let p=sdI(y);if(p)Q=!0,yield p;if(X=VxI(y)??X,y.candidates?.[0]?.finishReason)R=!0;if(y.usageMetadata)V=y.usageMetadata;H.push(...idI(y))}if(X){if(Q||H.length)throw Error(`Gemini response incomplete (${X.replace(" before any text","")}).`);throw Error(`Gemini returned no content (${X}).`)}if(!R&&(Q||H.length))throw Error("Gemini response incomplete (missing finishReason).");let C=r4(H);if(C)yield C;if(V)Z.onUsage?.({inputTokens:V.promptTokenCount,outputTokens:V.candidatesTokenCount})}}});function E5Z(G,Z={}){return aK(G,{extraHeaders:cxI(),onProgress:Z.onProgress})}function jhG(G=process.env){return G.GEMINI_OAUTH_CLIENT_SECRET||KhG(v5Z)}async function u5Z(G){try{let Z=await fetch("https://www.googleapis.com/oauth2/v1/userinfo?alt=json",{headers:{authorization:`Bearer ${G}`}});if(Z.ok)return(await Z.json()).email}catch{}return}async function FxI(G){return new ThG(G).login()}async function dxI(G){let Z=await fetch(DhG,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:RxI,client_secret:jhG(),refresh_token:G,grant_type:"refresh_token"})});if(!Z.ok)throw Error(`Google token refresh failed (HTTP ${Z.status}): ${await Z.text()}`);let b=await Z.json();return{access:b.access_token,refresh:b.refresh_token||G,expires:Date.now()+b.expires_in*1000-300000}}var KhG=(G)=>atob(G),RxI,v5Z,C5Z="https://accounts.google.com/o/oauth2/v2/auth",DhG="https://oauth2.googleapis.com/token",y5Z=8085,L5Z="/oauth2callback",A5Z,ThG;var QxI=KW(()=>{lr();Wr();Nr();RxI=KhG(["NjgxMjU1ODA5Mzk1","LW9vOGZ0Mm9wcmRy","bnA5ZTNhcWY2YXYz","aG1kaWIxMzVqLmFw","cHMuZ29vZ2xldXNl","cmNvbnRlbnQuY29t"].join("")),v5Z=["R09DU1BYLTR1SGdN","UG0tMW83U2stZ2VW","NkN1NWNsWEZzeGw="].join("");A5Z=["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/userinfo.email","https://www.googleapis.com/auth/userinfo.profile"];ThG=class ThG extends $z{constructor(G){super(G,{preferredPort:y5Z,callbackPath:L5Z})}async generateAuthUrl(G,Z){let b=new URLSearchParams({client_id:RxI,response_type:"code",redirect_uri:Z,scope:A5Z.join(" "),state:G,access_type:"offline",prompt:"consent"});return{url:`${C5Z}?${b.toString()}`,instructions:"Complete the sign-in in your browser."}}async exchangeToken(G,Z,b){let Y=await fetch(DhG,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:RxI,client_secret:jhG(),code:G,grant_type:"authorization_code",redirect_uri:b})});if(!Y.ok)throw Error(`Google token exchange failed (HTTP ${Y.status}): ${await Y.text()}`);let V=await Y.json();if(!V.refresh_token)throw Error("No refresh token received from Google. Try again with prompt=consent.");let X=await u5Z(V.access_token),R=process.env.GOOGLE_CLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT_ID||void 0;if(!R)try{R=await E5Z(V.access_token)}catch{R=void 0}return{access:V.access_token,refresh:V.refresh_token,expires:Date.now()+V.expires_in*1000-300000,email:X,projectId:R}}}});function HxI(G=process.env){return G.ANTIGRAVITY_OAUTH_CLIENT_SECRET||ShG(p5Z)}function qhG(G,Z={}){return aK(G,{metadata:{...br},extraHeaders:{"User-Agent":qp()},alwaysOnboard:!0,onProgress:Z.onProgress})}async function B5Z(G){try{let Z=await fetch("https://www.googleapis.com/oauth2/v1/userinfo?alt=json",{headers:{authorization:`Bearer ${G}`}});if(Z.ok)return(await Z.json()).email}catch{}return}async function hxI(G){return new PhG(G).login()}async function JxI(G){let Z=await fetch(nhG,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:mxI,client_secret:HxI(),refresh_token:G,grant_type:"refresh_token"})});if(!Z.ok)throw Error(`Antigravity token refresh failed (HTTP ${Z.status}): ${await Z.text()}`);let b=await Z.json();return{access:b.access_token,refresh:b.refresh_token||G,expires:Date.now()+b.expires_in*1000-300000}}var ShG=(G)=>atob(G),mxI,p5Z,k5Z="https://accounts.google.com/o/oauth2/v2/auth",nhG="https://oauth2.googleapis.com/token",z5Z=51121,g5Z="/oauth-callback",U5Z,PhG;var wxI=KW(()=>{lr();Wr();KK();mxI=ShG(["MTA3MTAwNjA2MDU5MS10","bWhzc2luMmgyMWxjcmUy","MzV2dG9sb2poNGc0MDNl","cC5hcHBzLmdvb2dsZXVz","ZXJjb250ZW50LmNvbQ=="].join("")),p5Z=["R09DU1BYLUs1OEZX","UjQ4NkxkTEoxbUxC","OHNYQzR6NnFEQWY="].join("");U5Z=["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/userinfo.email","https://www.googleapis.com/auth/userinfo.profile","https://www.googleapis.com/auth/cclog","https://www.googleapis.com/auth/experimentsandconfigs"];PhG=class PhG extends $z{constructor(G){super(G,{preferredPort:z5Z,callbackPath:g5Z})}async generateAuthUrl(G,Z){let b=new URLSearchParams({client_id:mxI,response_type:"code",redirect_uri:Z,scope:U5Z.join(" "),state:G,access_type:"offline",prompt:"consent"});return{url:`${k5Z}?${b.toString()}`,instructions:"Complete the Antigravity sign-in in your browser."}}async exchangeToken(G,Z,b){let Y=await fetch(nhG,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:mxI,client_secret:HxI(),code:G,grant_type:"authorization_code",redirect_uri:b})});if(!Y.ok)throw Error(`Antigravity token exchange failed (HTTP ${Y.status}): ${await Y.text()}`);let V=await Y.json();if(!V.refresh_token)throw Error("No refresh token received from Google. Try again with prompt=consent.");let X=await B5Z(V.access_token),R=process.env.GOOGLE_CLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT_ID||void 0;if(!R)try{R=await qhG(V.access_token)}catch{R=void 0}return{access:V.access_token,refresh:V.refresh_token,expires:Date.now()+V.expires_in*1000-300000,email:X,projectId:R}}}});var Yr;var ExI=KW(()=>{Yr={name:"jeo-code",version:"0.12.18",description:"Clean, highly optimized AI coding agent using spec-first loop",type:"module",main:"src/cli.ts",bin:{jeo:"src/cli.ts"},files:["src","scripts/install.sh","scripts/uninstall.sh","tsconfig.json","CHANGELOG.md","README.md","README.ko.md","README.ja.md","README.zh.md"],engines:{bun:">=1.3.14"},repository:{type:"git",url:"git+https://github.com/akillness/jeo-code.git"},homepage:"https://github.com/akillness/jeo-code#readme",bugs:{url:"https://github.com/akillness/jeo-code/issues"},keywords:["ai","coding-agent","bun","cli","spec-first","jeo"],publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},license:"MIT",scripts:{start:"bun src/cli.ts",typecheck:"tsc -p tsconfig.json --noEmit",build:"bun scripts/build-sandbox-worker.ts && bun build src/cli.ts --compile --keep-names --external chromium-bidi --no-compile-autoload-dotenv --outfile dist/jeo","build:binaries":"bun scripts/ci-release-build-binaries.ts","build:win":"bun scripts/ci-release-build-binaries.ts --targets win32-x64","pack:check":"bun scripts/check-package.ts","publish:npm":"npm publish --access public --registry https://registry.npmjs.org/","changelog:sync":"bun scripts/sync-changelog.ts",test:"bun test","build:hands":"bun scripts/build-sandbox-worker.ts","verify:sandbox":"bun scripts/verify-sandbox-isolation.ts","verify:browser":"bun scripts/verify-browser.ts","verify:discord":"bun scripts/verify-discord-integration.ts","verify:tmux":"bash scripts/tmux-verify.sh","dev:link":"bun scripts/dev-link.ts link","dev:doctor":"bun scripts/dev-link.ts doctor"},dependencies:{zod:"^3.24.1",chalk:"^5.3.0","js-tiktoken":"^1.0.21",typescript:"^5.6.3",playwright:"^1.61.0"},devDependencies:{"@types/bun":"^1.1.14",ws:"^8.21.0"},packageManager:"pnpm@10.33.4+sha512.1c67b3b359b2d408119ba1ed289f34b8fc3c6873412bec6fd264fbdc82489e510fcbecb9ce9d22dae7f3b76269d8441046014bdca53b9979cd7a561ad631b800"}});import*as $hG from"crypto";import*as $6 from"fs";import*as e4 from"os";import*as yxI from"path";function AxI(){return process.env.KIMI_CODE_OAUTH_HOST||process.env.KIMI_OAUTH_HOST||M5Z}function vxI(G,Z,b){return[G,Z,b].filter(Boolean).join(" ").trim()}function D5Z(){let G=e4.platform(),Z=e4.release(),b=e4.arch();if(G==="darwin")return vxI("macOS",Z,b);if(G==="win32")return vxI("Windows",Z,b);return vxI(G==="linux"?"Linux":G,Z,b)}function T5Z(){let G=$V("CONFIG_DIR")||yxI.join(e4.homedir(),".jeo"),Z=yxI.join(G,a5Z),b=CxI.get(Z);if(b)return b;try{let V=$6.readFileSync(Z,"utf-8").trim();if(V)return CxI.set(Z,V),V}catch(V){if(V?.code!=="ENOENT")throw V}let Y=$hG.randomUUID().replace(/-/g,"");return $6.mkdirSync(G,{recursive:!0,mode:448}),$6.writeFileSync(Z,`${Y}
66
66
  `,{mode:384}),CxI.set(Z,Y),Y}function y3(){return{"User-Agent":`KimiCLI/${Yr.version}`,"X-Msh-Platform":"kimi_cli","X-Msh-Version":Yr.version,"X-Msh-Device-Name":e4.hostname(),"X-Msh-Device-Model":D5Z(),"X-Msh-Os-Version":e4.version(),"X-Msh-Device-Id":T5Z()}}function S5Z(G,Z){return new Promise((b,Y)=>{if(Z?.aborted)return Y(Error("Login cancelled"));let V=()=>{clearTimeout(X),Y(Error("Login cancelled"))},X=setTimeout(()=>{Z?.removeEventListener("abort",V),b()},G);Z?.addEventListener("abort",V,{once:!0})})}async function n5Z(){let G=await fetch(`${AxI()}/api/oauth/device_authorization`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",...y3()},body:new URLSearchParams({client_id:LxI})});if(!G.ok){let Q=await G.text();throw Error(`Kimi device authorization failed: ${G.status} ${Q}`)}let Z=await G.json(),{user_code:b,device_code:Y,verification_uri:V}=Z;if(!b||!Y||!V)throw Error("Kimi device authorization response missing required fields");let X=typeof Z.expires_in==="number"?Z.expires_in*1000:K5Z,R=typeof Z.interval==="number"&&Z.interval>0?Z.interval*1000:x5Z;return{userCode:b,deviceCode:Y,verificationUri:V,verificationUriComplete:Z.verification_uri_complete||V,expiresInMs:X,intervalMs:R}}function _hG(G,Z){if(!G.access_token||typeof G.expires_in!=="number")throw Error("Kimi token response missing required fields");let b=G.refresh_token??Z;if(!b)throw Error("Kimi token response missing refresh token");return{access:G.access_token,refresh:b,expires:Date.now()+G.expires_in*1000-j5Z}}async function q5Z(G,Z,b,Y,V=S5Z){let X=Date.now()+b,R=Math.max(1000,Z);while(Date.now()<X){if(Y?.aborted)throw Error("Login cancelled");let Q=await fetch(`${AxI()}/api/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",...y3()},body:new URLSearchParams({client_id:LxI,device_code:G,grant_type:"urn:ietf:params:oauth:grant-type:device_code"})}),H=await Q.json();if(Q.ok&&H.access_token)return _hG(H);let w=H.error;if(w==="authorization_pending"){await V(R,Y);continue}if(w==="slow_down"){R+=5000;let A=typeof H.interval==="number"?H.interval*1000:void 0;if(A&&A>R)R=A;await V(R,Y);continue}if(w==="expired_token")throw Error("Kimi device authorization expired");if(w==="access_denied")throw Error("Kimi device authorization denied");let C=H.error_description?`: ${H.error_description}`:"";throw Error(`Kimi device flow failed: ${w??Q.status}${C}`)}throw Error("Kimi device flow timed out")}async function uxI(G){let Z=await n5Z();return G.onAuth?.({url:Z.verificationUriComplete,instructions:`Enter code: ${Z.userCode}`}),q5Z(Z.deviceCode,Z.intervalMs,Z.expiresInMs,G.signal)}async function pxI(G){let Z=await fetch(`${AxI()}/api/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",...y3()},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:G,client_id:LxI})});if(!Z.ok){let Y=await Z.json().catch(()=>{return}),V=Y?.error_description?`: ${Y.error_description}`:"";throw Error(`Kimi token refresh failed: ${Z.status}${V}`)}let b=await Z.json();return _hG(b,G)}var LxI="17e5f671-d194-4dfb-9706-5516cb48c098",M5Z="https://auth.kimi.com",a5Z="kimi-device-id",x5Z=5000,K5Z=900000,j5Z=300000,CxI;var Vr=KW(()=>{ExI();CxI=new Map});var L3;var _6=KW(()=>{taI();IxI();QxI();wxI();Vr();taI();IxI();QxI();wxI();Vr();L3={anthropic:{provider:"anthropic",label:"Anthropic (Claude Pro/Max)",login:saI,refresh:iaI,verifiedEndToEnd:!0,note:"Works directly with the bundled Anthropic Messages adapter."},openai:{provider:"openai",label:"OpenAI (ChatGPT/Codex)",login:raI,refresh:eaI,verifiedEndToEnd:!0,note:"ChatGPT/Codex OAuth served via the Codex Responses backend (chatgpt.com/backend-api/codex/responses). An OPENAI_API_KEY, when set, takes precedence and uses api.openai.com."},gemini:{provider:"gemini",label:"Google (Gemini API)",login:FxI,refresh:dxI,verifiedEndToEnd:!1,note:"This OAuth login alone no longer serves google/gemini-* models (the Cloud Code Assist / gemini-cli masquerade was removed) \u2014 set GEMINI_API_KEY to use them. The SAME Gemini models remain reachable OAuth-only via antigravity/* (run 'jeo auth login antigravity'; this gemini login also works as its fallback credential)."},antigravity:{provider:"antigravity",label:"Google Antigravity (Cloud Code Assist agent)",login:hxI,refresh:JxI,verifiedEndToEnd:!0,note:"Antigravity desktop-app OAuth client; serves antigravity/* models (Gemini 3, Claude, GPT-OSS via Cloud Code Assist). The Google Cloud projectId is discovered automatically at login."},kimi:{provider:"kimi",label:"Kimi Code (Moonshot subscription)",login:uxI,refresh:pxI,verifiedEndToEnd:!0,note:"Device-code OAuth (auth.kimi.com); the token is served via the Anthropic-compatible endpoint at api.kimi.com/coding. A KIMI_API_KEY, when set and no OAuth is stored, uses the OpenAI-compatible api.moonshot.ai/v1."}}});var thG={};X3(thG,{rotateOAuthToken:()=>ihG,refreshOAuthToken:()=>shG,classifyRefreshFailure:()=>kxI,OAUTH_REFRESH_SKEW_MS:()=>fhG});function kxI(G){let Z=G?.message??String(G);if(P5Z.test(Z))return"definitive";if(_5Z.test(Z)&&!$5Z.test(Z))return"definitive";return"transient"}async function shG(G){if(!A3(G))return{refreshed:!1,reason:"no_oauth_token",credential:await P0(G)};await tdI(G);try{let Z=await fz(G);if(!Z)return{refreshed:!1,reason:(await u3(G)).oauth?"manual_token_no_refresh":"no_oauth_token",credential:await P0(G)};if(Z.expires&&Z.expires>Date.now()+fhG)return{refreshed:!0,reason:"already_refreshed",credential:{kind:"oauth",provider:G,token:Z.access,projectId:Z.projectId}};if(!Z.refresh)return{refreshed:!1,reason:"no_refresh_token",credential:{kind:"oauth",provider:G,token:Z.access,projectId:Z.projectId}};let b=L3[G],Y;try{Y=await b.refresh(Z.refresh)}catch(X){if(kxI(X)==="definitive"){await cr(G);let Q=(await Cm()).providers[G];return{refreshed:!1,reason:"refresh_token_invalid",credential:Q?{kind:"api_key",provider:G,token:Q}:{kind:"none",provider:G}}}return{refreshed:!1,reason:"refresh_transient_error",credential:{kind:"oauth",provider:G,token:Z.access,projectId:Z.projectId}}}let V={access:Y.access,refresh:Y.refresh||Z.refresh,expires:Y.expires,accountId:Y.accountId??Z.accountId,email:Y.email??Z.email,projectId:Y.projectId??Z.projectId};return await rdI(G,V),{refreshed:!0,reason:"refreshed",credential:{kind:"oauth",provider:G,token:V.access,projectId:V.projectId}}}finally{await odI(G)}}async function ihG(G,Z){let{setOauthToken:b}=await Promise.resolve().then(() => (p3(),ohG));await b(G,Z)}var P5Z,$5Z,_5Z,fhG=60000;var zxI=KW(()=>{p3();_6();nh();P5Z=/invalid_grant|invalid_token|revoked|unauthorized|expired.*refresh|refresh.*expired/i,$5Z=/timeout|network|fetch failed|ECONNREFUSED/i,_5Z=/\b(401|403)\b/});var ohG={};X3(ohG,{snapshotProvider:()=>u3,setOauthToken:()=>BxI,setOauthCredentialNoLock:()=>rdI,setOauthCredential:()=>GQI,setApiKey:()=>IJG,resolveCredential:()=>P0,releaseLock:()=>odI,isOAuthProvider:()=>A3,getStoredOAuth:()=>fz,clearOauthToken:()=>cr,acquireLock:()=>tdI,OAUTH_PROVIDERS:()=>edI,API_KEY_ONLY_PROVIDERS:()=>IQI});import*as f6 from"path";import*as UxI from"os";import*as q1 from"fs/promises";function A3(G){return edI.includes(G)}function rhG(G){let Z=$V("CONFIG_DIR")||f6.join(UxI.homedir(),".jeo");return f6.join(Z,`oauth-${G}.lock`)}async function tdI(G,Z=5000){let b=rhG(G),Y=f6.dirname(b);await q1.mkdir(Y,{recursive:!0,mode:448});let V=Date.now()+Math.max(Z*2,1000);while(!0){try{let X=await q1.open(b,"wx"),R=JSON.stringify({pid:process.pid,createdAt:Date.now()});await X.writeFile(R,"utf-8"),await X.close();return}catch(X){if(X.code!=="EEXIST")throw X;try{let R=await q1.readFile(b,"utf-8"),Q=JSON.parse(R);if(typeof Q.createdAt==="number"&&Q.createdAt+Z<Date.now())await q1.unlink(b).catch(()=>{})}catch{try{if((await q1.stat(b)).mtimeMs+Z<Date.now())await q1.unlink(b).catch(()=>{})}catch{}}}if(Date.now()>=V){await q1.unlink(b).catch(()=>{});let X=await q1.open(b,"wx").catch(()=>null);if(X){await X.writeFile(JSON.stringify({pid:process.pid,createdAt:Date.now(),stolen:!0}),"utf-8"),await X.close();return}throw Error(`OAuth lock for ${G} could not be acquired within ${Math.max(Z*2,1000)}ms (${b})`)}await new Promise((X)=>setTimeout(X,50))}}async function odI(G){let Z=rhG(G);await q1.unlink(Z).catch(()=>{})}function ehG(G){if(!G)return;return typeof G==="string"?G:G.access}async function P0(G){let Z=await Cm(),b=Z.oauth?.[G],Y=$V("GEMINI_CREDS_PATH"),V=!!$V("CONFIG_DIR");if(!b&&G==="gemini"&&(Y||!V))try{let R=$V("GEMINI_CREDS_PATH")||f6.join(UxI.homedir(),".gemini","oauth_creds.json"),Q=await q1.readFile(R,"utf-8"),H=JSON.parse(Q);if(H&&H.access_token){let w;if(H.id_token){let y=H.id_token.split(".");if(y.length>=2)try{let k=y[1].replace(/-/g,"+").replace(/_/g,"/");w=JSON.parse(atob(k)).email}catch{}}let C=typeof H.expiry_date==="number"?H.expiry_date:typeof H.expiry_date==="string"?parseInt(H.expiry_date,10):void 0;if(isNaN(C))C=void 0;let A={access:H.access_token,refresh:H.refresh_token,expires:C,email:w};await GQI("gemini",A),console.error("[NOTICE] Transparently imported Gemini OAuth credentials from ~/.gemini/oauth_creds.json"),b=A}}catch{}if(b){if(typeof b!=="string"&&b.refresh&&b.expires&&b.expires<=Date.now())try{let Q=gxI.get(G);if(!Q)Q=(async()=>{let{refreshOAuthToken:w}=await Promise.resolve().then(() => (zxI(),thG));return w(G)})(),gxI.set(G,Q),Q.finally(()=>{gxI.delete(G)}).catch(()=>{});return(await Q).credential}catch{}let R=ehG(b);if(R)return{kind:"oauth",provider:G,token:R,projectId:typeof b==="object"?b.projectId:void 0}}let X=Z.providers[G];if(X)return{kind:"api_key",provider:G,token:X};return{kind:"none",provider:G}}async function u3(G){let Z=await Cm(),b=Z.oauth?.[G];return{apiKey:Z.providers[G],oauth:ehG(b),oauthExpires:typeof b==="object"?b.expires:void 0,oauthHasRefresh:typeof b==="object"?!!b.refresh:!1,oauthEmail:typeof b==="object"?b.email:void 0}}async function fz(G){let b=(await Cm()).oauth?.[G];return typeof b==="object"?b:void 0}async function BxI(G,Z){await C3((b)=>({oauth:{...b.oauth??{},[G]:Z}}))}async function rdI(G,Z){await C3((b)=>({oauth:{...b.oauth??{},[G]:Z}}))}async function GQI(G,Z){await tdI(G);try{await rdI(G,Z)}finally{await odI(G)}}async function cr(G){if(!(await ZQI()).oauth?.[G])return!1;return await C3((b)=>{let Y={...b.oauth??{}};return delete Y[G],{oauth:Y}}),!0}async function IJG(G,Z){await C3((b)=>({providers:{...b.providers??{},[G]:Z}}))}var edI,IQI,gxI;var p3=KW(()=>{nh();edI=["anthropic","openai","gemini","antigravity","kimi"],IQI=["xai","groq","deepseek","mistral","openrouter","together","cerebras","fireworks","nvidia","alibaba-coding-plan","huggingface","nanogpt","qwen-portal","synthetic","venice","zenmux","qianfan","xiaomi","xiaomi-token-plan-ams","xiaomi-token-plan-cn","xiaomi-token-plan-sgp","minimax-code","minimax-code-cn","zai","minimax","tencent","deepinfra","litellm"];gxI=new Map});var GJG=KW(()=>{p3();_6()});var Xr=KW(()=>{p3();GJG();zxI();_6()});import{createHash as f5Z,randomBytes as s5Z,randomUUID as ZJG}from"crypto";function cJG(G,Z){return(FJG(Z)?G.filter((Y)=>Y!==GvZ):G).join(",")}function XJG(G){return G.startsWith("anthropic/")?G.slice(10):G}function RJG(G,Z,b){return Z.kind==="oauth"&&!b&&!G.startsWith("claude-3-5-haiku")}function ZvZ(){return`user_${s5Z(32).toString("hex")}_account_${ZJG().toLowerCase()}_session_${ZJG().toLowerCase()}`}function lvZ(G){let Z=JSON.stringify(G)??"",b=f5Z("sha256").update(Z).digest("hex").slice(0,5),Y=new Uint8Array(2);crypto.getRandomValues(Y);let V=Array.from(Y,(X)=>X.toString(16).padStart(2,"0")).join("").slice(0,3);return`${r5Z} cc_version=${VJG}.${V}; cc_entrypoint=cli; cch=${b};`}function bvZ(G,Z,b,Y,V){let X=[];if(RJG(Z,b,V)){let R=G?{...Y,system:[G]}:Y;X.push({type:"text",text:lvZ(R)},{type:"text",text:o5Z})}if(G)X.push({type:"text",text:G});if(X.length===0)return;return X[X.length-1]={...X[X.length-1],cache_control:{type:"ephemeral"}},X}function WvZ(G,Z){let b;switch(G){case"low":b=4096;break;case"medium":b=8192;break;case"high":b=16384;break;case"xhigh":b=32768;break;default:return}return Math.min(b,Math.max(1024,Z-1024))}function bQI(G){let Z=/claude-(opus|sonnet|haiku|fable|mythos)-(\d+)(?:-(\d+))?/.exec(G);if(!Z)return;return{kind:Z[1],major:Number(Z[2]),minor:Z[3]!==void 0?Number(Z[3]):0}}function MxI(G,Z,b){if($V("ANTHROPIC_FALLBACK")==="0")return[];if(b)return[];let Y=bQI(G);if(!Y||Y.kind!=="fable")return[];return["claude-opus-4-8"]}function FJG(G){let Z=bQI(G);if(!Z)return!1;if(Z.major>=5)return!0;return Z.kind==="opus"&&Z.major===4&&Z.minor>=7}function NvZ(G){let Z=bQI(G);if(!Z)return"budget";if(Z.major>4||Z.major===4&&Z.minor>=6)return"adaptive";if(Z.major===4&&Z.minor===5&&Z.kind!=="haiku")return"budget-effort";return"budget"}function lJG(G){switch(G){case"low":return"low";case"medium":return"medium";case"high":return"high";default:return"medium"}}function bJG(G,Z,b){return b&&!!G.toolUse?.length&&!!G.reasoningArtifacts?.some((Y)=>Y.provider==="anthropic"&&Y.model===Z&&(!!Y.signature||!!Y.redacted))}function YvZ(G,Z,b){let Y=G.filter((X)=>X.role!=="system"),V=(X)=>({role:X.role,content:X.images?.length?[...X.images.map((R)=>({type:"image",source:{type:"base64",media_type:R.mediaType,data:R.data}})),...X.content?[{type:"text",text:X.content}]:[]]:X.content});return Y.map((X,R)=>{if(X.role==="assistant"&&bJG(X,Z,b)){let Q=[];for(let H of X.reasoningArtifacts){if(H.provider!=="anthropic"||H.model!==Z)continue;if(H.signature)Q.push({type:"thinking",thinking:H.text??"",signature:H.signature});else if(H.redacted)Q.push({type:"redacted_thinking",data:H.redacted})}for(let H of X.toolUse)Q.push({type:"tool_use",id:H.id,name:H.tool,input:H.arguments});return{role:"assistant",content:Q}}if(X.role==="user"&&X.toolResults?.length&&R>0&&Y[R-1].role==="assistant"&&bJG(Y[R-1],Z,b)){let Q=X.toolResults.map((H)=>({type:"tool_result",tool_use_id:H.id,content:H.output,is_error:H.isError}));for(let H of X.images??[])Q.push({type:"image",source:{type:"base64",media_type:H.mediaType,data:H.data}});if(X.toolResultExtra)Q.push({type:"text",text:X.toolResultExtra});return{role:"user",content:Q}}return V(X)})}function VvZ(G,Z,b,Y,V={kind:"none",provider:"anthropic"},X=!1,R=!1,Q=!1){let H=XJG(Z.model),w=Z.systemPrompt??G.find((f)=>f.role==="system")?.content,C=32000,A=Z.maxTokens??4000,y=b?A:Math.min(A,32000),k=Z.reasoningEffort,p=k!==void 0,O=p?NvZ(H):"budget",K=p&&O!=="adaptive"?WvZ(k,y):void 0,a=YvZ(G,Z.model,p&&!X),x=a[a.length-1];if(x){if(typeof x.content==="string"){if(x.content)x.content=[{type:"text",text:x.content,cache_control:{type:"ephemeral"}}]}else if(x.content.length>0){let f=x.content[x.content.length-1];x.content[x.content.length-1]={...f,cache_control:{type:"ephemeral"}}}}let S={model:H,messages:a,max_tokens:K!==void 0?Math.max(y,K+1024):y};if(RJG(H,V,Z.baseUrl))S.metadata={user_id:ZvZ()};if(k!==void 0){if(O==="adaptive"){if(S.thinking=FJG(H)?{type:"adaptive",display:"summarized"}:{type:"adaptive"},!Q)S.output_config={effort:lJG(k)}}else if(S.thinking={type:"enabled",budget_tokens:K,display:"summarized"},O==="budget-effort"&&!Q)S.output_config={effort:lJG(k)}}else if(Y&&Z.temperature!==void 0){let f=bQI(H);if(!(f&&(f.kind==="opus"||f.kind==="sonnet")&&(f.major>5||f.major===5&&f.minor>=5)))S.temperature=Z.temperature}if(Z.tools?.length)S.tools=Z.tools.map((f)=>({name:f.name,description:f.description,input_schema:f.parameters})),S.tool_choice={type:"auto"};if(b)S.stream=!0;if(!R){let f=MxI(H,V,Z.baseUrl);if(f.length)S.fallbacks=f.map((P)=>({model:P}))}let n=bvZ(w,H,V,S,Z.baseUrl);if(n)S.system=n;return JSON.stringify(l5(S))}function cvZ(G,Z,b,Y,V,X=!1,R=!1,Q=!1){return{url:Z.baseUrl?`${Z.baseUrl.replace(/\/$/,"")}/v1/messages`:i5Z,headers:{...JvZ(b,Y,XJG(Z.model),Z.baseUrl,R),...Z.extraHeaders},body:VvZ(G,Z,Y,V,b,X,R,Q)}}function XvZ(G,Z){return G===400&&Z.includes(t5Z)}function RvZ(G,Z){return G===400&&/thinking|signature|redacted_thinking/i.test(Z)}function FvZ(G,Z){return G===400&&/fallback/i.test(Z)}function dvZ(G,Z){return G===400&&/effort/i.test(Z)&&/output_config|not support/i.test(Z)}function QvZ(G){let Z=[];for(let[b,Y]of G){let V=b.toLowerCase();if(V==="retry-after"||V==="retry-after-ms"||V.startsWith("anthropic-ratelimit-"))Z.push(`${V}=${Y}`)}return Z.length>0?` Anthropic rate-limit evidence: ${Z.sort().join(", ")}`:""}async function WJG(G,Z,b,Y){let V=!0,X=!1,R=!1,Q=!1;for(let H=1;H<=5;H++){let{url:w,headers:C,body:A}=cvZ(G,Z,b,Y,V,X,R,Q),y=await fetch(w,{method:"POST",headers:C,body:A,signal:Z.signal});if(y.ok)return y;let k=await y.text().catch(()=>"");if(XvZ(y.status,k)&&V){V=!1;continue}if(RvZ(y.status,k)&&!X){X=!0;continue}if(FvZ(y.status,k)&&!R){R=!0;continue}if(dvZ(y.status,k)&&!Q){Q=!0;continue}let p=y.status===429?`${k}${QvZ(y.headers)}`:k;throw new xK("Anthropic",y.status,p,Y?"(stream)":void 0,lxI(y.headers.get("retry-after"))??bxI(k))}throw Error("Anthropic request failed: maximum retries reached without response")}function NJG(G){return(G.input_tokens??0)+(G.cache_read_input_tokens??0)+(G.cache_creation_input_tokens??0)}function lQI(G,Z){let b=G==="max_tokens"?" \u2014 output budget exhausted before any text; raise maxTokens or lower the thinking level":"",Y=G?Z?`stop_reason=${G}, category=${Z}`:`stop_reason=${G}`:void 0;return Error(`Anthropic returned no content${Y?` (${Y})`:""}${b}.`)}function YJG(G,Z){if(G&&G!=="end_turn"&&G!=="tool_use"&&G!=="stop_sequence"){let b=G==="max_tokens"?" \u2014 output budget exhausted; raise maxTokens or lower the thinking level":"";throw Error(`Anthropic response incomplete (stop_reason=${G}${Z?`, category=${Z}`:""})${b}.`)}}function mvZ(G){switch(G.toLowerCase()){case"darwin":return"MacOS";case"windows":case"win32":return"Windows";case"linux":return"Linux";case"freebsd":return"FreeBSD";default:return`Other::${G.toLowerCase()}`}}function HvZ(G){switch(G.toLowerCase()){case"amd64":case"x64":return"x64";case"arm64":case"aarch64":return"arm64";case"386":case"x86":case"ia32":return"x86";default:return`other::${G.toLowerCase()}`}}function hvZ(G,Z){return{accept:G?"text/event-stream":"application/json","anthropic-beta":cJG(IvZ,Z),"anthropic-dangerous-direct-browser-access":"true","user-agent":`claude-cli/${VJG} (external, cli)`,"x-app":"cli","x-stainless-arch":HvZ(process.arch),"x-stainless-lang":"js","x-stainless-os":mvZ(process.platform),"x-stainless-package-version":"0.74.0","x-stainless-retry-count":"0","x-stainless-runtime":"node","x-stainless-runtime-version":"v24.3.0","x-stainless-timeout":"600"}}function JvZ(G,Z,b,Y,V=!1){if(G.kind==="oauth"){if(Y)return{accept:Z?"text/event-stream":"application/json","content-type":"application/json",authorization:`Bearer ${G.token}`,"anthropic-version":"2023-06-01"};let X={"content-type":"application/json",authorization:`Bearer ${G.token}`,"anthropic-version":"2023-06-01",...hvZ(Z,b)};if(!V&&MxI(b,G,Y).length){let R=X["anthropic-beta"]?X["anthropic-beta"].split(","):[];if(!R.includes(OxI))R.push(OxI),X["anthropic-beta"]=R.join(",")}return X}if(G.kind==="api_key"){let X=e5Z.slice();if(!V&&MxI(b,G,Y).length)X.push(OxI);return{accept:Z?"text/event-stream":"application/json","content-type":"application/json","x-api-key":G.token,"anthropic-version":"2023-06-01","anthropic-beta":cJG(X,b)}}throw Error("anthropic adapter requires a credential")}var i5Z="https://api.anthropic.com/v1/messages",t5Z="`temperature` is deprecated for this model.",VJG="2.1.289",o5Z="You are a Claude agent, built on Anthropic's Claude Agent SDK.",r5Z="x-anthropic-billing-header:",e5Z,IvZ,GvZ="interleaved-thinking-2025-05-14",OxI="server-side-fallback-2026-06-01",Pp;var Rr=KW(()=>{WA();vK();e5Z=["interleaved-thinking-2025-05-14","context-management-2025-06-27","prompt-caching-scope-2026-01-05"],IvZ=["claude-code-20250219","oauth-2025-04-20","interleaved-thinking-2025-05-14","context-management-2025-06-27","prompt-caching-scope-2026-01-05"];Pp={name:"anthropic",supportsNativeTools:!0,async call(G,Z,b){let V=await(await WJG(G,Z,b,!1)).json();if(V.usage)Z.onUsage?.({inputTokens:NJG(V.usage),outputTokens:V.usage.output_tokens});if(!V.content.some((H)=>H.type==="text"&&H.text||H.type==="tool_use"&&H.name)&&V.stop_reason&&!["end_turn","tool_use","stop_sequence"].includes(V.stop_reason))throw lQI(V.stop_reason,V.stop_details?.category);YJG(V.stop_reason,V.stop_details?.category);let X=V.model??Z.model;for(let H of V.content)if(H.type==="thinking"&&(H.thinking||H.signature))Z.onReasoningArtifact?.({provider:"anthropic",model:X,text:H.thinking||void 0,signature:H.signature});else if(H.type==="redacted_thinking"&&H.data)Z.onReasoningArtifact?.({provider:"anthropic",model:X,redacted:H.data});let R=r4(V.content.filter((H)=>H.type==="tool_use"&&typeof H.name==="string").map((H)=>({tool:H.name,arguments:H.input??{}})));if(R)return R;let Q=V.content.find((H)=>H.type==="text")?.text??"";if(!Q)throw lQI(V.stop_reason,V.stop_details?.category);return Q},async*stream(G,Z,b){let Y=await WJG(G,Z,b,!0);if(!Y.body)return;let V,X=!1,R,Q,H=!1,w=Z.model,C=new Map,A=new Map;for await(let k of sv(Y.body,Z.onStreamActivity)){let p;try{p=JSON.parse(k)}catch{continue}if(p.type==="error"){let O=p.error?.type,K={invalid_request_error:400,authentication_error:401,permission_error:403,not_found_error:404,request_too_large:413,rate_limit_error:429,api_error:500,overloaded_error:529};throw new Uw("Anthropic",p.error?.message??"unknown error",O,O?K[O]:void 0)}if(p.type==="content_block_start"&&p.content_block?.type==="tool_use"&&typeof p.index==="number")C.set(p.index,{name:p.content_block.name??"",args:""});else if(p.type==="content_block_start"&&p.content_block?.type==="fallback"){if(C.clear(),A.clear(),p.content_block.to?.model)w=p.content_block.to.model}else if(p.type==="content_block_start"&&p.content_block?.type==="thinking"&&typeof p.index==="number")A.set(p.index,{text:""}),Z.onReasoningStart?.();else if(p.type==="content_block_start"&&p.content_block?.type==="redacted_thinking"&&p.content_block.data)Z.onReasoningStart?.(),Z.onReasoningArtifact?.({provider:"anthropic",model:w,redacted:p.content_block.data});else if(p.type==="content_block_delta"&&p.delta?.type==="input_json_delta"&&typeof p.index==="number"){let O=C.get(p.index);if(O)O.args+=p.delta.partial_json??""}else if(p.type==="content_block_delta"&&p.delta?.type==="text_delta"&&p.delta.text)X=!0,yield p.delta.text;else if(p.type==="content_block_delta"&&p.delta?.type==="thinking_delta"&&p.delta.thinking){if(Z.onReasoning?.(p.delta.thinking),typeof p.index==="number"){let O=A.get(p.index)??{text:""};O.text+=p.delta.thinking,A.set(p.index,O)}}else if(p.type==="content_block_delta"&&p.delta?.type==="signature_delta"&&p.delta.signature&&typeof p.index==="number"){let O=A.get(p.index)??{text:""};O.signature=(O.signature??"")+p.delta.signature,A.set(p.index,O)}else if(p.type==="message_start"&&p.message){if(p.message.model)w=p.message.model;if(p.message.stop_reason)R=p.message.stop_reason;if(p.message.stop_details?.category)Q=p.message.stop_details.category;if(p.message.usage)V=NJG(p.message.usage)}else if(p.type==="message_stop")H=!0;else if(p.type==="message_delta"){if(p.delta?.stop_reason)R=p.delta.stop_reason,H=!0;if(p.delta?.stop_details?.category)Q=p.delta.stop_details.category;if(p.usage)Z.onUsage?.({inputTokens:V,outputTokens:p.usage.output_tokens})}}if(!X&&!C.size&&R&&!["end_turn","tool_use","stop_sequence"].includes(R))throw lQI(R,Q);if(!H&&(X||C.size))throw Error("Anthropic response incomplete (missing terminal event).");YJG(R,Q);for(let k of A.values())if(k.text||k.signature)X=!0,Z.onReasoningArtifact?.({provider:"anthropic",model:w,text:k.text||void 0,signature:k.signature});let y=EK(C);if(y)X=!0,yield y;if(!X)throw lQI(R,Q)}}});import axI from"os";function dJG(){return`${mJG}/${Yr.version} (${axI.platform()} ${axI.release()}; ${axI.arch()})`}function s6(G){let Z=G.split(".");if(Z.length<2)return;try{let Y=JSON.parse(Buffer.from(Z[1],"base64url").toString("utf-8"))["https://api.openai.com/auth"]?.chatgpt_account_id;return typeof Y==="string"?Y:void 0}catch{return}}function QJG(G,Z){return!!G.toolUse?.length&&!!G.reasoningArtifacts?.some((b)=>b.provider==="openai"&&b.model===Z&&!!b.itemId&&!!b.encrypted)}function vvZ(G,Z,b=!1){let Y=G.filter((R)=>R.role!=="system"),V=[],X=(R)=>({role:R.role,content:[{type:R.role==="assistant"?"output_text":"input_text",text:R.content},...R.role!=="assistant"&&R.images?.length?R.images.map((Q)=>({type:"input_image",image_url:`data:${Q.mediaType};base64,${Q.data}`})):[]]});return Y.forEach((R,Q)=>{if(!b&&R.role==="assistant"&&QJG(R,Z)){for(let H of R.reasoningArtifacts)if(H.provider==="openai"&&H.model===Z&&H.itemId&&H.encrypted)V.push({type:"reasoning",id:H.itemId,encrypted_content:H.encrypted,summary:[]});for(let H of R.toolUse)V.push({type:"function_call",call_id:H.id,name:H.tool,arguments:JSON.stringify(H.arguments)});return}if(!b&&R.role==="user"&&R.toolResults?.length&&Q>0&&Y[Q-1].role==="assistant"&&QJG(Y[Q-1],Z)){for(let H of R.toolResults)V.push({type:"function_call_output",call_id:H.id,output:H.output});if(R.toolResultExtra)V.push({role:"user",content:[{type:"input_text",text:R.toolResultExtra}]});if(R.images?.length)V.push({role:"user",content:R.images.map((H)=>({type:"input_image",image_url:`data:${H.mediaType};base64,${H.data}`}))});return}V.push(X(R))}),V}function CvZ(G,Z,b,Y=!1){let V=Z.model.startsWith("openai/")?Z.model.slice(7):Z.model,X=b.kind==="none"?"":b.token,R=Z.systemPrompt??G.find((y)=>y.role==="system")?.content,Q=vvZ(G,Z.model,Y),H=yvZ(Z.sessionKey),w={model:V,instructions:R??"You are a helpful coding assistant.",input:Q,stream:!0,store:!1,...H?{prompt_cache_key:H}:{}};if(Z.tools?.length)w.tools=Z.tools.map((y)=>({type:"function",name:y.name,description:y.description,parameters:y.parameters,strict:!1})),w.tool_choice="auto";if(Z.reasoningEffort&&EvZ.has(Z.reasoningEffort))w.reasoning={effort:Z.reasoningEffort,summary:"auto"};if(b.kind==="api_key"){if(Z.maxTokens)w.max_output_tokens=Z.maxTokens;let y=(Z.baseUrl??"https://api.openai.com/v1").replace(/\/$/,"");return w.include=["reasoning.encrypted_content"],{url:`${y}/responses`,headers:{"content-type":"application/json",authorization:`Bearer ${X}`,accept:"text/event-stream","user-agent":dJG()},body:JSON.stringify(l5(w))}}let C=s6(X),A={"content-type":"application/json",authorization:`Bearer ${X}`,"OpenAI-Beta":"responses=experimental",originator:mJG,"user-agent":dJG(),accept:"text/event-stream"};if(C)A["chatgpt-account-id"]=C;if(H)A.session_id=H,A.conversation_id=H,A["x-client-request-id"]=H;return{url:wvZ,headers:A,body:JSON.stringify(l5(w))}}function yvZ(G){if(!G||G.length===0)return;let Z=G.toWellFormed();if(Z.length<=64)return Z;return`pc_${Bun.hash(Z).toString(36)}`}function HJG(G){let Z;try{Z=JSON.parse(G)}catch{return{}}if(Z.type==="response.output_item.added"&&Z.item?.type==="function_call")return{toolCallName:Z.item.name,toolCallIndex:Z.output_index};if(Z.type==="response.output_item.done"&&Z.item?.type==="reasoning"&&Z.item.id&&Z.item.encrypted_content)return{reasoningItem:{id:Z.item.id,encrypted:Z.item.encrypted_content}};if(Z.type==="response.function_call_arguments.delta"&&typeof Z.delta==="string")return{toolCallArgsDelta:Z.delta,toolCallIndex:Z.output_index};if(Z.type==="response.output_text.delta"&&typeof Z.delta==="string")return{delta:Z.delta};if(typeof Z.delta==="string"&&/^response\.reasoning[a-z_]*\.delta$/.test(Z.type??""))return{reasoningDelta:Z.delta};if(Z.type==="response.completed"||Z.type==="response.incomplete")return{...Z.response?.usage?{usage:{inputTokens:Z.response.usage.input_tokens,outputTokens:Z.response.usage.output_tokens}}:{},...Z.type==="response.completed"?{completed:!0}:{},...Z.type==="response.incomplete"?{incompleteReason:Z.response?.incomplete_details?.reason??"incomplete"}:{}};if(Z.type==="response.failed"||Z.type==="error"){let b=Z.response?.error??Z.error;return{error:b?.message??"Codex response failed",errorCode:b?.code}}return{}}function hJG(G,Z){if(Z.toolCallName!==void 0){let b=Z.toolCallIndex??0,Y=G.get(b)??{name:"",args:""};Y.name=Z.toolCallName,G.set(b,Y)}if(Z.toolCallArgsDelta){let b=Z.toolCallIndex??0,Y=G.get(b)??{name:"",args:""};Y.args+=Z.toolCallArgsDelta,G.set(b,Y)}}function JJG(G){let Z=G==="max_output_tokens"?" \u2014 output budget exhausted before any text (often reasoning tokens); raise maxTokens or lower reasoning effort":"";return Error(`OpenAI Codex returned no content${G?` (${G})`:""}${Z}.`)}function wJG(G,Z,b){return PdI((Y)=>{let{url:V,headers:X,body:R}=CvZ(G,Z,b,Y);return fetch(V,{method:"POST",headers:X,body:R,signal:Z.signal})},(Y,V)=>Y===400&&/reasoning|encrypted_content/i.test(V))}async function xxI(G,Z,b){let Y=await wJG(G,Z,b);if(!Y.ok)throw await n1("OpenAI",Y);if(!Y.body)return"";let V="",X,R=!1,Q=new Map;for await(let w of sv(Y.body)){let C=HJG(w);if(C.delta)V+=C.delta;if(C.reasoningDelta)Z.onReasoning?.(C.reasoningDelta);if(C.reasoningItem)Z.onReasoningArtifact?.({provider:"openai",model:Z.model,itemId:C.reasoningItem.id,encrypted:C.reasoningItem.encrypted});if(hJG(Q,C),C.usage)Z.onUsage?.(C.usage);if(C.incompleteReason)X=C.incompleteReason;if(C.completed)R=!0;if(C.error)throw new Uw("OpenAI Codex",C.error,C.errorCode)}if(X)throw new k3(X);if(!R&&(V||Q.size))throw new k3("missing_terminal_event");let H=EK(Q);if(H)return H;if(!V)throw JJG(X);return V}async function*KxI(G,Z,b){let Y=await wJG(G,Z,b);if(!Y.ok)throw await n1("OpenAI",Y,"(stream)");if(!Y.body)return;let V=!1,X,R=!1,Q=new Map;for await(let w of sv(Y.body,Z.onStreamActivity)){let C=HJG(w);if(C.reasoningDelta)Z.onReasoning?.(C.reasoningDelta);if(C.reasoningItem)Z.onReasoningArtifact?.({provider:"openai",model:Z.model,itemId:C.reasoningItem.id,encrypted:C.reasoningItem.encrypted});if(C.delta)V=!0,yield C.delta;if(hJG(Q,C),C.usage)Z.onUsage?.(C.usage);if(C.incompleteReason)X=C.incompleteReason;if(C.completed)R=!0;if(C.error)throw new Uw("OpenAI Codex",C.error,C.errorCode)}if(X)throw new k3(X);if(!R&&(V||Q.size))throw new k3("missing_terminal_event");let H=EK(Q);if(H)V=!0,yield H;if(!V)throw JJG(X)}var wvZ="https://chatgpt.com/backend-api/codex/responses",EvZ,mJG="codex_cli_rs",k3;var WQI=KW(()=>{WA();vK();ExI();EvZ=new Set(["low","medium","high"]);k3=class k3 extends Error{constructor(G){let Z=G==="max_output_tokens"?" \u2014 output budget exhausted; raise maxTokens or lower reasoning effort":"";super(`OpenAI Codex response incomplete (finish_reason=${G})${Z}.`);this.name="ResponsesIncompleteError"}}});function EJG(G,Z){let b=Math.min(G.length,Z.length-1);for(let Y=b;Y>0;Y--){let V=!0,X=G.length-Y;for(let R=0;R<Y;R++)if(G.charCodeAt(X+R)!==Z.charCodeAt(R)){V=!1;break}if(V)return Y}return 0}function NQI(G){let Z=!1,b="";return{push:(X)=>{let R=b+X;b="";let Q="";for(;;)if(!Z){let H=R.indexOf("<think>");if(H===-1){let w=EJG(R,"<think>");Q+=R.slice(0,R.length-w),b=R.slice(R.length-w);break}Q+=R.slice(0,H),R=R.slice(H+7),Z=!0}else{let H=R.indexOf("</think>");if(H===-1){let C=EJG(R,"</think>"),A=R.slice(0,R.length-C);if(A)G?.(A);b=R.slice(R.length-C);break}let w=R.slice(0,H);if(w)G?.(w);R=R.slice(H+8),Z=!1}return Q},flush:()=>{let X=b;if(b="",Z){if(X)G?.(X);return""}return X}}}function jxI(G){let Z=G;Z=Z.replace(/<think\b[^>]*>[\s\S]*?<\/think>/gi,"");let b=Z.toLowerCase().lastIndexOf("</think>");if(b!==-1)Z=Z.slice(b+8);return Z=Z.replace(/<\/?(?:think|tool_call|tool_response|tool_result|parameter|invoke|function|function_call|antml:[a-z_]+)\b[^>]*>/gi,""),Z=Z.replace(/<\|[^|>]*\|>/g,""),Z.trim()}function DxI(G){let Z=G.startsWith("openai/")?G.slice(7):G,b=Z.match(/^gpt-(\d+)/);return/^o\d/.test(Z)||(b?Number(b[1])>=5:!1)}function LvZ(G,Z,b){switch(Z){case"openrouter":G.reasoning={effort:b};break;case"qwen":G.enable_thinking=!0;break;case"zai":G.thinking={type:"enabled"};break}}function vJG(G,Z,b,Y){let V=Z.model.startsWith("openai/")?Z.model.slice(7):Z.model,X=Z.systemPrompt??G.find((y)=>y.role==="system")?.content,R=[];if(X)R.push({role:"system",content:X});for(let y of G){if(y.role==="system")continue;let k=y.images?.length?[...y.content?[{type:"text",text:y.content}]:[],...y.images.map((p)=>({type:"image_url",image_url:{url:`data:${p.mediaType};base64,${p.data}`}}))]:y.content;R.push({role:y.role,content:k})}let Q=DxI(V),w=Boolean(Z.baseUrl||process.env.OPENAI_BASE_URL&&!/\bapi\.openai\.com\b/.test(process.env.OPENAI_BASE_URL))?16000:4000,C={model:V,messages:R};if(Q){if(C.max_completion_tokens=Z.maxTokens??w,Z.reasoningEffort)C.reasoning_effort=Z.reasoningEffort}else C.temperature=Z.temperature??0.2,C.max_tokens=Z.maxTokens??w;if(Z.reasoningEffort&&!Q)LvZ(C,Z.reasoningFormat,Z.reasoningEffort);if(Y)C.stream=!0,C.stream_options={include_usage:!0};if(Z.tools?.length)C.tools=Z.tools.map((y)=>({type:"function",function:{name:y.name,description:y.description,parameters:y.parameters}})),C.tool_choice="auto";if(Z.jsonMode&&!Z.tools?.length)C.response_format={type:"json_object"};return{url:`${(Z.baseUrl??process.env.OPENAI_BASE_URL??"https://api.openai.com/v1").replace(/\/$/,"")}/chat/completions`,headers:{"content-type":"application/json",Authorization:`Bearer ${pvZ(b)}`},body:JSON.stringify(l5(C))}}function CJG(G){let Z=G==="length"?" \u2014 output budget exhausted before any text (often reasoning tokens); raise maxTokens or lower reasoning effort":"";return Error(`OpenAI returned no content${G?` (finish_reason=${G})`:""}${Z}.`)}function yJG(G){if(G&&G!=="stop"&&G!=="tool_calls"&&G!=="function_call")throw Error(`OpenAI response incomplete (finish_reason=${G})${G==="length"?" \u2014 output budget exhausted; raise maxTokens or lower reasoning effort":""}.`)}function LJG(G){if(!G)return"";return jxI(G)}function AJG(G,Z){let b;try{b=JSON.parse(G)}catch{return!1}if(!Array.isArray(b.tools)||b.tools.length===0)return!1;return/jinja|template|tool|function[_ ]?call|does not support|not supported/i.test(Z)}function uJG(G){let Z=JSON.parse(G);return delete Z.tools,delete Z.tool_choice,JSON.stringify(Z)}function AvZ(G){if(!G)return;if(typeof G.reasoning_content==="string"&&G.reasoning_content)return G.reasoning_content;if(typeof G.reasoning_text==="string"&&G.reasoning_text)return G.reasoning_text;let Z=G.reasoning;if(typeof Z==="string"&&Z)return Z;if(Z&&typeof Z==="object"){let b=Z;if(typeof b.text==="string"&&b.text)return b.text;if(typeof b.content==="string"&&b.content)return b.content}if(Array.isArray(G.reasoning_details)){let b=G.reasoning_details.map((Y)=>typeof Y?.text==="string"?Y.text:typeof Y?.content==="string"?Y.content:"").join("");if(b)return b}return}function uvZ(G){if(!G?.length)return[];let Z=[];for(let b of G){let Y=b.function?.name;if(!Y)continue;let V={};try{V=b.function?.arguments?JSON.parse(b.function.arguments):{}}catch{V={}}Z.push({tool:Y,arguments:V})}return Z}function pvZ(G){if(G.kind==="oauth")return G.token;if(G.kind==="api_key")return G.token;return"no-key"}var jK;var YQI=KW(()=>{WA();WQI();vK();jK={name:"openai",supportsNativeTools:!0,async call(G,Z,b){if(b.kind==="oauth")return xxI(G,Z,b);if(b.kind==="api_key"&&!Z.baseUrl&&DxI(Z.model))try{return await xxI(G,Z,b)}catch(k){if(k instanceof k3||k instanceof Uw)throw k}let{url:Y,headers:V,body:X}=vJG(G,Z,b,!1),R=await fetch(Y,{method:"POST",headers:V,body:X,signal:Z.signal});if(R.status===400){let k=await R.clone().text().catch(()=>"");if(AJG(X,k))R=await fetch(Y,{method:"POST",headers:V,body:uJG(X),signal:Z.signal})}if(!R.ok)throw await n1("OpenAI",R);let Q=await R.json();if(Q.usage)Z.onUsage?.({inputTokens:Q.usage.prompt_tokens,outputTokens:Q.usage.completion_tokens});let H=Q.choices[0]?.finish_reason;yJG(H);let w=r4(uvZ(Q.choices[0]?.message?.tool_calls));if(w)return w;let C=Q.choices[0]?.message?.content??"";if(C)return C;let A=Q.choices[0]?.message,y=LJG(A?.reasoning_content??A?.reasoning??"");if(y)return y;throw CJG(H)},async*stream(G,Z,b){if(b.kind==="oauth"){yield*KxI(G,Z,b);return}if(b.kind==="api_key"&&!Z.baseUrl&&DxI(Z.model)){let K=!1;try{for await(let a of KxI(G,Z,b))K=!0,yield a;return}catch(a){if(K||a instanceof k3||a instanceof Uw)throw a}}let{url:Y,headers:V,body:X}=vJG(G,Z,b,!0),R=await fetch(Y,{method:"POST",headers:V,body:X,signal:Z.signal});if(R.status===400){let K=await R.clone().text().catch(()=>"");if(/stream_options/i.test(K)){let a=JSON.parse(X);delete a.stream_options,R=await fetch(Y,{method:"POST",headers:V,body:JSON.stringify(a),signal:Z.signal})}else if(AJG(X,K))R=await fetch(Y,{method:"POST",headers:V,body:uJG(X),signal:Z.signal})}if(!R.ok)throw await n1("OpenAI",R,"(stream)");if(!R.body)return;let Q=!1,H,w=!1,C="",A=(K)=>{C+=K,Z.onReasoning?.(K)},y=NQI(A),k=new Map;for await(let K of sv(R.body,Z.onStreamActivity)){let a;try{a=JSON.parse(K)}catch{continue}let x=a.choices?.[0]?.delta?.content;if(x){w=!0;let f=y.push(x);if(f)Q=!0,yield f}let S=AvZ(a.choices?.[0]?.delta);if(S)A(S);let n=a.choices?.[0]?.delta?.tool_calls;if(n)for(let f of n){let P=f.index??0,_=k.get(P)??{name:"",args:""};if(f.function?.name)_.name=f.function.name;if(f.function?.arguments)_.args+=f.function.arguments;k.set(P,_)}if(a.choices?.[0]?.finish_reason)H=a.choices[0].finish_reason;if(a.usage)Z.onUsage?.({inputTokens:a.usage.prompt_tokens,outputTokens:a.usage.completion_tokens})}if(!H&&(w||C||k.size))throw Error("OpenAI response incomplete (missing finish_reason).");yJG(H);let p=y.flush();if(p)Q=!0,yield p;let O=EK(k);if(O)Q=!0,yield O;if(!Q){let K=LJG(C);if(K){yield K;return}throw CJG(H)}}}});function kvZ(G){let Z=(G??process.env.OLLAMA_HOST??"http://localhost:11434").trim();return(/^https?:\/\//i.test(Z)?Z:`http://${Z}`).replace(/\/$/,"")}function gvZ(G){if(typeof G==="number"&&G>0)return Math.floor(G);let Z=process.env.OLLAMA_NUM_CTX??process.env.OLLAMA_CONTEXT_LENGTH,b=Z?Number.parseInt(Z,10):NaN;return Number.isFinite(b)&&b>0?b:zvZ}function pJG(G,Z,b){let Y=Z.model.startsWith("ollama/")?Z.model.slice(7):Z.model,V=Z.systemPrompt??G.find((H)=>H.role==="system")?.content,X=[];if(V)X.push({role:"system",content:V});for(let H of G){if(H.role==="system")continue;if(H.images?.length)X.push({role:H.role,content:H.content,images:H.images.map((w)=>w.data)});else X.push({role:H.role,content:H.content})}let R={model:Y,messages:X,stream:b,options:{temperature:Z.temperature??0.2,num_predict:Z.maxTokens??4000,num_ctx:gvZ(Z.numCtx)}};if(Z.jsonMode)R.format="json";return{url:`${kvZ(Z.baseUrl)}/api/chat`,body:JSON.stringify(l5(R))}}function kJG(G){let Z=G==="length"?" \u2014 output budget exhausted before any text; raise maxTokens":"";return Error(`Ollama returned no content${G?` (done_reason=${G})`:""}${Z}.`)}function zJG(G){if(G&&G!=="stop")throw Error(`Ollama response incomplete (done_reason=${G})${G==="length"?" \u2014 output budget exhausted; raise maxTokens":""}.`)}var zvZ=16384,TxI;var SxI=KW(()=>{WA();TxI={name:"ollama",async call(G,Z){let{url:b,body:Y}=pJG(G,Z,!1),V=await fetch(b,{method:"POST",headers:{"content-type":"application/json"},body:Y,signal:Z.signal});if(!V.ok)throw await n1("Ollama",V,`at ${b}`);let X=await V.json();Z.onUsage?.({inputTokens:X.prompt_eval_count,outputTokens:X.eval_count,durationMs:X.total_duration?Math.round(X.total_duration/1e6):void 0}),zJG(X.done_reason);let R=X.message?.content??"";if(!R)throw kJG(X.done_reason);return R},async*stream(G,Z){let{url:b,body:Y}=pJG(G,Z,!0),V=await fetch(b,{method:"POST",headers:{"content-type":"application/json"},body:Y,signal:Z.signal});if(!V.ok)throw await n1("Ollama",V,`(stream) at ${b}`);if(!V.body)return;let X=!1,R,Q=!1,H=!1,w=NQI(Z.onReasoning);for await(let A of ZxI(V.body,Z.onStreamActivity)){let y;try{y=JSON.parse(A)}catch{continue}let k=y.message?.content;if(k){H=!0;let O=w.push(k);if(O)X=!0,yield O}let p=y.message?.thinking;if(p)Z.onReasoning?.(p);if(y.done){if(Q=!0,y.done_reason)R=y.done_reason;Z.onUsage?.({inputTokens:y.prompt_eval_count,outputTokens:y.eval_count,durationMs:y.total_duration?Math.round(y.total_duration/1e6):void 0});break}}if(!Q&&H)throw Error("Ollama response incomplete (missing done event).");zJG(R);let C=w.flush();if(C)X=!0,yield C;if(!X)throw kJG(R)}}});function z3(G){let Z=`${G.name}/`,b=m3(G.name),Y=(X)=>({...X,model:X.model.startsWith(Z)?X.model.slice(Z.length):X.model,baseUrl:X.baseUrl??G.baseUrl,reasoningFormat:X.reasoningFormat??G.thinkingFormat}),V=(X)=>G.keyless?UvZ:X;return{name:G.name,supportsNativeTools:jK.supportsNativeTools,call:async(X,R,Q)=>{try{return await jK.call(X,Y(R),V(Q))}catch(H){throw _z(H,b)}},async*stream(X,R,Q){try{yield*jK.stream(X,Y(R),V(Q))}catch(H){throw _z(H,b)}}}}var UvZ;var Fr=KW(()=>{YQI();WA();fv();UvZ={kind:"none",provider:"openai"}});var nxI;var qxI=KW(()=>{Fr();nxI=z3({name:"lmstudio",baseUrl:"http://localhost:1234/v1",keyless:!0})});function UJG(G){return G?{kind:"api_key",provider:"openai",token:G}:{kind:"none",provider:"openai"}}var BvZ="https://api.x.ai/v1",gJG;var PxI=KW(()=>{Fr();gJG=z3({name:"xai",baseUrl:BvZ})});function OJG(G){return{...G,model:G.model.startsWith("kimi/")?G.model.slice(5):G.model,baseUrl:G.baseUrl??MvZ,extraHeaders:{...y3(),...G.extraHeaders}}}var OvZ="https://api.moonshot.ai/v1",MvZ="https://api.kimi.com/coding",$xI,BJG,MJG;var aJG=KW(()=>{Vr();Rr();Fr();WA();fv();$xI=z3({name:"kimi",baseUrl:OvZ}),BJG=m3("kimi");MJG={name:"kimi",supportsNativeTools:$xI.supportsNativeTools,call:async(G,Z,b)=>{if(b.kind!=="oauth")return $xI.call(G,Z,b);try{return await Pp.call(G,OJG(Z),b)}catch(Y){throw _z(Y,BJG)}},async*stream(G,Z,b){if(b.kind!=="oauth"){yield*$xI.stream(G,Z,b);return}try{yield*Pp.stream(G,OJG(Z),b)}catch(Y){throw _z(Y,BJG)}}}});function xJG(G){let Z=`${G.name}/`,b=m3(G.name),Y=(V)=>({...V,model:V.model.startsWith(Z)?V.model.slice(Z.length):V.model,baseUrl:V.baseUrl??G.baseUrl});return{name:G.name,supportsNativeTools:Pp.supportsNativeTools,call:async(V,X,R)=>{try{return await Pp.call(V,Y(X),R)}catch(Q){throw _z(Q,b)}},async*stream(V,X,R){try{yield*Pp.stream(V,Y(X),R)}catch(Q){throw _z(Q,b)}}}}var KJG=KW(()=>{Rr();WA();fv()});function jJG(G){return G.protocol==="anthropic"?xJG({name:G.name,baseUrl:G.baseUrl}):z3({name:G.name,baseUrl:G.baseUrl,thinkingFormat:G.thinkingFormat})}function DJG(G=EaI()){let Z=G.filter((Y)=>!avZ.has(Y.name)),b=new Set(Z.map((Y)=>Y.name));for(let Y of _xI)if(!b.has(Y))S1.unregister(Y),_xI.delete(Y);for(let Y of Z)S1.register(Y.name,jJG(Y)),_xI.add(Y.name)}var avZ,_xI;var TJG=KW(()=>{PaI();Rr();YQI();Nr();SxI();qxI();PxI();KK();aJG();Fr();KJG();Dz();qo();S1.register("anthropic",Pp);S1.register("openai",jK);S1.register("gemini",XxI);S1.register("antigravity",_dI);S1.register("ollama",TxI);S1.register("lmstudio",nxI);S1.register("xai",gJG);S1.register("kimi",MJG);for(let G of Dp)S1.register(G.name,jJG(G));avZ=new Set(S1.listProviders()),_xI=new Set;R0G((G)=>DJG(G));DJG()});function VQI(G,Z=DK){if(Object.prototype.hasOwnProperty.call(Z,G))return Z[G];return G}async function SJG(G,Z){let Y=(Z??await Cm()).modelAliases??{},V={...DK,...Y};return VQI(G,V)}async function xvZ(){let Z=(await Cm()).modelAliases??{};return{...DK,...Z}}function KvZ(G,Z=DK){return Object.entries(Z).filter(([,b])=>b===G).map(([b])=>b).sort()}async function nJG(G){return KvZ(G,await xvZ())}var DK;var qJG=KW(()=>{nh();UdI();DK={fast:"ollama/qwen2.5:0.5b",local:"ollama/qwen2.5:0.5b",sonnet:"claude-sonnet-5-5",opus:"claude-opus-5-5",gpt:"gpt-5.5",flash:"gemini-2.5-flash",grok:"grok-4.3",kimi:"kimi-k2-0711-preview","opus-5.5":"claude-opus-5-5","sonnet-5.5":"claude-sonnet-5-5","opus5.5":"claude-opus-5-5","sonnet5.5":"claude-sonnet-5-5","antigravity/gemini-3.1-pro-high":"antigravity/gemini-pro-agent"}});function cQI(G){if(!G)return!1;if(_JG(G))return!1;if(RQI(G))return!1;if(/Antigravity Cloud Code Assist response incomplete \(finishReason=MALFORMED_FUNCTION_CALL\)/i.test(dr(G)))return!0;if(Qr(G))return!0;let Z="";if(G instanceof Error)Z=G.message;else if(typeof G==="object"&&"message"in G&&typeof G.message==="string")Z=G.message;else Z=String(G);let b=Z.toLowerCase();if(b.includes("fetch")||b.includes("network")||b.includes("econn")||b.includes("timeout")||b.includes("overloaded")||b.includes("rate limit")||b.includes("rate_limit")||b.includes("stream idle")||b.includes("no chunk")||b.includes("socket connection was closed")||b.includes("socket hang up")||b.includes("other side closed")||b.includes("und_err_socket"))return!0;if(b.includes("returned no content"))return!/max_tokens|max_output_tokens|finish_reason=length|done_reason=length|output budget exhausted/.test(b);if(typeof G==="object"&&G!==null){let V=G.status,X=typeof V==="number"?V:typeof V==="string"?Number(V):NaN;if(!isNaN(X)&&PJG.has(X))return!0}let Y=b.match(/http[\s/]*?(\d{3})/);if(Y&&PJG.has(Number(Y[1])))return!0;return!1}async function XQI(G,Z){let b=Z?.retries??3,Y=Z?.baseDelayMs??250,V=Z?.maxDelayMs??4000,X=Z?.isRetryable??cQI,R=Z?.sleep??((p)=>{let{promise:O,resolve:K}=Promise.withResolvers();return setTimeout(K,p),O}),Q=Z?.random??Math.random,H=Z?.onRetry,w=Z?.rateLimitMinDelayMs??0,C=Z?.rateLimitRetries,A=Z?.rateLimitMaxServerDelayMs,y=Z?.signal,k=1;while(!0)try{return await G()}catch(p){let O=$JG(p),K=TvZ(p);if(O&&typeof A==="number"&&K!==void 0&&K>A)throw p;let a=O&&typeof C==="number"?Math.max(b,C):b;if(k>=a||!X(p,k))throw p;let x=Math.min(Y*Math.pow(2,k-1),V),S=x/2+Q()*(x/2),n=K!==void 0?K:S,f=O?Math.min(w*Math.pow(2,k-1),jvZ):0,P=Math.max(n,f);if(H&&H(k,p,P)===!1)throw p;await DvZ(R,P,y),k++}}function DvZ(G,Z,b){if(!b)return G(Z);if(b.aborted)return Promise.reject(b.reason??Error("aborted"));let{promise:Y,resolve:V,reject:X}=Promise.withResolvers(),R=()=>X(b.reason??Error("aborted"));return b.addEventListener("abort",R,{once:!0}),G(Z).then((Q)=>{b.removeEventListener("abort",R),V(Q)},(Q)=>{b.removeEventListener("abort",R),X(Q)}),Y}function TvZ(G){if(typeof G==="object"&&G!==null){let Z=G.retryAfterMs;if(typeof Z==="number"&&Number.isFinite(Z)&&Z>=0)return Z}return}function $JG(G){if(typeof G==="object"&&G!==null){let b=G.status;if((typeof b==="number"?b:typeof b==="string"?Number(b):NaN)===429)return!0}let Z=G instanceof Error?G.message:typeof G==="string"?G:"";return/\b429\b/.test(Z)||/rate[ _]?limit/i.test(Z)}function dr(G){if(G instanceof Error)return G.message;if(typeof G==="string")return G;if(typeof G==="object"&&G!==null&&typeof G.message==="string")return G.message;return""}function _JG(G){return SvZ.test(dr(G))}function RQI(G){return/stop_reason=refusal|finish_reason=content_filter|\(content_filter\)|(?:block|finish)Reason=(?:SAFETY|PROHIBITED_CONTENT|BLOCKLIST|RECITATION|SPII)|Refusal \(\w+\)/i.test(dr(G))}function Qr(G){let Z;if(G&&typeof G==="object"&&"code"in G)Z=String(G.code);if(Z&&["ConnectionRefused","ECONNREFUSED","ENOTFOUND","EHOSTUNREACH","EAI_AGAIN"].includes(Z))return!0;return/unable to connect\. is the computer able to access the url\?/i.test(dr(G))}async function fxI(G,Z,b){try{return await G()}catch(Y){if(Qr(Y))throw new mr(Z,b,Y);throw Y}}var PJG,jvZ=30000,SvZ,mr;var Hr=KW(()=>{PJG=new Set([408,425,429,500,502,503,504,529]);SvZ=/usage.?limit|usage_limit_reached|usage_not_included|limit_reached|model.?limit|message.?limit|limit for this model|quota.?exceeded|out_of_credits|request would exceed your account.?s rate limit|resource has been exhausted[^\n]*(?:quota|limit)|exceeded your/i;mr=class mr extends Error{provider;baseUrl;code;constructor(G,Z,b){let Y=b&&typeof b==="object"&&"code"in b?String(b.code):void 0;super(dr(b),{cause:b});this.provider=G;this.baseUrl=Z;this.name="ConnectionContextError",this.code=Y}}});function qvZ(G){let Z=[],b=new Set;for(let[Y,V]of G.split(/\r?\n/u).entries()){let X=V.trimEnd();if(!X.trim())continue;let R=X.indexOf("\t");if(R<0)throw new iv(`Malformed agy model list record at line ${Y+1}; expected <slug>\\t<label>.`,"protocol");let Q=X.slice(0,R),H=X.slice(R+1);if(!Q.trim()||!H.trim()||/[\s/]/u.test(Q))throw new iv(`Malformed agy model list record at line ${Y+1}; slug and label are required.`,"protocol");if(b.has(Q))continue;b.add(Q),Z.push(`agy/${Q}`)}return Z}async function iJG(G={}){let Z=nvZ(G.timeoutMs,15000,15000);if(G.signal?.aborted)throw new iv("Agy model discovery was aborted before spawn.","cancelled");let b=G.executable??"agy",Y=G.cwd??process.cwd(),V;try{V=Bun.spawn([b,"models"],{cwd:Y,stdin:"ignore",stdout:"pipe",stderr:"pipe"})}catch(P){throw new iv(`Failed to start agy model discovery: ${fJG(P)}. Install agy and authenticate it with its own CLI.`,"spawn")}let X="",R="",Q=0,H=0,w=!1,C=!1,A=!1,y,k,p,O,K=()=>{if(A)return;A=!0,k?.cancel().catch(()=>{}),p?.cancel().catch(()=>{}),sJG(V,"SIGTERM"),y=setTimeout(()=>sJG(V,"SIGKILL"),250)},a=(P)=>{if(P==="timeout")w=!0;else C=!0;K()},x=()=>a("cancelled");if(G.signal)G.signal.addEventListener("abort",x,{once:!0});let S=async(P,_)=>{let r=P.getReader();if(_==="stdout")k=r;else p=r;let bI=new TextDecoder;try{for(;;){let cI=await r.read();if(cI.done)break;let zI=bI.decode(cI.value,{stream:!0});if(_==="stdout"){if(Q+=cI.value.byteLength,Q>262144)throw new iv("Agy model list exceeded the bounded output limit.","protocol");X=FQI(X,zI,262144)}else if(H+=cI.value.byteLength,R=FQI(R,zI,262144),H>262144)R=`${R}
67
67
  [agy stderr truncated]`}let JI=bI.decode();if(_==="stdout")X=FQI(X,JI,262144);else R=FQI(R,JI,262144)}finally{r.releaseLock()}},n=S(V.stdout,"stdout").catch((P)=>{O=P,K()}),f=S(V.stderr,"stderr").catch((P)=>{if(!O)O=P;K()});try{let P=setTimeout(()=>a("timeout"),Z),_;try{_=await V.exited,await Promise.all([n,f])}finally{clearTimeout(P)}if(C)throw new iv("Agy model discovery was cancelled.","cancelled",_,R);if(w)throw new iv(`Agy model discovery timed out after ${Z}ms.`,"timeout",_,R);if(O)throw O;if(_!==0){let r=R.trim()||`agy models exited with code ${_}`;throw new iv(`${r} (exit ${_}).`,"exit",_,R)}return qvZ(X)}catch(P){if(!A&&V.exitCode===null)K();if(P instanceof iv)throw P;throw new iv(`Agy model discovery failed: ${fJG(P)}${R.trim()?` \u2014 ${R.trim()}`:""}`,"protocol",V.exitCode,R)}finally{if(G.signal)G.signal.removeEventListener("abort",x);try{await V.exited}catch{}clearTimeout(y);try{await k?.cancel()}catch{}try{await p?.cancel()}catch{}}}var iv,nvZ=(G,Z,b)=>{if(G===void 0)return Z;if(!Number.isFinite(G)||G<=0)throw new iv("Agy timeout must be a positive finite number of milliseconds.","protocol");return Math.min(Math.max(1,Math.ceil(G)),b)},fJG=(G)=>G instanceof Error?G.message:String(G),FQI=(G,Z,b)=>{if(!Z)return G;let Y=G+Z;return Y.length<=b?Y:Y.slice(0,b)},sJG=(G,Z)=>{try{G.kill(Z)}catch{}};var sxI=KW(()=>{iv=class iv extends Error{kind;exitCode;stderr;constructor(G,Z,b,Y){super(G);this.kind=Z;this.exitCode=b;this.stderr=Y;this.name="AgyCliError"}}});var PvZ;var ixI=KW(()=>{nh();Xr();_6();Dz();qo();PvZ=["anthropic","openai","gemini","antigravity","agy","ollama","lmstudio","xai","kimi",...ydI]});import{createHash as tJG}from"crypto";async function i6(G){let Z=G;if(!Z){let V=await u3("openai");if(!V.oauth)return;Z={kind:"oauth",provider:"openai",token:V.oauth}}if(Z.kind!=="oauth"||Z.provider!=="openai")return;let b=await fz("openai");return s6(Z.token)||(b?.access===Z.token?b.accountId?.trim():void 0)||`token:${tJG("sha256").update(Z.token).digest("hex")}`}async function hr(G){try{let Z=G;if(!Z){let H=await u3("antigravity"),w=H.oauth?"antigravity":"gemini",C=H.oauth?H:await u3("gemini");if(!C.oauth)return;Z={kind:"oauth",provider:w,token:C.oauth}}if(Z.kind!=="oauth"||Z.provider!=="antigravity"&&Z.provider!=="gemini")return;let b=Z.provider,Y=await fz(b).catch(()=>{return}),V=Y?.access===Z.token,X=V?Y?.email?.trim().toLowerCase():"",R=V?X?`email:${X}`:Y?.refresh?`refresh:${Y.refresh}`:`access:${Z.token}`:`access:${Z.token}`,Q=Z.projectId?.trim()||(V?Y?.projectId?.trim():void 0)||process.env.GOOGLE_CLOUD_PROJECT?.trim()||process.env.GOOGLE_CLOUD_PROJECT_ID?.trim()||"";return tJG("sha256").update(`${b}\x00${R}\x00${Q}\x00${qp()}`,"utf8").digest("hex")}catch{return}}var dQI=KW(()=>{fv();p3();KK();WQI()});function tvZ(G){if(G.kind==="oauth")return{authorization:`Bearer ${G.token}`,"anthropic-version":"2023-06-01"};if(G.kind==="api_key")return{"x-api-key":G.token,"anthropic-version":"2023-06-01"};return{}}function ovZ(G){if(G==="ollama"||G==="lmstudio")return;return G}function rvZ(G,Z,b,Y,V){let X=R3(G);if(X){let R=(b??X.baseUrl).replace(/\/$/,""),Q=Z?.kind==="api_key"||Z?.kind==="oauth"?Z.token:"";if(X.protocol==="anthropic")return{url:`${R}/v1/models`,headers:Q?{"x-api-key":Q,"anthropic-version":"2023-06-01"}:{}};return{url:`${R}/models`,headers:Q?{Authorization:`Bearer ${Q}`}:{}}}switch(G){case"anthropic":return{url:"https://api.anthropic.com/v1/models",headers:tvZ(Z)};case"openai":{let R=Z?.kind==="oauth"||Z?.kind==="api_key"?Z.token:"";if(Z?.kind==="oauth"&&(V?.forceCodexCatalog||!b&&!process.env.OPENAI_BASE_URL)){let H=s6(R)||Y,w={Authorization:`Bearer ${R}`,"OpenAI-Beta":"responses=experimental",originator:"codex_cli_rs"};if(H)w["chatgpt-account-id"]=H;return{url:svZ,headers:w}}return{url:`${(b??process.env.OPENAI_BASE_URL??"https://api.openai.com/v1").replace(/\/$/,"")}/models`,headers:R?{Authorization:`Bearer ${R}`}:{}}}case"gemini":{let R=Z?.kind==="oauth"?Z.token:void 0,Q=Z?.kind==="api_key"?Z.token:void 0;return{url:R?"https://generativelanguage.googleapis.com/v1beta/models?pageSize=1000":`https://generativelanguage.googleapis.com/v1beta/models?pageSize=1000&key=${Q??""}`,headers:R?{authorization:`Bearer ${R}`}:{}}}case"antigravity":{let R=Z?.kind==="oauth"?Z.token:"";return{url:ivZ,headers:R?{authorization:`Bearer ${R}`,"content-type":"application/json","User-Agent":qp()}:{},method:"POST",body:JSON.stringify(Z?.kind==="oauth"&&Z.projectId?{project:Z.projectId}:{})}}case"ollama":return{url:`${(b??"http://localhost:11434").replace(/\/$/,"")}/api/tags`,headers:{}};case"lmstudio":return{url:`${(b??"http://localhost:1234/v1").replace(/\/$/,"")}/models`,headers:{}};case"xai":{let R=Z?.kind==="api_key"?Z.token:"";return{url:"https://api.x.ai/v1/models",headers:R?{Authorization:`Bearer ${R}`}:{}}}case"kimi":{if(Z?.kind==="oauth")return{url:"https://api.kimi.com/coding/v1/models",headers:{...y3(),Authorization:`Bearer ${Z.token}`}};let R=Z?.kind==="api_key"?Z.token:"";return{url:"https://api.moonshot.ai/v1/models",headers:R?{Authorization:`Bearer ${R}`}:{}}}}throw Error(`discoveryRequest: unhandled provider '${G}'`)}function evZ(G){return!/(^|[-/])(text-embedding|embedding|tts|whisper|dall-e|moderation|omni-moderation|davinci|babbage|computer-use|realtime|audio|image|sora|transcribe|instruct)([-/]|$)/i.test(G)&&!/^codex([-/]|$)/i.test(G)}function ICZ(G){return!/(^|[-/])(embedding|aqa|tts|image|imagen|veo|lyria|nano-banana|deep-research|computer-use|antigravity)([-/]|$)/i.test(G)}function Iy(G){return G.replace(/^models\//,"").replace(/^antigravity\//,"")}function oJG(G,Z,b={}){let Y=Z;if(R3(G))return(Y.data??[]).map((X)=>X.id?`${G}/${X.id}`:"").filter(Boolean);if(G==="ollama")return(Y.models??[]).map((X)=>`ollama/${X.name??""}`).filter((X)=>X!=="ollama/");if(G==="lmstudio")return(Y.data??[]).map((X)=>`lmstudio/${X.id??""}`).filter((X)=>X!=="lmstudio/");if(G==="xai")return(Y.data??[]).map((X)=>X.id??"").filter(Boolean);if(G==="kimi")return(Y.data??[]).map((X)=>X.id??"").filter(Boolean);if(G==="antigravity"){let X=Z,R=(p)=>Array.isArray(p)?p.filter((O)=>typeof O==="string").map(Iy):[],Q=Array.isArray(X.deprecatedModelIds)?R(X.deprecatedModelIds):Object.keys(X.deprecatedModelIds??{}).map(Iy),H=new Set((Array.isArray(X.agentModelSorts)?X.agentModelSorts:[]).flatMap((p)=>Array.isArray(p?.groups)?p.groups:[]).flatMap((p)=>R(p?.modelIds)));for(let p of Object.values(X.tieredModelIds??{}))for(let O of R(p))H.add(O);if(typeof X.defaultAgentModelId==="string")H.add(Iy(X.defaultAgentModelId));let w=Array.isArray(X.agentModelSorts)||X.tieredModelIds!==void 0||X.defaultAgentModelId!==void 0,C=new Set([...R(X.tabModelIds),...R(X.imageGenerationModelIds),...R(X.audioTranscriptionModelIds),...Q]),A=new Set([...C,...R(X.commitMessageModelIds),...R(X.mqueryModelIds)]),y=X.models;return(Array.isArray(y)?y.map((p)=>[p?.slug??p?.id??p?.name??"",p]):Object.entries(y??{})).map(([p,O])=>[typeof p==="string"?Iy(p):"",O]).filter(([p,O])=>p.length>0&&O?.isInternal!==!0&&!C.has(p)&&(w?H.size>0&&(H.has(p)||!A.has(p)&&typeof O?.displayName==="string"&&O.displayName.trim().length>0):!A.has(p))).map(([p])=>`antigravity/${p}`)}if(G==="gemini")return(Y.models??[]).filter((X)=>!X.supportedGenerationMethods||X.supportedGenerationMethods.includes("generateContent")).map((X)=>(X.name??"").replace(/^models\//,"")).filter((X)=>X&&ICZ(X));if(G==="openai"&&Y.models?.some((X)=>X.slug||X.id))return Y.models.filter((X)=>X.visibility===void 0||X.visibility==="list").map((X)=>X.slug??X.id??"").filter((X)=>X&&!/(^|[-/])auto-review([-/]|$)/i.test(X));let V=(Y.data??[]).map((X)=>X.id??"").filter(Boolean);return G==="openai"&&!b.openaiCompatible?V.filter(evZ):V}async function rJG(G,Z={}){if(G==="agy")try{let p=await iJG({cwd:Z.cwd,timeoutMs:Z.timeoutMs,signal:Z.signal,executable:Z.executable}),O=[...new Set(p)];return pdI("agy",O,{source:"cli_session",replace:!0}),{provider:"agy",models:O,ok:!0,source:"cli_session"}}catch(p){let O=p instanceof Error?p.message:String(p);return{provider:"agy",models:[],ok:!1,source:"cli_session",error:O}}let b=Z.fetchImpl??fetch,Y=Z.limit??(G==="openai"||G==="antigravity"?Number.POSITIVE_INFINITY:_vZ),V=Z.baseUrl,X=G==="openai"&&!!Z.codexCatalog,R,Q,H,w="keyless";if(G==="xai"){let p=(Z.config??await Cm()).providers?.xai;if(!p)return{provider:G,models:[],ok:!1,source:"none",error:"not logged in"};R={kind:"api_key",provider:"openai",token:p},w="api_key"}else if(G!=="ollama"&&G!=="lmstudio"){let p=ovZ(G);R=await P0(p),w=R.kind==="oauth"?"oauth":R.kind==="api_key"?"api_key":"none";let K=Z.config??await Cm();if(G==="openai"&&!X)V=(V??K.openaiBaseUrl??process.env.OPENAI_BASE_URL)?.replace(/\/+$/,"");if(G==="antigravity"){if(R.kind!=="oauth"){let S=await P0("gemini");if(S.kind==="oauth")R=S,w="oauth"}if(R.kind!=="oauth")return fo(void 0),{provider:G,models:[],ok:!1,source:w,error:"not logged in with Antigravity OAuth"}}let a=p;if(G!=="antigravity"&&R.kind==="oauth"&&K.providers?.[a]&&!Z.preferOAuth&&!X)R={kind:"api_key",provider:a,token:K.providers[a]},w="api_key";if(G==="openai"&&V&&R.kind==="oauth"&&!X){let S=K.providers?.openai;R=S?{kind:"api_key",provider:"openai",token:S}:{kind:"none",provider:"openai"},w=S?"api_key":"keyless"}if(G==="openai"&&w==="oauth"&&R.kind==="oauth"){let S=await fz("openai").catch(()=>{return});Q=s6(R.token)||(S?.access===R.token?S.accountId:void 0),H=await i6(R),z6(H)}if(G==="gemini"&&R.kind==="oauth")return{provider:G,models:[],ok:!1,source:w,error:"OAuth cannot serve gemini models \u2014 set GEMINI_API_KEY, or use antigravity/* (Cloud Code Assist)"};if(w==="none"&&!(G==="openai"&&!!V))return{provider:G,models:[],ok:!1,source:w,error:"not logged in"}}let C={...H?{accountId:H}:{},...V?{baseUrl:V}:{}},A=Z.timeoutMs??$vZ,y=Z.signal?AbortSignal.any([Z.signal,AbortSignal.timeout(A)]):AbortSignal.timeout(A),k;try{if(G==="antigravity"&&R?.kind==="oauth"){k=await hr(R),C.accountId=k;try{let bI=await $dI(R,{signal:y,discover:(JI)=>aK(JI,{fetchImpl:b,metadata:{...br},extraHeaders:{"User-Agent":qp()},alwaysOnboard:!0,signal:y,requestTimeoutMs:A})});R={...R,projectId:bI}}catch(bI){if(Z.signal?.aborted)throw bI}y=Z.signal?AbortSignal.any([Z.signal,AbortSignal.timeout(A)]):AbortSignal.timeout(A),C.accountId=await hr(R);let r=await hr();if(r!==C.accountId&&r!==k)return{provider:G,models:[],ok:!1,source:w,error:"account changed during model discovery",...C};fo(C.accountId)}let{url:p,headers:O,method:K,body:a}=rvZ(G,R,V,Q,X?{forceCodexCatalog:!0}:void 0),x=await b(p,{method:K??"GET",headers:O,body:a,signal:y});if(!x.ok){let r=x.status===401||x.status===403?"auth rejected":`HTTP ${x.status}`;return{provider:G,models:[],ok:!1,source:w,error:r,...C}}let S=await x.json();if(G==="openai"){let r=S,bI=Array.isArray(r?.models)?r.models:r?.data;if(!Array.isArray(bI)||bI.some((JI)=>!JI||typeof JI!=="object"||![JI.slug,JI.id].some((cI)=>typeof cI==="string"&&cI.trim().length>0)))return{provider:G,models:[],ok:!1,source:w,error:"invalid models response",...C}}if(G==="antigravity"){let r=S,bI=r?.models,JI=bI&&typeof bI==="object"?Object.entries(bI):void 0,cI=r?.agentModelSorts,zI=cI!==void 0&&(!Array.isArray(cI)||cI.some((MI)=>!MI||typeof MI!=="object"||!Array.isArray(MI.groups)||MI.groups.some((tI)=>!tI||!Array.isArray(tI.modelIds)||tI.modelIds.some((kG)=>typeof kG!=="string"||!Iy(kG).trim())))),SI=["tabModelIds","imageGenerationModelIds","audioTranscriptionModelIds","commitMessageModelIds","mqueryModelIds"].some((MI)=>{let tI=r?.[MI];return tI!==void 0&&(!Array.isArray(tI)||tI.some((kG)=>typeof kG!=="string"||!Iy(kG).trim()))}),xI=r?.deprecatedModelIds,pG=xI!==void 0&&(Array.isArray(xI)?xI.some((MI)=>typeof MI!=="string"||!Iy(MI).trim()):!xI||typeof xI!=="object"||Object.keys(xI).some((MI)=>!Iy(MI).trim())),IZ=r?.tieredModelIds,sI=IZ!==void 0&&(!IZ||typeof IZ!=="object"||Array.isArray(IZ)||Object.values(IZ).some((MI)=>!Array.isArray(MI)||MI.some((tI)=>typeof tI!=="string"||!Iy(tI).trim()))),TG=r?.defaultAgentModelId,yG=TG!==void 0&&(typeof TG!=="string"||!Iy(TG).trim());if(!JI||JI.some(([MI,tI])=>{if(!tI||typeof tI!=="object"||Array.isArray(tI))return!0;let kG=Array.isArray(bI)?tI.slug??tI.id??tI.name:MI;return typeof kG!=="string"||!Iy(kG).trim()})||zI||SI||pG||sI||yG)return{provider:G,models:[],ok:!1,source:w,error:"invalid models response",...C}}let n=oJG(G,S,{openaiCompatible:G==="openai"&&!!V}),f={};if(G==="antigravity"&&S&&typeof S==="object"&&"models"in S&&S.models&&typeof S.models==="object")for(let[r,bI]of Object.entries(S.models)){if(!bI||typeof bI!=="object"||!("displayName"in bI)||typeof bI.displayName!=="string"||!bI.displayName.trim())continue;let JI=Array.isArray(S.models)?"slug"in bI&&typeof bI.slug==="string"?bI.slug:("id"in bI)&&typeof bI.id==="string"?bI.id:("name"in bI)&&typeof bI.name==="string"?bI.name:"":r,cI=`antigravity/${Iy(JI)}`;if(n.includes(cI))f[cI]=bI.displayName}if(G==="gemini"){let r=S?.nextPageToken;for(let bI=0;r&&bI<4;bI++){let JI=`${p}&pageToken=${encodeURIComponent(r)}`,cI=await b(JI,{method:"GET",headers:O,signal:y});if(!cI.ok)break;let zI=await cI.json();n=n.concat(oJG(G,zI)),r=zI.nextPageToken}}let P=[...new Set(n)].sort(),_=P.slice(0,Y);if(G==="openai"&&w==="oauth"&&!V){if(await i6()!==H)return{provider:G,models:[],ok:!1,source:w,error:"account changed during model discovery",...C};z6(H)}if(G==="antigravity"){let r=await hr();if(r!==C.accountId&&r!==k)return{provider:G,models:[],ok:!1,source:w,error:"account changed during model discovery",...C};fo(C.accountId)}if(pdI(G,P,{source:w,baseUrl:V,replace:G==="openai"||G==="antigravity",...w==="oauth"&&C.accountId?{accountId:C.accountId}:{}}),G==="openai"&&w==="oauth"&&!V)paI(P,H);if(G==="kimi"&&w==="oauth")BaI(P);return{provider:G,models:_,ok:!0,source:w,...Object.keys(f).length?{displayNames:f}:{},...C}}catch(p){let O=y.aborted||p?.name==="TimeoutError"||p?.name==="AbortError"?"timeout":"unreachable";return{provider:G,models:[],ok:!1,source:w,error:O,...C}}}var $vZ=5000,_vZ=100,fvZ="2.0.0",svZ,ivZ="https://daily-cloudcode-pa.googleapis.com/v1internal:fetchAvailableModels";var txI=KW(()=>{nh();Xr();sxI();ixI();fv();WQI();p3();Dz();dQI();KK();Wr();Vr();svZ=`https://chatgpt.com/backend-api/codex/models?client_version=${fvZ}`});var QwG={};X3(QwG,{thinkingToReasoningEffort:()=>bwG,thinkingMaxTokens:()=>ZwG,streamMaxMs:()=>RwG,streamIdleMs:()=>FwG,retryableStream:()=>dwG,resolveRoleModel:()=>NwG,resolveRetryOptions:()=>YwG,resolveProvider:()=>TK,resolveMaxOutputTokens:()=>lwG,resolveCall:()=>rxI,qualifyModelId:()=>lCZ,providerModelFor:()=>GwG,oauthServesModel:()=>t6,modelServableWithConfig:()=>GKI,effectiveCredentialForProvider:()=>VwG,describeModelDetailed:()=>WCZ,describeModel:()=>WwG,credentialForCall:()=>cwG,createModelManager:()=>ZKI,callTimeoutMs:()=>IKI});function TK(G){let Z=LK(G);if(Z)return Z.provider;let b=J0G(G);if(b)return b.provider;let Y=(G??"").toLowerCase();if(Y.startsWith("ollama/"))return"ollama";if(Y.startsWith("lmstudio/"))return"lmstudio";if(Y.startsWith("antigravity/"))return"antigravity";if(Y.startsWith("agy/"))return"agy";if(Y.startsWith("xai/"))return"xai";if(Y.startsWith("kimi/"))return"kimi";for(let V of CaI())if(Y.startsWith(`${V}/`))return V;if(Y.startsWith("openai/"))return"openai";if(Y.startsWith("google/"))return"gemini";if(Y.includes("grok"))return"xai";if(Y.includes("kimi")||Y.includes("moonshot"))return"kimi";if(Y.includes("gpt")||/(^|\/)o\d/.test(Y))return"openai";if(Y.includes("gemini"))return"gemini";return"anthropic"}function ZCZ(G){return yaI(G)?`${G}/`:GCZ[G]??`${G}/`}function lCZ(G,Z){let b=(G??"").trim();if(!b)return b;return TK(b)===Z?b:`${ZCZ(Z)}${b}`}function GwG(G){if(G.startsWith("ollama/")||G.startsWith("openai/")||G.startsWith("anthropic/")||G.startsWith("google/")||G.startsWith("antigravity/")||G.startsWith("lmstudio/")||G.startsWith("xai/")||G.startsWith("agy/")||G.startsWith("kimi/")||yaI(G.split("/")[0]))return G;return y0G(G,TK(G))}function ZwG(G){if(G==="low")return 8000;if(G==="high")return 24000;if(G==="xhigh")return 31999;return 16000}function lwG(G,Z){let b=G?LK(VQI(G,DK)):void 0;if(!b)return ZwG(Z);let Y=Number($V("MAX_OUTPUT_TOKENS")),V=Number.isFinite(Y)&&Y>0?Y:bCZ;return Math.min(CK(b.id)?.maxOutputTokens??V,V)}function bwG(G){if(!G)return;return G==="xhigh"?"high":G}async function WwG(G,Z){let b=await SJG(G,Z);return{input:G,resolved:b,provider:TK(b)}}function NwG(G,Z){return Z.roles?.[G]||Z.defaultModel}async function WCZ(G){let{resolved:Z,provider:b}=await WwG(G);return{input:G,resolved:Z,provider:b,entry:LK(Z),aliases:await nJG(Z)}}function YwG(G,Z="request"){let b={isRetryable:cQI},Y;if(Z==="request"){if(typeof G?.requestMaxRetries==="number")Y=G.requestMaxRetries;else if(typeof G?.maxRetries==="number")Y=G.maxRetries}else if(Z==="stream"){if(typeof G?.streamMaxRetries==="number")Y=G.streamMaxRetries;else if(typeof G?.maxRetries==="number")Y=G.maxRetries}if(typeof Y==="number")b.retries=Y+1;if(typeof G?.maxDelayMs==="number")b.maxDelayMs=G.maxDelayMs;if(typeof G?.rateLimitRetries==="number")b.rateLimitRetries=G.rateLimitRetries+1;else if(typeof Y==="number")b.rateLimitRetries=Y+1;else b.rateLimitRetries=NCZ;if(typeof G?.rateLimitMinDelayMs==="number")b.rateLimitMinDelayMs=G.rateLimitMinDelayMs;else if(typeof G?.maxDelayMs!=="number")b.rateLimitMinDelayMs=YCZ;if(typeof G?.rateLimitMaxServerDelayMs==="number")b.rateLimitMaxServerDelayMs=G.rateLimitMaxServerDelayMs;let V=G?.failFastStatuses,X=G?.failFastPatterns;if(V&&V.length>0||X&&X.length>0){let R=b.isRetryable??cQI,Q=new Set(V??[]),H=(X??[]).map((w)=>w.toLowerCase());b.isRetryable=(w,C)=>{if(w&&typeof w==="object"){let A=w.status,y=typeof A==="number"?A:typeof A==="string"?Number(A):NaN;if(!Number.isNaN(y)&&Q.has(y))return!1}if(H.length>0){let y=(w instanceof Error?w.message:typeof w==="object"&&w!==null&&typeof w.message==="string"?w.message:String(w)).toLowerCase();if(H.some((k)=>y.includes(k)))return!1}return R(w,C)}}return b}function t6(G,Z){if(G==="openai")return kaI(Z);if(G==="kimi")return E0G(Z);if(A3(G)&&L3[G].verifiedEndToEnd===!1)return!1;return!0}function GKI(G,Z,b){if(G==="agy")return!1;if(G==="ollama"||G==="lmstudio")return!0;if(G==="antigravity")return!!(b.oauth?.antigravity||b.oauth?.gemini);if(G==="openai"&&b.openaiBaseUrl)return!0;let Y=G;if(b.providers?.[Y])return!0;if(b.oauth?.[Y])return t6(Y,Z);return!1}function VwG(G,Z,b,Y){if(Z.kind==="oauth"){if(t6(G,Y))return Z;let V=b.providers[G];if(V)return{kind:"api_key",provider:G,token:V};if(A3(G)&&L3[G].verifiedEndToEnd===!1){let X=G==="gemini"?" Or use an antigravity/* model instead \u2014 the SAME Gemini models served OAuth-only via Cloud Code Assist (run 'jeo auth login antigravity').":"";throw Error(`Provider '${G}' has only an OAuth token, but its OAuth backend is not compatible with the bundled adapter. Set ${G.toUpperCase()}_API_KEY (or run 'jeo setup') to use ${Y}.${X}`)}}return Z}function cwG(G,Z,b,Y){if(G==="openai"&&!!Y&&Z.kind==="oauth")return b.providers.openai?{kind:"api_key",provider:"openai",token:b.providers.openai}:{kind:"none",provider:"openai"};return Z}async function rxI(G,Z="request"){let b=await Cm(),Y={...b.modelAliases??{}},V=VQI(G.model??b.defaultModel,{...DK,...Y}),X=TK(V);if(X==="agy")throw Error("agy models are full-agent CLI sessions, not raw LLM calls; run the selected agy model through the explicit CLI bridge.");let R=S1.get(X),Q=G.baseUrl??(X==="openai"?b.openaiBaseUrl:void 0)??(X==="ollama"?b.ollamaBaseUrl:void 0)??(X==="lmstudio"?b.lmstudioBaseUrl:void 0),H={model:GwG(V),systemPrompt:G.systemPrompt,temperature:G.temperature??0.2,maxTokens:G.maxTokens??lwG(V,b.thinkingLevel),jsonMode:G.jsonMode,baseUrl:Q,numCtx:G.numCtx??(X==="ollama"?b.ollamaNumCtx:void 0),onUsage:G.onUsage,signal:G.signal,reasoningEffort:G.reasoningEffort==="none"?void 0:G.reasoningEffort??bwG(b.thinkingLevel),onReasoning:G.onReasoning,onReasoningArtifact:G.onReasoningArtifact,tools:G.tools,sessionKey:G.sessionKey},w={...YwG(b.retry,Z),...G.onRetry?{onRetry:G.onRetry}:{},...H.signal?{signal:H.signal}:{}};if(X==="ollama"||X==="lmstudio")return{adapter:R,callOptions:H,credential:{kind:"none",provider:"openai"},retry:w,provider:X,baseUrl:Q};if(X==="xai"){let p=b.providers?.xai;if(!p)throw Error("No credential for provider 'xai'. Set XAI_API_KEY (or providers.xai in config).");return{adapter:R,callOptions:H,credential:UJG(p),retry:w,provider:X,baseUrl:Q}}if(X==="antigravity"){let p=await P0("antigravity");if(p.kind!=="oauth")p=await P0("gemini");if(p.kind!=="oauth")throw Error("Antigravity models use Google OAuth. Run 'jeo auth login antigravity' (recommended) or 'jeo auth login gemini', then retry \u2014 the Google Cloud projectId is discovered automatically.");return{adapter:R,callOptions:H,credential:p,retry:w,provider:X,baseUrl:Q}}let C=X,A=await P0(C),y=VwG(C,A,b,V);if(X==="openai"&&Q&&G.baseUrl===void 0&&y.kind==="oauth"&&!b.providers.openai&&!kdI("openai",V,{openaiBaseUrl:Q})){G.signal?.throwIfAborted();let p=await i6(y);if(p&&!zaI(p)){let O=oxI.get(p);if(!O)O=rJG("openai",{config:b,codexCatalog:!0}),oxI.set(p,O),O.finally(()=>oxI.delete(p)).catch(()=>{});let K=G.signal;if(K){let a=Promise.withResolvers(),x=()=>a.reject(K.reason);K.addEventListener("abort",x,{once:!0});try{K.throwIfAborted(),await Promise.race([O,a.promise])}finally{K.removeEventListener("abort",x)}}else await O}if(G.signal?.throwIfAborted(),await i6()!==p)throw Error("OpenAI credential changed during model discovery; retry the request.");if(p&&zaI(p)&&kaI(V,p))Q=void 0,H.baseUrl=void 0}let k=X==="openai"&&!!Q;if(X==="openai"&&y.kind==="oauth"&&!k&&!t6("openai",V))throw Error(`OpenAI OAuth \uC790\uACA9\uC99D\uBA85\uC740 Codex \uBAA8\uB378(${_o.join("/")})\uB9CC \uC9C0\uC6D0. OPENAI_API_KEY\uB97C \uC124\uC815\uD558\uAC70\uB098 \uBAA8\uB378\uC744 \uBCC0\uACBD\uD558\uC138\uC694`);if(X==="kimi"&&y.kind==="oauth"&&!t6("kimi",V))throw Error(`Kimi OAuth (Kimi Code subscription) serves only the Kimi Code models (${zdI.join(", ")}). Set KIMI_API_KEY for Moonshot API models, or pick a Kimi Code model with /model.`);if(y.kind==="none"&&!k)throw Error(`No credential for provider '${X}'. Run 'jeo setup', 'jeo auth login', or set ${X.toUpperCase()}_API_KEY / ${X.toUpperCase()}_OAUTH_TOKEN.`);return{adapter:R,callOptions:H,credential:cwG(X,y,b,Q),retry:w,provider:X,baseUrl:Q}}function XwG(G,Z){return G?AbortSignal.any([G,Z]):Z}function eJG(G,Z){return XwG(G,AbortSignal.timeout(Z))}function cCZ(G){let Z,b=Date.now();return{promise:new Promise((V,X)=>{let R=()=>{let Q=Date.now(),H=G.deadlineAt!==void 0?G.deadlineAt-Q:1/0;if(H<=0){G.onIdle?.(),X(Error("stream exceeded the overall deadline (JEO_STREAM_MAX_MS) \u2014 slow-drip stream aborted"));return}let w=G.lastActivityAt?G.lastActivityAt():b,C=G.idleMs-(Q-w),A=Math.min(C,H);if(A<=0){G.onIdle?.(),X(Error(`stream idle for ${G.idleMs}ms (no chunk) \u2014 provider sent no token within the idle window (load or long thinking); retrying. Raise JEO_STREAM_IDLE_MS or lower the thinking level if this persists.`));return}Z=setTimeout(R,A)};R()}),cleanup:()=>clearTimeout(Z),touch:()=>{b=Date.now()}}}async function IwG(G,Z){if(!Z)return G.next();return Promise.race([G.next(),Z])}function RwG(G){let Z=$V("STREAM_MAX_MS",G);if(Z===void 0||Z==="")return exI;let b=parseInt(Z,10);if(!Number.isFinite(b)||b<0)return exI;return b===0?void 0:b}function FwG(G){let Z=$V("STREAM_IDLE_MS",G),b=Z!==void 0?parseInt(Z,10):NaN;return Number.isFinite(b)&&b>0?b:VCZ}function IKI(G){let Z=$V("CALL_TIMEOUT_MS",G),b=Z!==void 0?parseInt(Z,10):NaN;return Number.isFinite(b)&&b>0?b:exI}async function*dwG(G,Z,b){let Y=()=>{},V=()=>{};try{let{iter:X,first:R,watchdog:Q}=await XQI(async()=>{Y();let H=G(),w=b?cCZ(b):void 0;Y=w?.cleanup??(()=>{}),V=w?.touch??(()=>{});let C=await IwG(H,w?.promise);if(!C.done)V();return{iter:H,first:C,watchdog:w?.promise}},Z);if(!R.done){yield R.value;for(;;){let H=await IwG(X,Q);if(H.done)break;V(),yield H.value}}}finally{Y()}}function ZKI(){return{resolveProvider:TK,async call(G,Z={}){let{adapter:b,callOptions:Y,credential:V,retry:X,provider:R,baseUrl:Q}=await rxI(Z);return fxI(()=>XQI(()=>b.call(G,{...Y,signal:eJG(Y.signal,IKI())},V),X),R,Q)},async*stream(G,Z={}){let{adapter:b,callOptions:Y,credential:V,retry:X,provider:R,baseUrl:Q}=await rxI(Z,"stream");if(b.stream){let H=b.stream.bind(b),w=null,C=Date.now(),A=()=>{C=Date.now()},y=Y.onReasoning,k=Y.onReasoningStart,p={...Y,onReasoning:(a)=>{A(),y?.(a)},onReasoningStart:()=>{A(),k?.()},onStreamActivity:A},O=()=>{w=new AbortController;let a=XwG(Y.signal,w.signal);return H(G,{...p,signal:a},V)[Symbol.asyncIterator]()},K=RwG();try{yield*dwG(O,X,{idleMs:FwG(),...K!==void 0?{deadlineAt:Date.now()+K}:{},lastActivityAt:()=>C,onIdle:()=>w?.abort()})}catch(a){if(Qr(a))throw new mr(R,Q,a);throw a}}else yield await fxI(()=>XQI(()=>b.call(G,{...Y,signal:eJG(Y.signal,IKI())},V),X),R,Q)}}}var GCZ,bCZ=64000,NCZ=6,YCZ=2000,oxI,exI=1800000,VCZ=300000;var QQI=KW(()=>{PaI();_6();nh();Xr();TJG();qJG();UdI();fv();PxI();Dz();Hr();txI();dQI();GCZ={anthropic:"anthropic/",openai:"openai/",gemini:"google/",antigravity:"antigravity/",agy:"agy/",ollama:"ollama/",lmstudio:"lmstudio/",xai:"xai/",kimi:"kimi/"};oxI=new Map});var mwG=KW(()=>{fv()});var HwG=KW(()=>{Rr();YQI();Nr();KK();SxI();qxI();QQI();ixI();txI();dQI();fv();mwG()});async function o6(G,Z={}){if(!Z.onToken)return hwG.call(G,Z);let b="";for await(let Y of hwG.stream(G,Z)){b+=Y;try{Z.onToken(Y)}catch{}}return b}var hwG;var r6=KW(()=>{HwG();hwG=ZKI()});function SK(G){return G.replace(/\\/g,"/").replace(/^\.?\/+/,"").replace(/\.md$/i,"")}function RCZ(G){let Z=G.replace(/\\/g,"/"),b=Z.lastIndexOf("/");return b===-1?Z:Z.slice(b+1)}function lKI(G){let Z=RCZ(G).toLowerCase();return XCZ.includes(Z)}function Jr(G){return G.normalize("NFKD").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").replace(/-{2,}/g,"-")||"untitled"}function JwG(G){let Z=G.trim();if(Z.length>=2&&(Z[0]==='"'&&Z[Z.length-1]==='"'||Z[0]==="'"&&Z[Z.length-1]==="'"))return Z.slice(1,-1);return Z}function FCZ(G){let Z=G.trim();if(Z.length===0)return"";if(Z[0]==='"'&&Z[Z.length-1]==='"'||Z[0]==="'"&&Z[Z.length-1]==="'")return JwG(Z);if(Z==="true")return!0;if(Z==="false")return!1;if(/^-?\d+(\.\d+)?$/.test(Z)){let b=Number(Z);if(Number.isFinite(b))return b}return Z}function dCZ(G){let Z=G.trim();if(Z.startsWith("[")&&Z.endsWith("]")){let b=Z.slice(1,-1).trim();if(b==="")return[];return b.split(",").map((Y)=>JwG(Y.trim()))}return FCZ(Z)}function wr(G){let Z=G.split(`
68
68
  `);if(Z[0]?.trim()!=="---")return{frontmatter:{},body:G,hasFrontmatter:!1};let b=-1;for(let X=1;X<Z.length;X++)if(Z[X]?.trim()==="---"){b=X;break}if(b===-1)return{frontmatter:{},body:G,hasFrontmatter:!1};let Y={};for(let X=1;X<b;X++){let R=Z[X]??"",Q=R.trim();if(Q===""||Q.startsWith("#"))continue;let H=R.indexOf(":");if(H===-1)continue;let w=R.slice(0,H).trim();if(!w)continue;Y[w]=dCZ(R.slice(H+1))}let V=Z.slice(b+1).join(`
@@ -0,0 +1,84 @@
1
+ /**
2
+ * Session-start model resolution against the models jeo is actually logged in to.
3
+ *
4
+ * A session opens on the configured default model. That default is honored only
5
+ * when the stored login can serve it; otherwise the first turn would fail with
6
+ * "No credential for provider …" even though another logged-in model works. In that
7
+ * case the session starts on the first authenticated candidate (recents, then role
8
+ * tiers) and says so. The saved config is never rewritten here: the fallback is
9
+ * session-local, so the configured default is untouched.
10
+ *
11
+ * Fail-open: a probe that throws keeps the configured default.
12
+ */
13
+ import { describeModel, modelServableWithConfig } from "../ai/model-manager";
14
+ import { describeProvider } from "../ai/provider-status";
15
+ import { customProviderDef } from "../ai/providers/custom-providers";
16
+ import type { Config } from "./state";
17
+
18
+ export type ModelAuthCheck = (model: string, cfg: Config) => Promise<boolean>;
19
+
20
+ export interface StartupModel {
21
+ /** The model the session should treat as its default. */
22
+ model: string;
23
+ /** The configured default this replaced, when no login could serve it. */
24
+ fellBackFrom?: string;
25
+ /** One-line explanation for the user, present only when a fallback happened. */
26
+ notice?: string;
27
+ }
28
+
29
+ /**
30
+ * Whether jeo's stored credentials can serve `model` right now. Same two gates
31
+ * routing uses: the provider has a live credential, and, for built-in providers,
32
+ * that credential serves this specific model (ChatGPT OAuth serves only Codex ids).
33
+ * agy runs as an external CLI session and custom providers resolve their own key,
34
+ * so for those only provider readiness applies. Local providers are keyless.
35
+ */
36
+ export const isModelAuthenticated: ModelAuthCheck = async (model, cfg) => {
37
+ const { resolved, provider } = await describeModel(model, cfg);
38
+ const status = await describeProvider(provider, cfg);
39
+ if (!status.ready) return false;
40
+ if (provider === "agy" || customProviderDef(provider)) return true;
41
+ return modelServableWithConfig(provider, resolved, cfg);
42
+ };
43
+
44
+ const FALLBACK_ROLES = ["medium", "high", "smol", "xhigh", "slow", "plan"] as const;
45
+
46
+ /** Fallback order: the user's recently picked models, then their configured role tiers. */
47
+ function fallbackCandidates(cfg: Config): string[] {
48
+ const ordered = [...(cfg.recentModels ?? []), ...FALLBACK_ROLES.map(role => cfg.roles?.[role])];
49
+ const seen = new Set<string>([cfg.defaultModel]);
50
+ const out: string[] = [];
51
+ for (const model of ordered) {
52
+ if (typeof model !== "string" || !model.trim() || seen.has(model)) continue;
53
+ seen.add(model);
54
+ out.push(model);
55
+ }
56
+ return out;
57
+ }
58
+
59
+ /**
60
+ * Resolve the model a new session should open on: the configured default when the
61
+ * login serves it, else the first authenticated fallback, else the configured
62
+ * default unchanged (the first turn then reports the real credential error).
63
+ */
64
+ export async function resolveStartupDefaultModel(cfg: Config, check: ModelAuthCheck = isModelAuthenticated): Promise<StartupModel> {
65
+ const configured = cfg.defaultModel;
66
+ try {
67
+ if (await check(configured, cfg)) return { model: configured };
68
+ } catch {
69
+ return { model: configured };
70
+ }
71
+ for (const candidate of fallbackCandidates(cfg)) {
72
+ let ok = false;
73
+ try { ok = await check(candidate, cfg); } catch { ok = false; }
74
+ if (!ok) continue;
75
+ let provider = "its provider";
76
+ try { provider = (await describeModel(configured, cfg)).provider; } catch { /* keep the generic wording */ }
77
+ return {
78
+ model: candidate,
79
+ fellBackFrom: configured,
80
+ notice: `[model] default '${configured}' has no usable ${provider} login; this session starts on authenticated '${candidate}'. Run 'jeo auth login ${provider}' to restore it, or /model to pick another.`,
81
+ };
82
+ }
83
+ return { model: configured };
84
+ }
@@ -188,8 +188,6 @@ export async function runSessionSlash(input: string, ctx: SessionSlashCtx): Prom
188
188
  history.length = 1;
189
189
  for (const m of messages) history.push(m);
190
190
  sessionId = rid;
191
- // Restore the model this session was last using (per-session model).
192
- if (header.model) { sessionModel = header.model; sessionModelChanged = true; }
193
191
  // Restore the unsent input-box draft left over at last save, if any.
194
192
  if (header.draft) draft = header.draft;
195
193
 
@@ -66,6 +66,7 @@ import type { SandboxConfig, SandboxSupervisor } from "../agent/sandbox/types";
66
66
  import { runAgySessionTurn } from "./launch/agy-turn";
67
67
  import { listProviderModels } from "../ai/model-discovery";
68
68
  import { rememberModelPatch, recentModelsForDisplay } from "../agent/model-recency";
69
+ import { resolveStartupDefaultModel } from "../agent/session-model";
69
70
  import { describeModel, describeAllProviders, describeProvider, resolveProvider, thinkingMaxTokens, resolveMaxOutputTokens, thinkingToReasoningEffort, discoverModels, flattenModels, resolveSelection, catalogMetadata, catalogByProvider, liveProviderCatalogModels, resolveRoleModel, CODEX_MODELS, qualifyModelId, modelServableWithConfig, isLocalProviderReachable } from "../ai";
70
71
  import { rehydrateLiveModels, writeModelCache } from "../ai/model-cache";
71
72
  import type { ProviderModelsResult, PickEntry, ProviderName, ModelRole, ThinkLevel } from "../ai";
@@ -544,7 +545,6 @@ async function runLaunchSession(args: string[], registerEndpointCleanup?: (clean
544
545
  }
545
546
  } catch {}
546
547
  const cfg = await readGlobalConfig();
547
- const defaultModel = cfg.defaultModel;
548
548
  let initialSessionModel =
549
549
  flags.model ??
550
550
  (flags.modelRole ? resolveRoleModel(flags.modelRole, cfg) : flags.provider ? providerDefaultModel(flags.provider) : undefined);
@@ -564,6 +564,11 @@ async function runLaunchSession(args: string[], registerEndpointCleanup?: (clean
564
564
  return;
565
565
  }
566
566
  }
567
+ // A session always opens on the configured default model, or, when the stored login cannot
568
+ // serve it, on the first authenticated model (session-local; the saved default is untouched).
569
+ // An explicit --model/--model-role/--provider pin takes precedence and skips this.
570
+ const startupModel = initialSessionModel === undefined ? await resolveStartupDefaultModel(cfg) : { model: cfg.defaultModel, notice: undefined };
571
+ const defaultModel = startupModel.model;
567
572
 
568
573
  if (flags.tmux) {
569
574
  if (!process.env.TMUX && jeoEnv("TMUX_LAUNCHED") !== "1") {
@@ -987,7 +992,6 @@ async function runLaunchSession(args: string[], registerEndpointCleanup?: (clean
987
992
  const { header, messages } = await loadSession(id, cwd);
988
993
  for (const m of messages) history.push(m);
989
994
  sessionId = id;
990
- if (!initialSessionModel && header.model) sessionModel = header.model;
991
995
  const modelNote = sessionModel ? ` · model ${sessionModel}` : "";
992
996
  console.log(`Resumed session ${id} (${messages.length} messages).${modelNote}`);
993
997
  // Reproduce the prior screen exactly (gjc/gajae-code parity): a bare
@@ -1049,9 +1053,6 @@ async function runLaunchSession(args: string[], registerEndpointCleanup?: (clean
1049
1053
  const { header, messages } = await loadSession(id, cwd);
1050
1054
  for (const m of messages) history.push(m);
1051
1055
  sessionId = id;
1052
- // Restore the model this session was last using unless the CLI explicitly
1053
- // pinned one (flags.model/role/provider → initialSessionModel wins).
1054
- if (!initialSessionModel && header.model) sessionModel = header.model;
1055
1056
  // Restore the unsent input-box draft (gajae-code parity) — see
1056
1057
  // startupDraft's own doc comment for why this path can't feed
1057
1058
  // queuedPromptInput.partial directly yet.
@@ -2497,6 +2498,7 @@ async function runLaunchSession(args: string[], registerEndpointCleanup?: (clean
2497
2498
  };
2498
2499
 
2499
2500
  if (isOneShot) {
2501
+ if (startupModel.notice) console.error(startupModel.notice);
2500
2502
  // A one-shot run has ~17 exit points below. The session notify endpoint (a
2501
2503
  // listening socket + a discovery file the Telegram daemon polls) is created for
2502
2504
  // the WHOLE launch lifetime up at `startSessionNotifyEndpoint`, but its teardown
@@ -2843,6 +2845,7 @@ async function runLaunchSession(args: string[], registerEndpointCleanup?: (clean
2843
2845
  if (sweepable) await playWelcomeSweep(welcomeData, { cycles: sweepCycles });
2844
2846
  else console.log(renderWelcome(welcomeData).join("\n"));
2845
2847
  }
2848
+ if (startupModel.notice) console.log(chalk.yellow(startupModel.notice));
2846
2849
 
2847
2850
 
2848
2851