u-foo 4.0.3 → 4.0.10

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.
Files changed (160) hide show
  1. package/README.md +239 -19
  2. package/README.zh-CN.md +3 -3
  3. package/bin/ucode.js +10 -2
  4. package/bin/ufoo.js +3 -0
  5. package/dist/tui/darwin-arm64/ufoo-tui +0 -0
  6. package/dist/tui/darwin-x64/ufoo-tui +0 -0
  7. package/dist/tui/linux-arm64/ufoo-tui +0 -0
  8. package/dist/tui/linux-x64/ufoo-tui +0 -0
  9. package/{OBSERVABILITY.md → docs/OBSERVABILITY.md} +3 -3
  10. package/docs/README.md +27 -0
  11. package/extensions/ufoo-browser/LICENSE +152 -0
  12. package/extensions/ufoo-browser/NOTICE +10 -0
  13. package/extensions/ufoo-browser/README.md +30 -0
  14. package/extensions/ufoo-browser/background.js +409 -0
  15. package/extensions/ufoo-browser/icons/icon-128.png +0 -0
  16. package/extensions/ufoo-browser/icons/icon-16.png +0 -0
  17. package/extensions/ufoo-browser/icons/icon-256.png +0 -0
  18. package/extensions/ufoo-browser/icons/icon-32.png +0 -0
  19. package/extensions/ufoo-browser/icons/icon-48.png +0 -0
  20. package/extensions/ufoo-browser/icons/logo.png +0 -0
  21. package/extensions/ufoo-browser/icons/toolbar-16.png +0 -0
  22. package/extensions/ufoo-browser/icons/toolbar-32.png +0 -0
  23. package/extensions/ufoo-browser/icons/toolbar-logo.png +0 -0
  24. package/extensions/ufoo-browser/manifest.json +30 -0
  25. package/extensions/ufoo-browser/popup.css +71 -0
  26. package/extensions/ufoo-browser/popup.html +44 -0
  27. package/extensions/ufoo-browser/popup.js +153 -0
  28. package/package.json +7 -5
  29. package/scripts/postinstall.js +6 -0
  30. package/src/agents/capabilities/browser/index.js +49 -0
  31. package/src/agents/capabilities/coding/backgroundHooks.js +94 -0
  32. package/src/agents/capabilities/coding/index.js +30 -1
  33. package/src/agents/capabilities/index.js +5 -2
  34. package/src/agents/capabilities/planning/index.js +44 -5
  35. package/src/agents/capabilities/turnRecall/index.js +341 -0
  36. package/src/agents/controller/controllerToolExecutor.js +2 -2
  37. package/src/agents/internal/internalRunner.js +30 -8
  38. package/src/agents/internal/taskControl.js +107 -0
  39. package/src/agents/profiles/coding.js +1 -1
  40. package/src/agents/profiles/main.js +1 -1
  41. package/src/agents/prompts/mainAgent.js +1 -0
  42. package/src/agents/prompts/native/toolDescriptions/bash.js +7 -1
  43. package/src/agents/providers/claudeSessionFiles.js +1 -1
  44. package/src/agents/providers/codexThreadProvider.js +6 -1
  45. package/src/agents/providers/credentials/agy.js +171 -0
  46. package/src/agents/providers/directAuthStatus.js +20 -2
  47. package/src/agents/providers/modelsCatalog.js +26 -5
  48. package/src/agents/providers/nativeTransport.js +145 -73
  49. package/src/agents/providers/providerId.js +17 -0
  50. package/src/agents/providers/runtimeConfig.js +67 -20
  51. package/src/agents/providers/transports/antigravityTransport.js +242 -0
  52. package/src/agents/providers/transports/index.js +1 -0
  53. package/src/agents/providers/transports/openaiChatTransport.js +3 -2
  54. package/src/agents/providers/transports/openaiResponsesTransport.js +2 -1
  55. package/src/agents/providers/transports/responsesProtocol.js +119 -18
  56. package/src/agents/providers/transports/transportContract.js +1 -0
  57. package/src/agents/providers/upstreamRuntime.js +3 -1
  58. package/src/agents/runtime/context/contextBudget.js +1 -19
  59. package/src/agents/runtime/context/contextWindow.js +5 -0
  60. package/src/agents/runtime/context/replayHistory.js +16 -10
  61. package/src/agents/runtime/context/runtimeStore.js +0 -1
  62. package/src/agents/runtime/context/sessionJournal.js +1 -1
  63. package/src/agents/runtime/context/slidingWindowManager.js +792 -0
  64. package/src/agents/runtime/context/topicSelector.js +338 -0
  65. package/src/agents/runtime/context/turnAnalyzer.js +767 -0
  66. package/src/agents/runtime/context/turnIndexStore.js +515 -0
  67. package/src/agents/runtime/core/agentLoop.js +140 -35
  68. package/src/agents/runtime/core/executionBudget.js +2 -1
  69. package/src/agents/runtime/core/toolErrorGuard.js +39 -0
  70. package/src/agents/runtime/createAgentRuntime.js +80 -7
  71. package/src/agents/runtime/index.js +5 -0
  72. package/src/agents/runtime/protocol/materialize.js +1 -1
  73. package/src/agents/runtime/tasks/hooks.js +137 -0
  74. package/src/app/chat/ChatController.js +8 -4
  75. package/src/app/chat/daemonMessageRouter.js +3 -1
  76. package/src/app/chat/inputSubmitHandler.js +2 -2
  77. package/src/app/chat/transport.js +1 -1
  78. package/src/app/cli/browserCommands.js +340 -0
  79. package/src/app/cli/busCoreCommands.js +63 -3
  80. package/src/app/cli/features/doctor.js +21 -0
  81. package/src/app/cli/metricsCommands.js +1 -1
  82. package/src/app/cli/run.js +81 -1
  83. package/src/app/cli/setupCommands.js +200 -0
  84. package/src/code/UcodeController.js +31 -1
  85. package/src/code/agent.js +76 -25
  86. package/src/code/busConsumer.js +13 -12
  87. package/src/code/commands.js +0 -1
  88. package/src/code/context/assembler.js +11 -88
  89. package/src/code/context/planGraphService.js +121 -6
  90. package/src/code/context/planProjection.js +10 -2
  91. package/src/code/context/reducers.js +172 -4
  92. package/src/code/context/stateCommit.js +0 -32
  93. package/src/code/context/transcript.js +7 -4
  94. package/src/code/internalThread.js +9 -1
  95. package/src/code/launcher/ucode.js +4 -2
  96. package/src/code/modelCommand.js +6 -5
  97. package/src/code/nativeRunner.js +232 -62
  98. package/src/code/repl.js +27 -1
  99. package/src/code/runtime/agentWakeup.js +20 -3
  100. package/src/code/runtime/backgroundWakeHost.js +45 -0
  101. package/src/code/runtime/taskFocusContext.js +7 -0
  102. package/src/code/runtime/taskLoop.js +24 -1
  103. package/src/code/sessionStore.js +14 -10
  104. package/src/code/taskDecomposer.js +16 -7
  105. package/src/code/tools/backgroundProcess.js +23 -0
  106. package/src/code/tools/bash.js +764 -12
  107. package/src/code/tools/executor.js +13 -4
  108. package/src/code/tools/planGraph.js +1 -0
  109. package/src/code/tools/specs.js +62 -4
  110. package/src/code/tools/taskRun.js +38 -0
  111. package/src/config.js +92 -6
  112. package/src/coordination/bus/index.js +2 -2
  113. package/src/coordination/bus/message.js +10 -1
  114. package/src/coordination/bus/nickname.js +3 -1
  115. package/src/coordination/bus/subscriber.js +25 -10
  116. package/src/coordination/bus/utils.js +4 -0
  117. package/src/coordination/bus/wakeEndpoint.js +198 -0
  118. package/src/coordination/history/agentPerformance.js +18 -18
  119. package/src/coordination/history/agentTrace.js +7 -3
  120. package/src/coordination/state/paths.js +4 -0
  121. package/src/coordination/state/workspaceAccess.js +3 -1
  122. package/src/orchestration/groups/modelConfig.js +66 -0
  123. package/src/orchestration/groups/validateTemplate.js +2 -0
  124. package/src/runtime/browser/broker.js +1027 -0
  125. package/src/runtime/browser/brokerClient.js +108 -0
  126. package/src/runtime/browser/componentInstaller.js +275 -0
  127. package/src/runtime/browser/installState.js +329 -0
  128. package/src/runtime/browser/manifest.js +145 -0
  129. package/src/runtime/browser/native-host-runner.js +198 -0
  130. package/src/runtime/browser/nativeHost.js +213 -0
  131. package/src/runtime/browser/nativeMessagingProtocol.js +50 -0
  132. package/src/runtime/browser/paths.js +134 -0
  133. package/src/runtime/browser/playwrightSession.js +614 -0
  134. package/src/runtime/daemon/agentHost.js +175 -28
  135. package/src/runtime/daemon/busBridge.js +2 -1
  136. package/src/runtime/daemon/deliveryScheduler.js +70 -2
  137. package/src/runtime/daemon/globalDaemon.js +20 -0
  138. package/src/runtime/daemon/groupOrchestrator.js +20 -1
  139. package/src/runtime/daemon/index.js +6 -4
  140. package/src/runtime/daemon/ops.js +14 -8
  141. package/src/tools/handlers/listAgents.js +1 -1
  142. package/src/tools/handlers/readBusSummary.js +1 -1
  143. package/src/tools/handlers/routeAgent.js +122 -5
  144. package/src/tools/schemaFixtures.js +1 -1
  145. package/src/ui/agentSurface.js +60 -6
  146. package/src/ui/format/index.js +34 -2
  147. package/src/ui/format/markdownRenderer.js +4 -2
  148. package/src/ui/rustChatHost.js +22 -7
  149. package/src/ui/rustMultiSession.js +14 -2
  150. package/src/ui/rustUcodeHost.js +249 -80
  151. package/src/ui/ucodeAgentSession.js +88 -0
  152. package/templates/groups/build-lane.json +57 -3
  153. package/templates/groups/build-ultra.json +114 -6
  154. package/templates/groups/design-system.json +57 -3
  155. package/templates/groups/product-discovery.json +57 -3
  156. package/templates/groups/ui-plan-review.json +57 -3
  157. package/templates/groups/ui-polish.json +57 -3
  158. package/templates/groups/verify-ship.json +57 -3
  159. package/src/agents/runtime/context/checkpointStore.js +0 -38
  160. package/src/agents/runtime/context/compaction.js +0 -151
