jeo-code 0.12.24 → 0.12.25
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 +7 -1
- package/README.ja.md +1 -1
- package/README.ko.md +1 -1
- package/README.md +1 -1
- package/README.zh.md +1 -1
- package/package.json +1 -1
- package/src/agent/sandbox/hands-source.text +1 -1
- package/src/util/shared-global.ts +5 -7
package/CHANGELOG.md
CHANGED
|
@@ -9,6 +9,11 @@ The README mirrors the latest 5 entries — regenerate with `bun run changelog:s
|
|
|
9
9
|
|
|
10
10
|
## [Unreleased]
|
|
11
11
|
|
|
12
|
+
## [0.12.25] - 2026-11-06
|
|
13
|
+
|
|
14
|
+
### Changed
|
|
15
|
+
- **`jeo update` no longer special-cases another tool** - the `shared global unchanged: N packages (...)` line used to list `jeopi-cli` first; it now lists every other package in plain ascending order, at most three shown.
|
|
16
|
+
|
|
12
17
|
## [0.12.24] - 2026-11-06
|
|
13
18
|
|
|
14
19
|
### Added
|
|
@@ -2757,7 +2762,8 @@ _Initial release._
|
|
|
2757
2762
|
### Added
|
|
2758
2763
|
- Initial jeo-code agent and CLI.
|
|
2759
2764
|
|
|
2760
|
-
[Unreleased]: https://github.com/akillness/jeo-code/compare/v0.12.
|
|
2765
|
+
[Unreleased]: https://github.com/akillness/jeo-code/compare/v0.12.25...HEAD
|
|
2766
|
+
[0.12.25]: https://github.com/akillness/jeo-code/releases/tag/v0.12.25
|
|
2761
2767
|
[0.12.24]: https://github.com/akillness/jeo-code/releases/tag/v0.12.24
|
|
2762
2768
|
[0.12.23]: https://github.com/akillness/jeo-code/releases/tag/v0.12.23
|
|
2763
2769
|
[0.12.22]: https://github.com/akillness/jeo-code/compare/v0.12.21...v0.12.22
|
package/README.ja.md
CHANGED
|
@@ -462,10 +462,10 @@ CI は `.github/workflows/npm-publish.yml` で公開します — GitHub リリ
|
|
|
462
462
|
|
|
463
463
|
<!-- CHANGELOG:START (auto-generated from CHANGELOG.md — run `bun run changelog:sync`) -->
|
|
464
464
|
- **[Unreleased]**
|
|
465
|
+
- **[0.12.25]** (2026-11-06)
|
|
465
466
|
- **[0.12.24]** (2026-11-06)
|
|
466
467
|
- **[0.12.23]** (2026-11-06)
|
|
467
468
|
- **[0.12.22]** (2026-11-04)
|
|
468
|
-
- **[0.12.21]** (2026-11-04)
|
|
469
469
|
|
|
470
470
|
See [CHANGELOG.md](CHANGELOG.md) for the full history.
|
|
471
471
|
<!-- CHANGELOG:END -->
|
package/README.ko.md
CHANGED
|
@@ -517,10 +517,10 @@ CI는 `.github/workflows/npm-publish.yml`로 배포합니다 — GitHub 릴리
|
|
|
517
517
|
|
|
518
518
|
<!-- CHANGELOG:START (auto-generated from CHANGELOG.md — run `bun run changelog:sync`) -->
|
|
519
519
|
- **[Unreleased]**
|
|
520
|
+
- **[0.12.25]** (2026-11-06)
|
|
520
521
|
- **[0.12.24]** (2026-11-06)
|
|
521
522
|
- **[0.12.23]** (2026-11-06)
|
|
522
523
|
- **[0.12.22]** (2026-11-04)
|
|
523
|
-
- **[0.12.21]** (2026-11-04)
|
|
524
524
|
|
|
525
525
|
See [CHANGELOG.md](CHANGELOG.md) for the full history.
|
|
526
526
|
<!-- CHANGELOG:END -->
|
package/README.md
CHANGED
|
@@ -506,10 +506,10 @@ Huge thanks to [gajae-code](https://github.com/Yeachan-Heo/gajae-code) for the i
|
|
|
506
506
|
|
|
507
507
|
<!-- CHANGELOG:START (auto-generated from CHANGELOG.md — run `bun run changelog:sync`) -->
|
|
508
508
|
- **[Unreleased]**
|
|
509
|
+
- **[0.12.25]** (2026-11-06)
|
|
509
510
|
- **[0.12.24]** (2026-11-06)
|
|
510
511
|
- **[0.12.23]** (2026-11-06)
|
|
511
512
|
- **[0.12.22]** (2026-11-04)
|
|
512
|
-
- **[0.12.21]** (2026-11-04)
|
|
513
513
|
|
|
514
514
|
See [CHANGELOG.md](CHANGELOG.md) for the full history.
|
|
515
515
|
<!-- CHANGELOG:END -->
|
package/README.zh.md
CHANGED
|
@@ -460,10 +460,10 @@ CI 通过 `.github/workflows/npm-publish.yml` 发布 — GitHub 发布 release
|
|
|
460
460
|
|
|
461
461
|
<!-- CHANGELOG:START (auto-generated from CHANGELOG.md — run `bun run changelog:sync`) -->
|
|
462
462
|
- **[Unreleased]**
|
|
463
|
+
- **[0.12.25]** (2026-11-06)
|
|
463
464
|
- **[0.12.24]** (2026-11-06)
|
|
464
465
|
- **[0.12.23]** (2026-11-06)
|
|
465
466
|
- **[0.12.22]** (2026-11-04)
|
|
466
|
-
- **[0.12.21]** (2026-11-04)
|
|
467
467
|
|
|
468
468
|
See [CHANGELOG.md](CHANGELOG.md) for the full history.
|
|
469
469
|
<!-- CHANGELOG:END -->
|
package/package.json
CHANGED
|
@@ -62,7 +62,7 @@ button:hover{background:#1b1c27}
|
|
|
62
62
|
<script>__SCRIPT__</script>
|
|
63
63
|
</body></html>`});async function chG(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 XhG(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 ixI(G){return new RhG(G).login()}async function sxI(G){let Z=await chG(VhG,{grant_type:"refresh_token",client_id:fxI,refresh_token:G});return{...XhG(Z),refresh:Z.refresh_token||G}}var qEZ=(G)=>atob(G),fxI,PEZ="https://claude.ai/oauth/authorize",VhG="https://api.anthropic.com/v1/oauth/token",$EZ=54545,_EZ="/callback",fEZ="org:create_api_key user:profile user:inference",RhG;var txI=xW(()=>{lr();fxI=qEZ("OWQxYzI1MGEtZTYxYi00NGQ5LTg4ZWQtNTk0NGQxOTYyZjVl");RhG=class RhG extends $z{#I="";constructor(G){super(G,{preferredPort:$EZ,callbackPath:_EZ})}async generateAuthUrl(G,Z){let b=await TdI();this.#I=b.verifier;let Y=new URLSearchParams({code:"true",client_id:fxI,response_type:"code",redirect_uri:Z,scope:fEZ,code_challenge:b.challenge,code_challenge_method:"S256",state:G});return{url:`${PEZ}?${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 chG(VhG,{grant_type:"authorization_code",client_id:fxI,code:Y,state:V,redirect_uri:b,code_verifier:this.#I});return XhG(R)}}});function W5Z(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 QhG(G){let Z=W5Z(G),b=Z?.[tEZ]?.chatgpt_account_id,Y=Z?.[oEZ]?.email?.trim?.().toLowerCase?.();return{accountId:typeof b==="string"&&b?b:void 0,email:typeof Y==="string"&&Y?Y:void 0}}async function mhG(G,Z,b){let Y=await fetch(dhG,{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}=QhG(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 rxI(G){try{return await new HhG(G).login()}catch(Z){if(Z instanceof SdI)return G.onProgress?.(`Port ${oxI} is busy \u2014 falling back to device-code login.`),N5Z(G);throw Z}}async function N5Z(G){G.onProgress?.("Initiating device authorization\u2026");let Z=await fetch(rEZ,{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+l5Z;G.onAuth?.({url:G5Z,instructions:`Enter code: ${Y}`}),G.onProgress?.(`Waiting for browser authorization (code: ${Y})\u2026`);for(let X=0;X<b5Z;X++){if(await Bun.sleep(X===0?Math.min(V,Z5Z):V),G.signal?.aborted)throw Error("Device authorization cancelled");let R=await fetch(eEZ,{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"),mhG(Q.authorization_code,Q.code_verifier,I5Z)}throw Error("Device authorization timed out \u2014 user did not complete login in time")}async function exI(G){let Z=await fetch(dhG,{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}=QhG(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",iEZ="https://auth.openai.com/oauth/authorize",dhG="https://auth.openai.com/oauth/token",oxI=1455,FhG="/auth/callback",sEZ="openid profile email offline_access",ndI=15000,tEZ="https://api.openai.com/auth",oEZ="https://api.openai.com/profile",rEZ="https://auth.openai.com/api/accounts/deviceauth/usercode",eEZ="https://auth.openai.com/api/accounts/deviceauth/token",I5Z="https://auth.openai.com/deviceauth/callback",G5Z="https://auth.openai.com/codex/device",Z5Z=5000,l5Z=3000,b5Z=120,HhG;var IaI=xW(()=>{lr();HhG=class HhG extends $z{#I="";constructor(G){super(G,{preferredPort:oxI,callbackPath:FhG,redirectUri:`http://localhost:${oxI}${FhG}`})}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:sEZ,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:`${iEZ}?${Y.toString()}`,instructions:"Complete login in your browser."}}async exchangeToken(G,Z,b){return mhG(G,this.#I,b)}}});var JhG={};X3(JhG,{discoverGoogleProjectId:()=>xK,ANTIGRAVITY_DISCOVERY_METADATA:()=>br});function V5Z(G,Z){let b=AbortSignal.timeout(Z);if(!G)return b;return typeof AbortSignal.any==="function"?AbortSignal.any([G,b]):b}function hhG(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 c5Z(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 X5Z(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 xK(G,Z={}){let b=Z.fetchImpl??fetch,Y=Z.sleep??((a)=>new Promise((S)=>setTimeout(S,a))),V=Z.env??process.env,X=Z.maxPollAttempts??5,R=V.GOOGLE_CLOUD_PROJECT||V.GOOGLE_CLOUD_PROJECT_ID||void 0,Q=Z.metadata??Y5Z,H=Z.requestTimeoutMs??30000,w=()=>V5Z(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 a;try{a=await A.clone().json()}catch{a=void 0}if(X5Z(a))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 a=hhG(y.cloudaicompanionProject)??R;if(a)return a;if(!Z.alwaysOnboard)throw Error(GaI)}let k=c5Z(y.allowedTiers)||"free-tier";if(!Z.alwaysOnboard&&k!=="free-tier"&&k!=="legacy-tier"&&!R)throw Error(GaI);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 a=1;!K.done&&K.name&&a<=X;a++){Z.onProgress?.(`Waiting for project provisioning (attempt ${a}/${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 x=hhG(K.response?.cloudaicompanionProject)??R;if(x)return x;throw Error(`Cloud Code Assist did not return a provisioned project id${K.done?"":` after ${X} attempts`}. ${GaI}`)}var Y5Z,br,GaI="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=xW(()=>{Y5Z=Object.freeze({ideType:"IDE_UNSPECIFIED",platform:"PLATFORM_UNSPECIFIED",pluginType:"GEMINI"}),br=Object.freeze({ideType:"ANTIGRAVITY",platform:"PLATFORM_UNSPECIFIED",pluginType:"GEMINI"})});async function*ZaI(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*iv(G,Z){for await(let b of ZaI(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 aK)return new aK(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 laI(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 baI(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=laI(Z.headers.get("retry-after"))??baI(Y);return new aK(G,Z.status,Y,b,V)}var aK,Uw;var WA=xW(()=>{aK=class aK 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 WaI(G,new WeakMap)}function WaI(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(WaI(X,Z));return V}let Y={};Z.set(G,Y);for(let[V,X]of Object.entries(G))Y[V.toWellFormed()]=WaI(X,Z);return Y}var UhG={};X3(UhG,{resolveAntigravityProjectId:()=>$dI,getAntigravityUserAgent:()=>qp,antigravityRequest:()=>ghG,antigravityAdapter:()=>_dI});import{randomUUID as R5Z}from"crypto";function d5Z(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 phG(G){return G.replace(/^antigravity\//,"")}function khG(G){let Z=phG(G.model);if(Z.toLowerCase().includes("claude")){let b=d5Z(G.reasoningEffort);return b===void 0?void 0:{includeThoughts:!0,thinkingBudget:b}}return fdI(Z,G.reasoningEffort)}function m5Z(G){let Z=khG(G);return Z!==void 0&&(("thinkingLevel"in Z)||Z.thinkingBudget>0)}function zhG(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=zhG(G);if(b)return b;let Y=whG.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(),JhG));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\`.`)}whG.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 H5Z(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 h5Z(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 ghG(G,Z,b,Y=uhG,V){if(b.kind!=="oauth")throw Error("Antigravity provider requires Google/Gemini CLI OAuth credentials.");let X=V??zhG(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=phG(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=khG(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:H5Z(G),sessionId:h5Z(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-${R5Z()}`}));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 EhG(G){let Z=G.error;if(!Z)return;throw new Uw("Antigravity",Z.message??"unknown error",Z.status,Z.code)}function vhG(G){let Z=G.response?.candidates?.[0]?.finishReason;if(Z&&Z!=="STOP")return`finishReason=${Z}`;return}function ChG(G){return G.response?.candidates?.[0]?.content?.parts?.filter((Z)=>!Z.thought).map((Z)=>Z.text??"").join("")??""}function yhG(G){return G.response?.candidates?.[0]?.content?.parts?.filter((Z)=>Z.thought).map((Z)=>Z.text??"").join("")??""}function LhG(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 AhG(G,Z,b){let Y=await $dI(b,{signal:Z.signal}),V;for(let X of Q5Z){let{url:R,headers:Q,body:H}=ghG(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 uhG="https://daily-cloudcode-pa.googleapis.com",F5Z="https://daily-cloudcode-pa.sandbox.googleapis.com",Q5Z,whG,_dI;var KK=xW(()=>{WA();vK();Nr();nh();Q5Z=[uhG,F5Z];whG=new Map;_dI={name:"antigravity",supportsNativeTools:!0,async call(G,Z,b){let Y=await AhG(G,Z,b);if(!Y.body)return"";let V="",X,R,Q=!1,H=[];for await(let C of iv(Y.body)){let A;try{A=JSON.parse(C)}catch{continue}EhG(A);let y=yhG(A);if(y)Z.onReasoning?.(y);let k=ChG(A);if(k)V+=k;if(R=vhG(A)??R,A.response?.candidates?.[0]?.finishReason)Q=!0;if(H.push(...LhG(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 AhG(G,Z,b);if(!Y.body)return;if(m5Z(Z))Z.onReasoningStart?.();let V=!1,X,R,Q=!1,H=[];for await(let C of iv(Y.body,Z.onStreamActivity)){let A;try{A=JSON.parse(C)}catch{continue}EhG(A);let y=yhG(A);if(y)Z.onReasoning?.(y);let k=ChG(A);if(k)V=!0,yield k;if(R=vhG(A)??R,A.response?.candidates?.[0]?.finishReason)Q=!0;if(H.push(...LhG(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 J5Z(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??xhG(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 xhG(G){return G.includes("-high")?"high":G.includes("-medium")?"medium":G.includes("-low")?"low":G.includes("thinking")?"medium":void 0}function w5Z(G){let Z=G.toLowerCase().match(/gemini-(\d+)(?:\.(\d+))?/);return!!Z&&Number(Z[1])===3}function E5Z(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(w5Z(G)){let V=Z??xhG(G.toLowerCase());if(V===void 0)return;return{includeThoughts:!0,thinkingLevel:E5Z(V)}}let Y=J5Z(G,Z,b);return Y===void 0?void 0:{includeThoughts:!0,thinkingBudget:Y}}function ahG(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 BhG(G,Z,b){return b&&!!G.toolUse?.length&&!!G.reasoningArtifacts?.some((Y)=>Y.provider==="gemini"&&Y.model===Z&&!!Y.thoughtSignature)}function KhG(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"&&BhG(y,Z.model,Q)){let x=y.reasoningArtifacts.find((a)=>a.provider==="gemini"&&a.model===Z.model&&a.thoughtSignature)?.thoughtSignature;O=y.toolUse.map((a,S)=>{let n={functionCall:{name:a.tool,args:a.arguments}};if(S===0&&x)n.thoughtSignature=x;return n})}else if(y.role==="user"&&y.toolResults?.length&&k>0&&H[k-1].role==="assistant"&&BhG(H[k-1],Z.model,Q)){let x=H[k-1].toolUse??[];if(O=y.toolResults.map((a)=>({functionResponse:{name:x.find((S)=>S.id===a.id)?.tool??"tool",response:{output:a.output}}})),y.toolResultExtra)O.push({text:y.toolResultExtra})}else O=[...y.images?.map((x)=>({inlineData:{mimeType:x.mediaType,data:x.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 OhG(G,Z,b,Y,V=!1){let{geminiModel:X,payload:R}=KhG(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 caI(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 C5Z(G,Z,b,Y,V=!1){let{geminiModel:X,payload:R}=KhG(G,Z,V);return{url:`${v5Z}/v1internal:streamGenerateContent?alt=sse`,headers:{authorization:`Bearer ${b}`,"content-type":"application/json",accept:"text/event-stream",...caI(X)},body:JSON.stringify(l5({project:Y,model:X,request:R}))}}function NaI(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 idI(G){return G.candidates?.[0]?.content?.parts?.filter((Z)=>!Z.thought).map((Z)=>Z.text??"").join("")??""}function jhG(G){return G.candidates?.[0]?.content?.parts?.filter((Z)=>Z.thought).map((Z)=>Z.text??"").join("")??""}function YaI(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 sdI(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 VaI(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 DhG(G,Z){if(!Z)return;throw new Uw(G,Z.message??"unknown error",Z.status,Z.code)}async function*MhG(G,Z,b){let{resolveAntigravityProjectId:Y}=await Promise.resolve().then(() => (KK(),UhG)),V=await Y(b,{signal:Z.signal}),X=await NaI((k)=>C5Z(G,Z,b.token,V,k),Z.signal);if(!X.ok)throw await n1("Gemini (Cloud Code Assist)",X);if(!X.body)return;if(ahG(Z))Z.onReasoningStart?.();let R,Q=!1,H,w=!1,C=[],A=new Set;for await(let k of iv(X.body,Z.onStreamActivity)){let p;try{p=JSON.parse(k)}catch{continue}DhG("Gemini (Cloud Code Assist)",p.error);let O=p.response;if(!O)continue;let K=jhG(O);if(K)Z.onReasoning?.(K);YaI(O,Z,A);let x=idI(O);if(x)Q=!0,yield x;if(H=VaI(O)??H,O.candidates?.[0]?.finishReason)w=!0;if(O.usageMetadata)R=O.usageMetadata;C.push(...sdI(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 v5Z="https://cloudcode-pa.googleapis.com",XaI;var Nr=xW(()=>{WA();vK();XaI={name:"gemini",supportsNativeTools:!0,async call(G,Z,b){if(b.kind==="oauth"){let H="";for await(let w of MhG(G,Z,b))H+=w;return H}let Y=await NaI((H)=>OhG(G,Z,b,"generateContent",H),Z.signal);if(!Y.ok)throw await n1("Gemini",Y);let V=await Y.json();if(YaI(V,Z,new Set),V.usageMetadata)Z.onUsage?.({inputTokens:V.usageMetadata.promptTokenCount,outputTokens:V.usageMetadata.candidatesTokenCount});let X=VaI(V);if(X){let H=!!idI(V)||sdI(V).length>0;throw Error(H?`Gemini response incomplete (${X.replace(" before any text","")}).`:`Gemini returned no content (${X}).`)}let R=r4(sdI(V));if(R)return R;return idI(V)},async*stream(G,Z,b){if(b.kind==="oauth"){yield*MhG(G,Z,b);return}let Y=await NaI((A)=>OhG(G,Z,b,"streamGenerateContent",A),Z.signal);if(!Y.ok)throw await n1("Gemini",Y,"(stream)");if(!Y.body)return;if(ahG(Z))Z.onReasoningStart?.();let V,X,R=!1,Q=!1,H=[],w=new Set;for await(let A of iv(Y.body,Z.onStreamActivity)){let y;try{y=JSON.parse(A)}catch{continue}DhG("Gemini",y.error);let k=jhG(y);if(k)Z.onReasoning?.(k);YaI(y,Z,w);let p=idI(y);if(p)Q=!0,yield p;if(X=VaI(y)??X,y.candidates?.[0]?.finishReason)R=!0;if(y.usageMetadata)V=y.usageMetadata;H.push(...sdI(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 y5Z(G,Z={}){return xK(G,{extraHeaders:caI(),onProgress:Z.onProgress})}function ShG(G=process.env){return G.GEMINI_OAUTH_CLIENT_SECRET||ThG(L5Z)}async function z5Z(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 FaI(G){return new qhG(G).login()}async function daI(G){let Z=await fetch(nhG,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:RaI,client_secret:ShG(),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 ThG=(G)=>atob(G),RaI,L5Z,A5Z="https://accounts.google.com/o/oauth2/v2/auth",nhG="https://oauth2.googleapis.com/token",u5Z=8085,p5Z="/oauth2callback",k5Z,qhG;var QaI=xW(()=>{lr();Wr();Nr();RaI=ThG(["NjgxMjU1ODA5Mzk1","LW9vOGZ0Mm9wcmRy","bnA5ZTNhcWY2YXYz","aG1kaWIxMzVqLmFw","cHMuZ29vZ2xldXNl","cmNvbnRlbnQuY29t"].join("")),L5Z=["R09DU1BYLTR1SGdN","UG0tMW83U2stZ2VW","NkN1NWNsWEZzeGw="].join("");k5Z=["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/userinfo.email","https://www.googleapis.com/auth/userinfo.profile"];qhG=class qhG extends $z{constructor(G){super(G,{preferredPort:u5Z,callbackPath:p5Z})}async generateAuthUrl(G,Z){let b=new URLSearchParams({client_id:RaI,response_type:"code",redirect_uri:Z,scope:k5Z.join(" "),state:G,access_type:"offline",prompt:"consent"});return{url:`${A5Z}?${b.toString()}`,instructions:"Complete the 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:RaI,client_secret:ShG(),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 z5Z(V.access_token),R=process.env.GOOGLE_CLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT_ID||void 0;if(!R)try{R=await y5Z(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 HaI(G=process.env){return G.ANTIGRAVITY_OAUTH_CLIENT_SECRET||PhG(g5Z)}function _hG(G,Z={}){return xK(G,{metadata:{...br},extraHeaders:{"User-Agent":qp()},alwaysOnboard:!0,onProgress:Z.onProgress})}async function x5Z(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 haI(G){return new fhG(G).login()}async function JaI(G){let Z=await fetch($hG,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:maI,client_secret:HaI(),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 PhG=(G)=>atob(G),maI,g5Z,U5Z="https://accounts.google.com/o/oauth2/v2/auth",$hG="https://oauth2.googleapis.com/token",B5Z=51121,O5Z="/oauth-callback",M5Z,fhG;var waI=xW(()=>{lr();Wr();KK();maI=PhG(["MTA3MTAwNjA2MDU5MS10","bWhzc2luMmgyMWxjcmUy","MzV2dG9sb2poNGc0MDNl","cC5hcHBzLmdvb2dsZXVz","ZXJjb250ZW50LmNvbQ=="].join("")),g5Z=["R09DU1BYLUs1OEZX","UjQ4NkxkTEoxbUxC","OHNYQzR6NnFEQWY="].join("");M5Z=["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"];fhG=class fhG extends $z{constructor(G){super(G,{preferredPort:B5Z,callbackPath:O5Z})}async generateAuthUrl(G,Z){let b=new URLSearchParams({client_id:maI,response_type:"code",redirect_uri:Z,scope:M5Z.join(" "),state:G,access_type:"offline",prompt:"consent"});return{url:`${U5Z}?${b.toString()}`,instructions:"Complete the Antigravity sign-in in your browser."}}async exchangeToken(G,Z,b){let Y=await fetch($hG,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:maI,client_secret:HaI(),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 x5Z(V.access_token),R=process.env.GOOGLE_CLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT_ID||void 0;if(!R)try{R=await _hG(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 EaI=xW(()=>{Yr={name:"jeo-code",version:"0.12.24",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:shared-global":"bun scripts/verify-shared-global-isolation.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 ihG from"crypto";import*as $6 from"fs";import*as e4 from"os";import*as yaI from"path";function AaI(){return process.env.KIMI_CODE_OAUTH_HOST||process.env.KIMI_OAUTH_HOST||K5Z}function vaI(G,Z,b){return[G,Z,b].filter(Boolean).join(" ").trim()}function n5Z(){let G=e4.platform(),Z=e4.release(),b=e4.arch();if(G==="darwin")return vaI("macOS",Z,b);if(G==="win32")return vaI("Windows",Z,b);return vaI(G==="linux"?"Linux":G,Z,b)}function q5Z(){let G=$V("CONFIG_DIR")||yaI.join(e4.homedir(),".jeo"),Z=yaI.join(G,j5Z),b=CaI.get(Z);if(b)return b;try{let V=$6.readFileSync(Z,"utf-8").trim();if(V)return CaI.set(Z,V),V}catch(V){if(V?.code!=="ENOENT")throw V}let Y=ihG.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*iv(G,Z){for await(let b of ZaI(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 aK)return new aK(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 laI(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 baI(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=laI(Z.headers.get("retry-after"))??baI(Y);return new aK(G,Z.status,Y,b,V)}var aK,Uw;var WA=xW(()=>{aK=class aK 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 WaI(G,new WeakMap)}function WaI(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(WaI(X,Z));return V}let Y={};Z.set(G,Y);for(let[V,X]of Object.entries(G))Y[V.toWellFormed()]=WaI(X,Z);return Y}var UhG={};X3(UhG,{resolveAntigravityProjectId:()=>$dI,getAntigravityUserAgent:()=>qp,antigravityRequest:()=>ghG,antigravityAdapter:()=>_dI});import{randomUUID as R5Z}from"crypto";function d5Z(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 phG(G){return G.replace(/^antigravity\//,"")}function khG(G){let Z=phG(G.model);if(Z.toLowerCase().includes("claude")){let b=d5Z(G.reasoningEffort);return b===void 0?void 0:{includeThoughts:!0,thinkingBudget:b}}return fdI(Z,G.reasoningEffort)}function m5Z(G){let Z=khG(G);return Z!==void 0&&(("thinkingLevel"in Z)||Z.thinkingBudget>0)}function zhG(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=zhG(G);if(b)return b;let Y=whG.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(),JhG));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\`.`)}whG.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 H5Z(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 h5Z(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 ghG(G,Z,b,Y=uhG,V){if(b.kind!=="oauth")throw Error("Antigravity provider requires Google/Gemini CLI OAuth credentials.");let X=V??zhG(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=phG(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=khG(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:H5Z(G),sessionId:h5Z(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-${R5Z()}`}));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 EhG(G){let Z=G.error;if(!Z)return;throw new Uw("Antigravity",Z.message??"unknown error",Z.status,Z.code)}function vhG(G){let Z=G.response?.candidates?.[0]?.finishReason;if(Z&&Z!=="STOP")return`finishReason=${Z}`;return}function ChG(G){return G.response?.candidates?.[0]?.content?.parts?.filter((Z)=>!Z.thought).map((Z)=>Z.text??"").join("")??""}function yhG(G){return G.response?.candidates?.[0]?.content?.parts?.filter((Z)=>Z.thought).map((Z)=>Z.text??"").join("")??""}function LhG(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 AhG(G,Z,b){let Y=await $dI(b,{signal:Z.signal}),V;for(let X of Q5Z){let{url:R,headers:Q,body:H}=ghG(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 uhG="https://daily-cloudcode-pa.googleapis.com",F5Z="https://daily-cloudcode-pa.sandbox.googleapis.com",Q5Z,whG,_dI;var KK=xW(()=>{WA();vK();Nr();nh();Q5Z=[uhG,F5Z];whG=new Map;_dI={name:"antigravity",supportsNativeTools:!0,async call(G,Z,b){let Y=await AhG(G,Z,b);if(!Y.body)return"";let V="",X,R,Q=!1,H=[];for await(let C of iv(Y.body)){let A;try{A=JSON.parse(C)}catch{continue}EhG(A);let y=yhG(A);if(y)Z.onReasoning?.(y);let k=ChG(A);if(k)V+=k;if(R=vhG(A)??R,A.response?.candidates?.[0]?.finishReason)Q=!0;if(H.push(...LhG(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 AhG(G,Z,b);if(!Y.body)return;if(m5Z(Z))Z.onReasoningStart?.();let V=!1,X,R,Q=!1,H=[];for await(let C of iv(Y.body,Z.onStreamActivity)){let A;try{A=JSON.parse(C)}catch{continue}EhG(A);let y=yhG(A);if(y)Z.onReasoning?.(y);let k=ChG(A);if(k)V=!0,yield k;if(R=vhG(A)??R,A.response?.candidates?.[0]?.finishReason)Q=!0;if(H.push(...LhG(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 J5Z(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??xhG(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 xhG(G){return G.includes("-high")?"high":G.includes("-medium")?"medium":G.includes("-low")?"low":G.includes("thinking")?"medium":void 0}function w5Z(G){let Z=G.toLowerCase().match(/gemini-(\d+)(?:\.(\d+))?/);return!!Z&&Number(Z[1])===3}function E5Z(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(w5Z(G)){let V=Z??xhG(G.toLowerCase());if(V===void 0)return;return{includeThoughts:!0,thinkingLevel:E5Z(V)}}let Y=J5Z(G,Z,b);return Y===void 0?void 0:{includeThoughts:!0,thinkingBudget:Y}}function ahG(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 BhG(G,Z,b){return b&&!!G.toolUse?.length&&!!G.reasoningArtifacts?.some((Y)=>Y.provider==="gemini"&&Y.model===Z&&!!Y.thoughtSignature)}function KhG(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"&&BhG(y,Z.model,Q)){let x=y.reasoningArtifacts.find((a)=>a.provider==="gemini"&&a.model===Z.model&&a.thoughtSignature)?.thoughtSignature;O=y.toolUse.map((a,S)=>{let n={functionCall:{name:a.tool,args:a.arguments}};if(S===0&&x)n.thoughtSignature=x;return n})}else if(y.role==="user"&&y.toolResults?.length&&k>0&&H[k-1].role==="assistant"&&BhG(H[k-1],Z.model,Q)){let x=H[k-1].toolUse??[];if(O=y.toolResults.map((a)=>({functionResponse:{name:x.find((S)=>S.id===a.id)?.tool??"tool",response:{output:a.output}}})),y.toolResultExtra)O.push({text:y.toolResultExtra})}else O=[...y.images?.map((x)=>({inlineData:{mimeType:x.mediaType,data:x.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 OhG(G,Z,b,Y,V=!1){let{geminiModel:X,payload:R}=KhG(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 caI(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 C5Z(G,Z,b,Y,V=!1){let{geminiModel:X,payload:R}=KhG(G,Z,V);return{url:`${v5Z}/v1internal:streamGenerateContent?alt=sse`,headers:{authorization:`Bearer ${b}`,"content-type":"application/json",accept:"text/event-stream",...caI(X)},body:JSON.stringify(l5({project:Y,model:X,request:R}))}}function NaI(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 idI(G){return G.candidates?.[0]?.content?.parts?.filter((Z)=>!Z.thought).map((Z)=>Z.text??"").join("")??""}function jhG(G){return G.candidates?.[0]?.content?.parts?.filter((Z)=>Z.thought).map((Z)=>Z.text??"").join("")??""}function YaI(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 sdI(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 VaI(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 DhG(G,Z){if(!Z)return;throw new Uw(G,Z.message??"unknown error",Z.status,Z.code)}async function*MhG(G,Z,b){let{resolveAntigravityProjectId:Y}=await Promise.resolve().then(() => (KK(),UhG)),V=await Y(b,{signal:Z.signal}),X=await NaI((k)=>C5Z(G,Z,b.token,V,k),Z.signal);if(!X.ok)throw await n1("Gemini (Cloud Code Assist)",X);if(!X.body)return;if(ahG(Z))Z.onReasoningStart?.();let R,Q=!1,H,w=!1,C=[],A=new Set;for await(let k of iv(X.body,Z.onStreamActivity)){let p;try{p=JSON.parse(k)}catch{continue}DhG("Gemini (Cloud Code Assist)",p.error);let O=p.response;if(!O)continue;let K=jhG(O);if(K)Z.onReasoning?.(K);YaI(O,Z,A);let x=idI(O);if(x)Q=!0,yield x;if(H=VaI(O)??H,O.candidates?.[0]?.finishReason)w=!0;if(O.usageMetadata)R=O.usageMetadata;C.push(...sdI(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 v5Z="https://cloudcode-pa.googleapis.com",XaI;var Nr=xW(()=>{WA();vK();XaI={name:"gemini",supportsNativeTools:!0,async call(G,Z,b){if(b.kind==="oauth"){let H="";for await(let w of MhG(G,Z,b))H+=w;return H}let Y=await NaI((H)=>OhG(G,Z,b,"generateContent",H),Z.signal);if(!Y.ok)throw await n1("Gemini",Y);let V=await Y.json();if(YaI(V,Z,new Set),V.usageMetadata)Z.onUsage?.({inputTokens:V.usageMetadata.promptTokenCount,outputTokens:V.usageMetadata.candidatesTokenCount});let X=VaI(V);if(X){let H=!!idI(V)||sdI(V).length>0;throw Error(H?`Gemini response incomplete (${X.replace(" before any text","")}).`:`Gemini returned no content (${X}).`)}let R=r4(sdI(V));if(R)return R;return idI(V)},async*stream(G,Z,b){if(b.kind==="oauth"){yield*MhG(G,Z,b);return}let Y=await NaI((A)=>OhG(G,Z,b,"streamGenerateContent",A),Z.signal);if(!Y.ok)throw await n1("Gemini",Y,"(stream)");if(!Y.body)return;if(ahG(Z))Z.onReasoningStart?.();let V,X,R=!1,Q=!1,H=[],w=new Set;for await(let A of iv(Y.body,Z.onStreamActivity)){let y;try{y=JSON.parse(A)}catch{continue}DhG("Gemini",y.error);let k=jhG(y);if(k)Z.onReasoning?.(k);YaI(y,Z,w);let p=idI(y);if(p)Q=!0,yield p;if(X=VaI(y)??X,y.candidates?.[0]?.finishReason)R=!0;if(y.usageMetadata)V=y.usageMetadata;H.push(...sdI(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 y5Z(G,Z={}){return xK(G,{extraHeaders:caI(),onProgress:Z.onProgress})}function ShG(G=process.env){return G.GEMINI_OAUTH_CLIENT_SECRET||ThG(L5Z)}async function z5Z(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 FaI(G){return new qhG(G).login()}async function daI(G){let Z=await fetch(nhG,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:RaI,client_secret:ShG(),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 ThG=(G)=>atob(G),RaI,L5Z,A5Z="https://accounts.google.com/o/oauth2/v2/auth",nhG="https://oauth2.googleapis.com/token",u5Z=8085,p5Z="/oauth2callback",k5Z,qhG;var QaI=xW(()=>{lr();Wr();Nr();RaI=ThG(["NjgxMjU1ODA5Mzk1","LW9vOGZ0Mm9wcmRy","bnA5ZTNhcWY2YXYz","aG1kaWIxMzVqLmFw","cHMuZ29vZ2xldXNl","cmNvbnRlbnQuY29t"].join("")),L5Z=["R09DU1BYLTR1SGdN","UG0tMW83U2stZ2VW","NkN1NWNsWEZzeGw="].join("");k5Z=["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/userinfo.email","https://www.googleapis.com/auth/userinfo.profile"];qhG=class qhG extends $z{constructor(G){super(G,{preferredPort:u5Z,callbackPath:p5Z})}async generateAuthUrl(G,Z){let b=new URLSearchParams({client_id:RaI,response_type:"code",redirect_uri:Z,scope:k5Z.join(" "),state:G,access_type:"offline",prompt:"consent"});return{url:`${A5Z}?${b.toString()}`,instructions:"Complete the 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:RaI,client_secret:ShG(),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 z5Z(V.access_token),R=process.env.GOOGLE_CLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT_ID||void 0;if(!R)try{R=await y5Z(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 HaI(G=process.env){return G.ANTIGRAVITY_OAUTH_CLIENT_SECRET||PhG(g5Z)}function _hG(G,Z={}){return xK(G,{metadata:{...br},extraHeaders:{"User-Agent":qp()},alwaysOnboard:!0,onProgress:Z.onProgress})}async function x5Z(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 haI(G){return new fhG(G).login()}async function JaI(G){let Z=await fetch($hG,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:maI,client_secret:HaI(),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 PhG=(G)=>atob(G),maI,g5Z,U5Z="https://accounts.google.com/o/oauth2/v2/auth",$hG="https://oauth2.googleapis.com/token",B5Z=51121,O5Z="/oauth-callback",M5Z,fhG;var waI=xW(()=>{lr();Wr();KK();maI=PhG(["MTA3MTAwNjA2MDU5MS10","bWhzc2luMmgyMWxjcmUy","MzV2dG9sb2poNGc0MDNl","cC5hcHBzLmdvb2dsZXVz","ZXJjb250ZW50LmNvbQ=="].join("")),g5Z=["R09DU1BYLUs1OEZX","UjQ4NkxkTEoxbUxC","OHNYQzR6NnFEQWY="].join("");M5Z=["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"];fhG=class fhG extends $z{constructor(G){super(G,{preferredPort:B5Z,callbackPath:O5Z})}async generateAuthUrl(G,Z){let b=new URLSearchParams({client_id:maI,response_type:"code",redirect_uri:Z,scope:M5Z.join(" "),state:G,access_type:"offline",prompt:"consent"});return{url:`${U5Z}?${b.toString()}`,instructions:"Complete the Antigravity sign-in in your browser."}}async exchangeToken(G,Z,b){let Y=await fetch($hG,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:maI,client_secret:HaI(),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 x5Z(V.access_token),R=process.env.GOOGLE_CLOUD_PROJECT||process.env.GOOGLE_CLOUD_PROJECT_ID||void 0;if(!R)try{R=await _hG(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 EaI=xW(()=>{Yr={name:"jeo-code",version:"0.12.25",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:shared-global":"bun scripts/verify-shared-global-isolation.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 ihG from"crypto";import*as $6 from"fs";import*as e4 from"os";import*as yaI from"path";function AaI(){return process.env.KIMI_CODE_OAUTH_HOST||process.env.KIMI_OAUTH_HOST||K5Z}function vaI(G,Z,b){return[G,Z,b].filter(Boolean).join(" ").trim()}function n5Z(){let G=e4.platform(),Z=e4.release(),b=e4.arch();if(G==="darwin")return vaI("macOS",Z,b);if(G==="win32")return vaI("Windows",Z,b);return vaI(G==="linux"?"Linux":G,Z,b)}function q5Z(){let G=$V("CONFIG_DIR")||yaI.join(e4.homedir(),".jeo"),Z=yaI.join(G,j5Z),b=CaI.get(Z);if(b)return b;try{let V=$6.readFileSync(Z,"utf-8").trim();if(V)return CaI.set(Z,V),V}catch(V){if(V?.code!=="ENOENT")throw V}let Y=ihG.randomUUID().replace(/-/g,"");return $6.mkdirSync(G,{recursive:!0,mode:448}),$6.writeFileSync(Z,`${Y}
|
|
66
66
|
`,{mode:384}),CaI.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":n5Z(),"X-Msh-Os-Version":e4.version(),"X-Msh-Device-Id":q5Z()}}function P5Z(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 $5Z(){let G=await fetch(`${AaI()}/api/oauth/device_authorization`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",...y3()},body:new URLSearchParams({client_id:LaI})});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:T5Z,R=typeof Z.interval==="number"&&Z.interval>0?Z.interval*1000:D5Z;return{userCode:b,deviceCode:Y,verificationUri:V,verificationUriComplete:Z.verification_uri_complete||V,expiresInMs:X,intervalMs:R}}function shG(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-S5Z}}async function _5Z(G,Z,b,Y,V=P5Z){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(`${AaI()}/api/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",...y3()},body:new URLSearchParams({client_id:LaI,device_code:G,grant_type:"urn:ietf:params:oauth:grant-type:device_code"})}),H=await Q.json();if(Q.ok&&H.access_token)return shG(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 uaI(G){let Z=await $5Z();return G.onAuth?.({url:Z.verificationUriComplete,instructions:`Enter code: ${Z.userCode}`}),_5Z(Z.deviceCode,Z.intervalMs,Z.expiresInMs,G.signal)}async function paI(G){let Z=await fetch(`${AaI()}/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:LaI})});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 shG(b,G)}var LaI="17e5f671-d194-4dfb-9706-5516cb48c098",K5Z="https://auth.kimi.com",j5Z="kimi-device-id",D5Z=5000,T5Z=900000,S5Z=300000,CaI;var Vr=xW(()=>{EaI();CaI=new Map});var L3;var _6=xW(()=>{txI();IaI();QaI();waI();Vr();txI();IaI();QaI();waI();Vr();L3={anthropic:{provider:"anthropic",label:"Anthropic (Claude Pro/Max)",login:ixI,refresh:sxI,verifiedEndToEnd:!0,note:"Works directly with the bundled Anthropic Messages adapter."},openai:{provider:"openai",label:"OpenAI (ChatGPT/Codex)",login:rxI,refresh:exI,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:FaI,refresh:daI,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:haI,refresh:JaI,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:uaI,refresh:paI,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 ehG={};X3(ehG,{rotateOAuthToken:()=>rhG,refreshOAuthToken:()=>ohG,classifyRefreshFailure:()=>kaI,OAUTH_REFRESH_SKEW_MS:()=>thG});function kaI(G){let Z=G?.message??String(G);if(f5Z.test(Z))return"definitive";if(s5Z.test(Z)&&!i5Z.test(Z))return"definitive";return"transient"}async function ohG(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()+thG)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(kaI(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 rhG(G,Z){let{setOauthToken:b}=await Promise.resolve().then(() => (p3(),IJG));await b(G,Z)}var f5Z,i5Z,s5Z,thG=60000;var zaI=xW(()=>{p3();_6();nh();f5Z=/invalid_grant|invalid_token|revoked|unauthorized|expired.*refresh|refresh.*expired/i,i5Z=/timeout|network|fetch failed|ECONNREFUSED/i,s5Z=/\b(401|403)\b/});var IJG={};X3(IJG,{snapshotProvider:()=>u3,setOauthToken:()=>BaI,setOauthCredentialNoLock:()=>rdI,setOauthCredential:()=>GQI,setApiKey:()=>lJG,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 UaI from"os";import*as q1 from"fs/promises";function A3(G){return edI.includes(G)}function GJG(G){let Z=$V("CONFIG_DIR")||f6.join(UaI.homedir(),".jeo");return f6.join(Z,`oauth-${G}.lock`)}async function tdI(G,Z=5000){let b=GJG(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=GJG(G);await q1.unlink(Z).catch(()=>{})}function ZJG(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(UaI.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=gaI.get(G);if(!Q)Q=(async()=>{let{refreshOAuthToken:w}=await Promise.resolve().then(() => (zaI(),ehG));return w(G)})(),gaI.set(G,Q),Q.finally(()=>{gaI.delete(G)}).catch(()=>{});return(await Q).credential}catch{}let R=ZJG(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:ZJG(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 BaI(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 lJG(G,Z){await C3((b)=>({providers:{...b.providers??{},[G]:Z}}))}var edI,IQI,gaI;var p3=xW(()=>{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"];gaI=new Map});var bJG=xW(()=>{p3();_6()});var Xr=xW(()=>{p3();bJG();zaI();_6()});import{createHash as t5Z,randomBytes as o5Z,randomUUID as WJG}from"crypto";function FJG(G,Z){return(mJG(Z)?G.filter((Y)=>Y!==bvZ):G).join(",")}function dJG(G){return G.startsWith("anthropic/")?G.slice(10):G}function QJG(G,Z,b){return Z.kind==="oauth"&&!b&&!G.startsWith("claude-3-5-haiku")}function WvZ(){return`user_${o5Z(32).toString("hex")}_account_${WJG().toLowerCase()}_session_${WJG().toLowerCase()}`}function NvZ(G){let Z=JSON.stringify(G)??"",b=t5Z("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`${GvZ} cc_version=${RJG}.${V}; cc_entrypoint=cli; cch=${b};`}function YvZ(G,Z,b,Y,V){let X=[];if(QJG(Z,b,V)){let R=G?{...Y,system:[G]}:Y;X.push({type:"text",text:NvZ(R)},{type:"text",text:IvZ})}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 VvZ(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 MaI(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 mJG(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 cvZ(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 NJG(G){switch(G){case"low":return"low";case"medium":return"medium";case"high":return"high";default:return"medium"}}function YJG(G,Z,b){return b&&!!G.toolUse?.length&&!!G.reasoningArtifacts?.some((Y)=>Y.provider==="anthropic"&&Y.model===Z&&(!!Y.signature||!!Y.redacted))}function XvZ(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"&&YJG(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"&&YJG(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 RvZ(G,Z,b,Y,V={kind:"none",provider:"anthropic"},X=!1,R=!1,Q=!1){let H=dJG(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?cvZ(H):"budget",K=p&&O!=="adaptive"?VvZ(k,y):void 0,x=XvZ(G,Z.model,p&&!X),a=x[x.length-1];if(a){if(typeof a.content==="string"){if(a.content)a.content=[{type:"text",text:a.content,cache_control:{type:"ephemeral"}}]}else if(a.content.length>0){let f=a.content[a.content.length-1];a.content[a.content.length-1]={...f,cache_control:{type:"ephemeral"}}}}let S={model:H,messages:x,max_tokens:K!==void 0?Math.max(y,K+1024):y};if(QJG(H,V,Z.baseUrl))S.metadata={user_id:WvZ()};if(k!==void 0){if(O==="adaptive"){if(S.thinking=mJG(H)?{type:"adaptive",display:"summarized"}:{type:"adaptive"},!Q)S.output_config={effort:NJG(k)}}else if(S.thinking={type:"enabled",budget_tokens:K,display:"summarized"},O==="budget-effort"&&!Q)S.output_config={effort:NJG(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=MaI(H,V,Z.baseUrl);if(f.length)S.fallbacks=f.map((P)=>({model:P}))}let n=YvZ(w,H,V,S,Z.baseUrl);if(n)S.system=n;return JSON.stringify(l5(S))}function FvZ(G,Z,b,Y,V,X=!1,R=!1,Q=!1){return{url:Z.baseUrl?`${Z.baseUrl.replace(/\/$/,"")}/v1/messages`:r5Z,headers:{...vvZ(b,Y,dJG(Z.model),Z.baseUrl,R),...Z.extraHeaders},body:RvZ(G,Z,Y,V,b,X,R,Q)}}function dvZ(G,Z){return G===400&&Z.includes(e5Z)}function QvZ(G,Z){return G===400&&/thinking|signature|redacted_thinking/i.test(Z)}function mvZ(G,Z){return G===400&&/fallback/i.test(Z)}function HvZ(G,Z){return G===400&&/effort/i.test(Z)&&/output_config|not support/i.test(Z)}function hvZ(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 VJG(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}=FvZ(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(dvZ(y.status,k)&&V){V=!1;continue}if(QvZ(y.status,k)&&!X){X=!0;continue}if(mvZ(y.status,k)&&!R){R=!0;continue}if(HvZ(y.status,k)&&!Q){Q=!0;continue}let p=y.status===429?`${k}${hvZ(y.headers)}`:k;throw new aK("Anthropic",y.status,p,Y?"(stream)":void 0,laI(y.headers.get("retry-after"))??baI(k))}throw Error("Anthropic request failed: maximum retries reached without response")}function cJG(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 XJG(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 JvZ(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 wvZ(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 EvZ(G,Z){return{accept:G?"text/event-stream":"application/json","anthropic-beta":FJG(lvZ,Z),"anthropic-dangerous-direct-browser-access":"true","user-agent":`claude-cli/${RJG} (external, cli)`,"x-app":"cli","x-stainless-arch":wvZ(process.arch),"x-stainless-lang":"js","x-stainless-os":JvZ(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 vvZ(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",...EvZ(Z,b)};if(!V&&MaI(b,G,Y).length){let R=X["anthropic-beta"]?X["anthropic-beta"].split(","):[];if(!R.includes(OaI))R.push(OaI),X["anthropic-beta"]=R.join(",")}return X}if(G.kind==="api_key"){let X=ZvZ.slice();if(!V&&MaI(b,G,Y).length)X.push(OaI);return{accept:Z?"text/event-stream":"application/json","content-type":"application/json","x-api-key":G.token,"anthropic-version":"2023-06-01","anthropic-beta":FJG(X,b)}}throw Error("anthropic adapter requires a credential")}var r5Z="https://api.anthropic.com/v1/messages",e5Z="`temperature` is deprecated for this model.",RJG="2.1.289",IvZ="You are a Claude agent, built on Anthropic's Claude Agent SDK.",GvZ="x-anthropic-billing-header:",ZvZ,lvZ,bvZ="interleaved-thinking-2025-05-14",OaI="server-side-fallback-2026-06-01",Pp;var Rr=xW(()=>{WA();vK();ZvZ=["interleaved-thinking-2025-05-14","context-management-2025-06-27","prompt-caching-scope-2026-01-05"],lvZ=["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 VJG(G,Z,b,!1)).json();if(V.usage)Z.onUsage?.({inputTokens:cJG(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);XJG(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 VJG(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 iv(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=cJG(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).");XJG(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 xaI from"os";function HJG(){return`${JJG}/${Yr.version} (${xaI.platform()} ${xaI.release()}; ${xaI.arch()})`}function i6(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 hJG(G,Z){return!!G.toolUse?.length&&!!G.reasoningArtifacts?.some((b)=>b.provider==="openai"&&b.model===Z&&!!b.itemId&&!!b.encrypted)}function LvZ(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"&&hJG(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"&&hJG(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 AvZ(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=LvZ(G,Z.model,Y),H=uvZ(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&&yvZ.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":HJG()},body:JSON.stringify(l5(w))}}let C=i6(X),A={"content-type":"application/json",authorization:`Bearer ${X}`,"OpenAI-Beta":"responses=experimental",originator:JJG,"user-agent":HJG(),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:CvZ,headers:A,body:JSON.stringify(l5(w))}}function uvZ(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 wJG(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 EJG(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 vJG(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 CJG(G,Z,b){return PdI((Y)=>{let{url:V,headers:X,body:R}=AvZ(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 aaI(G,Z,b){let Y=await CJG(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 iv(Y.body)){let C=wJG(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(EJG(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 vJG(X);return V}async function*KaI(G,Z,b){let Y=await CJG(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 iv(Y.body,Z.onStreamActivity)){let C=wJG(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(EJG(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 vJG(X)}var CvZ="https://chatgpt.com/backend-api/codex/responses",yvZ,JJG="codex_cli_rs",k3;var WQI=xW(()=>{WA();vK();EaI();yvZ=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 yJG(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=yJG(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=yJG(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 jaI(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 DaI(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 pvZ(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 LJG(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=DaI(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)pvZ(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 ${gvZ(b)}`},body:JSON.stringify(l5(C))}}function AJG(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 uJG(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 pJG(G){if(!G)return"";return jaI(G)}function kJG(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 zJG(G){let Z=JSON.parse(G);return delete Z.tools,delete Z.tool_choice,JSON.stringify(Z)}function kvZ(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 zvZ(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 gvZ(G){if(G.kind==="oauth")return G.token;if(G.kind==="api_key")return G.token;return"no-key"}var jK;var YQI=xW(()=>{WA();WQI();vK();jK={name:"openai",supportsNativeTools:!0,async call(G,Z,b){if(b.kind==="oauth")return aaI(G,Z,b);if(b.kind==="api_key"&&!Z.baseUrl&&DaI(Z.model))try{return await aaI(G,Z,b)}catch(k){if(k instanceof k3||k instanceof Uw)throw k}let{url:Y,headers:V,body:X}=LJG(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(kJG(X,k))R=await fetch(Y,{method:"POST",headers:V,body:zJG(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;uJG(H);let w=r4(zvZ(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=pJG(A?.reasoning_content??A?.reasoning??"");if(y)return y;throw AJG(H)},async*stream(G,Z,b){if(b.kind==="oauth"){yield*KaI(G,Z,b);return}if(b.kind==="api_key"&&!Z.baseUrl&&DaI(Z.model)){let K=!1;try{for await(let x of KaI(G,Z,b))K=!0,yield x;return}catch(x){if(K||x instanceof k3||x instanceof Uw)throw x}}let{url:Y,headers:V,body:X}=LJG(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 x=JSON.parse(X);delete x.stream_options,R=await fetch(Y,{method:"POST",headers:V,body:JSON.stringify(x),signal:Z.signal})}else if(kJG(X,K))R=await fetch(Y,{method:"POST",headers:V,body:zJG(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 iv(R.body,Z.onStreamActivity)){let x;try{x=JSON.parse(K)}catch{continue}let a=x.choices?.[0]?.delta?.content;if(a){w=!0;let f=y.push(a);if(f)Q=!0,yield f}let S=kvZ(x.choices?.[0]?.delta);if(S)A(S);let n=x.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(x.choices?.[0]?.finish_reason)H=x.choices[0].finish_reason;if(x.usage)Z.onUsage?.({inputTokens:x.usage.prompt_tokens,outputTokens:x.usage.completion_tokens})}if(!H&&(w||C||k.size))throw Error("OpenAI response incomplete (missing finish_reason).");uJG(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=pJG(C);if(K){yield K;return}throw AJG(H)}}}});function UvZ(G){let Z=(G??process.env.OLLAMA_HOST??"http://localhost:11434").trim();return(/^https?:\/\//i.test(Z)?Z:`http://${Z}`).replace(/\/$/,"")}function OvZ(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:BvZ}function gJG(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:OvZ(Z.numCtx)}};if(Z.jsonMode)R.format="json";return{url:`${UvZ(Z.baseUrl)}/api/chat`,body:JSON.stringify(l5(R))}}function UJG(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 BJG(G){if(G&&G!=="stop")throw Error(`Ollama response incomplete (done_reason=${G})${G==="length"?" \u2014 output budget exhausted; raise maxTokens":""}.`)}var BvZ=16384,TaI;var SaI=xW(()=>{WA();TaI={name:"ollama",async call(G,Z){let{url:b,body:Y}=gJG(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}),BJG(X.done_reason);let R=X.message?.content??"";if(!R)throw UJG(X.done_reason);return R},async*stream(G,Z){let{url:b,body:Y}=gJG(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 ZaI(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).");BJG(R);let C=w.flush();if(C)X=!0,yield C;if(!X)throw UJG(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?MvZ: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 MvZ;var Fr=xW(()=>{YQI();WA();fv();MvZ={kind:"none",provider:"openai"}});var naI;var qaI=xW(()=>{Fr();naI=z3({name:"lmstudio",baseUrl:"http://localhost:1234/v1",keyless:!0})});function MJG(G){return G?{kind:"api_key",provider:"openai",token:G}:{kind:"none",provider:"openai"}}var xvZ="https://api.x.ai/v1",OJG;var PaI=xW(()=>{Fr();OJG=z3({name:"xai",baseUrl:xvZ})});function aJG(G){return{...G,model:G.model.startsWith("kimi/")?G.model.slice(5):G.model,baseUrl:G.baseUrl??KvZ,extraHeaders:{...y3(),...G.extraHeaders}}}var avZ="https://api.moonshot.ai/v1",KvZ="https://api.kimi.com/coding",$aI,xJG,KJG;var jJG=xW(()=>{Vr();Rr();Fr();WA();fv();$aI=z3({name:"kimi",baseUrl:avZ}),xJG=m3("kimi");KJG={name:"kimi",supportsNativeTools:$aI.supportsNativeTools,call:async(G,Z,b)=>{if(b.kind!=="oauth")return $aI.call(G,Z,b);try{return await Pp.call(G,aJG(Z),b)}catch(Y){throw _z(Y,xJG)}},async*stream(G,Z,b){if(b.kind!=="oauth"){yield*$aI.stream(G,Z,b);return}try{yield*Pp.stream(G,aJG(Z),b)}catch(Y){throw _z(Y,xJG)}}}});function DJG(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 TJG=xW(()=>{Rr();WA();fv()});function SJG(G){return G.protocol==="anthropic"?DJG({name:G.name,baseUrl:G.baseUrl}):z3({name:G.name,baseUrl:G.baseUrl,thinkingFormat:G.thinkingFormat})}function nJG(G=ExI()){let Z=G.filter((Y)=>!jvZ.has(Y.name)),b=new Set(Z.map((Y)=>Y.name));for(let Y of _aI)if(!b.has(Y))S1.unregister(Y),_aI.delete(Y);for(let Y of Z)S1.register(Y.name,SJG(Y)),_aI.add(Y.name)}var jvZ,_aI;var qJG=xW(()=>{PxI();Rr();YQI();Nr();SaI();qaI();PaI();KK();jJG();Fr();TJG();Dz();qo();S1.register("anthropic",Pp);S1.register("openai",jK);S1.register("gemini",XaI);S1.register("antigravity",_dI);S1.register("ollama",TaI);S1.register("lmstudio",naI);S1.register("xai",OJG);S1.register("kimi",KJG);for(let G of Dp)S1.register(G.name,SJG(G));jvZ=new Set(S1.listProviders()),_aI=new Set;d0G((G)=>nJG(G));nJG()});function VQI(G,Z=DK){if(Object.prototype.hasOwnProperty.call(Z,G))return Z[G];return G}async function PJG(G,Z){let Y=(Z??await Cm()).modelAliases??{},V={...DK,...Y};return VQI(G,V)}async function DvZ(){let Z=(await Cm()).modelAliases??{};return{...DK,...Z}}function TvZ(G,Z=DK){return Object.entries(Z).filter(([,b])=>b===G).map(([b])=>b).sort()}async function $JG(G){return TvZ(G,await DvZ())}var DK;var _JG=xW(()=>{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(sJG(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)&&fJG.has(X))return!0}let Y=b.match(/http[\s/]*?(\d{3})/);if(Y&&fJG.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=iJG(p),K=qvZ(p);if(O&&typeof A==="number"&&K!==void 0&&K>A)throw p;let x=O&&typeof C==="number"?Math.max(b,C):b;if(k>=x||!X(p,k))throw p;let a=Math.min(Y*Math.pow(2,k-1),V),S=a/2+Q()*(a/2),n=K!==void 0?K:S,f=O?Math.min(w*Math.pow(2,k-1),SvZ):0,P=Math.max(n,f);if(H&&H(k,p,P)===!1)throw p;await nvZ(R,P,y),k++}}function nvZ(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 qvZ(G){if(typeof G==="object"&&G!==null){let Z=G.retryAfterMs;if(typeof Z==="number"&&Number.isFinite(Z)&&Z>=0)return Z}return}function iJG(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 sJG(G){return PvZ.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 faI(G,Z,b){try{return await G()}catch(Y){if(Qr(Y))throw new mr(Z,b,Y);throw Y}}var fJG,SvZ=30000,PvZ,mr;var Hr=xW(()=>{fJG=new Set([408,425,429,500,502,503,504,529]);PvZ=/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 _vZ(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 sv(`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 sv(`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 rJG(G={}){let Z=$vZ(G.timeoutMs,15000,15000);if(G.signal?.aborted)throw new sv("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 sv(`Failed to start agy model discovery: ${tJG(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(()=>{}),oJG(V,"SIGTERM"),y=setTimeout(()=>oJG(V,"SIGKILL"),250)},x=(P)=>{if(P==="timeout")w=!0;else C=!0;K()},a=()=>x("cancelled");if(G.signal)G.signal.addEventListener("abort",a,{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 sv("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(()=>x("timeout"),Z),_;try{_=await V.exited,await Promise.all([n,f])}finally{clearTimeout(P)}if(C)throw new sv("Agy model discovery was cancelled.","cancelled",_,R);if(w)throw new sv(`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 sv(`${r} (exit ${_}).`,"exit",_,R)}return _vZ(X)}catch(P){if(!A&&V.exitCode===null)K();if(P instanceof sv)throw P;throw new sv(`Agy model discovery failed: ${tJG(P)}${R.trim()?` \u2014 ${R.trim()}`:""}`,"protocol",V.exitCode,R)}finally{if(G.signal)G.signal.removeEventListener("abort",a);try{await V.exited}catch{}clearTimeout(y);try{await k?.cancel()}catch{}try{await p?.cancel()}catch{}}}var sv,$vZ=(G,Z,b)=>{if(G===void 0)return Z;if(!Number.isFinite(G)||G<=0)throw new sv("Agy timeout must be a positive finite number of milliseconds.","protocol");return Math.min(Math.max(1,Math.ceil(G)),b)},tJG=(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)},oJG=(G,Z)=>{try{G.kill(Z)}catch{}};var iaI=xW(()=>{sv=class sv 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 fvZ;var saI=xW(()=>{nh();Xr();_6();Dz();qo();fvZ=["anthropic","openai","gemini","antigravity","agy","ollama","lmstudio","xai","kimi",...ydI]});import{createHash as eJG}from"crypto";async function s6(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 i6(Z.token)||(b?.access===Z.token?b.accountId?.trim():void 0)||`token:${eJG("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 eJG("sha256").update(`${b}\x00${R}\x00${Q}\x00${qp()}`,"utf8").digest("hex")}catch{return}}var dQI=xW(()=>{fv();p3();KK();WQI()});function evZ(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 ICZ(G){if(G==="ollama"||G==="lmstudio")return;return G}function GCZ(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:evZ(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=i6(R)||Y,w={Authorization:`Bearer ${R}`,"OpenAI-Beta":"responses=experimental",originator:"codex_cli_rs"};if(H)w["chatgpt-account-id"]=H;return{url:ovZ,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:rvZ,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 ZCZ(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 lCZ(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 IwG(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&&lCZ(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(ZCZ):V}async function GwG(G,Z={}){if(G==="agy")try{let p=await rJG({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:svZ),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=ICZ(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 x=p;if(G!=="antigravity"&&R.kind==="oauth"&&K.providers?.[x]&&!Z.preferOAuth&&!X)R={kind:"api_key",provider:x,token:K.providers[x]},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=i6(R.token)||(S?.access===R.token?S.accountId:void 0),H=await s6(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??ivZ,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)=>xK(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:x}=GCZ(G,R,V,Q,X?{forceCodexCatalog:!0}:void 0),a=await b(p,{method:K??"GET",headers:O,body:x,signal:y});if(!a.ok){let r=a.status===401||a.status===403?"auth rejected":`HTTP ${a.status}`;return{provider:G,models:[],ok:!1,source:w,error:r,...C}}let S=await a.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()))}),aI=r?.deprecatedModelIds,pG=aI!==void 0&&(Array.isArray(aI)?aI.some((MI)=>typeof MI!=="string"||!Iy(MI).trim()):!aI||typeof aI!=="object"||Object.keys(aI).some((MI)=>!Iy(MI).trim())),IZ=r?.tieredModelIds,iI=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||iI||yG)return{provider:G,models:[],ok:!1,source:w,error:"invalid models response",...C}}let n=IwG(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(IwG(G,zI)),r=zI.nextPageToken}}let P=[...new Set(n)].sort(),_=P.slice(0,Y);if(G==="openai"&&w==="oauth"&&!V){if(await s6()!==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)pxI(P,H);if(G==="kimi"&&w==="oauth")BxI(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 ivZ=5000,svZ=100,tvZ="2.0.0",ovZ,rvZ="https://daily-cloudcode-pa.googleapis.com/v1internal:fetchAvailableModels";var taI=xW(()=>{nh();Xr();iaI();saI();fv();WQI();p3();Dz();dQI();KK();Wr();Vr();ovZ=`https://chatgpt.com/backend-api/codex/models?client_version=${tvZ}`});var hwG={};X3(hwG,{thinkingToReasoningEffort:()=>YwG,thinkingMaxTokens:()=>WwG,streamMaxMs:()=>QwG,streamIdleMs:()=>mwG,retryableStream:()=>HwG,resolveRoleModel:()=>cwG,resolveRetryOptions:()=>XwG,resolveProvider:()=>TK,resolveMaxOutputTokens:()=>NwG,resolveCall:()=>raI,qualifyModelId:()=>NCZ,providerModelFor:()=>bwG,oauthServesModel:()=>t6,modelServableWithConfig:()=>GKI,effectiveCredentialForProvider:()=>RwG,describeModelDetailed:()=>VCZ,describeModel:()=>VwG,credentialForCall:()=>FwG,createModelManager:()=>ZKI,callTimeoutMs:()=>IKI});function TK(G){let Z=LK(G);if(Z)return Z.provider;let b=E0G(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 CxI())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 WCZ(G){return yxI(G)?`${G}/`:bCZ[G]??`${G}/`}function NCZ(G,Z){let b=(G??"").trim();if(!b)return b;return TK(b)===Z?b:`${WCZ(Z)}${b}`}function bwG(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/")||yxI(G.split("/")[0]))return G;return A0G(G,TK(G))}function WwG(G){if(G==="low")return 8000;if(G==="high")return 24000;if(G==="xhigh")return 31999;return 16000}function NwG(G,Z){let b=G?LK(VQI(G,DK)):void 0;if(!b)return WwG(Z);let Y=Number($V("MAX_OUTPUT_TOKENS")),V=Number.isFinite(Y)&&Y>0?Y:YCZ;return Math.min(CK(b.id)?.maxOutputTokens??V,V)}function YwG(G){if(!G)return;return G==="xhigh"?"high":G}async function VwG(G,Z){let b=await PJG(G,Z);return{input:G,resolved:b,provider:TK(b)}}function cwG(G,Z){return Z.roles?.[G]||Z.defaultModel}async function VCZ(G){let{resolved:Z,provider:b}=await VwG(G);return{input:G,resolved:Z,provider:b,entry:LK(Z),aliases:await $JG(Z)}}function XwG(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=cCZ;if(typeof G?.rateLimitMinDelayMs==="number")b.rateLimitMinDelayMs=G.rateLimitMinDelayMs;else if(typeof G?.maxDelayMs!=="number")b.rateLimitMinDelayMs=XCZ;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 kxI(Z);if(G==="kimi")return C0G(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 RwG(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 FwG(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 raI(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:bwG(V),systemPrompt:G.systemPrompt,temperature:G.temperature??0.2,maxTokens:G.maxTokens??NwG(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??YwG(b.thinkingLevel),onReasoning:G.onReasoning,onReasoningArtifact:G.onReasoningArtifact,tools:G.tools,sessionKey:G.sessionKey},w={...XwG(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:MJG(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=RwG(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 s6(y);if(p&&!zxI(p)){let O=oaI.get(p);if(!O)O=GwG("openai",{config:b,codexCatalog:!0}),oaI.set(p,O),O.finally(()=>oaI.delete(p)).catch(()=>{});let K=G.signal;if(K){let x=Promise.withResolvers(),a=()=>x.reject(K.reason);K.addEventListener("abort",a,{once:!0});try{K.throwIfAborted(),await Promise.race([O,x.promise])}finally{K.removeEventListener("abort",a)}}else await O}if(G.signal?.throwIfAborted(),await s6()!==p)throw Error("OpenAI credential changed during model discovery; retry the request.");if(p&&zxI(p)&&kxI(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:FwG(X,y,b,Q),retry:w,provider:X,baseUrl:Q}}function dwG(G,Z){return G?AbortSignal.any([G,Z]):Z}function ZwG(G,Z){return dwG(G,AbortSignal.timeout(Z))}function FCZ(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 lwG(G,Z){if(!Z)return G.next();return Promise.race([G.next(),Z])}function QwG(G){let Z=$V("STREAM_MAX_MS",G);if(Z===void 0||Z==="")return eaI;let b=parseInt(Z,10);if(!Number.isFinite(b)||b<0)return eaI;return b===0?void 0:b}function mwG(G){let Z=$V("STREAM_IDLE_MS",G),b=Z!==void 0?parseInt(Z,10):NaN;return Number.isFinite(b)&&b>0?b:RCZ}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:eaI}async function*HwG(G,Z,b){let Y=()=>{},V=()=>{};try{let{iter:X,first:R,watchdog:Q}=await XQI(async()=>{Y();let H=G(),w=b?FCZ(b):void 0;Y=w?.cleanup??(()=>{}),V=w?.touch??(()=>{});let C=await lwG(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 lwG(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 raI(Z);return faI(()=>XQI(()=>b.call(G,{...Y,signal:ZwG(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 raI(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:(x)=>{A(),y?.(x)},onReasoningStart:()=>{A(),k?.()},onStreamActivity:A},O=()=>{w=new AbortController;let x=dwG(Y.signal,w.signal);return H(G,{...p,signal:x},V)[Symbol.asyncIterator]()},K=QwG();try{yield*HwG(O,X,{idleMs:mwG(),...K!==void 0?{deadlineAt:Date.now()+K}:{},lastActivityAt:()=>C,onIdle:()=>w?.abort()})}catch(x){if(Qr(x))throw new mr(R,Q,x);throw x}}else yield await faI(()=>XQI(()=>b.call(G,{...Y,signal:ZwG(Y.signal,IKI())},V),X),R,Q)}}}var bCZ,YCZ=64000,cCZ=6,XCZ=2000,oaI,eaI=1800000,RCZ=300000;var QQI=xW(()=>{PxI();_6();nh();Xr();qJG();_JG();UdI();fv();PaI();Dz();Hr();taI();dQI();bCZ={anthropic:"anthropic/",openai:"openai/",gemini:"google/",antigravity:"antigravity/",agy:"agy/",ollama:"ollama/",lmstudio:"lmstudio/",xai:"xai/",kimi:"kimi/"};oaI=new Map});var JwG=xW(()=>{fv()});var wwG=xW(()=>{Rr();YQI();Nr();KK();SaI();qaI();QQI();saI();taI();dQI();fv();JwG()});async function o6(G,Z={}){if(!Z.onToken)return EwG.call(G,Z);let b="";for await(let Y of EwG.stream(G,Z)){b+=Y;try{Z.onToken(Y)}catch{}}return b}var EwG;var r6=xW(()=>{wwG();EwG=ZKI()});function SK(G){return G.replace(/\\/g,"/").replace(/^\.?\/+/,"").replace(/\.md$/i,"")}function QCZ(G){let Z=G.replace(/\\/g,"/"),b=Z.lastIndexOf("/");return b===-1?Z:Z.slice(b+1)}function lKI(G){let Z=QCZ(G).toLowerCase();return dCZ.includes(Z)}function Jr(G){return G.normalize("NFKD").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").replace(/-{2,}/g,"-")||"untitled"}function vwG(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 mCZ(G){let Z=G.trim();if(Z.length===0)return"";if(Z[0]==='"'&&Z[Z.length-1]==='"'||Z[0]==="'"&&Z[Z.length-1]==="'")return vwG(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 HCZ(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)=>vwG(Y.trim()))}return mCZ(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]=HCZ(R.slice(H+1))}let V=Z.slice(b+1).join(`
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Read-only view of the shared bun global install (`~/.bun/install/global`) that `jeo update`
|
|
3
|
-
* writes into with `bun install -g jeo-code@V`. That directory also holds other tools
|
|
4
|
-
* gajae-code, ...), so `jeo update` must prove it leaves every other top-level package alone.
|
|
3
|
+
* writes into with `bun install -g jeo-code@V`. That directory also holds other tools
|
|
4
|
+
* (gajae-code, ...), so `jeo update` must prove it leaves every other top-level package alone.
|
|
5
5
|
*
|
|
6
6
|
* This module only ever reads: it never writes, deletes, renames, spawns or executes anything.
|
|
7
7
|
* Restore commands are formatted as strings for a human to run.
|
|
@@ -120,7 +120,7 @@ export interface ManifestDeps {
|
|
|
120
120
|
|
|
121
121
|
/**
|
|
122
122
|
* Top-level dependencies of the global package.json. Empty names and non-string specs are dropped into
|
|
123
|
-
* `ignored` (
|
|
123
|
+
* `ignored` (another tool's older updater wrote a `"": "."` dependency that no lockfile could ever cover). `external` is
|
|
124
124
|
* every name except jeo-code, in manifest order. An absent `dependencies` means zero dependencies.
|
|
125
125
|
*/
|
|
126
126
|
export function readManifestDeps(dir: string): { ok: true; deps: ManifestDeps } | { ok: false; error: string } {
|
|
@@ -243,13 +243,11 @@ export function formatRestoreCommands(cs: readonly ExternalChange[]): string[] {
|
|
|
243
243
|
});
|
|
244
244
|
}
|
|
245
245
|
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
/** `shared global unchanged: 3 packages (jeopi-cli X, a Y, b Z, ...)`; jeopi-cli leads, then ascending, at most 3 shown. */
|
|
246
|
+
/** `shared global unchanged: 3 packages (a X, b Y, c Z, ...)`: ascending by name, at most 3 shown. */
|
|
249
247
|
export function formatUnchangedSummary(after: InstalledSnapshot): string {
|
|
250
248
|
const present = Object.entries(after)
|
|
251
249
|
.filter((e): e is [string, string] => e[0] !== SELF_PACKAGE && e[1] !== null)
|
|
252
|
-
.sort(([a], [b]) => (a
|
|
250
|
+
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
|
|
253
251
|
const count = `${present.length} ${present.length === 1 ? "package" : "packages"}`;
|
|
254
252
|
if (present.length === 0) return `shared global unchanged: ${count}`;
|
|
255
253
|
const shown = present.slice(0, 3).map(([name, version]) => `${name} ${version}`);
|