jeo-code 0.12.23 → 0.12.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -9,6 +9,17 @@ The README mirrors the latest 5 entries — regenerate with `bun run changelog:s
9
9
 
10
10
  ## [Unreleased]
11
11
 
12
+ ## [0.12.24] - 2026-11-06
13
+
14
+ ### Added
15
+ - **`jeo doctor` hooks section** - a read-only `[hooks]` line (and `hooks` in `--json`) shows the global `hooks.enabled` state, the user registry and the project `.jeo/hooks.json` as written (valid and invalid entry counts, unreadable or `enabled: false` files) and what runs right now per event. Installers write these files and an unrunnable entry is dropped silently, so this is where to see why a hook is idle. It never affects `ready` or `--strict`, and prints nothing when no hook is configured and nothing is wrong.
16
+
17
+ ### Fixed
18
+ - **A one-shot task now ranks the skills the system prompt advertises** - `jeo launch "<task>"` never passed the task to `skillsPromptSection`, so its relevance sort did not run and the ~40 visible skills (of 780+ installed) were whatever the directory listing returned first. The task now reaches it; matching is Unicode-aware (Korean, Japanese and Chinese words were dropped by the ASCII-only tokenizer); and a skill's description counts, at most +8, always below an exact name (+20) or name part (+10) match. Interactive sessions have no task at boot and are unchanged - per-prompt routing there stays with `pre-prompt` hooks.
19
+
20
+ ### Changed
21
+ - **The done gate names an unmeasured shell call** - when the workspace snapshot around a bash/computer call is inconclusive (entry cap, time cap, or an error such as an unreadable subdirectory), the call is still counted as a possible file change (unchanged, deliberate), but the engine now emits one `workspace snapshot inconclusive (<reason>)` notice per distinct reason and the unverified / stale-verification message appends it. Before, a read-only `pwd` in such a directory ended `UNVERIFIED` after three correction rounds with only "You modified files this turn".
22
+
12
23
  ## [0.12.23] - 2026-11-06
13
24
 
14
25
  ### Added
@@ -2746,7 +2757,8 @@ _Initial release._
2746
2757
  ### Added
2747
2758
  - Initial jeo-code agent and CLI.
2748
2759
 
2749
- [Unreleased]: https://github.com/akillness/jeo-code/compare/v0.12.23...HEAD
2760
+ [Unreleased]: https://github.com/akillness/jeo-code/compare/v0.12.24...HEAD
2761
+ [0.12.24]: https://github.com/akillness/jeo-code/releases/tag/v0.12.24
2750
2762
  [0.12.23]: https://github.com/akillness/jeo-code/releases/tag/v0.12.23
2751
2763
  [0.12.22]: https://github.com/akillness/jeo-code/compare/v0.12.21...v0.12.22
2752
2764
  [0.12.21]: https://github.com/akillness/jeo-code/releases/tag/v0.12.21
package/README.ja.md CHANGED
@@ -231,6 +231,8 @@ jeo ultragoal
231
231
 
232
232
  **ユーザーレジストリ.** `~/.jeo/hooks.json`(`.jeo/hooks.json` と同形式、`JEO_CONFIG_DIR` に従う)は、jeo-skills のプロンプトルーティングやナレッジパイプラインのようにフックを代わりに設置するツール向けのフック専用ファイルで、認証情報が書き換えられないよう `config.json` から分離されています。優先順位: `config.json` の `"hooks": { "enabled": false }` はすべてを無効にし、プロジェクト `.jeo/hooks.json` の `"enabled": false` はそのプロジェクトだけを除外し、それ以外は `hooks.enabled: true` なしでレジストリが設定済みフックより先に実行されます。プロジェクト自身の `hooks` リストは `config.json` のリストだけを置き換えレジストリは置き換えず、プロジェクト / `config.json` のフックは従来どおり `hooks.enabled: true` のときだけ実行されます。サンドボックスセッションはレジストリをスキップします。
233
233
 
234
+ `jeo doctor` は現在実行されるフックを `[hooks]` 行(`--json` では `hooks`)で表示し、レジストリ/プロジェクトファイルが読めない、エントリが不正で無視された、グローバルスイッチやプロジェクトのオプトアウトがすべてを止めている場合に警告します。
235
+
234
236
  ## メモリフロー
235
237
 
236
238
  `jeo` は `.jeo/memory/` 配下に **ローカルファースト・蒸留されたプロジェクトメモリ** を保持します(リモートバックエンドなし、ネイティブ依存ゼロ)。過去のセッションは [OKF](docs/okf_mem/) コンセプトバンドルへ蒸留され、次のセッションは関連性の高い予算内のスライスだけをシステムプロンプトへ再注入します — 指示ではなく DATA として堅牢化されます。`JEO_NO_MEMORY=1` ですべて無効化。
@@ -460,10 +462,10 @@ CI は `.github/workflows/npm-publish.yml` で公開します — GitHub リリ
460
462
 
461
463
  <!-- CHANGELOG:START (auto-generated from CHANGELOG.md — run `bun run changelog:sync`) -->
462
464
  - **[Unreleased]**
465
+ - **[0.12.24]** (2026-11-06)
463
466
  - **[0.12.23]** (2026-11-06)
464
467
  - **[0.12.22]** (2026-11-04)
465
468
  - **[0.12.21]** (2026-11-04)
466
- - **[0.12.20]** (2026-11-04)
467
469
 
468
470
  See [CHANGELOG.md](CHANGELOG.md) for the full history.
469
471
  <!-- CHANGELOG:END -->
package/README.ko.md CHANGED
@@ -285,6 +285,8 @@ jeo ultragoal # 5. 최종 증거 기반 종
285
285
 
286
286
  **사용자 레지스트리.** `~/.jeo/hooks.json`(`.jeo/hooks.json`과 같은 형식, `JEO_CONFIG_DIR`을 따름)은 jeo-skills의 프롬프트 라우팅·지식 파이프라인처럼 훅을 대신 설치하는 도구를 위한 훅 전용 파일이며, 자격 증명이 다시 쓰이지 않도록 `config.json`과 분리되어 있습니다. 우선순위: `config.json`의 `"hooks": { "enabled": false }`는 모든 훅을 끄고, 프로젝트 `.jeo/hooks.json`의 `"enabled": false`는 그 프로젝트만 제외하며, 그 외에는 `hooks.enabled: true` 없이도 레지스트리가 설정된 훅보다 먼저 실행됩니다. 프로젝트 자체 `hooks` 목록은 `config.json` 목록만 대체하고 레지스트리는 대체하지 않으며, 프로젝트 / `config.json` 훅은 여전히 `hooks.enabled: true`일 때만 실행됩니다. 샌드박스 세션은 레지스트리를 건너뜁니다.
287
287
 
288
+ `jeo doctor` 는 지금 실행되는 훅을 `[hooks]` 줄(`--json` 에서는 `hooks`)로 보여 주고, 레지스트리/프로젝트 파일을 읽을 수 없거나 항목이 잘못되어 무시되었거나 전역 스위치·프로젝트 opt-out 이 모든 훅을 끈 경우 경고합니다.
289
+
288
290
  ## 메모리 흐름
289
291
 
290
292
  `jeo`는 `.jeo/memory/` 아래에 **로컬 우선·증류된 프로젝트 메모리**를 둡니다(원격 백엔드 없음, 네이티브 의존성 0). 지난 세션은 [OKF](docs/okf_mem/) 개념 번들로 증류되고, 다음 세션은 관련성 높은 예산 한도 내 일부만 시스템 프롬프트로 다시 주입합니다 — 지시가 아닌 DATA로 강화 처리됩니다. `JEO_NO_MEMORY=1`로 전체 비활성화.
@@ -515,10 +517,10 @@ CI는 `.github/workflows/npm-publish.yml`로 배포합니다 — GitHub 릴리
515
517
 
516
518
  <!-- CHANGELOG:START (auto-generated from CHANGELOG.md — run `bun run changelog:sync`) -->
517
519
  - **[Unreleased]**
520
+ - **[0.12.24]** (2026-11-06)
518
521
  - **[0.12.23]** (2026-11-06)
519
522
  - **[0.12.22]** (2026-11-04)
520
523
  - **[0.12.21]** (2026-11-04)
521
- - **[0.12.20]** (2026-11-04)
522
524
 
523
525
  See [CHANGELOG.md](CHANGELOG.md) for the full history.
524
526
  <!-- CHANGELOG:END -->
package/README.md CHANGED
@@ -288,6 +288,8 @@ Both are advisory: a non-zero exit, timeout or abort prints a notice and never b
288
288
 
289
289
  **User registry.** `~/.jeo/hooks.json` (same shape as `.jeo/hooks.json`; follows `JEO_CONFIG_DIR`) is a hooks-only file for tools that install hooks for you, such as jeo-skills' prompt routing and knowledge pipeline, kept apart from `config.json` so credentials are never rewritten. Precedence: `"hooks": { "enabled": false }` in `config.json` disables everything; a project `.jeo/hooks.json` with `"enabled": false` opts that project out; otherwise the registry runs, with no `hooks.enabled: true` needed, ahead of configured hooks. A project's own `hooks` list still replaces the `config.json` list, never the registry, and project / `config.json` hooks still run only with `hooks.enabled: true`. Sandboxed sessions skip the registry.
290
290
 
291
+ `jeo doctor` prints a `[hooks]` line (and `hooks` in `--json`) with what runs right now, and warns when the registry or project file is unreadable, an entry was dropped as invalid, or a kill switch or project opt-out is silencing everything.
292
+
291
293
  ## Memory flow
292
294
 
293
295
  `jeo` keeps a **local-first, distilled project memory** under `.jeo/memory/` (no remote backend, zero native deps). Past sessions are distilled into an [OKF](docs/okf_mem/) concept bundle, and the next session injects only the relevant, budget-bounded slice back into the system prompt — hardened as DATA, never as instructions. Disable everything with `JEO_NO_MEMORY=1`.
@@ -504,10 +506,10 @@ Huge thanks to [gajae-code](https://github.com/Yeachan-Heo/gajae-code) for the i
504
506
 
505
507
  <!-- CHANGELOG:START (auto-generated from CHANGELOG.md — run `bun run changelog:sync`) -->
506
508
  - **[Unreleased]**
509
+ - **[0.12.24]** (2026-11-06)
507
510
  - **[0.12.23]** (2026-11-06)
508
511
  - **[0.12.22]** (2026-11-04)
509
512
  - **[0.12.21]** (2026-11-04)
510
- - **[0.12.20]** (2026-11-04)
511
513
 
512
514
  See [CHANGELOG.md](CHANGELOG.md) for the full history.
513
515
  <!-- CHANGELOG:END -->
package/README.zh.md CHANGED
@@ -231,6 +231,8 @@ jeo ultragoal
231
231
 
232
232
  **用户注册表。** `~/.jeo/hooks.json`(与 `.jeo/hooks.json` 格式相同,遵循 `JEO_CONFIG_DIR`)是供代你安装钩子的工具(如 jeo-skills 的提示路由和知识管道)使用的仅含钩子的文件,与 `config.json` 分离,因此凭据不会被重写。优先级:`config.json` 中的 `"hooks": { "enabled": false }` 会禁用一切;项目 `.jeo/hooks.json` 中的 `"enabled": false` 仅让该项目退出;否则注册表无需 `hooks.enabled: true` 即可运行,并排在已配置钩子之前。项目自己的 `hooks` 列表仍然只替换 `config.json` 的列表,绝不替换注册表,且项目 / `config.json` 钩子仍然只在 `hooks.enabled: true` 时运行。沙箱会话会跳过注册表。
233
233
 
234
+ `jeo doctor` 会用 `[hooks]` 行(`--json` 中为 `hooks`)显示当前实际运行的钩子,并在注册表/项目文件无法读取、条目因无效被忽略,或全局开关/项目退出让所有钩子失效时发出警告。
235
+
234
236
  ## 内存流程
235
237
 
236
238
  `jeo` 在 `.jeo/memory/` 下保存 **本地优先、蒸馏后的项目内存**(无远程后端,零原生依赖)。过往会话被蒸馏为 [OKF](docs/okf_mem/) 概念包,下一次会话仅把相关的、受预算约束的切片重新注入系统提示 —— 作为 DATA 而非指令加固。用 `JEO_NO_MEMORY=1` 完全禁用。
@@ -458,10 +460,10 @@ CI 通过 `.github/workflows/npm-publish.yml` 发布 — GitHub 发布 release
458
460
 
459
461
  <!-- CHANGELOG:START (auto-generated from CHANGELOG.md — run `bun run changelog:sync`) -->
460
462
  - **[Unreleased]**
463
+ - **[0.12.24]** (2026-11-06)
461
464
  - **[0.12.23]** (2026-11-06)
462
465
  - **[0.12.22]** (2026-11-04)
463
466
  - **[0.12.21]** (2026-11-04)
464
- - **[0.12.20]** (2026-11-04)
465
467
 
466
468
  See [CHANGELOG.md](CHANGELOG.md) for the full history.
467
469
  <!-- CHANGELOG:END -->
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jeo-code",
3
- "version": "0.12.23",
3
+ "version": "0.12.24",
4
4
  "description": "Clean, highly optimized AI coding agent using spec-first loop",
5
5
  "type": "module",
6
6
 
@@ -549,14 +549,28 @@ export async function runAgentLoop(history: Message[], opts: AgentLoopOptions):
549
549
  // Turn-scoped memo: once the workspace is over the snapshot cap, gated calls count as
550
550
  // mutations without re-walking a tree that is known to be too large.
551
551
  let snapshotCapped = false;
552
+ // Why a bash/computer bracket could not be measured (cap or error), when one failed. The call still
553
+ // counts as a possible mutation, but the user and the done gate are told the real reason instead of
554
+ // only "files were modified" — a busy or oversized cwd (e.g. $HOME, /tmp) looks identical otherwise.
555
+ let unmeasuredSnapshot = null as string | null;
556
+ const reportedUnmeasured = new Set<string>();
557
+ const noteUnmeasured = (snap: WorkspaceSnapshot): WorkspaceSnapshot => {
558
+ if (snap.ok) return snap;
559
+ unmeasuredSnapshot = `${snap.reason}: ${snap.detail}`;
560
+ if (!reportedUnmeasured.has(unmeasuredSnapshot)) {
561
+ reportedUnmeasured.add(unmeasuredSnapshot);
562
+ ev.onNotice?.(`workspace snapshot inconclusive (${unmeasuredSnapshot}); shell calls are counted as possible file changes`);
563
+ }
564
+ return snap;
565
+ };
552
566
  const takeSnapshot = async (racySinceMs?: number): Promise<WorkspaceSnapshot> => {
553
567
  if (snapshotCapped) return { ok: false, reason: "cap", detail: "workspace exceeded the snapshot cap earlier this turn" };
554
568
  try {
555
569
  const snap = await snapshotter(cwd, racySinceMs);
556
570
  if (!snap.ok && snap.reason === "cap") snapshotCapped = true;
557
- return snap;
571
+ return noteUnmeasured(snap);
558
572
  } catch (err) {
559
- return { ok: false, reason: "error", detail: err instanceof Error ? err.message : String(err) };
573
+ return noteUnmeasured({ ok: false, reason: "error", detail: err instanceof Error ? err.message : String(err) });
560
574
  }
561
575
  };
562
576
  // bash/computer calls whose mutation status is decided by a workspace diff. Recognized
@@ -1205,7 +1219,7 @@ export async function runAgentLoop(history: Message[], opts: AgentLoopOptions):
1205
1219
  };
1206
1220
  const candidate = stripLeakedReasoningTags(String(toolCalls[0].arguments?.reason ?? ""));
1207
1221
  if (candidate.trim()) lastCompletionCandidate = candidate;
1208
- const doneGate = classifyDoneGate({ ...evidence, pendingHookFailure });
1222
+ const doneGate = classifyDoneGate({ ...evidence, pendingHookFailure, unmeasured: unmeasuredSnapshot ?? undefined });
1209
1223
  const nudge = await ev.onBeforeDone?.((toolCalls[0].arguments?.reason as string) ?? "", evidence);
1210
1224
  const rejection = [doneGate.block ? doneGate.message : "", nudge].filter(Boolean).join("\n\n");
1211
1225
  if (rejection) {
@@ -159,6 +159,66 @@ export async function loadHooks(cwd: string, signal?: AbortSignal): Promise<Hook
159
159
  return userHooks.length ? [...userHooks, ...configured] : configured;
160
160
  }
161
161
 
162
+ /** One hook file as `describeHooks` sees it, read fresh (never from the loader cache). */
163
+ export interface HookFileReport {
164
+ path: string;
165
+ /** `missing`; `ok`; `disabled` (`enabled: false`); `unreadable` (not valid JSON or not an object). */
166
+ state: "missing" | "ok" | "disabled" | "unreadable";
167
+ /** Entries that can run. */
168
+ entries: number;
169
+ /** Entries dropped as unrunnable (unknown event, missing `run`, bad `timeoutMs`). */
170
+ invalid: number;
171
+ }
172
+
173
+ export interface HookReport {
174
+ /** `config.hooks.enabled`: `on` (true), `off` (false: global kill switch), `unset`. */
175
+ gate: "on" | "off" | "unset";
176
+ registry: HookFileReport;
177
+ project: HookFileReport;
178
+ /** What `loadHooks(cwd)` returns right now, counted by event. */
179
+ active: Partial<Record<HookEvent, number>>;
180
+ total: number;
181
+ }
182
+
183
+ async function inspectHookFile(file: string): Promise<HookFileReport> {
184
+ let text: string;
185
+ try {
186
+ text = await fs.readFile(file, "utf-8");
187
+ } catch (err: unknown) {
188
+ const missing = isRecord(err) && err.code === "ENOENT";
189
+ return { path: file, state: missing ? "missing" : "unreadable", entries: 0, invalid: 0 };
190
+ }
191
+ let parsed: unknown;
192
+ try { parsed = JSON.parse(text); } catch { return { path: file, state: "unreadable", entries: 0, invalid: 0 }; }
193
+ if (!isRecord(parsed)) return { path: file, state: "unreadable", entries: 0, invalid: 0 };
194
+ const list = Array.isArray(parsed.hooks) ? parsed.hooks : [];
195
+ const entries = list.filter(isHookEntry).length;
196
+ return { path: file, state: parsed.enabled === false ? "disabled" : "ok", entries, invalid: list.length - entries };
197
+ }
198
+
199
+ /**
200
+ * Read-only account of the hook setup for `jeo doctor`: the global switch, the user
201
+ * registry and the project file as written (with how many entries were dropped as
202
+ * unrunnable), and what actually runs for `cwd`. Installers write these files, and a bad
203
+ * entry is otherwise dropped silently, so this is the one place to see why a hook is idle.
204
+ */
205
+ export async function describeHooks(cwd: string): Promise<HookReport> {
206
+ const config = await readGlobalConfig();
207
+ const gate = config.hooks?.enabled === true ? "on" : config.hooks?.enabled === false ? "off" : "unset";
208
+ const [registry, project] = await Promise.all([inspectHookFile(userHooksPath()), inspectHookFile(path.join(cwd, ".jeo", "hooks.json"))]);
209
+ const active: Partial<Record<HookEvent, number>> = {};
210
+ let total = 0;
211
+ try {
212
+ for (const hook of await loadHooks(cwd)) {
213
+ active[hook.event] = (active[hook.event] ?? 0) + 1;
214
+ total++;
215
+ }
216
+ } catch {
217
+ // An unreadable project file must not take the whole report down.
218
+ }
219
+ return { gate, registry, project, active, total };
220
+ }
221
+
162
222
  async function runHookCommand(
163
223
  runCmd: string,
164
224
  payload: unknown,
@@ -233,6 +233,12 @@ export interface DoneGateInput {
233
233
  verificationStale?: boolean;
234
234
  /** The run-command of the most recent still-failing post-turn hook, or null. */
235
235
  pendingHookFailure: string | null;
236
+ /**
237
+ * Why the host could not measure a shell call's effect on the workspace this turn (snapshot cap or
238
+ * error), when that happened. Such a call is counted as a possible mutation, so the gate says why
239
+ * instead of claiming files were modified.
240
+ */
241
+ unmeasured?: string;
236
242
  }
237
243
 
238
244
  /** Verdict from {@link classifyDoneGate}: whether to bounce `done`, and the message. */
@@ -257,6 +263,10 @@ export function classifyDoneGate(input: DoneGateInput): DoneGateVerdict {
257
263
  const stale = input.sawVerification && input.verificationStale === true;
258
264
  const block = input.sawMutation && (!input.sawVerification || stale || hookFailing);
259
265
  if (!block) return { state: "done_ok", block: false, message: "" };
266
+ const unmeasuredNote = input.unmeasured
267
+ ? ` Note: the host could not measure a shell call's effect on the workspace (${input.unmeasured}), so it is counted as a possible file change; ` +
268
+ "if every command you ran was read-only, say so in your reply."
269
+ : "";
260
270
  if (hookFailing) {
261
271
  return {
262
272
  state: "done_hook_failing",
@@ -272,7 +282,8 @@ export function classifyDoneGate(input: DoneGateInput): DoneGateVerdict {
272
282
  block: true,
273
283
  message:
274
284
  "You verified earlier, but then modified files again — your last passing test/build no longer reflects the current tree. " +
275
- "Re-run the narrowest verification command against the latest changes (e.g. a standalone bash call such as 'bun test', 'bun run typecheck', 'tsc --noEmit', 'npm test', 'pytest', 'cargo test', or 'go test ./...'), then call done.",
285
+ "Re-run the narrowest verification command against the latest changes (e.g. a standalone bash call such as 'bun test', 'bun run typecheck', 'tsc --noEmit', 'npm test', 'pytest', 'cargo test', or 'go test ./...'), then call done." +
286
+ unmeasuredNote,
276
287
  };
277
288
  }
278
289
  return {
@@ -280,6 +291,7 @@ export function classifyDoneGate(input: DoneGateInput): DoneGateVerdict {
280
291
  block: true,
281
292
  message:
282
293
  "You modified files this turn but have no passing verification (no test/build/typecheck command succeeded, or the latest recognized verification failed). " +
283
- "Run the narrowest command that proves your change works (e.g. a standalone bash call such as 'bun test', 'bun run typecheck', 'tsc --noEmit', 'npm test', 'pytest', 'cargo test', or 'go test ./...'), then call done.",
294
+ "Run the narrowest command that proves your change works (e.g. a standalone bash call such as 'bun test', 'bun run typecheck', 'tsc --noEmit', 'npm test', 'pytest', 'cargo test', or 'go test ./...'), then call done." +
295
+ unmeasuredNote,
284
296
  };
285
297
  }
@@ -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.23",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.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}
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,4 +1,5 @@
1
1
  import { readGlobalConfig } from "../agent/state";
2
+ import { describeHooks, type HookReport } from "../agent/hooks";
2
3
  import { findRetiredPins } from "../ai/model-retirements";
3
4
  import { resolveCredential, snapshotProvider, type AuthProvider, type Credential } from "../auth";
4
5
  import { resolveProvider, describeProvider } from "../ai";
@@ -308,6 +309,28 @@ function sharedInstallLines(report: SharedInstallReport): string[] {
308
309
  return lines;
309
310
  }
310
311
 
312
+ /** Human lines for the hook setup. Silent when nothing is configured and nothing is wrong. */
313
+ function hookLines(report: HookReport | { error: string }): string[] {
314
+ if ("error" in report) return [chalk.yellow(`[hooks] check failed (${report.error})`)];
315
+ const { gate, registry, project, active, total } = report;
316
+ const lines: string[] = [];
317
+ if (gate === "off") lines.push(chalk.yellow("[hooks] disabled globally (config.json hooks.enabled=false): no hook runs, the registry included."));
318
+ if (project.state === "disabled") lines.push(chalk.yellow(`[hooks] ${project.path} sets enabled:false: no hook runs in this project.`));
319
+ for (const file of [registry, project]) {
320
+ if (file.state === "unreadable") lines.push(chalk.yellow(`[hooks] ${file.path} is not readable JSON: its hooks are ignored.`));
321
+ if (file.invalid > 0) lines.push(chalk.yellow(`[hooks] ${file.path}: ${file.invalid} invalid entr${file.invalid === 1 ? "y" : "ies"} ignored (unknown event, missing run, or bad timeoutMs).`));
322
+ }
323
+ if (project.state === "ok" && project.entries > 0 && gate !== "on") {
324
+ lines.push(chalk.yellow(`[hooks] ${project.path} lists ${project.entries} hook(s) that do not run: project hooks need hooks.enabled=true in config.json.`));
325
+ }
326
+ if (total > 0) {
327
+ const parts = Object.entries(active).map(([event, count]) => `${event} ${count}`).join(", ");
328
+ lines.push(`${chalk.green("[hooks]")} ${total} active (${parts})${registry.state === "ok" ? `; registry ${registry.path}` : ""}`);
329
+ }
330
+ if (lines.length > 0) lines.push("");
331
+ return lines;
332
+ }
333
+
311
334
  export async function runDoctorCommand(args: string[] = [], deps: DoctorDeps = {}): Promise<void> {
312
335
  const strict = args.includes("--strict");
313
336
  const json = args.includes("--json");
@@ -476,6 +499,14 @@ export async function runDoctorCommand(args: string[] = [], deps: DoctorDeps = {
476
499
  sharedInstall = { error: err instanceof Error ? err.message : String(err) };
477
500
  }
478
501
 
502
+ // Hook setup: read-only, never affects `ready` or the exit code.
503
+ let hooks: HookReport | { error: string };
504
+ try {
505
+ hooks = await describeHooks(process.cwd());
506
+ } catch (err) {
507
+ hooks = { error: err instanceof Error ? err.message : String(err) };
508
+ }
509
+
479
510
  // --- JSON output mode (CI / scripting) ---
480
511
  if (json) {
481
512
  const report = {
@@ -498,6 +529,7 @@ export async function runDoctorCommand(args: string[] = [], deps: DoctorDeps = {
498
529
  })),
499
530
  oauth: oauthHealth,
500
531
  ready,
532
+ hooks,
501
533
  ...(routingEnabled ? { routing: { enabled: true, smolConfigured, preview: routingPreview, ...(routingNotes.length ? { notes: routingNotes } : {}) } } : {}),
502
534
  sharedInstall,
503
535
 
@@ -595,6 +627,8 @@ export async function runDoctorCommand(args: string[] = [], deps: DoctorDeps = {
595
627
  }
596
628
  console.log("");
597
629
 
630
+ for (const line of hookLines(hooks)) console.log(line);
631
+
598
632
  // Final verdict
599
633
  if (ready) {
600
634
  console.log(`${chalk.green("[READY]")} Default model '${config.defaultModel}' is reachable.`);
@@ -812,7 +812,7 @@ async function runLaunchSession(args: string[], registerEndpointCleanup?: (clean
812
812
  "- If the user pasted SKILL.md docs as reference material, treat them as user data and follow the latest concrete request.\n" +
813
813
  "- Before writing code or files in a domain a loaded skill covers, read that SKILL.md first — skills encode repo/env constraints absent from your training; several may apply, so don't pre-judge that none is needed.\n" +
814
814
  "- Your done reason must describe YOUR work or answer — never recite skill documentation.\n" +
815
- skillsPromptSection(workflowSkills));
815
+ skillsPromptSection(workflowSkills, flags.message || undefined));
816
816
 
817
817
  // Re-assemble the system prompt for a given memory block. The OKF memory block is
818
818
  // recomputed per turn (with that turn's query) so failure-first ranking actually
@@ -117,6 +117,36 @@ export function buildSkillTask(skill: SkillDoc, intent: string, invokedAs?: stri
117
117
  : "Carry out this skill's workflow now. If it needs a concrete target you weren't given, make a reasonable assumption or ask the user via done."),
118
118
  ].join("\n");
119
119
  }
120
+ const TASK_STOPWORDS: Record<string, true> = {
121
+ the: true, and: true, for: true, with: true, use: true, this: true, that: true, from: true, into: true,
122
+ you: true, your: true, can: true, please: true, make: true,
123
+ };
124
+ const isAscii = (text: string): boolean => /^[\x00-\x7f]+$/.test(text);
125
+
126
+ /** Words of any script (Korean, Japanese, Chinese included), lowercased; ASCII needs 3+ chars, others 2+. */
127
+ function relevanceTokens(text: string): Set<string> {
128
+ const words = text.toLowerCase().match(/[\p{L}\p{N}][\p{L}\p{N}._-]*/gu) ?? [];
129
+ return new Set(words.filter(w => w.length >= (isAscii(w) ? 3 : 2) && TASK_STOPWORDS[w] !== true));
130
+ }
131
+
132
+ /**
133
+ * How well a skill fits a task. An exact name (+20) or a name part (+10) match always outranks
134
+ * description matches, which add at most +8 so a chatty description cannot beat an explicit name.
135
+ * Non-ASCII words carry no spaces or inflection boundaries ("설치해줘"), so they match a description
136
+ * as a substring either way round.
137
+ */
138
+ function skillRelevance(skill: SkillDoc, task: Set<string>): number {
139
+ const name = skill.name.toLowerCase();
140
+ const score = (task.has(name) ? 20 : 0) + (name.split(/[._-]/).some(part => task.has(part)) ? 10 : 0);
141
+ const description = `${skill.summary} ${skill.whenToUse}`.toLowerCase();
142
+ const words = relevanceTokens(description);
143
+ let hits = 0;
144
+ for (const token of task) {
145
+ if (isAscii(token) ? words.has(token) : description.includes(token) || [...words].some(w => !isAscii(w) && token.includes(w))) hits++;
146
+ }
147
+ return score + Math.min(hits, 8);
148
+ }
149
+
120
150
  export function skillsPromptSection(skills: SkillDoc[] = SKILLS, currentTask?: string): string {
121
151
  const bundleSkills: SkillDoc[] = [];
122
152
  let configuredSkills: SkillDoc[] = [];
@@ -130,18 +160,13 @@ export function skillsPromptSection(skills: SkillDoc[] = SKILLS, currentTask?: s
130
160
  }
131
161
  }
132
162
 
133
- // When a task is provided and skills exceed budget, sort configured skills by relevance
163
+ // When a task is provided and skills exceed budget, rank configured skills by relevance (stable for ties).
134
164
  if (currentTask && currentTask.trim().length > 0 && configuredSkills.length > 5) {
135
- const qTokens = new Set(
136
- currentTask.toLowerCase().match(/[a-z0-9._-]{3,}/g) ?? []
137
- );
138
- configuredSkills = [...configuredSkills].sort((a, b) => {
139
- const aScore = (a.name.toLowerCase().split(/[._-]/).some(t => qTokens.has(t)) ? 10 : 0) +
140
- (qTokens.has(a.name.toLowerCase()) ? 20 : 0);
141
- const bScore = (b.name.toLowerCase().split(/[._-]/).some(t => qTokens.has(t)) ? 10 : 0) +
142
- (qTokens.has(b.name.toLowerCase()) ? 20 : 0);
143
- return bScore - aScore;
144
- });
165
+ const task = relevanceTokens(currentTask);
166
+ configuredSkills = configuredSkills
167
+ .map((skill, index) => ({ skill, index, score: skillRelevance(skill, task) }))
168
+ .sort((a, b) => b.score - a.score || a.index - b.index)
169
+ .map(entry => entry.skill);
145
170
  }
146
171
 
147
172
  const lines: string[] = [];