@@ -0,0 +1,171 @@
1
+ "use strict";
2
+
3
+ const { execFile } = require("child_process");
4
+ const { createHash } = require("crypto");
5
+ const fs = require("fs");
6
+ const os = require("os");
7
+ const path = require("path");
8
+ const { promisify } = require("util");
9
+
10
+ const DEFAULT_AGY_BASE_URL = "https://daily-cloudcode-pa.googleapis.com";
11
+ const AGY_SETUP_HINT = "Sign in with `agy`, or set UFOO_AGY_ACCESS_TOKEN or UFOO_AGY_AUTH_PATH.";
12
+ const CLOUD_CODE_ORIGINS = new Set([
13
+ DEFAULT_AGY_BASE_URL,
14
+ "https://cloudcode-pa.googleapis.com",
15
+ "https://daily-cloudcode-pa.sandbox.googleapis.com",
16
+ ]);
17
+ const KEYRING_ENCODING = "go-keyring-base64:";
18
+ const execFileAsync = (...args) => promisify(execFile)(...args);
19
+ let refreshInFlight;
20
+ let projectCache;
21
+
22
+ function parseLocalLogin(raw) {
23
+ try {
24
+ const text = raw.trim();
25
+ const entry = JSON.parse(text.startsWith(KEYRING_ENCODING)
26
+ ? Buffer.from(text.slice(KEYRING_ENCODING.length), "base64").toString("utf8")
27
+ : text);
28
+ return { accessToken: String(entry.token?.access_token || "").trim(), expiresAt: String(entry.token?.expiry || "") };
29
+ } catch {
30
+ throw new Error("Unable to read the local agy login. Sign in again with `agy`.");
31
+ }
32
+ }
33
+
34
+ async function readLocalLogin({ homeDir, platform, runCommand }) {
35
+ const options = { timeout: 20000, maxBuffer: 128 * 1024 };
36
+ if (platform === "darwin") {
37
+ try {
38
+ const { stdout } = await runCommand("/usr/bin/security", ["find-generic-password", "-s", "gemini", "-a", "antigravity", "-w"], options);
39
+ return { ...parseLocalLogin(stdout), source: "agy macOS Keychain" };
40
+ } catch (error) {
41
+ if (error.code !== 44) {
42
+ throw new Error("Unable to read the agy Keychain item. Allow access in macOS or configure UFOO_AGY_AUTH_PATH.");
43
+ }
44
+ }
45
+ }
46
+ if (platform === "linux") {
47
+ try {
48
+ const { stdout } = await runCommand("secret-tool", ["lookup", "service", "gemini", "username", "antigravity"], options);
49
+ if (stdout.trim()) return { ...parseLocalLogin(stdout), source: "agy Secret Service" };
50
+ } catch (error) {
51
+ if (error.code !== "ENOENT" && error.code !== 1) {
52
+ throw new Error("Unable to read the agy Secret Service item. Unlock the keyring or configure UFOO_AGY_AUTH_PATH.");
53
+ }
54
+ }
55
+ }
56
+ let raw;
57
+ try {
58
+ raw = await fs.promises.readFile(path.join(homeDir, ".gemini", "antigravity-cli", "antigravity-oauth-token"), "utf8");
59
+ } catch (error) {
60
+ if (error.code === "ENOENT") return null;
61
+ throw new Error("Cannot read the local agy auth file.");
62
+ }
63
+ return { ...parseLocalLogin(raw), source: "agy auth file" };
64
+ }
65
+
66
+ function expiryIsDue(expiresAt) {
67
+ return Date.parse(expiresAt) <= Date.now() + 30000;
68
+ }
69
+
70
+ async function refreshLocalLogin(options) {
71
+ if (!refreshInFlight) {
72
+ const installed = path.join(options.homeDir, ".local", "bin", "agy");
73
+ const command = fs.existsSync(installed) ? installed : "agy";
74
+ refreshInFlight = Promise.resolve().then(() => options.runCommand(command, ["models"], {
75
+ cwd: os.tmpdir(), env: { ...options.env, AGY_CLI_DISABLE_AUTO_UPDATE: "true" },
76
+ timeout: 20000, maxBuffer: 256 * 1024,
77
+ })).catch(() => {
78
+ throw new Error("Antigravity login needs renewal. Open `agy` and check your sign-in.");
79
+ }).finally(() => { refreshInFlight = null; });
80
+ }
81
+ await refreshInFlight;
82
+ return readLocalLogin(options);
83
+ }
84
+
85
+ function buildAgyHeaders({ accessToken, userAgent }) {
86
+ return {
87
+ Authorization: `Bearer ${accessToken}`,
88
+ "Content-Type": "application/json",
89
+ "User-Agent": userAgent,
90
+ };
91
+ }
92
+
93
+ async function discoverAgyProject({ baseUrl, credential, fetchImpl, signal }) {
94
+ const origin = new URL(baseUrl).origin;
95
+ const key = createHash("sha256").update(origin).update("\0").update(credential.accessToken).digest("hex");
96
+ if (projectCache?.key === key && projectCache.expiresAt > Date.now()) return projectCache.projectId;
97
+
98
+ const timeout = AbortSignal.timeout(8000);
99
+ const response = await fetchImpl(`${origin}/v1internal:loadCodeAssist`, {
100
+ method: "POST",
101
+ headers: buildAgyHeaders(credential),
102
+ body: JSON.stringify({ metadata: { ideType: "ANTIGRAVITY" } }),
103
+ signal: signal ? AbortSignal.any([signal, timeout]) : timeout,
104
+ redirect: "error",
105
+ });
106
+ if (!response.ok) {
107
+ throw new Error(`Antigravity project lookup failed (HTTP ${response.status}). Check your sign-in with \`agy\`.`);
108
+ }
109
+ const payload = await response.json();
110
+ const project = payload.cloudaicompanionProject || payload.projectId || payload.project;
111
+ const projectId = typeof project === "string" ? project.trim() : String(project?.id || "").trim();
112
+ if (!projectId) throw new Error("Antigravity did not return a Cloud Code project. Open `agy` to finish account setup.");
113
+ projectCache = { key, projectId, expiresAt: Date.now() + 10 * 60 * 1000 };
114
+ return projectId;
115
+ }
116
+
117
+ async function resolveAgyCredentials({
118
+ apiKey = "", env = process.env, homeDir = os.homedir(), platform = process.platform,
119
+ runCommand = execFileAsync, fetchImpl = global.fetch, baseUrl = env.UFOO_AGY_BASE_URL || DEFAULT_AGY_BASE_URL,
120
+ signal, requireProject = true,
121
+ } = {}) {
122
+ const explicitToken = String(apiKey || env.UFOO_AGY_ACCESS_TOKEN || "").trim();
123
+ const authPath = String(env.UFOO_AGY_AUTH_PATH || "").trim();
124
+ let credential;
125
+ let projectId = String(env.UFOO_AGY_PROJECT_ID || "").trim();
126
+ let storedUserAgent = "";
127
+ if (explicitToken) {
128
+ credential = { accessToken: explicitToken, expiresAt: "", source: "configured access token" };
129
+ } else if (authPath) {
130
+ let data;
131
+ try {
132
+ const file = authPath.startsWith("~/") ? path.join(homeDir, authPath.slice(2)) : authPath;
133
+ data = JSON.parse(await fs.promises.readFile(file, "utf8"));
134
+ } catch {
135
+ throw new Error("Cannot read Antigravity auth JSON from UFOO_AGY_AUTH_PATH.");
136
+ }
137
+ if (data?.type !== "antigravity" || data.disabled === true) {
138
+ throw new Error("UFOO_AGY_AUTH_PATH must point to an enabled Antigravity auth file.");
139
+ }
140
+ credential = { accessToken: String(data.access_token || "").trim(),
141
+ expiresAt: String(data.expired || "").trim(), source: "Antigravity auth file" };
142
+ projectId ||= String(data.project_id || "").trim();
143
+ storedUserAgent = data.user_agent;
144
+ } else {
145
+ if (!CLOUD_CODE_ORIGINS.has(new URL(baseUrl).origin)) {
146
+ throw new Error("Set explicit Antigravity credentials for the configured API URL.");
147
+ }
148
+ const options = { env, homeDir, platform, runCommand };
149
+ credential = await readLocalLogin(options);
150
+ if (credential?.accessToken && requireProject && expiryIsDue(credential.expiresAt)) {
151
+ credential = await refreshLocalLogin(options);
152
+ }
153
+ }
154
+ if (!credential?.accessToken) {
155
+ throw Object.assign(new Error(`Antigravity API credentials are missing. ${AGY_SETUP_HINT}`),
156
+ { code: "AGY_CREDENTIALS_MISSING" });
157
+ }
158
+ if (Date.parse(credential.expiresAt) <= Date.now()) {
159
+ throw new Error("Antigravity access token expired. Renew it with the client that manages it.");
160
+ }
161
+ credential.userAgent = String(env.UFOO_AGY_USER_AGENT || storedUserAgent || "antigravity/hub/2.32.1 darwin/arm64").trim();
162
+ if (!projectId && requireProject) {
163
+ if (!CLOUD_CODE_ORIGINS.has(new URL(baseUrl).origin)) {
164
+ throw new Error("Set UFOO_AGY_PROJECT_ID for the configured Antigravity API URL.");
165
+ }
166
+ projectId = await discoverAgyProject({ baseUrl, credential, fetchImpl, signal });
167
+ }
168
+ return { ...credential, projectId };
169
+ }
170
+
171
+ module.exports = { DEFAULT_AGY_BASE_URL, AGY_SETUP_HINT, resolveAgyCredentials, buildAgyHeaders };
@@ -4,6 +4,7 @@ const fs = require("fs");
4
4
  const os = require("os");
