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
@@ -1,7 +1,8 @@
1
1
  "use strict";
2
2
 
3
- const { loadConfig, defaultAgentModelForProvider, sameModelProvider } = require("../../config");
3
+ const { loadConfig, defaultAgentModelForProvider, defaultAuxModelForProvider, sameModelProvider } = require("../../config");
4
4
  const { readKimiAccessToken } = require("./credentials/kimi");
5
+ const { DEFAULT_AGY_BASE_URL } = require("./credentials/agy");
5
6
 
6
7
  const DEFAULT_OPENAI_BASE_URL = "https://api.openai.com/v1";
7
8
  const DEFAULT_ANTHROPIC_BASE_URL = "https://api.anthropic.com/v1";
@@ -12,18 +13,7 @@ const DEFAULT_GROK_BUILD_BASE_URL = DEFAULT_XAI_BASE_URL;
12
13
  const DEFAULT_GROK_BUILD_MODEL = "grok-4.6";
13
14
  const DEFAULT_KIMI_MODEL = "k3";
14
15
 
15
- function normalizeProvider(value = "") {
16
- const text = String(value || "").trim().toLowerCase();
17
- if (!text) return "";
18
- if (text === "custom") return "openai";
19
- if (text === "codex" || text === "codex-cli" || text === "codex-code") return "codex";
20
- if (text === "claude" || text === "claude-cli" || text === "claude-code") return "anthropic";
21
- if (text === "kimi" || text === "kimi-code" || text === "moonshot") return "kimi";
22
- if (text === "grok" || text === "grok-build" || text === "grok-shell" || text === "grok-api") return "grok-build";
23
- if (text === "xai") return "xai";
24
- if (text === "openai" || text === "anthropic") return text;
25
- return text;
26
- }
16
+ const { normalizeProvider } = require("./providerId");
27
17
 