5
5
  const path = require("path");
6
6
  const { loadConfig } = require("../../config");
7
+ const { AGY_SETUP_HINT, resolveAgyCredentials } = require("./credentials/agy");
7
8
  const {
8
9
  resolveCodexAuthPaths,
9
10
  resolveCodexUpstreamCredentials,
@@ -250,7 +251,7 @@ async function inspectAgyDirectAuth({
250
251
  const classification = classifyAgyLogTail(tail);
251
252
  const base = {
252
253
  provider: "agy",
253
- transport: "antigravity-tui", // No API mode — TUI is the only path.
254
+ transport: "antigravity-tui",
254
255
  credentialKind: "oauth",
255
256
  source: "google-keyring",
256
257
  credentialPath: file || logDir || "",
@@ -371,7 +372,18 @@ async function inspectDirectAuthStatus(options = {}) {
371
372
  return inspectClaudeDirectAuth(nextOptions);
372
373
  }
373
374
  if (selected === "agy") {
374
- return inspectAgyDirectAuth(nextOptions);
375
+ const env = options.env || process.env;
376
+ const base = { provider: "agy", transport: "antigravity", credentialKind: "oauth" };
377
+ try {
378
+ const { source, expiresAt } = await resolveAgyCredentials({
379
+ env, homeDir: options.homeDir, platform: options.platform, requireProject: false,
380
+ });
381
+ return { ...base, ok: true, state: "present", source, expiresAt };
382
+ } catch (error) {
383
+ const cli = error.code === "AGY_CREDENTIALS_MISSING" ? await inspectAgyDirectAuth(nextOptions) : null;
384
+ return { ...base, ok: false, errorCode: error.code || "AGY_API_CREDENTIALS",
385
+ error: error.message, cliAuthenticated: cli?.ok === true };
386
+ }
375
387
  }
376
388
  if (selected === "kimi") {
377
389
  return inspectKimiDirectAuth(nextOptions);
@@ -479,6 +491,12 @@ function formatClaudeDirectAuthStatus(status = {}, options = {}) {
479
491
  }
480
492
 
481
493
  function formatAgyDirectAuthStatus(status = {}, options = {}) {
494
+ if (status.transport === "antigravity") {
495
+ return status.ok
496
+ ? [`Agy API: credentials present · ${status.source}`]
497
+ : [`Agy API: ${status.error || AGY_SETUP_HINT}`,
498
+ ...(status.cliAuthenticated ? [" The agy CLI is signed in with its keychain credentials."] : [])];
499
+ }
482
500
  if (options.compact === true) {
483
501
  if (status.ok) {
484
502
  const details = [
@@ -13,6 +13,8 @@ const CACHE_TTL_MS = 60_000;
13
13
  const { createHash } = require("crypto");
14
14
  const { resolveCodexClientVersion, resolveCodexUserAgent, resolveGrokClientVersion } = require("./clientIdentity");
15
15
  const { normalizeProvider } = require("./runtimeConfig");
16
+ const { DEFAULT_AGY_BASE_URL, resolveAgyCredentials, buildAgyHeaders } = require("./credentials/agy");
17
+ const { resolveAgyUrl } = require("./transports/antigravityTransport");
16
18
 
17
19
  const OFFICIAL_MODEL_ORIGINS = Object.freeze({
18
20
  openai: ["https://api.openai.com"],
@@ -21,6 +23,7 @@ const OFFICIAL_MODEL_ORIGINS = Object.freeze({
21
23
  kimi: ["https://api.kimi.com"],
22
24
  "grok-build": ["https://api.x.ai"],
23
25
  xai: ["https://api.x.ai"],
26
+ agy: [DEFAULT_AGY_BASE_URL, "https://cloudcode-pa.googleapis.com"],
24
27
  });
25
28
 
26
29
  function usesCustomModelEndpoint({ provider = "", transport = "", baseUrl = "", allowUnlistedModels = false } = {}) {
@@ -72,6 +75,7 @@ function resolveAnthropicModelsUrl(baseUrl = "") {
72
75
  }
73
76
 
74
77
  function resolveModelsUrl({ transport = "", baseUrl = "", provider = "", clientVersion = "", codexHome = "" } = {}) {
78
+ if (transport === "antigravity") return baseUrl ? resolveAgyUrl(baseUrl, "fetchAvailableModels") : "";
75
79
  let url;
76
80
  if (String(transport || "") === "anthropic-messages") {
77
81
  url = resolveAnthropicModelsUrl(baseUrl);
@@ -173,7 +177,15 @@ async function listProviderModels(options = {}) {
173
177
  const timeoutMs = Math.max(1000, Number(options.timeoutMs) || DEFAULT_TIMEOUT_MS);
174
178
  const fetchImpl = typeof options.fetchImpl === "function" ? options.fetchImpl : fetch;
175
179
  const skipCache = options.skipCache === true;
176
- const url = resolveModelsUrl({ transport, baseUrl, provider, clientVersion: options.clientVersion, codexHome: options.codexHome });
180
+ const antigravity = transport === "antigravity";
181
+ let url = "";
182
+ let agy;
183
+ try {
184
+ url = resolveModelsUrl({ transport, baseUrl, provider, clientVersion: options.clientVersion, codexHome: options.codexHome });
185
+ if (url && antigravity) agy = await resolveAgyCredentials({ apiKey, env: options.env, baseUrl, fetchImpl });
186
+ } catch (error) {
187
+ return { ok: false, models: [], url, error: error.message, status: 0, cached: false };
188
+ }
177
189
 
178
190
  if (!url) {
179
191
  return {
@@ -186,7 +198,8 @@ async function listProviderModels(options = {}) {
186
198
  };
187
199
  }
188
200
 
189
- const key = cacheKey({ transport, baseUrl, url, apiKey, provider, requestHeaders });
201
+ const key = cacheKey({ transport, baseUrl, url, apiKey: agy?.accessToken || apiKey, provider,
202
+ requestHeaders: agy ? { project: agy.projectId, userAgent: agy.userAgent } : requestHeaders });
190
203
  if (!skipCache) {
191
204
  const hit = modelsCache.get(key);
192
205
  if (hit && (Date.now() - hit.at) < CACHE_TTL_MS) {
@@ -210,7 +223,12 @@ async function listProviderModels(options = {}) {
210
223
  do {
211
224
  if (seenPages.has(nextUrl)) throw new Error("models route repeated a pagination cursor");
212
225
  seenPages.add(nextUrl);
213
- const response = await fetchImpl(nextUrl, {
226
+ const response = await fetchImpl(nextUrl, agy ? {
227
+ method: "POST",
228
+ headers: { Accept: "application/json", ...buildAgyHeaders(agy) },
229
+ body: JSON.stringify({ project: agy.projectId }),
230
+ signal: controller?.signal,
231
+ } : {
214
232
  method: "GET",
215
233
  headers: { ...buildListHeaders({ transport, apiKey, provider, clientVersion: options.clientVersion, codexHome: options.codexHome }), ...requestHeaders },
216
234
  signal: controller ? controller.signal : undefined,
@@ -236,11 +254,14 @@ async function listProviderModels(options = {}) {
236
254
  return result;
237
255
  }
238
256
 
239
- for (const id of extractModelIds(payload, { visibleOnly: provider.toLowerCase() === "codex" })) {
257
+ const pageModels = agy && payload?.models && typeof payload.models === "object" && !Array.isArray(payload.models)
258
+ ? Object.keys(payload.models)
259
+ : extractModelIds(payload, { visibleOnly: provider.toLowerCase() === "codex" });
260
+ for (const id of pageModels) {
240
261
  if (!models.includes(id)) models.push(id);
241
262
  }
242
263
  nextUrl = "";
243
- if (payload && payload.has_more) {
264
+ if (!agy && payload && payload.has_more) {
244
265
  const cursor = payload.last_id || payload.data?.at(-1)?.id;
245
266
  if (!cursor) throw new Error("models route omitted its pagination cursor");
246
267
  const pageUrl = new URL(url);
@@ -11,6 +11,12 @@ const { buildResponsesPayload, isResponsesKeepalive, responseEventDelta, parseRe
11
11
 
12
12
  const DEFAULT_NATIVE_TIMEOUT_MS = 43200000;
13
13
  const DEFAULT_NATIVE_CONNECT_TIMEOUT_MS = 10 * 60 * 1000;
14
+ const NATIVE_MAX_RETRIES = 3;
15
+ const RETRYABLE_STATUS = new Set([408, 429, 500, 502, 503, 504, 529]);
16
+ const RETRYABLE_CODES = new Set([
17
+ "ECONNRESET", "ECONNREFUSED", "EPIPE", "ETIMEDOUT", "EAI_AGAIN", "ENETUNREACH", "EHOSTUNREACH",
18
+ "UND_ERR_CONNECT_TIMEOUT", "UND_ERR_SOCKET", "UND_ERR_HEADERS_TIMEOUT", "UND_ERR_BODY_TIMEOUT",
19
+ ]);
14
20
  const DEFAULT_OPENAI_MAX_TOKENS = 32768;
15
21
  const DEFAULT_ANTHROPIC_MAX_TOKENS = 32768;
16
22
  // Undici otherwise imposes its own 10-second connection deadline, regardless
@@ -275,6 +281,33 @@ function emitPhase(callback, event = {}) {
275
281
  }
276
282
  }
277
283
 
284
+ function isRetryableRequestError(error) {
285
+ if (RETRYABLE_STATUS.has(error?.status)) return true;
286
+ for (let current = error, depth = 0; current && depth < 5; current = current.cause, depth += 1) {
287
+ if (RETRYABLE_CODES.has(current.code)) return true;
288
+ }
289
+ return error instanceof TypeError && error.message === "fetch failed" && !error.cause?.code;
290
+ }
291
+
292
+ function retryDelayMs(response, attempt) {
293
+ const value = response?.headers?.get?.("retry-after");
294
+ let requested = Number.NaN;
295
+ if (value != null && String(value).trim()) {
296
+ requested = /^\d+(?:\.\d+)?$/.test(value) ? Number(value) * 1000 : Date.parse(value) - Date.now();
297
+ }
298
+ return Math.min(30000, Math.max(1000 * 2 ** (attempt - 1), Number.isFinite(requested) ? requested : 0));
299
+ }
300
+
301
+ function waitForRetry(delayMs, signal) {
302
+ return new Promise((resolve, reject) => {
303
+ const cleanup = () => signal.removeEventListener("abort", abort);
304
+ const abort = () => { clearTimeout(timer); cleanup(); reject(new Error("provider retry cancelled")); };
305
+ const timer = setTimeout(() => { cleanup(); resolve(); }, delayMs);
306
+ signal.addEventListener("abort", abort, { once: true });
307
+ if (signal.aborted) abort();
308
+ });
309
+ }
310
+
278
311
  // Shared SSE transport skeleton: POST the payload, then read the stream as
279
312
  // SSE blocks, dispatch each non-[DONE] block to onEvent, and stop after the
280
313
  // batch that carried [DONE]. Timeout/cancel translation and request cleanup
@@ -292,67 +325,90 @@ async function runSseRequest({
292
325
  buildResult,
293
326
  } = {}) {
294
327
  const request = createRequestController({ signal, timeoutMs });
295
-
296
- emitPhase(onPhase, { type: "request_start" });
297
-
298
328
  try {
299
- const response = await fetch(url, {
300
- method: "POST",
301
- headers,
302
- body: JSON.stringify(payload),
303
- signal: request.signal,
304
- dispatcher: getNativeSseDispatcher(),
305
- });
306
-
307
- if (!response.ok) {
308
- const body = await response.text().catch(() => "");
309
- throw new Error(`provider request failed (${response.status}): ${clipText(body, 500)}`);
310
- }
329
+ for (let attempt = 0; ; attempt += 1) {
330
+ let response;
331
+ let reader;
332
+ // Protocol handlers retain their own accumulators. Once any event has
333
+ // reached one, replay would duplicate text/tool arguments; stop retrying.
334
+ let consumed = false;
335
+ emitPhase(onPhase, { type: "request_start" });
336
+ try {
337
+ response = await fetch(url, {
338
+ method: "POST",
339
+ headers,
340
+ body: JSON.stringify(payload),
341
+ signal: request.signal,
342
+ dispatcher: getNativeSseDispatcher(),
343
+ });
311
344
 
312
- const contentType = String(response.headers && typeof response.headers.get === "function"
313
- ? response.headers.get("content-type") || "" : "");
314
- if (/application\/(?:[a-z0-9.+-]*\+)?json\b/i.test(contentType)
315
- || !response.body || typeof response.body.getReader !== "function") {
316
- const data = await response.json();
317
- return onNonStream(data);
318
- }
345
+ if (!response.ok) {
346
+ const body = await response.text().catch(() => "");
347
+ throw Object.assign(new Error(`provider request failed (${response.status}): ${clipText(body, 500)}`), { status: response.status });
348
+ }
319
349
 
320
- const reader = response.body.getReader();
321
- const decoder = new TextDecoder();
322
- let rawBuffer = "";
323
- let sawDone = false;
324
-
325
- while (true) {
326
- const { done, value } = await reader.read();
327
- if (done) break;
328
-
329
- rawBuffer += decoder.decode(value, { stream: true });
330
- const parsed = parseSseBlocks(rawBuffer);
331
- rawBuffer = parsed.rest;
332
-
333
- for (const block of parsed.blocks) {
334
- const { event, data } = parseSseEventBlock(block);
335
- if (!data) continue;
336
- if (data === "[DONE]") {
337
- // Stop reading after this batch instead of waiting for the server
338
- // to close the connection, but keep the buffered tail and finish
339
- // the blocks already parsed alongside [DONE] instead of silently
340
- // dropping them.
341
- sawDone = true;
342
- continue;
350
+ const contentType = String(response.headers && typeof response.headers.get === "function"
351
+ ? response.headers.get("content-type") || "" : "");
352
+ if (/application\/(?:[a-z0-9.+-]*\+)?json\b/i.test(contentType)
353
+ || !response.body || typeof response.body.getReader !== "function") {
354
+ const data = await response.json();
355
+ consumed = true;
356
+ return onNonStream(data);
343
357
  }
344
358
 
345
- onEvent({ event, data });
346
- }
359
+ reader = response.body.getReader();
360
+ const decoder = new TextDecoder();
361
+ let rawBuffer = "";
362
+ let sawDone = false;
363
+
364
+ while (true) {
365
+ const { done, value } = await reader.read();
366
+ if (done) break;
367
+
368
+ rawBuffer += decoder.decode(value, { stream: true });
369
+ const parsed = parseSseBlocks(rawBuffer);
370
+ rawBuffer = parsed.rest;
371
+
372
+ for (const block of parsed.blocks) {
373
+ const { event, data } = parseSseEventBlock(block);
374
+ if (!data) continue;
375
+ if (data === "[DONE]") {
376
+ // Stop reading after this batch instead of waiting for the server
377
+ // to close the connection, but keep the buffered tail and finish
378
+ // the blocks already parsed alongside [DONE] instead of silently
379
+ // dropping them.
380
+ sawDone = true;
381
+ continue;
382
+ }
347
383
 
348
- if (sawDone) break;
349
- }
384
+ consumed = true;
385
+ onEvent({ event, data });
386
+ }
350
387
 
351
- if (typeof onTail === "function") {
352
- onTail(rawBuffer);
353
- }
388
+ if (sawDone) break;
389
+ }
390
+
391
+ if (typeof onTail === "function") {
392
+ consumed = consumed || Boolean(rawBuffer.trim());
393
+ onTail(rawBuffer);
394
+ }
354
395
 
355
- return buildResult();
396
+ return buildResult();
397
+ } catch (error) {
398
+ if (request.signal.aborted || consumed || attempt >= NATIVE_MAX_RETRIES || !isRetryableRequestError(error)) throw error;
399
+ const delayMs = retryDelayMs(response, attempt + 1);
400
+ emitPhase(onPhase, { type: "retry", attempt: attempt + 1, max_retries: NATIVE_MAX_RETRIES,
401
+ retry_delay_ms: delayMs, code: error.cause?.code || error.code || "", status: error.status || null });
402
+ await waitForRetry(delayMs, request.signal);
403
+ } finally {
404
+ if (reader) {
405
+ // A stream source may never settle cancellation. Cleanup must not
406
+ // hold a completed result or hide the original request failure.
407
+ try { Promise.resolve(reader.cancel?.()).catch(() => {}); } catch { /* preserve the request result */ }
408
+ try { reader.releaseLock?.(); } catch { /* preserve the request result */ }
409
+ }
410
+ }
411
+ }
356
412
  } catch (err) {
357
413
  if (request.timedOut()) {
358
414
  const timeoutError = new Error(`CLI timeout (${normalizeTimeoutMs(timeoutMs)}ms)`);
@@ -770,32 +826,25 @@ function extractAnthropicToolCalls(content = []) {
770
826
  }));
771
827
  }
772
828
 
773
- // Mark the newest message with a cache breakpoint so the append-only history
774
- // prefix is served from the prompt cache. The payload gets a copy: stamping
775
- // cache_control onto the shared history array would leave stale breakpoints
776
- // behind as later turns append, eventually exceeding the 4-breakpoint limit.
777
- function withAnthropicCacheBreakpoint(messages = []) {
778
- if (!Array.isArray(messages) || messages.length === 0) return messages;
779
- const copy = messages.slice();
780
- const lastIndex = copy.length - 1;
781
- const last = copy[lastIndex];
782
- if (!last || typeof last !== "object" || Array.isArray(last)) return copy;
783
- if (typeof last.content === "string") {
784
- if (!last.content) return copy;
785
- copy[lastIndex] = {
786
- ...last,
829
+ const STABLE_HISTORY_BOUNDARY_SYMBOL = Symbol.for("ufoo.stableHistoryBoundary");
830
+
831
+ function stampAnthropicCacheBlock(msg) {
832
+ if (!msg || typeof msg !== "object" || Array.isArray(msg)) return msg;
833
+ if (typeof msg.content === "string") {
834
+ if (!msg.content) return msg;
835
+ return {
836
+ ...msg,
787
837
  content: [
788
838
  {
789
839
  type: "text",
790
- text: last.content,
840
+ text: msg.content,
791
841
  cache_control: { ...ANTHROPIC_CACHE_CONTROL },
792
842
  },
793
843
  ],
794
844
  };
795
- return copy;
796
845
  }
797
- if (Array.isArray(last.content) && last.content.length > 0) {
798
- const blocks = last.content.slice();
846
+ if (Array.isArray(msg.content) && msg.content.length > 0) {
847
+ const blocks = msg.content.slice();
799
848
  const blockIndex = blocks.length - 1;
800
849
  const block = blocks[blockIndex];
801
850
  if (block && typeof block === "object" && !Array.isArray(block)) {
@@ -803,12 +852,33 @@ function withAnthropicCacheBreakpoint(messages = []) {
803
852
  ...block,
804
853
  cache_control: { ...ANTHROPIC_CACHE_CONTROL },
805
854
  };
806
- copy[lastIndex] = {
807
- ...last,
855
+ return {
856
+ ...msg,
808
857
  content: blocks,
809
858
  };
810
859
  }
811
860
  }
861
+ return msg;
862
+ }
863
+
864
+ // Mark the ShortStableSnapshot boundary (when present) and the newest message
865
+ // with cache breakpoints so both the cross-turn sliding window prefix and the
866
+ // intra-turn append-only tool loop prefix are served from the prompt cache.
867
+ function withAnthropicCacheBreakpoint(messages = []) {
868
+ if (!Array.isArray(messages) || messages.length === 0) return messages;
869
+ const copy = messages.slice();
870
+ const lastIndex = copy.length - 1;
871
+ let boundaryIndex = -1;
872
+ for (let i = lastIndex - 1; i >= 0; i -= 1) {
873
+ if (copy[i] && copy[i][STABLE_HISTORY_BOUNDARY_SYMBOL]) {
874
+ boundaryIndex = i;
875
+ break;
876
+ }
877
+ }
878
+ if (boundaryIndex >= 0) {
879
+ copy[boundaryIndex] = stampAnthropicCacheBlock(copy[boundaryIndex]);
880
+ }
881
+ copy[lastIndex] = stampAnthropicCacheBlock(copy[lastIndex]);
812
882
  return copy;
813
883
  }
814
884
 
@@ -1118,6 +1188,7 @@ const {
1118
1188
  createOpenAiChatTransport,
1119
1189
  createOpenAiResponsesTransport,
1120
1190
  createAnthropicMessagesTransport,
1191
+ createAntigravityTransport,
1121
1192
  } = require("./transports");
1122
1193
 
1123
1194
  // Transport descriptors: wire-format only. Plan Mode / leases / policy live in the loop.
@@ -1144,6 +1215,7 @@ const TRANSPORTS = {
1144
1215
  toJsonString,
1145
1216
  clipText,
1146
1217
  }),
1218
+ antigravity: createAntigravityTransport({ runSseRequest, parseSseEventBlock, toJsonString, clipText }),
1147
1219
  };
1148
1220
 
1149
1221
  module.exports = {
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+
3
+ function normalizeProvider(value = "") {
4
+ const text = String(value || "").trim().toLowerCase();
5
+ if (!text) return "";
6
+ if (text === "custom") return "openai";
7
+ if (text === "codex" || text === "codex-cli" || text === "codex-code") return "codex";
8
+ if (text === "claude" || text === "claude-cli" || text === "claude-code") return "anthropic";
9
+ if (text === "agy" || text === "agy-cli" || text === "antigravity") return "agy";
10
+ if (text === "kimi" || text === "kimi-code" || text === "moonshot") return "kimi";
11
+ if (text === "grok" || text === "grok-build" || text === "grok-shell" || text === "grok-api") return "grok-build";
12
+ if (text === "xai") return "xai";
13
+ if (text === "openai" || text === "anthropic") return text;
14
+ return text;
15
+ }
16
+
17
+ module.exports = { normalizeProvider };