28
18
  function normalizeKimiModel(value = "") {
29
19
  const raw = String(value || "").trim();
@@ -50,6 +40,7 @@ function resolveTransport({ provider = "", baseUrl = "" } = {}) {
50
40
  return "openai-responses";
51
41
  }
52
42
  if (normalizedProvider === "anthropic") return "anthropic-messages";
43
+ if (normalizedProvider === "agy") return "antigravity";
53
44
  if (normalizedProvider === "kimi") return "openai-chat";
54
45
  if (/\/responses(?:$|[/?#])/.test(url)) return "openai-responses";
55
46
 
@@ -67,9 +58,15 @@ function resolveRuntimeConfig({ workspaceRoot = process.cwd(), provider = "", mo
67
58
  ) || "openai";
68
59
  const custom = selectedProvider === "openai" && config.agentProvider === "custom"
69
60
  && (!useCodingConfig || !(config.ucodeProvider || process.env.UFOO_UCODE_PROVIDER));
70
- const configuredModel = sameModelProvider((useCodingConfig ? config.ucodeProvider : "") || config.agentProvider, selectedProvider)
71
- ? ((useCodingConfig ? config.ucodeModel : "") || config.agentModel)
72
- : "";
61
+ const useCodingGateway = useCodingConfig && (selectedProvider !== "agy" || normalizeProvider(config.ucodeProvider) === "agy");
62
+ const modelProviderMatches = sameModelProvider((useCodingConfig ? config.ucodeProvider : "") || config.agentProvider, selectedProvider);
63
+ function modelSetting(codingModel, agentModel) {
64
+ if (selectedProvider === "agy") {
65
+ return (useCodingGateway ? codingModel : "") || (normalizeProvider(config.agentProvider) === "agy" ? agentModel : "");
66
+ }
67
+ return modelProviderMatches ? ((useCodingConfig ? codingModel : "") || agentModel) : "";
68
+ }
69
+ const configuredModel = modelSetting(config.ucodeModel, config.agentModel);
73
70
 
74
71
  const selectedModel = String(
75
72
  model
@@ -94,19 +91,21 @@ function resolveRuntimeConfig({ workspaceRoot = process.cwd(), provider = "", mo
94
91
  )
95
92
  : selectedProvider === "xai"
96
93
  ? String(process.env.XAI_BASE_URL || DEFAULT_XAI_BASE_URL)
97
- : String(process.env.OPENAI_BASE_URL || DEFAULT_OPENAI_BASE_URL);
94
+ : selectedProvider === "agy"
95
+ ? String(process.env.UFOO_AGY_BASE_URL || DEFAULT_AGY_BASE_URL)
96
+ : String(process.env.OPENAI_BASE_URL || DEFAULT_OPENAI_BASE_URL);
98
97
 
99
98
  let baseUrl = String(
100
99
  (custom ? process.env.UFOO_AGENT_BASE_URL || config.agentBaseUrl : "")
101
100
  || (useCodingConfig ? process.env.UFOO_UCODE_BASE_URL : "")
102
- || (useCodingConfig ? config.ucodeBaseUrl : "")
101
+ || (useCodingGateway ? config.ucodeBaseUrl : "")
103
102
  || defaultBaseUrl
104
103
  ).trim();
105
104
  if (custom) baseUrl = String(process.env.UFOO_AGENT_BASE_URL || config.agentBaseUrl || "").trim();
106
105
 
107
106
  const explicitApiKey = String(custom ? process.env.UFOO_AGENT_API_KEY || config.agentApiKey || "" :
108
107
  (useCodingConfig ? process.env.UFOO_UCODE_API_KEY : "")
109
- || (useCodingConfig ? config.ucodeApiKey : "")
108
+ || (useCodingGateway ? config.ucodeApiKey : "")
110
109
  || ""
111
110
  ).trim();
112
111
  let apiKey = explicitApiKey;
@@ -144,9 +143,17 @@ function resolveRuntimeConfig({ workspaceRoot = process.cwd(), provider = "", mo
144
143
  baseUrl = String(process.env.OPENAI_BASE_URL || DEFAULT_OPENAI_BASE_URL).trim();
145
144
  }
146
145
 
146
+ const configuredAuxModel = modelSetting(config.ucodeAuxModel, config.agentAuxModel);
147
+ const selectedAuxModel = String(
148
+ (useCodingConfig ? process.env.UFOO_UCODE_AUX_MODEL : "")
149
+ || configuredAuxModel
150
+ || (custom ? "" : defaultAuxModelForProvider(selectedProvider))
151
+ ).trim();
152
+
147
153
  return {
148
154
  provider: selectedProvider,
149
155
  model: selectedModel,
156
+ auxModel: selectedAuxModel,
150
157
  baseUrl,
151
158
  apiKey,
152
159
  apiKeySource,
@@ -156,6 +163,46 @@ function resolveRuntimeConfig({ workspaceRoot = process.cwd(), provider = "", mo
156
163
  };
157
164
  }
158
165
 
166
+ // Model discovery and inference must resolve the same credentials and URL.
167
+ // The synchronous resolver alone cannot refresh subscription credentials.
168
+ async function resolveAuthenticatedRuntime(options = {}) {
169
+ const runtime = resolveRuntimeConfig(options);
170
+ const workspaceRoot = options.workspaceRoot || process.cwd();
171
+ let accountId = "";
172
+ if (runtime.provider === "codex" && !runtime.apiKey) {
173
+ try {
174
+ const config = loadConfig(workspaceRoot) || {};
175
+ const { resolveCodexUpstreamCredentials } = require("./credentials/codex");
176
+ const credential = await resolveCodexUpstreamCredentials({
177
+ authPath: config.codexAuthPath,
178
+ refreshWindowMs: Number(config.codexOauthRefreshWindowSec || 300) * 1000,
179
+ env: process.env,
180
+ ...(options.fetchImpl ? { fetchImpl: options.fetchImpl } : {}),
181
+ });
182
+ const token = String(credential && (credential.accessToken || credential.apiKey) || "").trim();
183
+ if (token) {
184
+ runtime.apiKey = token;
185
+ runtime.apiKeySource = String(credential.source || "codex-credential");
186
+ }
187
+ if (credential?.credentialKind === "api-key"
188
+ && !String(process.env.UFOO_UCODE_BASE_URL || "").trim()
189
+ && !String(config.ucodeBaseUrl || "").trim()) {
190
+ runtime.baseUrl = String(process.env.OPENAI_BASE_URL || DEFAULT_OPENAI_BASE_URL).trim();
191
+ }
192
+ if (credential?.credentialKind === "oauth") accountId = String(credential.accountId || "").trim();
193
+ } catch { /* Requests surface missing/invalid credentials. */ }
194
+ }
195
+ if (runtime.provider === "kimi" && runtime.apiKeySource === "kimi-credential" && runtime.kimiCredentialState !== "fresh") {
196
+ try {
197
+ const { resolveKimiUpstreamCredentials } = require("./credentials/kimi");
198
+ const credential = await resolveKimiUpstreamCredentials({ env: process.env,
199
+ ...(options.fetchImpl ? { fetchImpl: options.fetchImpl } : {}) });
200
+ if (credential?.accessToken) runtime.apiKey = String(credential.accessToken).trim();
201
+ } catch { /* Retain the file token; requests surface auth failures. */ }
202
+ }
203
+ return { ...runtime, accountId, requestHeaders: accountId ? { "chatgpt-account-id": accountId } : {} };
204
+ }
205
+
159
206
  function resolveCompletionUrl(baseUrl = "") {
160
207
  const raw = String(baseUrl || "").trim();
161
208
  if (!raw) return "";
@@ -185,4 +232,4 @@ function resolveAnthropicMessagesUrl(baseUrl = "") {
185
232
  return `${normalized}/messages`;
186
233
  }
187
234
 
188
- module.exports = { normalizeProvider, normalizeKimiModel, resolveTransport, resolveRuntimeConfig, resolveCompletionUrl, resolveResponsesUrl, resolveAnthropicMessagesUrl, DEFAULT_OPENAI_BASE_URL };
235
+ module.exports = { normalizeProvider, normalizeKimiModel, resolveTransport, resolveRuntimeConfig, resolveAuthenticatedRuntime, resolveCompletionUrl, resolveResponsesUrl, resolveAnthropicMessagesUrl, DEFAULT_OPENAI_BASE_URL };
@@ -0,0 +1,242 @@
1
+ "use strict";
2
+
3
+ const { createHash, randomUUID } = require("crypto");
4
+ const { buildAgyHeaders, resolveAgyCredentials } = require("../credentials/agy");
5
+ const { createAnthropicMessagesTransport } = require("./anthropicMessagesTransport");
6
+ const { assertTransport } = require("./transportContract");
7
+
8
+ function resolveAgyUrl(baseUrl, method = "streamGenerateContent") {
9
+ const url = new URL(baseUrl);
10
+ const basePath = url.pathname.replace(/\/+$/, "").replace(/\/v1internal:[^/]+$/, "");
11
+ url.pathname = `${basePath}/v1internal:${method}`;
12
+ url.searchParams.delete("$alt");
13
+ url.searchParams.delete("alt");
14
+ if (method === "streamGenerateContent") url.searchParams.set("alt", "sse");
15
+ return url.toString();
16
+ }
17
+
18
+ // Cloud Code accepts the Gemini Schema shape. Project only the keywords it
19
+ // understands, recursing into schemas rather than inspecting tool arguments.
20
+ function toAgySchema(schema = {}, requireNonempty = false) {
21
+ const { type, description, properties, items, required, enum: choices, anyOf, oneOf } = schema || {};
22
+ const variants = anyOf || oneOf;
23
+ if (Array.isArray(variants) && variants.length) {
24
+ if (!requireNonempty) return { anyOf: variants.map((option) => toAgySchema(option)) };
25
+ const usable = variants.filter((option) => option?.type !== "null");
26
+ const variant = toAgySchema({ ...usable[0], ...(description ? { description } : {}) }, requireNonempty);
27
+ if (usable.length < variants.length) variant.nullable = true;
28
+ return variant;
29
+ }
30
+ const result = {};
31
+ if (typeof type === "string") result.type = type;
32
+ if (description) result.description = description;
33
+ if (Array.isArray(choices) && choices.length) {
34
+ result.description = [description, `Allowed values: ${choices.map(JSON.stringify).join(", ")}.`].filter(Boolean).join(" ");
35
+ }
36
+ if (properties && typeof properties === "object") {
37
+ result.properties = Object.fromEntries(Object.entries(properties).map(([name, value]) => [name, toAgySchema(value, requireNonempty)]));
38
+ }
39
+ if (items && typeof items === "object" && !Array.isArray(items)) result.items = toAgySchema(items, requireNonempty);
40
+ if (Array.isArray(required) && required.length) result.required = required;
41
+ if (requireNonempty && result.type === "object" && !Object.keys(result.properties || {}).length) {
42
+ result.properties = { _unused: { type: "boolean", description: "Leave this field unset." } };
43
+ }
44
+ return result;
45
+ }
46
+
47
+ function agySessionId(sessionId) {
48
+ const hash = createHash("sha256").update(sessionId || randomUUID()).digest();
49
+ return `-${hash.readBigUInt64BE() >> 1n}`;
50
+ }
51
+
52
+ function toImagePart({ source } = {}) {
53
+ if (source?.type !== "base64" || !source.data || !source.media_type) return null;
54
+ return { inlineData: { mimeType: source.media_type, data: source.data } };
55
+ }
56
+
57
+ function toAgyContents(messages, model) {
58
+ const calls = new Map();
59
+ const contents = [];
60
+ for (const message of messages) {
61
+ if (message.role !== "assistant" && message.role !== "user") continue;
62
+ const role = message.role === "assistant" ? "model" : "user";
63
+ const blocks = Array.isArray(message.content) ? message.content : [{ type: "text", text: message.content }];
64
+ const parts = [];
65
+ const resultImages = [];
66
+ for (const block of blocks) {
67
+ if (!block) continue;
68
+ const signature = block.thoughtSignature && block.signatureModel === model
69
+ ? { thoughtSignature: block.thoughtSignature }
70
+ : {};
71
+ if (block.type === "text" && (block.text || signature.thoughtSignature)) {
72
+ parts.push({ text: block.text || "", ...signature });
73
+ } else if (block.type === "thinking" && signature.thoughtSignature) {
74
+ parts.push({ text: block.thinking || "", thought: true, ...signature });
75
+ } else if (block.type === "tool_use") {
76
+ const call = { name: block.name, ...(block.upstreamId ? { id: block.upstreamId } : {}) };
77
+ calls.set(block.id, call);
78
+ parts.push({ functionCall: { ...call, args: block.input || {} }, ...signature });
79
+ } else if (block.type === "tool_result" && calls.has(block.tool_use_id)) {
80
+ const result = Array.isArray(block.content) ? block.content : [{ type: "text", text: block.content }];
81
+ const text = result.filter((item) => item?.type === "text").map((item) => item.text).join("\n");
82
+ parts.push({ functionResponse: { ...calls.get(block.tool_use_id), response: {
83
+ [block.is_error ? "error" : "output"]: text,
84
+ } } });
85
+ resultImages.push(...result.filter((item) => item?.type === "image").map(toImagePart).filter(Boolean));
86
+ calls.delete(block.tool_use_id);
87
+ } else if (block.type === "image") {
88
+ const image = toImagePart(block);
89
+ if (image) parts.push(image);
90
+ }
91
+ }
92
+ parts.push(...resultImages);
93
+ if (!parts.length) continue;
94
+ const previous = contents.at(-1);
95
+ if (role === "user" && previous?.role === role && parts.every((part) => part.functionResponse)
96
+ && previous.parts.every((part) => part.functionResponse)) {
97
+ previous.parts.push(...parts);
98
+ } else {
99
+ contents.push({ role, parts });
100
+ }
101
+ }
102
+ return contents;
103
+ }
104
+
105
+ function agyThinkingConfig(model, effort) {
106
+ if (!effort) return null;
107
+ if (/^gemini-3/i.test(model)) {
108
+ // Pro accepts LOW or HIGH. Flash also supports MINIMAL and MEDIUM.
109
+ const flash = /flash/i.test(model);
110
+ const thinkingLevel = {
111
+ off: flash ? "minimal" : "low",
112
+ low: "low",
113
+ medium: flash ? "medium" : "high",
114
+ high: "high",
115
+ xhigh: "high",
116
+ max: "high",
117
+ }[effort];
118
+ return thinkingLevel ? { thinkingLevel, includeThoughts: effort !== "off" } : null;
119
+ }
120
+ const budget = { off: 0, low: 1024, medium: 4096, high: 8192, xhigh: 16384, max: 24576 }[effort];
121
+ return /thinking|^gemini-2\.5/i.test(model) && budget !== undefined
122
+ ? { thinkingBudget: budget, includeThoughts: effort !== "off" }
123
+ : null;
124
+ }
125
+
126
+ function createAntigravityTransport({ runSseRequest, parseSseEventBlock, ...messageDeps }) {
127
+ async function runTurn({
128
+ url, apiKey, model, sessionId, messages = [], tools = [], systemPrompt = "", systemBlocks = null,
129
+ thinkingLevel, maxOutputTokens, signal, timeoutMs, onTextDelta, onThinkingDelta, onPhase,
130
+ }) {
131
+ const credential = await resolveAgyCredentials({ apiKey, baseUrl: url, signal });
132
+ const claude = /^claude-/i.test(model);
133
+ const declarations = tools.map(({ function: tool }) => ({
134
+ name: tool.name,
135
+ description: tool.description,
136
+ parameters: toAgySchema(tool.parameters, claude),
137
+ }));
138
+ const systemTexts = systemBlocks?.length ? systemBlocks.map((block) => block.text) : [systemPrompt];
139
+ const systemParts = systemTexts.filter(Boolean).map((text) => ({ text }));
140
+ const thinkingConfig = agyThinkingConfig(model, thinkingLevel);
141
+ const generationConfig = {
142
+ ...(claude && maxOutputTokens ? { maxOutputTokens } : {}),
143
+ ...(thinkingConfig ? { thinkingConfig } : {}),
144
+ };
145
+ const payload = {
146
+ model,
147
+ project: credential.projectId,
148
+ requestType: "agent",
149
+ userAgent: "antigravity",
150
+ requestId: `agent-${randomUUID()}`,
151
+ request: {
152
+ contents: toAgyContents(messages, model),
153
+ sessionId: agySessionId(sessionId),
154
+ ...(systemParts.length ? { systemInstruction: { role: "user", parts: systemParts } } : {}),
155
+ ...(declarations.length ? {
156
+ tools: [{ functionDeclarations: declarations }],
157
+ toolConfig: { functionCallingConfig: { mode: claude ? "VALIDATED" : "AUTO" } },
158
+ } : {}),
159
+ ...(Object.keys(generationConfig).length ? { generationConfig } : {}),
160
+ },
161
+ };
162
+
163
+ let text = "";
164
+ let usage = null;
165
+ let finishReason = "";
166
+ const assistantContent = [];
167
+ const toolCalls = [];
168
+ function consume(chunk) {
169
+ const response = chunk?.response || chunk;
170
+ if (chunk?.error || response?.error) {
171
+ throw new Error(`Antigravity stream error: ${(chunk.error || response.error).message || "unknown error"}`);
172
+ }
173
+ const stats = response?.usageMetadata;
174
+ if (stats) {
175
+ usage = {
176
+ input: Number(stats.promptTokenCount) || 0,
177
+ output: (Number(stats.candidatesTokenCount) || 0) + (Number(stats.thoughtsTokenCount) || 0),
178
+ cacheRead: stats.cachedContentTokenCount == null ? null : Number(stats.cachedContentTokenCount) || 0,
179
+ cacheCreation: 0,
180
+ inputIncludesCache: true,
181
+ };
182
+ }
183
+ const candidate = response?.candidates?.[0];
184
+ if (candidate?.finishReason) finishReason = candidate.finishReason;
185
+ for (const part of candidate?.content?.parts || []) {
186
+ const signature = part.thoughtSignature ? { thoughtSignature: part.thoughtSignature, signatureModel: model } : {};
187
+ if (part.functionCall) {
188
+ const { name, args = {}, id: upstreamId } = part.functionCall;
189
+ if (!name) throw new Error("Antigravity returned a function call without a name.");
190
+ const id = `tool_${randomUUID()}`;
191
+ assistantContent.push({ type: "tool_use", id, name, input: args, upstreamId, ...signature });
192
+ toolCalls.push({ id, name, args });
193
+ continue;
194
+ }
195
+ const delta = typeof part.text === "string" ? part.text : "";
196
+ if (!delta && !part.thoughtSignature) continue;
197
+ if (part.thought) {
198
+ if (part.thoughtSignature) assistantContent.push({ type: "thinking", thinking: delta, ...signature });
199
+ if (delta) {
200
+ onPhase?.({ type: "thinking_delta", text: delta });
201
+ onThinkingDelta?.(delta);
202
+ }
203
+ } else {
204
+ assistantContent.push({ type: "text", text: delta, ...signature });
205
+ text += delta;
206
+ if (delta) {
207
+ onPhase?.({ type: "text_delta", text: delta });
208
+ onTextDelta?.(delta);
209
+ }
210
+ }
211
+ }
212
+ }
213
+ function buildResult() {
214
+ if (!finishReason) throw new Error("Antigravity response ended before a finish reason was received.");
215
+ if (!["STOP", "MAX_TOKENS"].includes(finishReason)) throw new Error(`Antigravity stopped: ${finishReason}`);
216
+ if (finishReason === "MAX_TOKENS" && toolCalls.length) {
217
+ throw new Error("Antigravity hit its output limit before completing the tool-call batch.");
218
+ }
219
+ return { text, assistantContent, toolCalls, usage };
220
+ }
221
+ const onEvent = ({ data }) => consume(JSON.parse(data));
222
+ return runSseRequest({
223
+ url, headers: { ...buildAgyHeaders(credential), Accept: "text/event-stream" }, payload, signal, timeoutMs, onPhase,
224
+ onNonStream(data) {
225
+ for (const chunk of Array.isArray(data) ? data : [data]) consume(chunk);
226
+ return buildResult();
227
+ },
228
+ onEvent,
229
+ onTail(tail) {
230
+ const { data } = parseSseEventBlock(tail);
231
+ if (data && data !== "[DONE]") onEvent({ data });
232
+ },
233
+ buildResult,
234
+ });
235
+ }
236
+
237
+ // Both adapters use content blocks with batched tool results in the journal.
238
+ const messages = createAnthropicMessagesTransport({ ...messageDeps, resolveUrl: resolveAgyUrl, runTurn });
239
+ return assertTransport({ ...messages, name: "antigravity" }, "antigravity");
240
+ }
241
+
242
+ module.exports = { createAntigravityTransport, resolveAgyUrl };
@@ -5,6 +5,7 @@ module.exports = {
5
5
  ...require("./openaiChatTransport"),
6
6
  ...require("./openaiResponsesTransport"),
7
7
  ...require("./anthropicMessagesTransport"),
8
+ ...require("./antigravityTransport"),
8
9
  ...require("./responsesProtocol"),
9
10
  ...require("./visionBlocks"),
10
11
  };
@@ -57,7 +57,7 @@ function createOpenAiChatTransport(deps = {}) {
57
57
  });
58
58
  }
59
59
  },
60
- prepareToolCalls({ messages, toolCalls }) {
60
+ prepareToolCalls({ messages, turnResult, toolCalls }) {
61
61
  const assistantToolCalls = [];
62
62
  for (const call of toolCalls) {
63
63
  const callId = String(call.id || `call_${randomUUID()}`);
@@ -76,9 +76,10 @@ function createOpenAiChatTransport(deps = {}) {
76
76
 
77
77
  if (assistantToolCalls.length === 0) return null;
78
78
 
79
+ const text = String((turnResult && turnResult.text) || "").trim();
79
80
  messages.push({
80
81
  role: "assistant",
81
- content: null,
82
+ content: text || null,
82
83
  tool_calls: assistantToolCalls,
83
84
  });
84
85
 
@@ -73,9 +73,10 @@ function createOpenAiResponsesTransport(deps = {}) {
73
73
  }
74
74
 
75
75
  if (assistantToolCalls.length === 0) return null;
76
+ const text = String((turnResult && turnResult.text) || "").trim();
76
77
  const assistantMessage = {
77
78
  role: "assistant",
78
- content: null,
79
+ content: text || null,
79
80
  tool_calls: assistantToolCalls,
80
81
  };
81
82
  attachResponsesReasoningItems(
@@ -2,6 +2,7 @@
2
2
 
3
3
  const DEFAULT_RESPONSES_MAX_OUTPUT_TOKENS = 32768;
4
4
  const RESPONSES_REASONING_ITEMS = Symbol("ufoo.responsesReasoningItems");
5
+ const RESPONSES_OUTPUT_ITEMS = Symbol("ufoo.responsesOutputItems");
5
6
 
6
7
  function cloneJsonValue(value) {
7
8
  try {
@@ -27,16 +28,55 @@ function reasoningItemsFromResponse(response = null) {
27
28
  .filter(Boolean);
28
29
  }
29
30
 
31
+ function orderedOutputItemsFromResponse(response = null) {
32
+ const output = response && typeof response === "object" && Array.isArray(response.output)
33
+ ? response.output
34
+ : [];
35
+ const items = [];
36
+ for (const item of output) {
37
+ if (!item || typeof item !== "object") continue;
38
+ if (
39
+ item.type === "reasoning"
40
+ && typeof item.encrypted_content === "string"
41
+ && item.encrypted_content.length > 0
42
+ ) {
43
+ const cloned = cloneJsonValue(item);
44
+ if (cloned) items.push(cloned);
45
+ continue;
46
+ }
47
+ if (item.type === "message") {
48
+ const cloned = cloneJsonValue(item);
49
+ if (cloned) items.push(cloned);
50
+ continue;
51
+ }
52
+ if (item.type === "function_call") {
53
+ const callId = String(item.call_id || item.id || "").trim();
54
+ if (callId) items.push({ type: "function_call", call_id: callId });
55
+ }
56
+ }
57
+ return items;
58
+ }
59
+
30
60
  function attachResponsesReasoningItems(message = null, response = null) {
31
61
  if (!message || typeof message !== "object") return message;
32
62
  const items = reasoningItemsFromResponse(response);
33
- if (items.length === 0) return message;
34
- Object.defineProperty(message, RESPONSES_REASONING_ITEMS, {
35
- value: items,
36
- enumerable: false,
37
- configurable: false,
38
- writable: false,
39
- });
63
+ if (items.length > 0) {
64
+ Object.defineProperty(message, RESPONSES_REASONING_ITEMS, {
65
+ value: items,
66
+ enumerable: false,
67
+ configurable: false,
68
+ writable: false,
69
+ });
70
+ }
71
+ const ordered = orderedOutputItemsFromResponse(response);
72
+ if (ordered.length > 0) {
73
+ Object.defineProperty(message, RESPONSES_OUTPUT_ITEMS, {
74
+ value: ordered,
75
+ enumerable: false,
76
+ configurable: false,
77
+ writable: false,
78
+ });
79
+ }
40
80
  return message;
41
81
  }
42
82
 
@@ -49,6 +89,15 @@ function getResponsesReasoningItems(message = null) {
49
89
  .filter(Boolean);
50
90
  }
51
91
 
92
+ function getResponsesOutputItems(message = null) {
93
+ const items = message && typeof message === "object"
94
+ ? message[RESPONSES_OUTPUT_ITEMS]
95
+ : null;
96
+ return (Array.isArray(items) ? items : [])
97
+ .map(cloneJsonValue)
98
+ .filter(Boolean);
99
+ }
100
+
52
101
  function resolveResponsesUrl(baseUrl = "") {
53
102
  const raw = String(baseUrl || "").trim();
54
103
  if (!raw) return "";
@@ -145,28 +194,79 @@ function messagesToResponsesInput(messages = []) {
145
194
  }
146
195
 
147
196
  if (role === "assistant" && Array.isArray(message.tool_calls)) {
148
- // With store=false and no previous_response_id, encrypted reasoning
149
- // output must be replayed before the corresponding function calls. The
150
- // items live on a non-enumerable message property, so this projection is
151
- // available only to the in-flight provider loop and cannot enter the
152
- // Session Journal through JSON serialization.
153
- input.push(...getResponsesReasoningItems(message));
197
+ // With store=false and no previous_response_id, encrypted reasoning and
198
+ // commentary message items must be replayed in their original order
199
+ // before the corresponding function calls so function_call stays paired
200
+ // with function_call_output.
201
+ const normalizedCalls = [];
202
+ const callsById = new Map();
154
203
  for (const call of message.tool_calls) {
155
204
  if (!call || typeof call !== "object") continue;
156
205
  const fn = call.function && typeof call.function === "object" ? call.function : call;
157
206
  const callId = String(call.id || call.call_id || "").trim();
158
207
  const name = String(fn.name || "").trim();
159
208
  if (!callId || !name) continue;
160
- input.push({
209
+ const callItem = {
161
210
  type: "function_call",
162
211
  call_id: callId,
163
212
  name,
164
213
  arguments: typeof fn.arguments === "string" ? fn.arguments : toJsonString(fn.arguments),
165
- });
214
+ };
215
+ normalizedCalls.push(callItem);
216
+ callsById.set(callId, callItem);
166
217
  }
167
- const assistantText = normalizeContentParts(message.content, "assistant");
168
- if (assistantText.length > 0) {
169
- input.push({ type: "message", role: "assistant", content: assistantText });
218
+
219
+ const orderedItems = getResponsesOutputItems(message);
220
+ const fallbackText = normalizeContentParts(message.content, "assistant");
221
+
222
+ if (orderedItems.length > 0) {
223
+ const turnBuffer = [];
224
+ const emittedCallIds = new Set();
225
+ let emittedMessageText = false;
226
+
227
+ for (const item of orderedItems) {
228
+ if (!item || typeof item !== "object") continue;
229
+ if (item.type === "reasoning" && item.encrypted_content) {
230
+ turnBuffer.push(item);
231
+ continue;
232
+ }
233
+ if (item.type === "message") {
234
+ const msgParts = normalizeContentParts(item.content, "assistant");
235
+ if (msgParts.length > 0) {
236
+ turnBuffer.push({ type: "message", role: "assistant", content: msgParts });
237
+ emittedMessageText = true;
238
+ }
239
+ continue;
240
+ }
241
+ if (item.type === "function_call") {
242
+ const callId = String(item.call_id || "").trim();
243
+ const mapped = callsById.get(callId);
244
+ if (mapped && !emittedCallIds.has(callId)) {
245
+ turnBuffer.push(mapped);
246
+ emittedCallIds.add(callId);
247
+ }
248
+ }
249
+ }
250
+
251
+ if (!emittedMessageText && fallbackText.length > 0) {
252
+ const firstCallIdx = turnBuffer.findIndex((entry) => entry && entry.type === "function_call");
253
+ const msgEntry = { type: "message", role: "assistant", content: fallbackText };
254
+ if (firstCallIdx >= 0) turnBuffer.splice(firstCallIdx, 0, msgEntry);
255
+ else turnBuffer.push(msgEntry);
256
+ }
257
+
258
+ for (const callItem of normalizedCalls) {
259
+ if (!emittedCallIds.has(callItem.call_id)) {
260
+ turnBuffer.push(callItem);
261
+ }
262
+ }
263
+ input.push(...turnBuffer);
264
+ } else {
265
+ input.push(...getResponsesReasoningItems(message));
266
+ if (fallbackText.length > 0) {
267
+ input.push({ type: "message", role: "assistant", content: fallbackText });
268
+ }
269
+ input.push(...normalizedCalls);
170
270
  }
171
271
  continue;
172
272
  }
@@ -490,6 +590,7 @@ module.exports = {
490
590
  DEFAULT_RESPONSES_MAX_OUTPUT_TOKENS,
491
591
  attachResponsesReasoningItems,
492
592
  getResponsesReasoningItems,
593
+ getResponsesOutputItems,
493
594
  reasoningItemsFromResponse,
494
595
  resolveResponsesUrl,
495
596
  messagesToResponsesInput,
@@ -21,6 +21,7 @@ const TRANSPORT_NAMES = Object.freeze([
21
21
  "openai-chat",
22
22
  "openai-responses",
23
23
  "anthropic-messages",
24
+ "antigravity",
24
25
  ]);
25
26
 
26
27
  function assertTransport(transport = null, name = "") {
@@ -14,6 +14,7 @@ function normalizeProvider(value = "") {
14
14
  if (!text) return "ucode";
15
15
  if (text === "codex-cli" || text === "codex-code" || text === "codex" || text === "openai") return "codex";
16
16
  if (text === "claude-cli" || text === "claude-code" || text === "claude" || text === "anthropic") return "claude";
17
+ if (text === "agy" || text === "agy-cli" || text === "antigravity") return "agy";
17
18
  if (text === "grok" || text === "grok-cli" || text === "grok-build" || text === "grok-shell" || text === "grok-api" || text === "xai") return "grok";
18
19
  if (text === "ucode") return "ucode";
19
20
  if (text === "kimi-cli" || text === "kimi-code" || text === "moonshot") return "kimi";
@@ -112,7 +113,8 @@ async function resolveUpstreamRuntime({
112
113
  const runtime = resolveRuntimeConfig({
113
114
  workspaceRoot: projectRoot,
114
115
  provider: normalizedProvider === "ucode" ? "" : normalizedProvider,
115
- model: model || resolveConfiguredModelForProvider(config, normalizedProvider) || defaultAgentModelForProvider(config.agentProvider),
116
+ model: model || resolveConfiguredModelForProvider(config, normalizedProvider)
117
+ || (normalizedProvider === "agy" ? defaultAgentModelForProvider("agy") : defaultAgentModelForProvider(config.agentProvider)),
116
118
  useCodingConfig: normalizedProvider === "ucode",
117
119
  });
118
120
  let credential = null;